@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/npm.ts ADDED
@@ -0,0 +1,429 @@
1
+ // npm packages as a compile installs them: one version of each name, flat,
2
+ // from the registry, as @cloudflare/worker-bundler's own installer did. That
3
+ // installer decoded every text file of every tarball into the file system a
4
+ // build reads: three.js ships 20 MB of sources and a page reads 2 MB of them.
5
+ // Each compile indexes a tarball in one pass. It keeps a bounded amount of
6
+ // its source bytes for random access, and decodes only files the build reads.
7
+ import { Gunzip } from 'fflate'
8
+ /* @ts-types="npm:@types/semver@^7.8.0" */ import { valid } from 'semver'
9
+ import { REGISTRY, sha256, type Tarball } from './home.js'
10
+ import {
11
+ asked,
12
+ documentAt,
13
+ type Metadata,
14
+ metadata,
15
+ resolve,
16
+ } from './resolve.js'
17
+ import { type Shelf, shelve, taken } from './shelf.js'
18
+ import { rooted, untar } from './tar.js'
19
+ import { spans } from './timing.js'
20
+
21
+ export { REGISTRY }
22
+
23
+ // The files of a package a build can read: its text, as worker-bundler kept
24
+ // it. A build reads nothing else (an image or a binary is never compiled in);
25
+ // a page fetches those from the package's home (./home.ts).
26
+ let TEXT = /\.(?:[cm]?[jt]sx?|json|md|txt|css|html|ya?ml|toml|xml|svg|map|py)$/i
27
+ let NAMED =
28
+ /^(?:license|readme|changelog|package\.json|tsconfig\.json|\.npmignore|\.gitignore)/i
29
+ let text = (path: string) =>
30
+ TEXT.test(path) || NAMED.test(path.slice(path.lastIndexOf('/') + 1))
31
+
32
+ let decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes)
33
+
34
+ // How much tarball to inflate at a time.
35
+ let STEP = 1 << 16
36
+
37
+ /**
38
+ * Walk a gzipped tarball's entries in order, inflating a slice at a time and
39
+ * never the whole: `each` and `take` are ./tar.ts `untar`'s.
40
+ */
41
+ let walk = (
42
+ tgz: Uint8Array,
43
+ each: (path: string, size: number, file: boolean) => boolean,
44
+ take: (path: string, bytes: Uint8Array) => boolean | void,
45
+ ) => {
46
+ let push = untar(each, take)
47
+ let stop = false
48
+ let inflate = new Gunzip((chunk) => void (stop ||= push(chunk)))
49
+ for (let i = 0; i < tgz.length && !stop; i += STEP) {
50
+ inflate.push(tgz.subarray(i, i + STEP), i + STEP >= tgz.length)
51
+ }
52
+ }
53
+
54
+ /** An installed package: its tarball, where that came from, and the text
55
+ * files it holds, by path from the package's own directory. */
56
+ type Packed = {
57
+ tgz: Uint8Array
58
+ from?: Tarball
59
+ root: string
60
+ holds: Set<string>
61
+ decoded: Map<string, string>
62
+ key?: string
63
+ }
64
+
65
+ // Only registry tarball content is shared across compiles. A Files keeps its
66
+ // own path overrides and a copy of the index, so writes/deletes never change
67
+ // another compile. Retain compressed bytes and only text actually read.
68
+ let held = new Map<string, Packed>()
69
+ let bytes = 0
70
+ // A container has 4 GiB; the tarballs of the packages apps share most fit.
71
+ let LIMIT = 128 << 20
72
+ let size = (pack: Packed) =>
73
+ pack.tgz.byteLength +
74
+ [...pack.holds].reduce((n, path) => n + path.length * 2, 0) +
75
+ [...pack.decoded].reduce(
76
+ (n, [path, text]) => n + (path.length + text.length) * 2,
77
+ 0,
78
+ )
79
+ let sizes = new Map<string, number>()
80
+ let keep = (pack: Packed) => {
81
+ let key = pack.key
82
+ if (!key) return
83
+ bytes -= sizes.get(key) ?? 0
84
+ held.delete(key)
85
+ sizes.delete(key)
86
+ let n = size(pack)
87
+ if (n > LIMIT) return
88
+ while (bytes + n > LIMIT) {
89
+ let oldest = held.keys().next().value!
90
+ bytes -= sizes.get(oldest)!
91
+ held.delete(oldest)
92
+ sizes.delete(oldest)
93
+ }
94
+ held.set(key, pack)
95
+ sizes.set(key, n)
96
+ bytes += n
97
+ }
98
+
99
+ let PACKAGE = /^node_modules\/(?:@[^/]+\/)?[^/]+\//
100
+ let SOURCES = /\.(?:[cm]?[jt]sx?|json|css)$/i
101
+ let SOURCE_LIMIT = 32 << 20
102
+
103
+ /**
104
+ * A compile's files: the ones it was handed, and each installed package's,
105
+ * which come out of its tarball the first time a build reads one. It is the
106
+ * file system ./bundle.ts builds from.
107
+ */
108
+ export class Files {
109
+ #files: Map<string, string>
110
+ #packages = new Map<string, Packed & { sources?: Map<string, Uint8Array> }>()
111
+ #sourceBytes = 0
112
+
113
+ constructor(files: Record<string, string> = {}) {
114
+ this.#files = new Map(Object.entries(files))
115
+ }
116
+
117
+ read(path: string): string | null {
118
+ let own = this.#files.get(path)
119
+ if (own != null) return own
120
+ let dir = PACKAGE.exec(path)?.[0] ?? ''
121
+ let pack = this.#packages.get(dir)
122
+ let rest = path.slice(dir.length)
123
+ if (!pack?.holds.has(rest)) return null
124
+ let decoded = pack.decoded.get(rest)
125
+ if (decoded != null) {
126
+ this.#files.set(path, decoded)
127
+ // Touch the immutable cached index, not the local deletion copy.
128
+ let cached = pack.key ? held.get(pack.key) : undefined
129
+ if (cached) keep(cached)
130
+ return decoded
131
+ }
132
+ if (SOURCES.test(rest)) pack.sources ??= this.#sources(pack)
133
+ let source = pack.sources?.get(pack.root + rest)
134
+ let out = source ? decode(source) : this.#extract(pack, rest)
135
+ if (out != null) {
136
+ this.#files.set(path, out)
137
+ pack.decoded.set(rest, out)
138
+ let cached = pack.key ? held.get(pack.key) : undefined
139
+ if (cached) keep(cached)
140
+ }
141
+ return out
142
+ }
143
+
144
+ #extract(pack: Packed, rest: string) {
145
+ let out: string | null = null
146
+ walk(
147
+ pack.tgz,
148
+ (at, _, file) => file && at == pack.root + rest,
149
+ (_, bytes) => {
150
+ out = decode(bytes)
151
+ return true
152
+ },
153
+ )
154
+ return out
155
+ }
156
+
157
+ #retain(path: string, size: number) {
158
+ if (!SOURCES.test(path) || this.#sourceBytes + size > SOURCE_LIMIT) {
159
+ return false
160
+ }
161
+ this.#sourceBytes += size
162
+ return true
163
+ }
164
+
165
+ #sources(pack: Packed) {
166
+ let sources = new Map<string, Uint8Array>()
167
+ if (this.#sourceBytes >= SOURCE_LIMIT) return sources
168
+ walk(
169
+ pack.tgz,
170
+ (path, size, file) =>
171
+ file && !sources.has(path) &&
172
+ pack.holds.has(path.slice(pack.root.length)) &&
173
+ !pack.decoded.has(path.slice(pack.root.length)) &&
174
+ this.#retain(path, size),
175
+ (path, bytes) => void sources.set(path, bytes),
176
+ )
177
+ return sources
178
+ }
179
+
180
+ /** The registry tarball an installed package came out of, when it came
181
+ * out of one. */
182
+ tarball(name: string): Tarball | undefined {
183
+ return this.#packages.get(`node_modules/${name}/`)?.from
184
+ }
185
+
186
+ write(path: string, content: string) {
187
+ this.#files.set(path, content)
188
+ }
189
+
190
+ delete(path: string) {
191
+ this.#files.delete(path)
192
+ let dir = PACKAGE.exec(path)?.[0] ?? ''
193
+ this.#packages.get(dir)?.holds.delete(path.slice(dir.length))
194
+ }
195
+
196
+ list(prefix = ''): string[] {
197
+ let paths = new Set(this.#files.keys())
198
+ for (let [dir, pack] of this.#packages) {
199
+ for (let path of pack.holds) paths.add(dir + path)
200
+ }
201
+ return [...paths].filter((path) => path.startsWith(prefix))
202
+ }
203
+
204
+ flush(): Promise<void> {
205
+ return Promise.resolve()
206
+ }
207
+
208
+ /** Install a package from its gzipped tarball, as `node_modules/<name>/`,
209
+ * reading only its package.json now, and `from` where it came from. */
210
+ hold(name: string, tgz: Uint8Array, from?: Tarball) {
211
+ let dir = `node_modules/${name}/`
212
+ // A replacement also replaces any text already read from that package.
213
+ for (let path of this.#files.keys()) {
214
+ if (path.startsWith(dir)) this.#files.delete(path)
215
+ }
216
+ let cached = from ? held.get(from.sha256) : undefined
217
+ if (cached) {
218
+ keep(cached)
219
+ this.#packages.set(dir, { ...cached, from, holds: new Set(cached.holds) })
220
+ let manifest = cached.decoded.get('package.json')
221
+ if (manifest != null) this.#files.set(dir + 'package.json', manifest)
222
+ return
223
+ }
224
+ let files: string[] = []
225
+ let holds: string[] = []
226
+ let manifests: Record<string, string> = {}
227
+ let sources = new Map<string, Uint8Array>()
228
+ walk(tgz, (path, size, file) => {
229
+ if (!file || !path) return false
230
+ files.push(path)
231
+ if (size && text(path)) holds.push(path)
232
+ return !!size && (manifest(path) ||
233
+ !sources.has(path) && this.#retain(path, size))
234
+ }, (path, bytes) => {
235
+ if (manifest(path)) manifests[path] = decode(bytes)
236
+ else sources.set(path, bytes)
237
+ })
238
+ let root = rooted(files)
239
+ let own = manifests[root + 'package.json']
240
+ if (own != null) this.#files.set(dir + 'package.json', own)
241
+ let pack: Packed = {
242
+ tgz,
243
+ from,
244
+ root,
245
+ holds: new Set(holds.map((path) => path.slice(root.length))),
246
+ decoded: new Map(
247
+ Object.entries(manifests).map((
248
+ [path, text],
249
+ ) => [path.slice(root.length), text]),
250
+ ),
251
+ key: from?.sha256,
252
+ }
253
+ keep(pack)
254
+ this.#packages.set(dir, { ...pack, sources, holds: new Set(pack.holds) })
255
+ }
256
+ }
257
+
258
+ let manifest = (path: string) => /^(?:[^/]+\/)?package\.json$/.test(path)
259
+
260
+ type Release = { from: Tarball; dependencies: Record<string, string> }
261
+
262
+ // Exact releases share the bounded tarball cache. Tags and ranges still ask
263
+ // the registry which version they mean. Fetch implementations have separate
264
+ // indexes so an injected registry cannot choose another registry's bytes.
265
+ let releases = new WeakMap<typeof fetch, Map<string, Release>>()
266
+
267
+ /** Forget every release and tarball memory holds, as a container that
268
+ * restarts does. */
269
+ export let forget = (): void => {
270
+ held.clear()
271
+ sizes.clear()
272
+ bytes = 0
273
+ releases = new WeakMap()
274
+ }
275
+ let exact = (get: typeof fetch) => {
276
+ let index = releases.get(get)
277
+ if (!index) releases.set(get, index = new Map())
278
+ return index
279
+ }
280
+
281
+ let remember = (index: Map<string, Release>, key: string, release: Release) => {
282
+ index.delete(key)
283
+ index.set(key, release)
284
+ if (index.size > 256) index.delete(index.keys().next().value!)
285
+ }
286
+
287
+ // A release on the shelf: what it depends on, and its tarball, both named by
288
+ // the release's registry URL and version so they are taken at once. The
289
+ // tarball is used only when its bytes are the SHA-256 the release names.
290
+ let named = async (key: string) => await sha256(new TextEncoder().encode(key))
291
+ let unshelved = async (
292
+ shelf: Shelf | undefined,
293
+ key: string,
294
+ ): Promise<{ release: Release; tgz: Uint8Array<ArrayBuffer> } | null> => {
295
+ if (!shelf) return null
296
+ let name = await named(key)
297
+ let [release, tgz] = await Promise.all([
298
+ taken<Release>(shelf, `release/${name}`),
299
+ shelf.take(`tarball/${name}`),
300
+ ])
301
+ return release?.from && tgz && await sha256(tgz) == release.from.sha256
302
+ ? { release, tgz }
303
+ : null
304
+ }
305
+ let shelved = async (
306
+ shelf: Shelf | undefined,
307
+ key: string,
308
+ release: Release,
309
+ tgz: Uint8Array<ArrayBuffer>,
310
+ ) => {
311
+ if (!shelf) return
312
+ let name = await named(key)
313
+ shelf.put(`tarball/${name}`, tgz)
314
+ shelve(shelf, `release/${name}`, release)
315
+ }
316
+
317
+ /**
318
+ * Install what `want` names, package name to version range, and what each
319
+ * needs, one version of each name beside the others. A package `fs` already
320
+ * holds (its package.json reads) is kept as it is. Answers what was installed,
321
+ * as `name@version`, and a line for each package that could not be. A
322
+ * release on `shelf` is installed from it without asking the registry;
323
+ * `report` hears the wall time spent asking the registry. `alone` installs
324
+ * what `want` names and nothing it needs.
325
+ */
326
+ export let install = async (
327
+ fs: Files,
328
+ want: Record<string, string>,
329
+ get: typeof fetch = fetch,
330
+ registry = REGISTRY,
331
+ { report, shelf, alone = false }: {
332
+ report?: (ms: number) => void
333
+ shelf?: Shelf
334
+ alone?: boolean
335
+ } = {},
336
+ ) => {
337
+ let installed: string[] = []
338
+ let warnings: string[] = []
339
+ let done = new Set<string>()
340
+ let pending = new Map<string, Promise<void>>()
341
+ let index = exact(get)
342
+ let span = spans(report)
343
+ let fetched = <T>(
344
+ url: string,
345
+ read: (response: Response) => Promise<T>,
346
+ init: RequestInit = {},
347
+ ) => span(() => asked(get, url, read, init))
348
+ let load = async (url: string, name: string, range: string) => {
349
+ let pin = valid(range)
350
+ let was = pin ? index.get(`${url}/${pin}`) : undefined
351
+ let packed = was && held.get(was.from.sha256)
352
+ if (was && packed) {
353
+ fs.hold(name, packed.tgz, was.from)
354
+ remember(index, `${url}/${pin}`, was)
355
+ return { version: pin!, dependencies: was.dependencies }
356
+ }
357
+ let pinned = pin ? await unshelved(shelf, `${url}/${pin}`) : null
358
+ if (pinned) {
359
+ fs.hold(name, pinned.tgz, pinned.release.from)
360
+ remember(index, `${url}/${pin}`, pinned.release)
361
+ return { version: pin!, dependencies: pinned.release.dependencies }
362
+ }
363
+ let meta: Metadata = await metadata(fetched, url, name)
364
+ let version = resolve(range, meta)
365
+ let release = version ? meta.versions[version] : undefined
366
+ if (!version || !release) return
367
+ let tarball = release.dist?.tarball
368
+ if (!tarball) throw new Error(`${name}@${version} names no tarball`)
369
+ let key = `${url}/${version}`
370
+ let known = index.get(key)
371
+ let ready = known?.from.url == tarball && held.get(known.from.sha256)
372
+ let dependencies = release.dependencies ?? {}
373
+ let from: Tarball
374
+ // A pin was looked for on the shelf before the registry was asked.
375
+ let kept = ready || pin ? null : await unshelved(shelf, key)
376
+ if (ready && known) {
377
+ fs.hold(name, ready.tgz, known.from)
378
+ from = known.from
379
+ } else if (kept?.release.from.url == tarball) {
380
+ fs.hold(name, kept.tgz, kept.release.from)
381
+ from = kept.release.from
382
+ } else {
383
+ let tgz = await fetched(tarball, async (r) => {
384
+ if (r.ok) return new Uint8Array(await r.arrayBuffer())
385
+ await r.body?.cancel()
386
+ throw new Error(`its tarball answered ${r.status} (${tarball})`)
387
+ })
388
+ from = { url: tarball, sha256: await sha256(tgz) }
389
+ fs.hold(name, tgz, from)
390
+ await shelved(shelf, key, { from, dependencies }, tgz)
391
+ }
392
+ remember(index, key, { from, dependencies })
393
+ return { version, dependencies }
394
+ }
395
+ let one = (name: string, range: string): Promise<void> | void => {
396
+ if (done.has(name)) return
397
+ if (fs.read(`node_modules/${name}/package.json`) != null) {
398
+ done.add(name)
399
+ return
400
+ }
401
+ let running = pending.get(name)
402
+ if (running) return running
403
+ let work = (async () => {
404
+ try {
405
+ let release = await load(documentAt(registry, name), name, range)
406
+ if (!release) {
407
+ warnings.push(`no version of ${name} satisfies ${range}`)
408
+ return
409
+ }
410
+ done.add(name)
411
+ installed.push(`${name}@${release.version}`)
412
+ if (alone) return
413
+ await Promise.all(
414
+ Object.entries(release.dependencies ?? {}).map(([dep, r]) =>
415
+ one(dep, r)
416
+ ),
417
+ )
418
+ } catch (e) {
419
+ warnings.push(`could not install ${name}: ${(e as Error).message}`)
420
+ }
421
+ })()
422
+ pending.set(name, work)
423
+ return work.finally(() => pending.delete(name))
424
+ }
425
+ await Promise.all(
426
+ Object.entries(want).map(([name, range]) => one(name, range)),
427
+ )
428
+ return { installed, warnings }
429
+ }
package/pack.js ADDED
@@ -0,0 +1,188 @@
1
+ // A page's modules packed into a few (D-499's fallback, T-5738, T-5647). A
2
+ // page of hashed modules goes live at once and loads every module it reaches
3
+ // beside its first, but hundreds of modules at once wait at the host's door,
4
+ // and a package's entries cannot shed what the page never uses; one pack is a
5
+ // few requests, tree-shaken. A host packs after the release is live, never
6
+ // before, and the page switches to the pack once it is kept.
7
+ //
8
+ // A pack is what esbuild bundles from the page's roots over the modules as
9
+ // compiled (./file.ts), each already JavaScript: the app's own, and the
10
+ // package modules its import map names (`imports`, a bare specifier to an
11
+ // address, and `packages`, each module's text by its address). A bare
12
+ // specifier the map does not name, or names a module not given, stays bare
13
+ // for the page's map. Every file a pack writes is served at the app's root,
14
+ // so what an app's module imports that the pack does not hold
15
+ // (`./api/client.js`, a JSON file) is written by its path from there, and a
16
+ // module's `import.meta.url` becomes its own address, as when it loaded
17
+ // alone. A module that computes a path it imports from, or reads
18
+ // `import.meta` beyond its URL, is not packed: its page keeps its modules.
19
+ import { parse } from "es-module-lexer/js";
20
+ import { bundle, Stopped } from "./bundle.js";
21
+ import { found } from "./graph.js";
22
+ import { moved, urlOf } from "./platform.js";
23
+ import { said } from "./said.js";
24
+ /** Modules a pack would not load as they load alone. */ export class Unpackable extends Error {
25
+ name = 'Unpackable';
26
+ }
27
+ let RELATIVE = /^\.\.?\//;
28
+ let META_URL = /^\s*\.\s*url\b/;
29
+ // An import() of a URL it makes whole, which means the same from a pack:
30
+ // against the page (`document.baseURI`), or the module's own address, which
31
+ // `import.meta.url` still is. Any other computed specifier may be a path
32
+ // from the module, which a pack moves.
33
+ let ADDRESSED = /^\s*new\s+URL\s*\(/;
34
+ // Where `spec`, imported by the module at `path`, is: its path from the
35
+ // app's root as written in a URL, and decoded, as a module is keyed.
36
+ let at = (path, spec)=>{
37
+ let url = new URL(spec, `https://app.invalid/${path}`);
38
+ return {
39
+ written: url.pathname.slice(1) + url.search,
40
+ path: decodeURIComponent(url.pathname.slice(1))
41
+ };
42
+ };
43
+ // Where a package module is read in a pack, beside the app's paths: by its
44
+ // file under `__m/`, so its imports of its package's other modules, written
45
+ // `./<file>`, resolve beside it.
46
+ let PACKAGE = '__m/';
47
+ let packageKey = (address)=>PACKAGE + address.slice(address.lastIndexOf('/') + 1);
48
+ // `spec` from a package module's address, which is a whole URL or, on the
49
+ // page's own origin, a path from its root.
50
+ let beside = (address, spec)=>{
51
+ let url = new URL(spec, new URL(address, 'https://origin.invalid'));
52
+ return url.origin == 'https://origin.invalid' ? url.pathname + url.search : url.href;
53
+ };
54
+ // Every module the roots reach, by import or by `import()`, each with its
55
+ // `import.meta.url` read as its own address: an app's module by its path,
56
+ // and a package module by the address the map names.
57
+ let reached = (roots, modules, packages, imports)=>{
58
+ let addresses = new Map(Object.keys(packages).map((address)=>[
59
+ packageKey(address),
60
+ address
61
+ ]));
62
+ let textOf = (key)=>addresses.has(key) ? packages[addresses.get(key)] : Object.hasOwn(modules, key) && !key.startsWith(PACKAGE) ? modules[key] : null;
63
+ let seen = new Map();
64
+ let next = [
65
+ ...roots
66
+ ];
67
+ while(next.length){
68
+ let path = next.pop();
69
+ let js = seen.has(path) ? null : textOf(path);
70
+ if (js == null) continue;
71
+ let lexed;
72
+ try {
73
+ lexed = parse(js)[0];
74
+ } catch {
75
+ throw new Unpackable(`${path} does not parse`);
76
+ }
77
+ for (let { n: spec, d, s, e } of lexed){
78
+ if (d == -2) {
79
+ if (!META_URL.test(js.slice(e))) {
80
+ throw new Unpackable(`${path} reads import.meta beyond its url`);
81
+ }
82
+ } else if (spec == null) {
83
+ // A package's modules import bare or whole URLs, never a path from
84
+ // their own (@yaks/esbuild/package), so what one computes means the
85
+ // same from a pack.
86
+ if (!addresses.has(path) && !ADDRESSED.test(js.slice(s, e))) {
87
+ throw new Unpackable(`${path} imports a module it computes`);
88
+ }
89
+ } else if (RELATIVE.test(spec)) {
90
+ let to = at(path, spec).path;
91
+ next.push(found(to, (p)=>textOf(p) != null) ?? to);
92
+ } else if (Object.hasOwn(imports, spec)) {
93
+ next.push(packageKey(imports[spec]));
94
+ }
95
+ }
96
+ let address = addresses.get(path);
97
+ seen.set(path, moved(js, ()=>urlOf(address ?? `./${encodeURI(path)}`)));
98
+ }
99
+ return {
100
+ texts: seen,
101
+ addresses
102
+ };
103
+ };
104
+ // What each file imports statically: another of the pack's files, or a bare
105
+ // specifier.
106
+ let linksOf = (files)=>Object.fromEntries(Object.entries(files).map(([file, js])=>{
107
+ let out = new Set();
108
+ for (let { n: spec, d } of parse(js)[0]){
109
+ if (spec == null || d != -1) continue;
110
+ if (RELATIVE.test(spec)) {
111
+ let to = spec.replace(/^\.\//, '');
112
+ if (Object.hasOwn(files, to)) out.add(`./${to}`);
113
+ } else if (!spec.startsWith('/') && !spec.includes(':')) out.add(spec);
114
+ }
115
+ return [
116
+ file,
117
+ [
118
+ ...out
119
+ ]
120
+ ];
121
+ }));
122
+ /** The modules `roots` reach, packed: one file a root, and chunks the roots
123
+ * share. Throws {@link Unpackable} for modules that would not load packed
124
+ * as they load alone or that esbuild refuses, and for a root no module is;
125
+ * `Stopped` when esbuild's process ended under it.
126
+ *
127
+ * ```ts
128
+ * import { assertEquals } from '@std/assert'
129
+ * let { entries, files, links } = await packModules({
130
+ * roots: ['main.ts'],
131
+ * modules: {
132
+ * 'main.ts': "import { n } from './lib/n.ts'\n" +
133
+ * "import { h } from 'preact'\nexport let x = h(n)",
134
+ * 'lib/n.ts': 'export let n = new URL("./a.png", import.meta.url).href',
135
+ * },
136
+ * })
137
+ * let main = files[entries['main.ts']]
138
+ * assertEquals(/from\s*['"]preact['"]/.test(main), true)
139
+ * assertEquals(main.includes('"./lib/n.ts"'), true)
140
+ * assertEquals(links[entries['main.ts']], ['preact'])
141
+ * ```
142
+ */ export let packModules = async ({ roots, modules, packages = {}, imports = {} })=>{
143
+ for (let root of roots){
144
+ if (!Object.hasOwn(modules, root)) {
145
+ throw new Unpackable(`${root} is no module of the app`);
146
+ }
147
+ }
148
+ let { texts, addresses } = reached(roots, modules, packages, imports);
149
+ let names = Object.fromEntries(roots.map((root, i)=>[
150
+ `pack-${i}`,
151
+ root
152
+ ]));
153
+ // What esbuild refuses of the app's code it refuses every time: the
154
+ // modules are not packed, and esbuild's lines say why.
155
+ let built = await bundle({
156
+ read: (path)=>texts.get(path) ?? null
157
+ }, names, {
158
+ loader: 'js',
159
+ // As a page's bundle was built (./compile.ts).
160
+ minify: true,
161
+ define: {
162
+ 'process.env.NODE_ENV': '"production"'
163
+ },
164
+ alias: (spec)=>{
165
+ let key = !RELATIVE.test(spec) && Object.hasOwn(imports, spec) && packageKey(imports[spec]);
166
+ return key && texts.has(key) ? key : undefined;
167
+ },
168
+ external: (spec, importer)=>{
169
+ if (!RELATIVE.test(spec)) return spec;
170
+ let to = at(importer, spec);
171
+ if (found(to.path, (p)=>texts.has(p))) return undefined;
172
+ // A package's file the pack does not hold, at its own address.
173
+ let address = addresses.get(importer);
174
+ return address ? beside(address, spec) : `./${to.written}`;
175
+ }
176
+ }).catch((e)=>{
177
+ throw e instanceof Stopped ? e : new Unpackable(said(e).join('\n'));
178
+ });
179
+ return {
180
+ entries: Object.fromEntries(Object.entries(names).map(([name, root])=>[
181
+ root,
182
+ `${name}.js`
183
+ ])),
184
+ files: built.files,
185
+ links: linksOf(built.files)
186
+ };
187
+ };
188
+ //# sourceMappingURL=pack.js.map
package/pack.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pack.js","sources":["./pack.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,6EAA6E;AAC7E,8EAA8E;AAC9E,2EAA2E;AAC3E,6DAA6D;AAC7D,EAAE;AACF,2EAA2E;AAC3E,wEAAwE;AACxE,0EAA0E;AAC1E,sEAAsE;AACtE,2EAA2E;AAC3E,4EAA4E;AAC5E,8DAA8D;AAC9D,4EAA4E;AAC5E,wEAAwE;AACxE,iEAAiE;AACjE,2EAA2E;AAC3E,SAAS,KAAK,6BAAsC;AACpD,SAAS,MAAM,EAAE,OAAO,sBAAqB;AAC7C,SAAS,KAAK,qBAAoB;AAClC,SAAS,KAAK,EAAE,KAAK,wBAAuB;AAC5C,SAAS,IAAI,oBAAmB;AAuBhC,sDAAsD,GACtD,OAAO,MAAM,mBAAmB;EACrB,OAAO,aAAY;AAC9B;AAEA,IAAI,WAAW;AACf,IAAI,WAAW;AACf,yEAAyE;AACzE,4EAA4E;AAC5E,yEAAyE;AACzE,uCAAuC;AACvC,IAAI,YAAY;AAEhB,wEAAwE;AACxE,qEAAqE;AACrE,IAAI,KAAK,CAAC,MAAc;EACtB,IAAI,MAAM,IAAI,IAAI,MAAM,CAAC,oBAAoB,EAAE,MAAM;EACrD,OAAO;IACL,SAAS,IAAI,QAAQ,CAAC,KAAK,CAAC,KAAK,IAAI,MAAM;IAC3C,MAAM,mBAAmB,IAAI,QAAQ,CAAC,KAAK,CAAC;EAC9C;AACF;AAEA,2EAA2E;AAC3E,4EAA4E;AAC5E,iCAAiC;AAC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