@yaks/esbuild 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +450 -2
  3. package/_dist/bundle.d.ts +6 -0
  4. package/_dist/bundle.d.ts.map +1 -0
  5. package/_dist/compile.d.ts +72 -0
  6. package/_dist/compile.d.ts.map +1 -0
  7. package/_dist/dependencies.d.ts +15 -0
  8. package/_dist/dependencies.d.ts.map +1 -0
  9. package/_dist/file.d.ts +185 -0
  10. package/_dist/file.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +104 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/home.d.ts +15 -0
  14. package/_dist/home.d.ts.map +1 -0
  15. package/_dist/link.d.ts +192 -0
  16. package/_dist/link.d.ts.map +1 -0
  17. package/_dist/lock.d.ts +30 -0
  18. package/_dist/lock.d.ts.map +1 -0
  19. package/_dist/mod.d.ts +6 -0
  20. package/_dist/mod.d.ts.map +1 -0
  21. package/_dist/pack.d.ts +42 -0
  22. package/_dist/pack.d.ts.map +1 -0
  23. package/_dist/package.d.ts +11 -0
  24. package/_dist/package.d.ts.map +1 -0
  25. package/_dist/plan.d.ts +135 -0
  26. package/_dist/plan.d.ts.map +1 -0
  27. package/_dist/platform.d.ts +27 -0
  28. package/_dist/platform.d.ts.map +1 -0
  29. package/_dist/resolve.d.ts +42 -0
  30. package/_dist/resolve.d.ts.map +1 -0
  31. package/_dist/shelf.d.ts +11 -0
  32. package/_dist/shelf.d.ts.map +1 -0
  33. package/_dist/strip.d.ts +51 -0
  34. package/_dist/strip.d.ts.map +1 -0
  35. package/_dist/timing.d.ts +6 -0
  36. package/_dist/timing.d.ts.map +1 -0
  37. package/_dist/unpack.d.ts +14 -0
  38. package/_dist/unpack.d.ts.map +1 -0
  39. package/analysis.js +72 -0
  40. package/analysis.js.map +1 -0
  41. package/analysis.ts +82 -0
  42. package/bundle.js +320 -0
  43. package/bundle.js.map +1 -0
  44. package/bundle.ts +415 -0
  45. package/common.js +129 -0
  46. package/common.js.map +1 -0
  47. package/common.ts +138 -0
  48. package/compile.js +500 -0
  49. package/compile.js.map +1 -0
  50. package/compile.ts +622 -0
  51. package/container.js +142 -0
  52. package/container.js.map +1 -0
  53. package/container.ts +183 -0
  54. package/deno.json +1 -0
  55. package/dependencies.js +31 -0
  56. package/dependencies.js.map +1 -0
  57. package/dependencies.ts +40 -0
  58. package/file.js +303 -0
  59. package/file.js.map +1 -0
  60. package/file.ts +443 -0
  61. package/forward.ts +49 -0
  62. package/graph.js +297 -0
  63. package/graph.js.map +1 -0
  64. package/graph.ts +360 -0
  65. package/home.js +40 -0
  66. package/home.js.map +1 -0
  67. package/home.ts +52 -0
  68. package/link.js +455 -0
  69. package/link.js.map +1 -0
  70. package/link.ts +596 -0
  71. package/lock.js +129 -0
  72. package/lock.js.map +1 -0
  73. package/lock.ts +161 -0
  74. package/mod.js +14 -0
  75. package/mod.js.map +1 -0
  76. package/mod.ts +43 -0
  77. package/npm.js +362 -0
  78. package/npm.js.map +1 -0
  79. package/npm.ts +429 -0
  80. package/pack.js +188 -0
  81. package/pack.js.map +1 -0
  82. package/pack.ts +225 -0
  83. package/package.js +199 -0
  84. package/package.js.map +1 -0
  85. package/package.json +60 -4
  86. package/package.ts +255 -0
  87. package/plan.js +273 -0
  88. package/plan.js.map +1 -0
  89. package/plan.ts +395 -0
  90. package/platform.js +160 -0
  91. package/platform.js.map +1 -0
  92. package/platform.ts +238 -0
  93. package/resolve.js +86 -0
  94. package/resolve.js.map +1 -0
  95. package/resolve.ts +144 -0
  96. package/said.js +44 -0
  97. package/said.js.map +1 -0
  98. package/said.ts +61 -0
  99. package/serve.ts +37 -0
  100. package/sha256.js +7 -0
  101. package/sha256.js.map +1 -0
  102. package/sha256.ts +10 -0
  103. package/shared.js +646 -0
  104. package/shared.js.map +1 -0
  105. package/shared.ts +813 -0
  106. package/shelf.js +73 -0
  107. package/shelf.js.map +1 -0
  108. package/shelf.ts +110 -0
  109. package/strip.js +114 -0
  110. package/strip.js.map +1 -0
  111. package/strip.ts +117 -0
  112. package/tar.js +87 -0
  113. package/tar.js.map +1 -0
  114. package/tar.ts +99 -0
  115. package/timing.js +37 -0
  116. package/timing.js.map +1 -0
  117. package/timing.ts +71 -0
  118. package/unpack.js +40 -0
  119. package/unpack.js.map +1 -0
  120. package/unpack.ts +60 -0
  121. package/used.js +91 -0
  122. package/used.js.map +1 -0
  123. package/used.ts +116 -0
package/graph.js ADDED
@@ -0,0 +1,297 @@
1
+ // The module graph of an app's code: from one entry, every file its relative
2
+ // imports reach, in the order the files name them, every package named on the
3
+ // way, and every module worker a file starts, which is an entry of its own
4
+ // (`new Worker(new URL('./grow.ts', import.meta.url))`). Two readings of one walk: the runtime's, where a specifier names
5
+ // a file exactly (`modules`), and esbuild's, which also tries the extensions
6
+ // and index files a TypeScript import leaves off (`sources`).
7
+ //
8
+ // Specifiers are parsed: an import in a comment or a string names nothing.
9
+ // A `Strip` the walk is handed turns TypeScript and JSX into JavaScript,
10
+ // keeping every import esbuild might keep (only `import type` and its kin go,
11
+ // since missing an import would leave a module out, the bug a walk exists to
12
+ // prevent), and es-module-lexer reads the imports of what is left. The runtime
13
+ // links neither, so its walk reads JavaScript alone and needs no `Strip`. A
14
+ // file that does not parse is a leaf: whatever loads it (esbuild, the runtime,
15
+ // the browser) says why, in a better sentence than a walk could.
16
+ import { parse } from "es-module-lexer/js";
17
+ // A Strip refuses a file with a SyntaxError, es-module-lexer with an Error
18
+ // carrying the offset (`idx`).
19
+ let unparsed = (e)=>e instanceof SyntaxError || e instanceof Error && 'idx' in e;
20
+ // What starts a Web Worker from an app file, read by its shape: the
21
+ // `new URL(path, import.meta.url)` form every bundler and browser resolves
22
+ // against the module that wrote it.
23
+ let STARTS = /\bnew\s+(?:Shared)?Worker\s*\(\s*new\s+URL\s*\(\s*(['"`])([^'"`$]+)\1\s*,\s*import\.meta\.url\s*\)/g;
24
+ /** The specifiers a script starts as Web Workers, read by their shape alone,
25
+ * so TypeScript reads as well as JavaScript.
26
+ *
27
+ * ```ts
28
+ * import { assertEquals } from '@std/assert'
29
+ * assertEquals(
30
+ * startsIn("new Worker(new URL('./grow.ts', import.meta.url), {})"),
31
+ * ['./grow.ts'],
32
+ * )
33
+ * ```
34
+ */ export let startsIn = (code)=>[
35
+ ...code.matchAll(STARTS)
36
+ ].map((m)=>m[2]);
37
+ let NOTHING = {
38
+ imports: [],
39
+ started: []
40
+ };
41
+ // A module read once: what it imports, and what it starts as a worker. A
42
+ // module that does not parse imports and starts nothing, and neither does
43
+ // TypeScript or JSX read with no `Strip`, which only a compiler runs.
44
+ let lexed = async (path, source, strip)=>{
45
+ let read = typed(path) ? strip : (_, js)=>js;
46
+ if (!read) return NOTHING;
47
+ try {
48
+ let js = await read(path, source);
49
+ return {
50
+ imports: parse(js)[0].flatMap(({ n, at })=>n == null ? [] : [
51
+ {
52
+ specifier: n,
53
+ text: !!at?.some(([key, value])=>key == 'type' && value == 'text')
54
+ }
55
+ ]),
56
+ started: startsIn(js)
57
+ };
58
+ } catch (e) {
59
+ if (unparsed(e)) return NOTHING;
60
+ throw e;
61
+ }
62
+ };
63
+ /** The specifiers a module imports, in reading order, or none when it does
64
+ * not parse. Its path says how to read it: TypeScript or JSX through `strip`,
65
+ * JavaScript as it is.
66
+ *
67
+ * ```ts
68
+ * import { assertEquals } from '@std/assert'
69
+ * import { strip } from '@yaks/esbuild/strip'
70
+ * assertEquals(
71
+ * await specifiers(
72
+ * 'a.tsx',
73
+ * `// import x from 'said'\nimport type { T } from 'types'\n` +
74
+ * `import a from './a.js'\nexport * from "three"\n` +
75
+ * `let b = <b>it's</b>\nimport('./b')`,
76
+ * strip,
77
+ * ),
78
+ * ['./a.js', 'three', './b'],
79
+ * )
80
+ * assertEquals(await specifiers('a.ts', 'let n: = 1', strip), [])
81
+ * ```
82
+ */ export let specifiers = async (path, source, strip)=>(await lexed(path, source, strip)).imports.map((i)=>i.specifier);
83
+ /** The specifiers of the scripts a module starts as Web Workers.
84
+ *
85
+ * ```ts
86
+ * import { assertEquals } from '@std/assert'
87
+ * import { strip } from '@yaks/esbuild/strip'
88
+ * assertEquals(
89
+ * await started(
90
+ * 'main.ts',
91
+ * `let w: Worker = new Worker(new URL('./grow.ts', import.meta.url), ` +
92
+ * `{ type: 'module' })\nnew SharedWorker(new URL("../hub.js", ` +
93
+ * `import.meta.url))\nnew Worker('plain.js')`,
94
+ * strip,
95
+ * ),
96
+ * ['./grow.ts', '../hub.js'],
97
+ * )
98
+ * ```
99
+ */ export let started = async (path, source, strip)=>(await lexed(path, source, strip)).started;
100
+ /** Whether a specifier names a file of the app rather than a package. */ export let relative = (spec)=>spec.startsWith('./') || spec.startsWith('../');
101
+ // A scheme (`node:`, `cloudflare:`, `https:`) is the runtime's or the web's,
102
+ // never an npm package.
103
+ let SCHEME = /^[a-z][a-z0-9+.-]*:/i;
104
+ /** The npm package a specifier names, or null when it names none.
105
+ *
106
+ * ```ts
107
+ * import { assertEquals } from '@std/assert'
108
+ * assertEquals(packageOf('three/examples/jsm/Addons.js'), 'three')
109
+ * assertEquals(packageOf('@hono/zod-validator'), '@hono/zod-validator')
110
+ * assertEquals(packageOf('node:fs'), null)
111
+ * assertEquals(packageOf('./a.js'), null)
112
+ * ```
113
+ */ export let packageOf = (spec)=>{
114
+ if (relative(spec) || spec.startsWith('/') || SCHEME.test(spec)) return null;
115
+ let parts = spec.split('/');
116
+ return spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
117
+ };
118
+ /**
119
+ * A specifier against the module that named it: module names are the app's
120
+ * own paths, so `./lib.wasm` from `worker.js` is `lib.wasm` and `../lib.wasm`
121
+ * from `a/b.js` is `lib.wasm`. `..` past the top pops nothing, so no
122
+ * specifier names a file outside the app.
123
+ *
124
+ * ```ts
125
+ * import { assertEquals } from '@std/assert'
126
+ * assertEquals(resolved('a/b.js', '../lib.wasm'), 'lib.wasm')
127
+ * assertEquals(resolved('worker.js', '../../x.js'), 'x.js')
128
+ * ```
129
+ */ export let resolved = (from, spec)=>{
130
+ let at = from.split('/').slice(0, -1);
131
+ for (let seg of spec.split('/')){
132
+ if (seg == '.' || seg == '') continue;
133
+ if (seg == '..') at.pop();
134
+ else at.push(seg);
135
+ }
136
+ return at.join('/');
137
+ };
138
+ // What the runtime links as JavaScript, and what esbuild compiles first.
139
+ let SCRIPT = /\.(?:js|mjs|cjs|ts|tsx|jsx|mts|cts)$/;
140
+ let TYPED = /\.(?:ts|tsx|jsx|mts|cts)$/;
141
+ /** Whether a path is a module with imports of its own to follow. */ export let script = (path)=>SCRIPT.test(path);
142
+ /** Whether a path is TypeScript or JSX, which only a compiler runs. */ export let typed = (path)=>TYPED.test(path);
143
+ /** The extensions a compile tries, in order, for a path with no file behind
144
+ * it, before an index file (./bundle.ts). The TypeScript file a `.js` import
145
+ * names by convention (`./util.js` for util.ts) is not among them: finding it
146
+ * here is what lets the compile say so (./compile.ts `unlinked`). */ export let TRIES = [
147
+ '.ts',
148
+ '.tsx',
149
+ '.js',
150
+ '.jsx',
151
+ '.mts',
152
+ '.mjs'
153
+ ];
154
+ let TWINS = {
155
+ '.js': [
156
+ '.ts',
157
+ '.tsx'
158
+ ],
159
+ '.jsx': [
160
+ '.tsx'
161
+ ],
162
+ '.mjs': [
163
+ '.mts'
164
+ ]
165
+ };
166
+ /** The TypeScript files a JavaScript path names by TypeScript's convention.
167
+ *
168
+ * ```ts
169
+ * import { assertEquals } from '@std/assert'
170
+ * assertEquals(twins('lib/util.js'), ['lib/util.ts', 'lib/util.tsx'])
171
+ * assertEquals(twins('util.ts'), [])
172
+ * ```
173
+ */ export let twins = (path)=>{
174
+ let ext = path.match(/\.m?jsx?$/)?.[0] ?? '';
175
+ let stem = path.slice(0, path.length - ext.length);
176
+ return (TWINS[ext] ?? []).map((twin)=>stem + twin);
177
+ };
178
+ /** The file a relative import of `path` loads, as a compile finds it: the
179
+ * path itself, then with each of `TRIES`, then its index file; null where
180
+ * none is a file.
181
+ *
182
+ * ```ts
183
+ * import { assertEquals } from '@std/assert'
184
+ * let has = (p: string) => ['lib/n.ts', 'ui/index.tsx'].includes(p)
185
+ * assertEquals(
186
+ * ['lib/n', 'ui', 'lib/n.ts', 'lib/m'].map((p) => found(p, has)),
187
+ * ['lib/n.ts', 'ui/index.tsx', 'lib/n.ts', null],
188
+ * )
189
+ * ```
190
+ */ export let found = (path, has)=>[
191
+ path,
192
+ ...TRIES.map((ext)=>path + ext),
193
+ ...TRIES.map((ext)=>`${path}/index${ext}`)
194
+ ].find(has) ?? null;
195
+ let candidates = (path)=>[
196
+ path,
197
+ ...TRIES.map((ext)=>path + ext),
198
+ ...TRIES.map((ext)=>`${path}/index${ext}`),
199
+ ...twins(path)
200
+ ];
201
+ let exact = async (read, path)=>{
202
+ let bytes = await read(path);
203
+ return bytes ? [
204
+ path,
205
+ bytes
206
+ ] : null;
207
+ };
208
+ let loose = async (read, path)=>{
209
+ for (let at of candidates(path)){
210
+ let bytes = await read(at);
211
+ if (bytes) return [
212
+ at,
213
+ bytes
214
+ ];
215
+ }
216
+ return null;
217
+ };
218
+ let walk = (find, strip)=>async (read, entry)=>{
219
+ let load = async (path)=>{
220
+ let hit = await find(read, path);
221
+ if (!hit) return null;
222
+ let [at, bytes] = hit;
223
+ return {
224
+ at,
225
+ bytes,
226
+ lex: script(at) ? await lexed(at, new TextDecoder().decode(bytes), strip) : null
227
+ };
228
+ };
229
+ let pending = [
230
+ entry
231
+ ];
232
+ let queued = new Set(pending);
233
+ let loaded = new Map();
234
+ while(pending.length){
235
+ let batch = pending.splice(0, 16);
236
+ let results = await Promise.allSettled(batch.map(load));
237
+ for (let [i, result] of results.entries()){
238
+ let path = batch[i];
239
+ loaded.set(path, result);
240
+ if (result.status != 'fulfilled' || !result.value?.lex) continue;
241
+ let { at, lex } = result.value;
242
+ for (let { specifier } of lex.imports){
243
+ if (!relative(specifier)) continue;
244
+ let next = resolved(at, specifier);
245
+ if (queued.has(next)) continue;
246
+ queued.add(next);
247
+ pending.push(next);
248
+ }
249
+ }
250
+ }
251
+ let files = new Map();
252
+ let texts = new Set();
253
+ let linked = new Set();
254
+ let named = [];
255
+ let started = [];
256
+ let seen = new Set();
257
+ let visit = async (path)=>{
258
+ if (seen.has(path)) return;
259
+ seen.add(path);
260
+ let result = loaded.get(path);
261
+ if (result?.status == 'rejected') throw result.reason;
262
+ let hit = result?.value;
263
+ if (!hit || files.has(hit.at)) return;
264
+ let { at, bytes, lex } = hit;
265
+ files.set(at, bytes);
266
+ if (!lex) return;
267
+ for (let { specifier, text } of lex.imports){
268
+ if (relative(specifier)) {
269
+ let next = resolved(at, specifier);
270
+ let found = loaded.get(next);
271
+ if (found?.status == 'fulfilled' && found.value) {
272
+ ;
273
+ (text ? texts : linked).add(found.value.at);
274
+ }
275
+ await visit(next);
276
+ } else if (!named.includes(specifier)) named.push(specifier);
277
+ }
278
+ for (let spec of lex.started.filter(relative))started.push([
279
+ at,
280
+ spec
281
+ ]);
282
+ };
283
+ await visit(entry);
284
+ return {
285
+ files,
286
+ texts,
287
+ linked,
288
+ named,
289
+ started
290
+ };
291
+ };
292
+ /** What the runtime loads from `entry`: each specifier names a file exactly,
293
+ * and only JavaScript is linked, so a TypeScript or JSX file is a leaf. */ export let modules = walk(exact);
294
+ /** What esbuild compiles from `entry`, reading TypeScript and JSX through
295
+ * `strip`: an import may leave off the extension or name a directory's
296
+ * index. */ export let sources = (strip)=>walk(loose, strip);
297
+ //# sourceMappingURL=graph.js.map
package/graph.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,2EAA2E;AAC3E,0HAA0H;AAC1H,6EAA6E;AAC7E,8DAA8D;AAC9D,EAAE;AACF,2EAA2E;AAC3E,yEAAyE;AACzE,8EAA8E;AAC9E,6EAA6E;AAC7E,+EAA+E;AAC/E,4EAA4E;AAC5E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I,OAAO,CAAE;QAC3C,IAAI,SAAS,YAAY;UACvB,IAAI,OAAO,SAAS,IAAI;UACxB,IAAI,QAAQ,OAAO,GAAG,CAAC;UACvB,IAAI,OAAO,UAAU,eAAe,MAAM,KAAK,EAAE;;YAC9C,CAAC,OAAO,QAAQ,MAAM,EAAE,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;UAC7C;UACA,MAAM,MAAM;QACd,OAAO,IAAI,CAAC,MAAM,QAAQ,CAAC,YAAY,MAAM,IAAI,CAAC;MACpD;MACA,KAAK,IAAI,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC,UAAW,QAAQ,IAAI,CAAC;QAAC;QAAI;OAAK;IACxE;IACA,MAAM,MAAM;IACZ,OAAO;MAAE;MAAO;MAAO;MAAQ;MAAO;IAAQ;EAChD;AAEA;yEACyE,GACzE,OAAO,IAAI,UAAgB,KAAK,OAAM;AAEtC;;UAEU,GACV,OAAO,IAAI,UAAU,CAAC,QAAuB,KAAK,OAAO,OAAM"}
package/graph.ts ADDED
@@ -0,0 +1,360 @@
1
+ // The module graph of an app's code: from one entry, every file its relative
2
+ // imports reach, in the order the files name them, every package named on the
3
+ // way, and every module worker a file starts, which is an entry of its own
4
+ // (`new Worker(new URL('./grow.ts', import.meta.url))`). Two readings of one walk: the runtime's, where a specifier names
5
+ // a file exactly (`modules`), and esbuild's, which also tries the extensions
6
+ // and index files a TypeScript import leaves off (`sources`).
7
+ //
8
+ // Specifiers are parsed: an import in a comment or a string names nothing.
9
+ // A `Strip` the walk is handed turns TypeScript and JSX into JavaScript,
10
+ // keeping every import esbuild might keep (only `import type` and its kin go,
11
+ // since missing an import would leave a module out, the bug a walk exists to
12
+ // prevent), and es-module-lexer reads the imports of what is left. The runtime
13
+ // links neither, so its walk reads JavaScript alone and needs no `Strip`. A
14
+ // file that does not parse is a leaf: whatever loads it (esbuild, the runtime,
15
+ // the browser) says why, in a better sentence than a walk could.
16
+ import { parse } from 'es-module-lexer/js'
17
+
18
+ /** An app file's bytes, or null when the app has no file at that path. */
19
+ export type Read = (path: string) => Promise<Uint8Array<ArrayBuffer> | null>
20
+
21
+ /** What an entry reaches. `files` is every app file, entry first; a file that
22
+ * is not a script is a leaf, since its imports are not ours to follow. */
23
+ export type Reached = {
24
+ files: Map<string, Uint8Array<ArrayBuffer>>
25
+ /** App paths imported with `type: 'text'`, regardless of extension. */
26
+ texts: Set<string>
27
+ /** App paths imported without the text loader. */
28
+ linked: Set<string>
29
+ /** Every specifier that is not a path: `three`, `hono/cors`, `node:fs`. */
30
+ named: string[]
31
+ /** Each Web Worker a reached file starts from the app's files, as the file
32
+ * that starts it and the specifier it names: an entry of its own, which the
33
+ * walk does not follow. What the specifier resolves against depends on
34
+ * whether that file is compiled (./plan.ts). */
35
+ started: [string, string][]
36
+ }
37
+
38
+ /** TypeScript or JSX as the JavaScript it becomes, every import kept, read
39
+ * by what its path says it is; JavaScript as it is written. Throws a
40
+ * SyntaxError where the source does not parse. `./strip` is sucrase's, at
41
+ * once; a host may answer from elsewhere, later. */
42
+ export type Strip = (path: string, source: string) => string | Promise<string>
43
+
44
+ // A Strip refuses a file with a SyntaxError, es-module-lexer with an Error
45
+ // carrying the offset (`idx`).
46
+ let unparsed = (e: unknown) =>
47
+ e instanceof SyntaxError || e instanceof Error && 'idx' in e
48
+
49
+ // What starts a Web Worker from an app file, read by its shape: the
50
+ // `new URL(path, import.meta.url)` form every bundler and browser resolves
51
+ // against the module that wrote it.
52
+ let STARTS =
53
+ /\bnew\s+(?:Shared)?Worker\s*\(\s*new\s+URL\s*\(\s*(['"`])([^'"`$]+)\1\s*,\s*import\.meta\.url\s*\)/g
54
+
55
+ /** The specifiers a script starts as Web Workers, read by their shape alone,
56
+ * so TypeScript reads as well as JavaScript.
57
+ *
58
+ * ```ts
59
+ * import { assertEquals } from '@std/assert'
60
+ * assertEquals(
61
+ * startsIn("new Worker(new URL('./grow.ts', import.meta.url), {})"),
62
+ * ['./grow.ts'],
63
+ * )
64
+ * ```
65
+ */
66
+ export let startsIn = (code: string): string[] =>
67
+ [...code.matchAll(STARTS)].map((m) => m[2])
68
+
69
+ type Imported = { specifier: string; text: boolean }
70
+ type Lexed = { imports: Imported[]; started: string[] }
71
+
72
+ let NOTHING: Lexed = { imports: [], started: [] }
73
+
74
+ // A module read once: what it imports, and what it starts as a worker. A
75
+ // module that does not parse imports and starts nothing, and neither does
76
+ // TypeScript or JSX read with no `Strip`, which only a compiler runs.
77
+ let lexed = async (
78
+ path: string,
79
+ source: string,
80
+ strip?: Strip,
81
+ ): Promise<Lexed> => {
82
+ let read = typed(path) ? strip : (_: string, js: string) => js
83
+ if (!read) return NOTHING
84
+ try {
85
+ let js = await read(path, source)
86
+ return {
87
+ imports: parse(js)[0].flatMap(({ n, at }) =>
88
+ n == null ? [] : [{
89
+ specifier: n,
90
+ text: !!at?.some(([key, value]) => key == 'type' && value == 'text'),
91
+ }]
92
+ ),
93
+ started: startsIn(js),
94
+ }
95
+ } catch (e) {
96
+ if (unparsed(e)) return NOTHING
97
+ throw e
98
+ }
99
+ }
100
+
101
+ /** The specifiers a module imports, in reading order, or none when it does
102
+ * not parse. Its path says how to read it: TypeScript or JSX through `strip`,
103
+ * JavaScript as it is.
104
+ *
105
+ * ```ts
106
+ * import { assertEquals } from '@std/assert'
107
+ * import { strip } from '@yaks/esbuild/strip'
108
+ * assertEquals(
109
+ * await specifiers(
110
+ * 'a.tsx',
111
+ * `// import x from 'said'\nimport type { T } from 'types'\n` +
112
+ * `import a from './a.js'\nexport * from "three"\n` +
113
+ * `let b = <b>it's</b>\nimport('./b')`,
114
+ * strip,
115
+ * ),
116
+ * ['./a.js', 'three', './b'],
117
+ * )
118
+ * assertEquals(await specifiers('a.ts', 'let n: = 1', strip), [])
119
+ * ```
120
+ */
121
+ export let specifiers = async (
122
+ path: string,
123
+ source: string,
124
+ strip: Strip,
125
+ ): Promise<string[]> =>
126
+ (await lexed(path, source, strip)).imports.map((i) => i.specifier)
127
+
128
+ /** The specifiers of the scripts a module starts as Web Workers.
129
+ *
130
+ * ```ts
131
+ * import { assertEquals } from '@std/assert'
132
+ * import { strip } from '@yaks/esbuild/strip'
133
+ * assertEquals(
134
+ * await started(
135
+ * 'main.ts',
136
+ * `let w: Worker = new Worker(new URL('./grow.ts', import.meta.url), ` +
137
+ * `{ type: 'module' })\nnew SharedWorker(new URL("../hub.js", ` +
138
+ * `import.meta.url))\nnew Worker('plain.js')`,
139
+ * strip,
140
+ * ),
141
+ * ['./grow.ts', '../hub.js'],
142
+ * )
143
+ * ```
144
+ */
145
+ export let started = async (
146
+ path: string,
147
+ source: string,
148
+ strip: Strip,
149
+ ): Promise<string[]> => (await lexed(path, source, strip)).started
150
+
151
+ /** Whether a specifier names a file of the app rather than a package. */
152
+ export let relative = (spec: string): boolean =>
153
+ spec.startsWith('./') || spec.startsWith('../')
154
+
155
+ // A scheme (`node:`, `cloudflare:`, `https:`) is the runtime's or the web's,
156
+ // never an npm package.
157
+ let SCHEME = /^[a-z][a-z0-9+.-]*:/i
158
+
159
+ /** The npm package a specifier names, or null when it names none.
160
+ *
161
+ * ```ts
162
+ * import { assertEquals } from '@std/assert'
163
+ * assertEquals(packageOf('three/examples/jsm/Addons.js'), 'three')
164
+ * assertEquals(packageOf('@hono/zod-validator'), '@hono/zod-validator')
165
+ * assertEquals(packageOf('node:fs'), null)
166
+ * assertEquals(packageOf('./a.js'), null)
167
+ * ```
168
+ */
169
+ export let packageOf = (spec: string): string | null => {
170
+ if (relative(spec) || spec.startsWith('/') || SCHEME.test(spec)) return null
171
+ let parts = spec.split('/')
172
+ return spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]
173
+ }
174
+
175
+ /**
176
+ * A specifier against the module that named it: module names are the app's
177
+ * own paths, so `./lib.wasm` from `worker.js` is `lib.wasm` and `../lib.wasm`
178
+ * from `a/b.js` is `lib.wasm`. `..` past the top pops nothing, so no
179
+ * specifier names a file outside the app.
180
+ *
181
+ * ```ts
182
+ * import { assertEquals } from '@std/assert'
183
+ * assertEquals(resolved('a/b.js', '../lib.wasm'), 'lib.wasm')
184
+ * assertEquals(resolved('worker.js', '../../x.js'), 'x.js')
185
+ * ```
186
+ */
187
+ export let resolved = (from: string, spec: string): string => {
188
+ let at = from.split('/').slice(0, -1)
189
+ for (let seg of spec.split('/')) {
190
+ if (seg == '.' || seg == '') continue
191
+ if (seg == '..') at.pop()
192
+ else at.push(seg)
193
+ }
194
+ return at.join('/')
195
+ }
196
+
197
+ // What the runtime links as JavaScript, and what esbuild compiles first.
198
+ let SCRIPT = /\.(?:js|mjs|cjs|ts|tsx|jsx|mts|cts)$/
199
+ let TYPED = /\.(?:ts|tsx|jsx|mts|cts)$/
200
+
201
+ /** Whether a path is a module with imports of its own to follow. */
202
+ export let script = (path: string): boolean => SCRIPT.test(path)
203
+
204
+ /** Whether a path is TypeScript or JSX, which only a compiler runs. */
205
+ export let typed = (path: string): boolean => TYPED.test(path)
206
+
207
+ /** The extensions a compile tries, in order, for a path with no file behind
208
+ * it, before an index file (./bundle.ts). The TypeScript file a `.js` import
209
+ * names by convention (`./util.js` for util.ts) is not among them: finding it
210
+ * here is what lets the compile say so (./compile.ts `unlinked`). */
211
+ export let TRIES = ['.ts', '.tsx', '.js', '.jsx', '.mts', '.mjs']
212
+ let TWINS: Record<string, string[]> = {
213
+ '.js': ['.ts', '.tsx'],
214
+ '.jsx': ['.tsx'],
215
+ '.mjs': ['.mts'],
216
+ }
217
+
218
+ /** The TypeScript files a JavaScript path names by TypeScript's convention.
219
+ *
220
+ * ```ts
221
+ * import { assertEquals } from '@std/assert'
222
+ * assertEquals(twins('lib/util.js'), ['lib/util.ts', 'lib/util.tsx'])
223
+ * assertEquals(twins('util.ts'), [])
224
+ * ```
225
+ */
226
+ export let twins = (path: string): string[] => {
227
+ let ext = path.match(/\.m?jsx?$/)?.[0] ?? ''
228
+ let stem = path.slice(0, path.length - ext.length)
229
+ return (TWINS[ext] ?? []).map((twin) => stem + twin)
230
+ }
231
+
232
+ /** The file a relative import of `path` loads, as a compile finds it: the
233
+ * path itself, then with each of `TRIES`, then its index file; null where
234
+ * none is a file.
235
+ *
236
+ * ```ts
237
+ * import { assertEquals } from '@std/assert'
238
+ * let has = (p: string) => ['lib/n.ts', 'ui/index.tsx'].includes(p)
239
+ * assertEquals(
240
+ * ['lib/n', 'ui', 'lib/n.ts', 'lib/m'].map((p) => found(p, has)),
241
+ * ['lib/n.ts', 'ui/index.tsx', 'lib/n.ts', null],
242
+ * )
243
+ * ```
244
+ */
245
+ export let found = (
246
+ path: string,
247
+ has: (path: string) => boolean,
248
+ ): string | null =>
249
+ [
250
+ path,
251
+ ...TRIES.map((ext) => path + ext),
252
+ ...TRIES.map((ext) => `${path}/index${ext}`),
253
+ ].find(has) ?? null
254
+
255
+ let candidates = (path: string) => [
256
+ path,
257
+ ...TRIES.map((ext) => path + ext),
258
+ ...TRIES.map((ext) => `${path}/index${ext}`),
259
+ ...twins(path),
260
+ ]
261
+
262
+ type Find = (
263
+ read: Read,
264
+ path: string,
265
+ ) => Promise<[string, Uint8Array<ArrayBuffer>] | null>
266
+
267
+ /** A walk of the module graph from one entry. */
268
+ export type Walk = (read: Read, entry: string) => Promise<Reached>
269
+
270
+ let exact: Find = async (read, path) => {
271
+ let bytes = await read(path)
272
+ return bytes ? [path, bytes] : null
273
+ }
274
+
275
+ let loose: Find = async (read, path) => {
276
+ for (let at of candidates(path)) {
277
+ let bytes = await read(at)
278
+ if (bytes) return [at, bytes]
279
+ }
280
+ return null
281
+ }
282
+
283
+ let walk = (find: Find, strip?: Strip): Walk => async (read, entry) => {
284
+ type Node = {
285
+ at: string
286
+ bytes: Uint8Array<ArrayBuffer>
287
+ lex: Lexed | null
288
+ }
289
+ let load = async (path: string): Promise<Node | null> => {
290
+ let hit = await find(read, path)
291
+ if (!hit) return null
292
+ let [at, bytes] = hit
293
+ return {
294
+ at,
295
+ bytes,
296
+ lex: script(at)
297
+ ? await lexed(at, new TextDecoder().decode(bytes), strip)
298
+ : null,
299
+ }
300
+ }
301
+ let pending = [entry]
302
+ let queued = new Set(pending)
303
+ let loaded = new Map<string, PromiseSettledResult<Node | null>>()
304
+ while (pending.length) {
305
+ let batch = pending.splice(0, 16)
306
+ let results = await Promise.allSettled(batch.map(load))
307
+ for (let [i, result] of results.entries()) {
308
+ let path = batch[i]
309
+ loaded.set(path, result)
310
+ if (result.status != 'fulfilled' || !result.value?.lex) continue
311
+ let { at, lex } = result.value
312
+ for (let { specifier } of lex.imports) {
313
+ if (!relative(specifier)) continue
314
+ let next = resolved(at, specifier)
315
+ if (queued.has(next)) continue
316
+ queued.add(next)
317
+ pending.push(next)
318
+ }
319
+ }
320
+ }
321
+ let files = new Map<string, Uint8Array<ArrayBuffer>>()
322
+ let texts = new Set<string>()
323
+ let linked = new Set<string>()
324
+ let named: string[] = []
325
+ let started: [string, string][] = []
326
+ let seen = new Set<string>()
327
+ let visit = async (path: string): Promise<void> => {
328
+ if (seen.has(path)) return
329
+ seen.add(path)
330
+ let result = loaded.get(path)
331
+ if (result?.status == 'rejected') throw result.reason
332
+ let hit = result?.value
333
+ if (!hit || files.has(hit.at)) return
334
+ let { at, bytes, lex } = hit
335
+ files.set(at, bytes)
336
+ if (!lex) return
337
+ for (let { specifier, text } of lex.imports) {
338
+ if (relative(specifier)) {
339
+ let next = resolved(at, specifier)
340
+ let found = loaded.get(next)
341
+ if (found?.status == 'fulfilled' && found.value) {
342
+ ;(text ? texts : linked).add(found.value.at)
343
+ }
344
+ await visit(next)
345
+ } else if (!named.includes(specifier)) named.push(specifier)
346
+ }
347
+ for (let spec of lex.started.filter(relative)) started.push([at, spec])
348
+ }
349
+ await visit(entry)
350
+ return { files, texts, linked, named, started }
351
+ }
352
+
353
+ /** What the runtime loads from `entry`: each specifier names a file exactly,
354
+ * and only JavaScript is linked, so a TypeScript or JSX file is a leaf. */
355
+ export let modules: Walk = walk(exact)
356
+
357
+ /** What esbuild compiles from `entry`, reading TypeScript and JSX through
358
+ * `strip`: an import may leave off the extension or name a directory's
359
+ * index. */
360
+ export let sources = (strip: Strip): Walk => walk(loose, strip)