forked from timreichen/Bundler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.ts
437 lines (406 loc) · 11.5 KB
/
cli.ts
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
#!/usr/bin/env -S deno run --unstable --allow-net --allow-read --allow-write --allow-env
import {
Bundler,
CSSPlugin,
FilePlugin,
HTMLPlugin,
JSONPlugin,
TerserPlugin,
TypescriptPlugin,
WebManifestPlugin,
} from "./mod.ts";
import {
colors,
flags,
ImportMap,
path,
resolveImportMap,
ts,
} from "./deps.ts";
import { parse, Program } from "./program.ts";
import {
createSha256,
formatBytes,
isFileURL,
isURL,
parsePaths,
timestamp,
} from "./_util.ts";
import { Asset, Bundle, Chunk } from "./plugins/plugin.ts";
import { Logger } from "./log/logger.ts";
async function writeBundles(bundler: Bundler, bundles: Bundle[]) {
const time = performance.now();
for (const bundle of bundles) {
const time = performance.now();
const output = path.fromFileUrl(bundle.output);
const source = typeof bundle.source === "string"
? new TextEncoder().encode(bundle.source)
: new Uint8Array(bundle.source);
await Deno.mkdir(path.dirname(output), { recursive: true });
await Deno.writeFile(output, source);
const { size } = await Deno.stat(output);
bundler.logger.info(
colors.green("Write File"),
output,
colors.dim(formatBytes(size)),
colors.dim(colors.italic(`(${timestamp(time)})`)),
);
}
const length = bundles.length;
if (length) {
bundler.logger.info(
colors.brightBlue("Write"),
"Files",
colors.dim(`${length} file${length === 1 ? "" : "s"}`),
colors.dim(colors.italic(`(${timestamp(time)})`)),
);
}
}
function parseBundleArgs(args: flags.Args) {
const {
_,
quiet = false,
"log-level": logLevelString = "info",
"out-dir": dist = "dist",
optimize = false,
watch = false,
reload = false,
"import-map": importMapPath,
config,
} = args;
if (reload) {
if (reload && Array.isArray(reload)) {
// reload = reload.map((filepath) =>
// filepath = new URL(path.resolve(Deno.cwd(), filepath), "file://").href
// );
}
}
const root = isFileURL(dist) ? dist : path.resolve(Deno.cwd(), dist);
const { inputs, outputMap } = parsePaths(_, root);
let logLevel;
switch (logLevelString) {
case "info": {
logLevel = Logger.logLevels.info;
break;
}
case "debug": {
logLevel = Logger.logLevels.debug;
break;
}
default: {
throw Error(`log level not supported: ${logLevelString}`);
}
}
return {
inputs,
outputMap,
logLevel,
quiet,
root,
optimize,
watch,
reload,
importMapPath,
config,
};
}
const cacheDir = path.resolve(Deno.cwd(), ".bundler");
const cacheAssetsDir = path.join(cacheDir, "assets");
async function exists(filename: string) {
try {
await Deno.stat(filename);
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return false;
}
throw error;
}
}
async function bundleCommand(args: flags.Args) {
let {
inputs,
outputMap,
logLevel,
quiet,
root,
optimize,
watch,
reload,
importMapPath,
config,
} = parseBundleArgs(args);
let compilerOptions: ts.CompilerOptions = {};
let importMap: ImportMap;
const denoJsonPath = path.join(Deno.cwd(), "deno.json");
const denoJsoncPath = path.join(Deno.cwd(), "deno.jsonc");
const configPath: string = config ??
(await exists(denoJsonPath) && denoJsonPath) ??
(await exists(denoJsoncPath) && denoJsoncPath);
if (configPath) {
const data = await Deno.readTextFile(configPath);
const json = JSON.parse(data);
importMapPath = importMapPath ?? json.importMap;
compilerOptions = (json && json.compilerOptions) ??
ts.convertCompilerOptionsFromJson(
json.compilerOptions,
Deno.cwd(),
).options;
}
if (importMapPath) {
let source: string;
if (isURL(importMapPath)) {
importMapPath = path.resolve(Deno.cwd(), importMapPath);
source = await Deno.readTextFile(importMapPath);
} else {
source = await fetch(importMapPath).then((data) => data.text());
}
importMap = resolveImportMap(
JSON.parse(source),
path.toFileUrl(importMapPath),
);
}
const plugins = [
new HTMLPlugin(),
new CSSPlugin(),
new TypescriptPlugin(compilerOptions),
new JSONPlugin(),
new WebManifestPlugin(),
new TerserPlugin(),
new FilePlugin(),
];
const bundler = new Bundler({ plugins, logLevel, quiet });
let cachedAssets: Record<string, Asset> = {};
let cachedChunks: Record<string, Chunk> = {};
try {
for await (const dirEntry of Deno.readDir(cacheAssetsDir)) {
const cachedAssetFilepath = path.join(cacheAssetsDir, dirEntry.name);
// if (
// reload === true ||
// Array.isArray(reload) && reload.includes(cachedAssetFilepath)
// ) {
// await Deno.remove(cachedAssetFilepath);
// continue;
// }
const source = await Deno.readTextFile(cachedAssetFilepath);
const asset: Asset = JSON.parse(source);
let cacheExpired = false;
if (isFileURL(asset.input)) {
try {
const input = path.fromFileUrl(asset.input);
const assetStat = await Deno.lstat(input);
const cachedAssetFileStat = await Deno.lstat(cachedAssetFilepath);
if (cachedAssetFileStat.mtime && assetStat.mtime) {
cacheExpired = cachedAssetFileStat.mtime < assetStat.mtime;
}
} catch (error) {
if (!(error instanceof Deno.errors.NotFound)) {
throw error;
}
}
}
if (!cacheExpired) {
try {
if (asset.source === null) {
asset.source = await Deno.readFileSync(
path.fromFileUrl(asset.input),
).buffer;
}
cachedAssets[asset.input] = asset;
continue;
} catch (error) {
if (!(error instanceof Deno.errors.NotFound)) {
throw error;
}
}
cachedAssets[asset.input] = asset;
}
await Deno.remove(cachedAssetFilepath);
}
} catch (error) {
if (!(error instanceof Deno.errors.NotFound)) {
throw error;
}
}
async function bundle() {
const time = performance.now();
const { assets, chunks, bundles } = await bundler.bundle(inputs, {
outputMap,
optimize,
reload,
root,
assets: Object.values(cachedAssets),
chunks: Object.values(cachedChunks),
importMap,
});
cachedAssets = {
...cachedAssets,
...Object.fromEntries(
assets.map((asset) => [asset.input, asset]),
),
};
cachedChunks = {
...cachedChunks,
...Object.fromEntries(
chunks.map((chunk) => [chunk.item.input, chunk]),
),
};
await writeBundles(
bundler,
bundles,
);
bundler.logger.info(
colors.green(`Done`),
`${assets.length} assets,`,
`${chunks.length} chunks,`,
`${bundles.length} bundles`,
colors.dim(colors.italic(`(${timestamp(time)})`)),
);
if (watch) {
const paths = Object.values(cachedAssets)
.map((asset) => new URL(asset.input).pathname)
.filter((pathname) => {
try {
Deno.statSync(pathname);
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return false;
}
throw error;
}
});
const watcher = Deno.watchFs(paths);
bundler.logger.info(
colors.brightBlue(`Watcher`),
"Process finished. Restarting on file change...",
);
for await (const event of watcher) {
switch (event.kind) {
case "modify":
case "remove":
case "create": {
bundler.logger.info(
colors.brightBlue(`Watcher`),
"File change detected! Restarting!",
);
for (const filepath of event.paths) {
try {
const fileURL = path.toFileUrl(filepath).href;
delete cachedAssets[fileURL];
for (const [input, chunk] of Object.entries(cachedChunks)) {
if (
chunk.item.input === fileURL ||
chunk.dependencyItems.some((dependencyItem) =>
dependencyItem.input === fileURL
)
) {
delete cachedChunks[input];
}
}
} catch {
//
}
}
await bundle();
watcher.close();
break;
}
}
}
}
for (const [input, cachedAsset] of Object.entries(cachedAssets)) {
const source = cachedAsset.source instanceof ArrayBuffer
? null
: cachedAsset.source;
Deno.mkdir(cacheAssetsDir, { recursive: true });
const cachedAssetFilepath = path.join(
cacheAssetsDir,
await createSha256(input),
);
await Deno.writeTextFile(
cachedAssetFilepath,
JSON.stringify({
...cachedAsset,
source,
}),
);
}
}
await bundle();
}
const program: Program = {
name: "bundler",
description: "Bundler for deno",
commands: [
{
name: "bundle",
description: "Bundle file(s)",
fn: bundleCommand,
arguments: [
{
name: "source_file",
description: "Script arg",
multiple: true,
},
],
options: [
{
name: "config",
description:
`The configuration file can be used to configure different aspects of\ndeno including TypeScript, linting, and code formatting. Typically
the configuration file will be called \`deno.json\` or \`deno.jsonc\`\nand automatically detected; in that case this flag is not necessary.\nSee
https://deno.land/manual@v1.22.0/getting_started/configuration_file`,
alias: "c",
args: [{ name: "FILE" }],
},
{
name: "help",
description: "Print help information",
alias: "h",
},
{
name: "import-map",
description:
`Load import map file from local file or remote URL.\nDocs: https://deno.land/manual/linking_to_external_code/import_maps\nSpecification: https://wicg.github.io/import-maps/\nExamples: https://github.com/WICG/import-maps#the-import-map`,
args: [{ name: "FILE" }],
},
{
name: "log-level",
description: `Set log level [possible values: debug, info]`,
alias: "L",
args: [{ name: "log-level" }],
},
{
name: "optimize",
description: `Minify source code`,
boolean: true,
},
{
name: "out-dir",
description: "Name of out_dir",
args: [{ name: "DIR" }],
},
{
name: "quiet",
description: "Suppress diagnostic output",
alias: "q",
boolean: true,
},
// {
// name: "reload",
// description:
// `Reload source code cache (recompile TypeScript)\n--reload\nReload everything\n--reload=https://deno.land/std\nReload only standard modules\n--reload=https://deno.land/std/fs/utils.ts,https://deno.land/std/fmt/colors.ts\nReloads specific modules`,
// alias: "r",
// boolean: true,
// },
{
name: "watch",
description: `Watch files and re-bundle on change`,
boolean: true,
},
],
},
],
};
await parse(program, Deno.args);