@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/bundle.ts ADDED
@@ -0,0 +1,415 @@
1
+ // One esbuild build over a compile's files (./npm.ts `Files`), the way
2
+ // @cloudflare/worker-bundler 0.2.4 ran it, so an app compiles to the bytes it
3
+ // compiled to when yak-esbuild ran worker-bundler in workerd: the same esbuild
4
+ // release (0.28.1), options, namespace and resolution. esbuild here is native,
5
+ // a process of its own beside this one, where worker-bundler ran it as
6
+ // WebAssembly inside the isolate.
7
+ //
8
+ // Every file a build reads comes out of the files, in the `virtual` namespace
9
+ // (an error names `virtual:main.ts`, and ./said.ts strips it). A relative
10
+ // import tries the path, then each extension, then an index file. A package
11
+ // import reads the package's package.json: its `exports` for the target
12
+ // environment and import kind, then `module` and `main`, then an index file. An
13
+ // import that resolves to nothing, or a `cloudflare:` one, is left an import,
14
+ // for ./compile.ts to judge.
15
+ import * as esbuild from 'esbuild'
16
+ import { legacy, resolve } from 'resolve.exports'
17
+ import { owner } from './common.js'
18
+ import { packageOf, TRIES } from './graph.js'
19
+ import { moved as rewrite } from './platform.js'
20
+
21
+ /** What a build reads: a path's text, or null when there is no such file. */
22
+ export type Source = { read(path: string): string | null }
23
+
24
+ /** How an entry is built. */
25
+ export type Options = {
26
+ /** Built for Node's built-ins (a worker with `nodejs_compat`), else for a
27
+ * browser. */
28
+ node?: boolean
29
+ minify?: boolean
30
+ define?: Record<string, string>
31
+ /** An import kept outside the bundle, possibly with a new address. */
32
+ external?: (
33
+ specifier: string,
34
+ importer: string,
35
+ attributes: Record<string, string>,
36
+ ) => string | undefined
37
+ /** A package import read from another of the build's files, by path,
38
+ * asked with how it is imported. */
39
+ alias?: (
40
+ specifier: string,
41
+ importer: string,
42
+ kind: esbuild.ImportKind,
43
+ ) => string | undefined
44
+ /** Bare package imports redirected before external and package resolution. */
45
+ packages?: Readonly<Record<string, string>>
46
+ /** The package supplying automatic JSX for an app's source. */
47
+ jsxImportSource?: string
48
+ /** The expression a package module's `import.meta.url` becomes, asked
49
+ * with the path of a module that reads it, or none to leave it. */
50
+ moved?: (path: string) => string | undefined
51
+ /** Also answer the module graph the build read, as `Built.inputs`, and
52
+ * each emitted file's exports, as `Built.exports`. */
53
+ graph?: boolean
54
+ /** How every file is read, whatever its extension says: `js` for files
55
+ * already compiled from their TypeScript and JSX. */
56
+ loader?: esbuild.Loader
57
+ }
58
+
59
+ /** One file a build read: whether esbuild read it as an ES module or as
60
+ * CommonJS, and each import, by the file it resolved to and the specifier it
61
+ * was written as. An import left unresolved is `external`. */
62
+ export type Input = {
63
+ format?: 'esm' | 'cjs'
64
+ imports: {
65
+ path: string
66
+ kind: esbuild.ImportKind
67
+ original?: string
68
+ external?: boolean
69
+ }[]
70
+ }
71
+
72
+ /** esbuild's process ended under a build. That is the compiler's room, not
73
+ * the app's code: a process killed for memory ends this way, and so does one
74
+ * stopped with the container it runs in. */
75
+ export class Stopped extends Error {
76
+ override name = 'Stopped'
77
+ }
78
+
79
+ /** Built entries: the first module, every emitted file, warnings, and, when
80
+ * the build was asked for its graph, the files read, by path, and the names
81
+ * each emitted file exports, by file. */
82
+ export type Built = {
83
+ code: string
84
+ files: Record<string, string>
85
+ warnings: string[]
86
+ inputs?: Record<string, Input>
87
+ exports?: Record<string, string[]>
88
+ }
89
+
90
+ let PACKAGE_TRIES = [...TRIES, '.json']
91
+
92
+ // A path, else the path with each extension, else its index file.
93
+ let tried = (files: Source, path: string, tries: string[]) => {
94
+ path = path.replace(/^\.\//, '').replace(/\/+/g, '/').replace(/\/$/, '')
95
+ return [
96
+ path,
97
+ ...tries.map((ext) => path + ext),
98
+ ...tries.map((ext) => `${path}/index${ext}`),
99
+ ].find((p) => files.read(p) != null)
100
+ }
101
+
102
+ // `dir` joined to a relative path, `..` popping a segment.
103
+ let joined = (dir: string, path: string) => {
104
+ let parts = dir ? dir.split('/') : []
105
+ for (let part of path.split('/')) {
106
+ if (part == '..') parts.pop()
107
+ else if (part != '.') parts.push(part)
108
+ }
109
+ return parts.join('/')
110
+ }
111
+
112
+ let inside = (name: string, path: string) =>
113
+ `node_modules/${name}/${path.replace(/^\.?\//, '')}`
114
+
115
+ /** The file a package import names, or undefined when the package is not
116
+ * installed or names no file. Throws for a package.json that is not JSON. */
117
+ export let packaged = (
118
+ files: Source,
119
+ spec: string,
120
+ { node = false, require = false }: { node?: boolean; require?: boolean } = {},
121
+ ) => {
122
+ let name = packageOf(spec)
123
+ if (!name) return
124
+ let manifest = files.read(`node_modules/${name}/package.json`)
125
+ if (manifest == null) return
126
+ let pkg = JSON.parse(manifest)
127
+ let subpath = spec.slice(name.length + 1)
128
+ try {
129
+ let [hit] = resolve(pkg, subpath ? `./${subpath}` : '.', {
130
+ browser: !node,
131
+ require,
132
+ }) ?? []
133
+ if (hit && files.read(inside(name, hit)) != null) return inside(name, hit)
134
+ } catch {
135
+ // An exports map hides paths it does not declare.
136
+ }
137
+ if (pkg.exports != null) return
138
+ let main = subpath ? undefined : legacy(pkg, { fields: ['module', 'main'] })
139
+ if (typeof main == 'string' && files.read(inside(name, main)) != null) {
140
+ return inside(name, main)
141
+ }
142
+ return tried(
143
+ files,
144
+ `node_modules/${name}${subpath ? `/${subpath}` : ''}`,
145
+ PACKAGE_TRIES,
146
+ )
147
+ }
148
+
149
+ // esbuild types a `.js`, `.jsx`, `.ts` or `.tsx` file by the `type` of the
150
+ // package.json above it only when its own resolver found the file; a file a
151
+ // plugin found it types by its extension alone. The type decides what an ES
152
+ // module's default import of CommonJS reads: `module.exports` from a module
153
+ // Node types as an ES module, as Node reads it, and otherwise the
154
+ // `exports.default` that CommonJS transpiled from an ES module claims with
155
+ // `__esModule`, often nothing. tslib's ES module entry, `modules/index.js`
156
+ // under `"type": "module"`, imports `../tslib.js` by default and destructures
157
+ // it. So a package file Node types as an ES module is named to esbuild with
158
+ // `.mjs` after its path, and every path esbuild hands back is its own again.
159
+ // An app's own files keep the reading they were written for.
160
+ let TYPED = /\.(?:js|jsx|ts|tsx)$/
161
+ let MJS = '.mjs'
162
+
163
+ /** The name esbuild reads a package's file by: its path, with `.mjs` after it
164
+ * when the nearest package.json within the package says `"type": "module"`.
165
+ *
166
+ * ```ts
167
+ * import { assertEquals } from '@std/assert'
168
+ * let files = {
169
+ * 'package.json': '{"type":"module"}',
170
+ * 'node_modules/tslib/package.json': '{}',
171
+ * 'node_modules/tslib/modules/package.json': '{"type":"module"}',
172
+ * 'node_modules/@yaks/kit/package.json': '{"type":"module"}',
173
+ * }
174
+ * let fs = { read: (path: string) => files[path as keyof typeof files] ?? null }
175
+ * let names = (paths: string[]) => paths.map((path) => typedName(fs, path))
176
+ * assertEquals(
177
+ * names([
178
+ * 'node_modules/tslib/modules/index.js',
179
+ * 'node_modules/tslib/tslib.js',
180
+ * 'node_modules/@yaks/kit/a/mod.ts',
181
+ * 'node_modules/@yaks/kit/style.css',
182
+ * 'node_modules/@yaks/kit/b.cjs',
183
+ * 'main.js',
184
+ * ]),
185
+ * [
186
+ * 'node_modules/tslib/modules/index.js.mjs',
187
+ * 'node_modules/tslib/tslib.js',
188
+ * 'node_modules/@yaks/kit/a/mod.ts.mjs',
189
+ * 'node_modules/@yaks/kit/style.css',
190
+ * 'node_modules/@yaks/kit/b.cjs',
191
+ * 'main.js',
192
+ * ],
193
+ * )
194
+ * assertEquals(
195
+ * plain(fs, 'node_modules/tslib/modules/index.js.mjs'),
196
+ * 'node_modules/tslib/modules/index.js',
197
+ * )
198
+ * assertEquals(plain(fs, 'node_modules/tslib/x.mjs'), 'node_modules/tslib/x.mjs')
199
+ * ```
200
+ */
201
+ export let typedName = (files: Source, path: string): string => {
202
+ let name = owner(path)
203
+ if (!name || !TYPED.test(path)) return path
204
+ let top = `node_modules/${name}`
205
+ for (
206
+ let dir = path.slice(0, path.lastIndexOf('/'));
207
+ dir.startsWith(top);
208
+ dir = dir.slice(0, dir.lastIndexOf('/'))
209
+ ) {
210
+ let manifest = files.read(`${dir}/package.json`)
211
+ if (manifest == null) continue
212
+ try {
213
+ return JSON.parse(manifest).type == 'module' ? path + MJS : path
214
+ } catch {
215
+ return path
216
+ }
217
+ }
218
+ return path
219
+ }
220
+
221
+ /** The path a name esbuild reads by stands for ({@link typedName}). */
222
+ export let plain = (files: Source, name: string): string => {
223
+ let path = name.slice(0, -MJS.length)
224
+ return name.endsWith(MJS) && typedName(files, path) == name ? path : name
225
+ }
226
+
227
+ let loader = (path: string): esbuild.Loader =>
228
+ /\.[mc]?ts$/.test(path)
229
+ ? 'ts'
230
+ : path.endsWith('.tsx')
231
+ ? 'tsx'
232
+ : path.endsWith('.jsx')
233
+ ? 'jsx'
234
+ : path.endsWith('.json')
235
+ ? 'json'
236
+ : path.endsWith('.css')
237
+ ? 'css'
238
+ : 'js'
239
+
240
+ let virtual = (
241
+ files: Source,
242
+ { external, alias, packages, moved, node = false, loader: every }: Options,
243
+ ): esbuild.Plugin => ({
244
+ name: 'virtual-fs',
245
+ setup(build) {
246
+ let found = (path: string) => ({
247
+ path: typedName(files, path),
248
+ namespace: 'virtual',
249
+ })
250
+ let left = (path: string) => ({ path, external: true })
251
+ build.onResolve(
252
+ { filter: /.*/ },
253
+ ({ kind, path, resolveDir, importer: name, with: attributes }) => {
254
+ let importer = plain(files, name)
255
+ if (kind == 'entry-point') return found(path)
256
+ path = packages?.[path] ?? path
257
+ let other = alias?.(path, importer, kind)
258
+ if (other) return found(other)
259
+ let url = external?.(path, importer, attributes)
260
+ if (url) return left(url)
261
+ if (path.startsWith('.')) {
262
+ let hit = tried(
263
+ files,
264
+ joined(resolveDir.replace(/^\//, ''), path),
265
+ TRIES,
266
+ )
267
+ return hit ? found(hit) : left(path)
268
+ }
269
+ if (path.startsWith('/')) {
270
+ return files.read(path.slice(1)) != null
271
+ ? found(path.slice(1))
272
+ : left(path)
273
+ }
274
+ if (path.startsWith('cloudflare:')) return left(path)
275
+ try {
276
+ let hit = packaged(files, path, {
277
+ node,
278
+ require: kind == 'require-call' || kind == 'require-resolve',
279
+ })
280
+ if (hit) return found(hit)
281
+ } catch {
282
+ // A package.json that is not JSON resolves nothing.
283
+ }
284
+ return left(path)
285
+ },
286
+ )
287
+ build.onLoad({ filter: /.*/, namespace: 'virtual' }, (args) => {
288
+ let path = plain(files, args.path)
289
+ let contents = files.read(path)
290
+ if (contents == null) {
291
+ return { errors: [{ text: `File not found: ${path}` }] }
292
+ }
293
+ if (
294
+ moved && path.startsWith('node_modules/') &&
295
+ /\.[mc]?[jt]sx?$/.test(path)
296
+ ) {
297
+ try {
298
+ contents = rewrite(contents, () => moved(path))
299
+ } catch {
300
+ // esbuild names the syntax error.
301
+ }
302
+ }
303
+ return {
304
+ contents,
305
+ loader: args.with.type == 'text' ? 'text' : every ?? loader(path),
306
+ resolveDir: path.slice(0, Math.max(0, path.lastIndexOf('/'))),
307
+ }
308
+ })
309
+ },
310
+ })
311
+
312
+ // What esbuild's JS API rejects with once its process is gone: "was stopped"
313
+ // for the builds it was running, "is no longer running" for any after.
314
+ let GONE = /^The service (?:was stopped|is no longer running)/
315
+
316
+ /** Build one entry into an ES module, or named entries with shared chunks.
317
+ * Throws esbuild's
318
+ * failure, whose `errors` ./said.ts reads, or {@link Stopped}, after which
319
+ * the next build starts esbuild afresh. */
320
+ export let bundle = async (
321
+ files: Source,
322
+ entry: string | Record<string, string>,
323
+ options: Options = {},
324
+ ): Promise<Built> => {
325
+ for (let path of typeof entry == 'string' ? [entry] : Object.values(entry)) {
326
+ if (files.read(path) == null) throw new Error(`${path}: no such file`)
327
+ }
328
+ try {
329
+ return await built(files, entry, options)
330
+ } catch (e) {
331
+ if (!GONE.test((e as Error)?.message)) throw e
332
+ await esbuild.stop()
333
+ throw new Stopped(`esbuild's process ended while building ${entry}`)
334
+ }
335
+ }
336
+
337
+ // An emitted file's name, as `Built.files` keys it.
338
+ let named = (path: string) => path.slice(path.lastIndexOf('/') + 1)
339
+
340
+ let built = async (
341
+ files: Source,
342
+ entry: string | Record<string, string>,
343
+ options: Options,
344
+ ): Promise<Built> => {
345
+ let { node = false, minify = false, define, graph = false } = options
346
+ let out = await esbuild.build({
347
+ entryPoints: typeof entry == 'string' ? [entry] : entry,
348
+ bundle: true,
349
+ write: false,
350
+ format: 'esm',
351
+ platform: node ? 'node' : 'browser',
352
+ target: 'es2022',
353
+ ...options.jsxImportSource
354
+ ? { jsx: 'automatic' as const, jsxImportSource: options.jsxImportSource }
355
+ : {},
356
+ minify,
357
+ plugins: [virtual(files, options)],
358
+ ...typeof entry == 'string'
359
+ ? { outfile: 'bundle.js' }
360
+ : { outdir: '/output', splitting: true, chunkNames: 'chunk-[hash]' },
361
+ // A plugin's relative resolveDir is taken from here, as esbuild-wasm took
362
+ // it from its own root: `node_modules/x/dist` is `/node_modules/x/dist`.
363
+ absWorkingDir: '/',
364
+ // Errors and warnings come back in the answer; nothing is printed.
365
+ logLevel: 'silent',
366
+ metafile: graph,
367
+ ...define ? { define } : {},
368
+ }).catch((e) => {
369
+ for (let m of [...e?.errors ?? [], ...e?.warnings ?? []]) placed(files, m)
370
+ throw e
371
+ })
372
+ out.warnings.forEach((w) => placed(files, w))
373
+ return {
374
+ code: out.outputFiles[0].text,
375
+ files: Object.fromEntries(
376
+ out.outputFiles.map((file) => [named(file.path), file.text]),
377
+ ),
378
+ warnings: out.warnings.map((w) => w.text),
379
+ ...out.metafile
380
+ ? {
381
+ inputs: inputs(files, out.metafile),
382
+ exports: Object.fromEntries(
383
+ Object.entries(out.metafile.outputs).map((
384
+ [path, { exports }],
385
+ ) => [named(path), exports]),
386
+ ),
387
+ }
388
+ : {},
389
+ }
390
+ }
391
+
392
+ // A path esbuild names, in the `virtual:` namespace every file is read in,
393
+ // as the path it stands for.
394
+ let bare = (files: Source, path: string) =>
395
+ plain(files, path.replace(/^virtual:/, ''))
396
+
397
+ // A message's file as the path it stands for, keeping its namespace for
398
+ // ./said.ts.
399
+ let placed = (files: Source, message: esbuild.Message) => {
400
+ let at = message.location
401
+ if (at?.file.startsWith('virtual:')) {
402
+ at.file = `virtual:${bare(files, at.file)}`
403
+ }
404
+ }
405
+
406
+ let inputs = (files: Source, meta: esbuild.Metafile) =>
407
+ Object.fromEntries(
408
+ Object.entries(meta.inputs).map(([path, input]) => [bare(files, path), {
409
+ format: input.format,
410
+ imports: input.imports.map((i) => ({ ...i, path: bare(files, i.path) })),
411
+ }]),
412
+ )
413
+
414
+ /** Stop esbuild's process, which otherwise outlives the last build. */
415
+ export let stop = (): Promise<void> => esbuild.stop()
package/common.js ADDED
@@ -0,0 +1,129 @@
1
+ // Which npm packages a page shares rather than bundles: those more than one
2
+ // consumer would carry a copy of. A consumer is what the compiler emits apart:
3
+ // the page scripts (one consumer together), each toolkit package, and each
4
+ // package shared here. Toolkit packages, Preact and Signals are shared
5
+ // already, so a consumer's walk stops at them.
6
+ //
7
+ // A package two consumers carry becomes a consumer of its own, whose entries
8
+ // are every specifier of it that anything imports. Each round takes only the
9
+ // topmost of those packages: once one is shared, what it carries is carried
10
+ // once, by it, and need not be shared too. A package stays bundled where an
11
+ // ES module URL cannot stand in for it: something requires it, or an import
12
+ // of it names a file esbuild reads as CommonJS, or one that is not a script.
13
+ import { packageOf, script } from "./graph.js";
14
+ let OWNER = /^node_modules\/((?:@[^/]+\/)?[^/]+)\//;
15
+ /** The npm package a path of the install lies in, or `''` for an app file. */ export let owner = (path)=>OWNER.exec(path)?.[1] ?? '';
16
+ /** The npm packages more than one consumer carries, from the module graph a
17
+ * build of every consumer's entries read: `consumers` maps each consumer to its
18
+ * entry files (`''` the page scripts, a toolkit package by its name), and
19
+ * `stops` names the packages already shared.
20
+ *
21
+ * ```ts
22
+ * import { assertEquals } from '@std/assert'
23
+ * let at = (path: string, original: string) =>
24
+ * ({ path, original, kind: 'import-statement' as const })
25
+ * let three = 'node_modules/three/build/three.module.js'
26
+ * let graph = {
27
+ * 'main.ts': { format: 'esm' as const, imports: [at(three, 'three')] },
28
+ * 'node_modules/@yaks/stage/mod.ts': {
29
+ * format: 'esm' as const,
30
+ * imports: [at(three, 'three')],
31
+ * },
32
+ * [three]: { format: 'esm' as const, imports: [] },
33
+ * }
34
+ * let consumers = {
35
+ * '': ['main.ts'],
36
+ * '@yaks/stage': ['node_modules/@yaks/stage/mod.ts'],
37
+ * }
38
+ * assertEquals(common(graph, consumers, new Set(['@yaks/stage'])), {
39
+ * entries: { three: { three } },
40
+ * uses: { '': ['three'], '@yaks/stage': ['three'], three: [] },
41
+ * })
42
+ * ```
43
+ */ export let common = (graph, consumers, stops)=>{
44
+ let crossings = Object.entries(graph).flatMap(([from, input])=>input.imports.filter((i)=>!i.external && owner(i.path) && owner(i.path) != owner(from)));
45
+ let into = (name)=>crossings.filter((c)=>owner(c.path) == name);
46
+ let starts = (name)=>[
47
+ ...new Set(into(name).map((c)=>c.path))
48
+ ];
49
+ let esm = (c)=>(c.kind == 'import-statement' || c.kind == 'dynamic-import') && packageOf(c.original ?? '') == owner(c.path) && script(c.path) && graph[c.path]?.format != 'cjs';
50
+ let shared = new Set();
51
+ // The npm packages a consumer's build would bundle, and the shared ones it
52
+ // would import instead.
53
+ let walk = (self, files)=>{
54
+ let carried = new Set(), meets = new Set();
55
+ let seen = new Set(files), queue = [
56
+ ...files
57
+ ];
58
+ for (let path of queue){
59
+ for (let edge of graph[path]?.imports ?? []){
60
+ // A build leaves the other toolkit packages outside, by specifier.
61
+ if (edge.external) {
62
+ let name = packageOf(edge.path);
63
+ if (name && name != self && stops.has(name)) meets.add(name);
64
+ continue;
65
+ }
66
+ let name = owner(edge.path);
67
+ let other = name && name != self;
68
+ if (other && (stops.has(name) || shared.has(name))) {
69
+ meets.add(name);
70
+ continue;
71
+ }
72
+ if (other) carried.add(name);
73
+ if (!seen.has(edge.path)) {
74
+ seen.add(edge.path);
75
+ queue.push(edge.path);
76
+ }
77
+ }
78
+ }
79
+ return {
80
+ carried,
81
+ meets
82
+ };
83
+ };
84
+ let all = ()=>({
85
+ ...consumers,
86
+ ...Object.fromEntries([
87
+ ...shared
88
+ ].map((name)=>[
89
+ name,
90
+ starts(name)
91
+ ]))
92
+ });
93
+ for(;;){
94
+ let count = new Map();
95
+ for (let [self, files] of Object.entries(all())){
96
+ for (let name of walk(self, files).carried){
97
+ count.set(name, (count.get(name) ?? 0) + 1);
98
+ }
99
+ }
100
+ let twice = [
101
+ ...count
102
+ ].filter(([name, n])=>n > 1 && into(name).every(esm)).map(([name])=>name);
103
+ if (!twice.length) break;
104
+ let under = new Set(twice.flatMap((name)=>[
105
+ ...walk(name, starts(name)).carried
106
+ ]));
107
+ let top = twice.filter((name)=>!under.has(name));
108
+ // Packages that carry one another share together.
109
+ for (let name of top.length ? top : twice)shared.add(name);
110
+ }
111
+ return {
112
+ entries: Object.fromEntries([
113
+ ...shared
114
+ ].sort().map((name)=>[
115
+ name,
116
+ Object.fromEntries(into(name).map((c)=>[
117
+ c.original,
118
+ c.path
119
+ ]))
120
+ ])),
121
+ uses: Object.fromEntries(Object.entries(all()).map(([self, files])=>[
122
+ self,
123
+ [
124
+ ...walk(self, files).meets
125
+ ].sort()
126
+ ]))
127
+ };
128
+ };
129
+ //# sourceMappingURL=common.js.map
package/common.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.js","sources":["./common.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+EAA+E;AAC/E,2EAA2E;AAC3E,uEAAuE;AACvE,+CAA+C;AAC/C,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,4EAA4E;AAC5E,4EAA4E;AAC5E,4EAA4E;AAC5E,6EAA6E;AAE7E,SAAS,SAAS,EAAE,MAAM,qBAAoB;AAW9C,IAAI,QAAQ;AACZ,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IAAI,MAAM,GAAG,MAAM,MAAO,OAAO,GAAG,CAAC;EACxD;EACA,OAAO;IACL,SAAS,OAAO,WAAW,CACzB;SAAI;KAAO,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC,OAAS;QAC/B;QACA,OAAO,WAAW,CAAC,KAAK,MAAM,GAAG,CAAC,CAAC,IAAM;YAAC,EAAE,QAAQ;YAAG,EAAE,IAAI;WAAC;OAC/D;IAEH,MAAM,OAAO,WAAW,CACtB,OAAO,OAAO,CAAC,OAAO,GAAG,CAAC,CACxB,CAAC,MAAM,MAAM,GACV;QAAC;QAAM;aAAI,KAAK,MAAM,OAAO,KAAK;SAAC,CAAC,IAAI;OAAG;EAEpD;AACF,EAAC"}
package/common.ts ADDED
@@ -0,0 +1,138 @@
1
+ // Which npm packages a page shares rather than bundles: those more than one
2
+ // consumer would carry a copy of. A consumer is what the compiler emits apart:
3
+ // the page scripts (one consumer together), each toolkit package, and each
4
+ // package shared here. Toolkit packages, Preact and Signals are shared
5
+ // already, so a consumer's walk stops at them.
6
+ //
7
+ // A package two consumers carry becomes a consumer of its own, whose entries
8
+ // are every specifier of it that anything imports. Each round takes only the
9
+ // topmost of those packages: once one is shared, what it carries is carried
10
+ // once, by it, and need not be shared too. A package stays bundled where an
11
+ // ES module URL cannot stand in for it: something requires it, or an import
12
+ // of it names a file esbuild reads as CommonJS, or one that is not a script.
13
+ import type { Input } from './bundle.ts'
14
+ import { packageOf, script } from './graph.js'
15
+
16
+ /** What a page shares beyond its toolkit packages, Preact and Signals. */
17
+ export type Common = {
18
+ /** Each shared npm package: every specifier of it imported from outside
19
+ * it, by the file it names. */
20
+ entries: Record<string, Record<string, string>>
21
+ /** The shared packages each consumer's build imports, by consumer. */
22
+ uses: Record<string, string[]>
23
+ }
24
+
25
+ let OWNER = /^node_modules\/((?:@[^/]+\/)?[^/]+)\//
26
+ /** The npm package a path of the install lies in, or `''` for an app file. */
27
+ export let owner = (path: string): string => OWNER.exec(path)?.[1] ?? ''
28
+
29
+ type Crossing = Input['imports'][number]
30
+
31
+ /** The npm packages more than one consumer carries, from the module graph a
32
+ * build of every consumer's entries read: `consumers` maps each consumer to its
33
+ * entry files (`''` the page scripts, a toolkit package by its name), and
34
+ * `stops` names the packages already shared.
35
+ *
36
+ * ```ts
37
+ * import { assertEquals } from '@std/assert'
38
+ * let at = (path: string, original: string) =>
39
+ * ({ path, original, kind: 'import-statement' as const })
40
+ * let three = 'node_modules/three/build/three.module.js'
41
+ * let graph = {
42
+ * 'main.ts': { format: 'esm' as const, imports: [at(three, 'three')] },
43
+ * 'node_modules/@yaks/stage/mod.ts': {
44
+ * format: 'esm' as const,
45
+ * imports: [at(three, 'three')],
46
+ * },
47
+ * [three]: { format: 'esm' as const, imports: [] },
48
+ * }
49
+ * let consumers = {
50
+ * '': ['main.ts'],
51
+ * '@yaks/stage': ['node_modules/@yaks/stage/mod.ts'],
52
+ * }
53
+ * assertEquals(common(graph, consumers, new Set(['@yaks/stage'])), {
54
+ * entries: { three: { three } },
55
+ * uses: { '': ['three'], '@yaks/stage': ['three'], three: [] },
56
+ * })
57
+ * ```
58
+ */
59
+ export let common = (
60
+ graph: Record<string, Input>,
61
+ consumers: Record<string, string[]>,
62
+ stops: Set<string>,
63
+ ): Common => {
64
+ let crossings: Crossing[] = Object.entries(graph).flatMap(([from, input]) =>
65
+ input.imports.filter((i) =>
66
+ !i.external && owner(i.path) && owner(i.path) != owner(from)
67
+ )
68
+ )
69
+ let into = (name: string) => crossings.filter((c) => owner(c.path) == name)
70
+ let starts = (name: string) => [...new Set(into(name).map((c) => c.path))]
71
+ let esm = (c: Crossing) =>
72
+ (c.kind == 'import-statement' || c.kind == 'dynamic-import') &&
73
+ packageOf(c.original ?? '') == owner(c.path) && script(c.path) &&
74
+ graph[c.path]?.format != 'cjs'
75
+ let shared = new Set<string>()
76
+ // The npm packages a consumer's build would bundle, and the shared ones it
77
+ // would import instead.
78
+ let walk = (self: string, files: string[]) => {
79
+ let carried = new Set<string>(), meets = new Set<string>()
80
+ let seen = new Set(files), queue = [...files]
81
+ for (let path of queue) {
82
+ for (let edge of graph[path]?.imports ?? []) {
83
+ // A build leaves the other toolkit packages outside, by specifier.
84
+ if (edge.external) {
85
+ let name = packageOf(edge.path)
86
+ if (name && name != self && stops.has(name)) meets.add(name)
87
+ continue
88
+ }
89
+ let name = owner(edge.path)
90
+ let other = name && name != self
91
+ if (other && (stops.has(name) || shared.has(name))) {
92
+ meets.add(name)
93
+ continue
94
+ }
95
+ if (other) carried.add(name)
96
+ if (!seen.has(edge.path)) {
97
+ seen.add(edge.path)
98
+ queue.push(edge.path)
99
+ }
100
+ }
101
+ }
102
+ return { carried, meets }
103
+ }
104
+ let all = () => ({
105
+ ...consumers,
106
+ ...Object.fromEntries([...shared].map((name) => [name, starts(name)])),
107
+ })
108
+ for (;;) {
109
+ let count = new Map<string, number>()
110
+ for (let [self, files] of Object.entries(all())) {
111
+ for (let name of walk(self, files).carried) {
112
+ count.set(name, (count.get(name) ?? 0) + 1)
113
+ }
114
+ }
115
+ let twice = [...count].filter(([name, n]) => n > 1 && into(name).every(esm))
116
+ .map(([name]) => name)
117
+ if (!twice.length) break
118
+ let under = new Set(
119
+ twice.flatMap((name) => [...walk(name, starts(name)).carried]),
120
+ )
121
+ let top = twice.filter((name) => !under.has(name))
122
+ // Packages that carry one another share together.
123
+ for (let name of top.length ? top : twice) shared.add(name)
124
+ }
125
+ return {
126
+ entries: Object.fromEntries(
127
+ [...shared].sort().map((name) => [
128
+ name,
129
+ Object.fromEntries(into(name).map((c) => [c.original!, c.path])),
130
+ ]),
131
+ ),
132
+ uses: Object.fromEntries(
133
+ Object.entries(all()).map((
134
+ [self, files],
135
+ ) => [self, [...walk(self, files).meets].sort()]),
136
+ ),
137
+ }
138
+ }