Repository navigation
Expand file tree
/
Copy pathtsup-plugins.ts
More file actions
145 lines (128 loc) · 5.14 KB
/
Copy pathtsup-plugins.ts
File metadata and controls
145 lines (128 loc) · 5.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import { existsSync } from "node:fs";
import fs from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { type Options } from "tsup";
type Plugin = Required<Options>["plugins"][number];
type EsBuildPlugin = Required<Options>["esbuildPlugins"][number];
export const copyDrizzlePlugin: Plugin = {
name: "copy-drizzle",
async buildEnd() {
const drizzleDir = "drizzle";
const destDir = join("dist", drizzleDir);
if (existsSync(drizzleDir)) {
await fs.cp(drizzleDir, destDir, { recursive: true });
}
}
};
const prependEntrySideEffectsEsBuildPlugin = (options: { cwd: string; require: string[]; moduleType: "esm" | "cjs" }): EsBuildPlugin => ({
name: "prepend-entry-side-effects",
setup(build) {
const importDep = options.moduleType === "esm" ? (moduleName: string) => `import "${moduleName}";` : (moduleName: string) => `require("${moduleName}");`;
build.onEnd(async result => {
const meta = result?.metafile;
if (!meta) return;
const SENTINEL = "// __PREPEND_ENTRY_SIDE_EFFECTS__\n";
const prefix = SENTINEL + options.require.map(importDep).join("\n") + "\n";
const outputFiles = (result.outputFiles || []).reduce(
(acc, file) => acc.set(file.path, file),
new Map<string, Exclude<typeof result.outputFiles, undefined>[number]>()
);
for (const [outFile, outInfo] of Object.entries(meta.outputs)) {
if (!outInfo.entryPoint) continue;
const entryOutputPath = join(options.cwd, outFile);
const inMemoryFile = outputFiles.get(entryOutputPath);
const src = inMemoryFile ? inMemoryFile.text : (await fs.readFile(entryOutputPath, "utf8")).toString();
if (!src.startsWith(SENTINEL)) {
if (inMemoryFile) {
inMemoryFile.contents = Buffer.from(prefix + src);
} else {
await fs.writeFile(entryOutputPath, prefix + src, "utf8");
}
}
}
});
}
});
export const applyDefaults = async ({ packageJson, prependEffectsToEntries, ...options }: ApplyDefaultsOptions): Promise<Options> => {
const { noExternal, external } = await getExternalConfig(packageJson);
const moduleType = packageJson.type === "module" ? "esm" : "cjs";
return {
sourcemap: true,
clean: true,
outDir: "dist",
splitting: true,
bundle: true,
platform: "node",
format: [moduleType],
...options,
noExternal: [...noExternal, ...(options.noExternal ?? [])],
external: [...external, ...(options.external ?? [])],
define: {
...options.define,
"process.env.APP_VERSION": JSON.stringify(packageJson.version)
},
esbuildOptions(options) {
options.metafile = options.metafile || !!prependEffectsToEntries;
},
esbuildPlugins: [
prependEffectsToEntries &&
prependEntrySideEffectsEsBuildPlugin({
require: prependEffectsToEntries,
cwd: process.cwd(),
moduleType
}),
...(options.esbuildPlugins ?? [])
].filter(Boolean) as EsBuildPlugin[],
swc: {
jsc: {
keepClassNames: true,
...options.swc?.jsc,
transform: {
useDefineForClassFields: false,
...options.swc?.jsc?.transform
}
}
} as Options["swc"]
};
};
interface ApplyDefaultsOptions extends Options {
packageJson: Record<string, any>;
prependEffectsToEntries?: string[];
}
async function getExternalConfig(packageJson: Record<string, any>) {
const deps = { ...packageJson.dependencies, ...packageJson.peerDependencies };
const bundledDeps = new Set<string>();
const externalDeps = new Set<string>();
for (const dep of Object.keys(deps)) {
const isInternal = dep !== "@akashnetwork/env-loader" && dep.startsWith("@akashnetwork/") && packageJson.dependencies[dep] === "*";
if (!isInternal) {
externalDeps.add(dep);
continue;
}
bundledDeps.add(dep);
const pkgJsonPath = fileURLToPath(import.meta.resolve(`${dep}/package.json`));
const pkgJson = JSON.parse(await fs.readFile(pkgJsonPath, "utf8"));
const depConfig = await getExternalConfig(pkgJson);
depConfig.noExternal.forEach(d => bundledDeps.add(d));
depConfig.external.forEach(nestedDep => {
if (hasOwnCopyOfDependency(dep, nestedDep)) {
bundledDeps.add(nestedDep);
externalDeps.delete(nestedDep);
// if package is not hoisted, we need to bundle it inside the app
// otherwise this package won't be found in runtime
console.warn(
`\x1b[33mWARN\x1b[0m: Bundling "${nestedDep}" internal package dependency of "${dep}" inside app. Use "npm ls ${nestedDep}" to check why it's not hoisted.`
);
} else if (!bundledDeps.has(nestedDep)) {
externalDeps.add(nestedDep);
}
});
}
return { noExternal: [...bundledDeps], external: [...externalDeps] };
}
function hasOwnCopyOfDependency(packageName: string, dependency: string): boolean {
const pathToPackage = import.meta.resolve(join(packageName, "package.json"));
const possiblyInternalPackagePath = fileURLToPath(import.meta.resolve(join(pathToPackage, "..", "node_modules", dependency)));
return existsSync(possiblyInternalPackagePath);
}