-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin-main.ts
More file actions
399 lines (340 loc) · 10.2 KB
/
plugin-main.ts
File metadata and controls
399 lines (340 loc) · 10.2 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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import { exists } from "jsr:@std/fs@^1";
import { dirname, esbuild, isAbsolute, parseJsonc } from "./deps.ts";
import {
denoPlugin,
extname,
join,
normalize,
parse,
resolve,
} from "./deps.ts";
import { serve, setServeDir } from "./serve.ts";
import {
DEFAULT_SERVE_DIR,
DenoTempFile,
IS_DEV,
omitKeys,
REACT_STATIC_TS_CONFIG,
REACT_STATIC_TS_CONFIG_DEV,
} from "./stuff.ts";
/**
* Options for configuring the build process
*/
export type BuildOptions = {
/** Watch for changes to source files and rebuild automatically */
watch?: boolean | string;
/** Whether to serve files only, or serve and build */
serve?: "only" | boolean;
/** Path to import map file (e.g. importMap.json) */
importMap?: string;
/** esbuild target (e.g. chrome99, firefox99, safari15) */
target?: string;
/** Path to config file (e.g. deno.json) */
configPath?: string;
/** Input file path (e.g. src/app.tsx) */
inFile: string;
/** Array of input files (used for code splitting) */
inFiles?: string[];
/** Output file path (e.g. public/app.js) */
outFile: string;
/** Output directory path (used for code splitting) */
outDir?: string;
/** Base directory for output files (used for code splitting) */
outbase: string;
/** Directory to serve files from (e.g. public) */
serveDir?: string;
/** Whether to include a hash in output filenames */
hash?: boolean;
/** External dependencies to exclude from bundle */
external?: string[];
/** Whether to automatically open browser when serving */
launchBrowser?: boolean;
/** Additional esbuild plugins */
plugins?: esbuild.Plugin[];
/** esbuild log level */
logLevel?: esbuild.LogLevel;
/** Warning messages to ignore */
ignoredWarnings?: string[];
/** Source map generation options */
sourcemap?: boolean | "linked" | "inline" | "external" | "both";
/** Port number to serve on */
port?: number;
/** Path to esbuild config file (e.g. esbuild.config.json) */
esbuildConfig?: string;
};
let isFirstBuild = true;
/**
* Configuration resource for managing TypeScript/JSX config conformance
*/
type ConformedConfig = {
readonly path: string | undefined;
[Symbol.dispose](): void;
};
/**
* Creates a conformed config with automatic resource cleanup
* @param options - Config options
* @returns Resource-managed config object
*/
async function withConformedConfig({
configPath,
inFiles,
isDev
}: {
configPath?: string;
inFiles?: string[];
isDev: boolean;
}): Promise<ConformedConfig> {
// Check if input files contain JSX/TSX
const isJsx = inFiles?.find((file) =>
file.endsWith(".jsx") || file.endsWith(".tsx")
);
const finalConfig = configPath
? parseJsonc(await Deno.readTextFile(configPath)) as Record<string, any>
: isJsx
? isDev ? REACT_STATIC_TS_CONFIG_DEV : REACT_STATIC_TS_CONFIG
: undefined;
// Adjust JSX compiler options based on dev mode
if (finalConfig && "compilerOptions" in finalConfig) {
if (!isDev && finalConfig["compilerOptions"]?.["jsx"] === "react-jsxdev") {
finalConfig["compilerOptions"]["jsx"] = "react-jsx";
}
if (isDev && finalConfig["compilerOptions"]?.["jsx"] === "react-jsx") {
finalConfig["compilerOptions"]["jsx"] = "react-jsxdev";
}
}
if (finalConfig && configPath && "importMap" in finalConfig) {
// Convert to absolute path if not already
if (finalConfig["importMap"] && !isAbsolute(finalConfig["importMap"])) {
finalConfig["importMap"] = resolve(dirname(configPath), finalConfig["importMap"] as string);
}
}
const tmpFile = finalConfig
? new DenoTempFile(JSON.stringify(finalConfig))
: undefined;
const finalConfigPath = tmpFile ? tmpFile.getPath() : configPath;
return {
path: finalConfigPath,
[Symbol.dispose]() {
tmpFile?.[Symbol.dispose]();
}
};
}
/**
* Builds a project using esbuild
* @param options - Build options
*/
export const build = async (options: BuildOptions): Promise<void> => {
const {
watch,
serve: shouldServe,
importMap,
target,
inFile,
inFiles,
outFile,
outDir: outDir_,
outbase,
serveDir = DEFAULT_SERVE_DIR,
plugins = [],
hash,
logLevel,
external,
configPath,
sourcemap,
launchBrowser,
port,
esbuildConfig: esbuildConfig_,
} = options;
// Generate directories recursively if they don't exist
const outDir = outDir_ ?? dirname(outFile);
await Deno.mkdir(outDir, { recursive: true });
const split = inFiles?.length ? true : false;
let esbuildConfig = esbuildConfig_
? esbuildConfig_.endsWith(".jsonc")
? parseJsonc(await Deno.readTextFile(esbuildConfig_))
: JSON.parse(await Deno.readTextFile(esbuildConfig_))
: undefined;
if (esbuildConfig) {
esbuildConfig = omitKeys(esbuildConfig, ["plugins"]);
}
let finalConfigPath: string | undefined = configPath;
if (!finalConfigPath && !importMap) {
// try to automatically find a deno.jsonc or deno.json file
const denoJson = await exists(join(Deno.cwd(), "deno.json"));
if (denoJson) {
finalConfigPath = "deno.json";
} else {
const denoJsonc = await exists(join(Deno.cwd(), "deno.jsonc"));
if (denoJsonc) {
finalConfigPath = "deno.jsonc";
}
}
}
// Conform config json to match needed JSX config
using config = await withConformedConfig({
configPath: finalConfigPath,
inFiles: inFiles,
isDev: IS_DEV
});
finalConfigPath = config.path;
const opts: esbuild.BuildOptions = {
plugins: [
denoPlugin({
configPath: importMap ?? finalConfigPath ?? undefined,
}),
],
entryPoints: split ? inFiles : [inFile],
...(split ? { outdir: outDir } : { outfile: outFile }),
bundle: true,
format: "esm",
outbase: outbase,
target: target ? target : ["chrome99", "firefox99", "safari15"],
platform: "browser",
treeShaking: true,
minify: !IS_DEV,
jsx: "automatic",
splitting: split,
logLevel,
external,
sourcemap: sourcemap,
// write: false,
banner: IS_DEV
? { js: "globalThis.window.DENO_ENV = 'development';\n" }
: undefined,
...esbuildConfig,
};
const context = await esbuild.context(opts);
const rebuild = async () => {
console.log(isFirstBuild ? "Building..." : "Rebuilding...");
const startTime = performance.now();
try {
// rebuild
const _result = await context.rebuild();
if (hash) {
// Add hash to output file
const { name, ext } = parse(outFile);
const hash = Math.random().toString(36).substring(2, 8);
const newOutFile = join(outDir, `${name}.${hash}${ext}`);
await Deno.rename(outFile, newOutFile);
// console.log(`Renamed ${outFile} to ${newOutFile}`);
// Delete old files (SKIP new file)
const files = Deno.readDirSync(outDir);
for (const file of files) {
const { name: fileName, ext: fileExt } = parse(file.name);
if (
file.isFile &&
fileName.startsWith(name + ".") &&
fileExt === ext &&
file.name !== `${name}.${hash}${ext}`
) {
const oldFile = join(outDir, file.name);
await Deno.remove(oldFile);
}
}
}
isFirstBuild = false;
const dt = performance.now() - startTime;
console.log(`%c✅ Built JS in ${dt.toFixed(2)}ms`, `color: green`);
} catch (e) {
const dt = performance.now() - startTime;
console.error(
`%c🚨 Build error after ${dt.toFixed(2)}ms`,
`color: red; font-weight: bold`,
);
console.error(e);
}
};
const serveBlock = async () => {
// Just serve and don't terminate
setServeDir(serveDir);
await serve({
launchBrowser,
port,
});
return;
};
const serveBackground = () => {
// Start a separate worker to serve the files
const worker = new Worker(new URL("serve.ts", import.meta.url).href, {
type: "module",
});
worker.postMessage({ serveDir, launchBrowser, port });
};
let exited = false;
const exit = async () => {
if (exited) return;
exited = true;
try {
esbuild.stop();
} catch (e) {
console.warn("Error stopping esbuild: ", e);
}
};
if (!watch && !shouldServe) {
// DEFAULT: Build once
await rebuild();
await exit();
}
Deno.addSignalListener("SIGINT", async () => {
await exit();
Deno.exit(0);
});
if (shouldServe === "only" || (shouldServe && !watch)) {
// SERVE-ONLY: Now, serve indefinitely
await serveBlock();
return;
} else if (!watch) {
// DEFAULT: Now exit
return;
}
if (shouldServe) {
// SERVE: Serve in background
serveBackground();
}
let timeSinceLastRebuild = 0;
let timer: number | null = null;
const debounceRebuild = () => {
if (performance.now() - timeSinceLastRebuild > 1000 * 1000) {
// 1 second
timeSinceLastRebuild = performance.now();
rebuild();
timer = null;
return;
} else {
if (timer) clearTimeout(timer);
timer = setTimeout(rebuild, 50);
}
};
debounceRebuild();
const inDir = dirname(inFile);
const watchDirs = typeof watch === "string"
? watch.split(",").map(normalize)
: [inDir];
const arePathsEqual = (path1: string, path2: string) => {
return normalize(resolve(path1)) === normalize(resolve(path2));
};
if (watchDirs.some((dir) => arePathsEqual(dir, outDir))) {
throw new Error(
"Input watch directory and output directories cannot be the same when using --watch, will cause infinite loop.",
);
}
const watcher = Deno.watchFs(watchDirs, { recursive: true });
for await (const event of watcher) {
// Skip events for files that might be output files (i.e. name and extension are similar, ignoring hash)
const paths = event.paths;
const isOutputFile = paths.some((path) => {
const { name, ext } = parse(path);
const nameWithoutHash = name.split(".").slice(0, -1).join(".");
const outFileName = parse(outFile).name;
const isSimilar =
(nameWithoutHash === outFileName || name === outFileName) &&
extname(outFile) === ext;
return isSimilar;
});
if (isOutputFile) {
continue;
}
debounceRebuild();
}
await exit();
};