@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/timing.ts ADDED
@@ -0,0 +1,71 @@
1
+ // Compiler wall-clock phases, measured in its native runtime rather than the
2
+ // host Worker's I/O-only clock. Callbacks carry only fixed names and numbers,
3
+ // never source text, package names or credentials.
4
+ export type Phase =
5
+ | 'install'
6
+ | 'registry'
7
+ | 'shelf'
8
+ | 'worker'
9
+ | 'carried'
10
+ | 'used'
11
+ | 'groups'
12
+ | 'cache'
13
+ | 'pages'
14
+ | 'total'
15
+ export type Timing = Record<Phase, number> & {
16
+ /** Shared-group cache lookups, counted rather than milliseconds. */
17
+ hits: number
18
+ misses: number
19
+ }
20
+ export type Report = (phase: Phase | 'hits' | 'misses', value: number) => void
21
+
22
+ /** Start a phase only when someone is listening; finish it even on failure. */
23
+ export let phase = (report: Report | undefined, name: Phase) => {
24
+ let at = report ? performance.now() : 0
25
+ let finished = false
26
+ return () => {
27
+ if (report && !finished) report(name, performance.now() - at)
28
+ finished = true
29
+ }
30
+ }
31
+
32
+ /** Wall time spent in overlapping work, counted once: `report` hears each
33
+ * stretch from the first start to the last finish. */
34
+ export let spans = (report?: (ms: number) => void) => {
35
+ let open = 0, began = 0
36
+ return async <T>(work: () => Promise<T>): Promise<T> => {
37
+ if (report && !open++) began = performance.now()
38
+ try {
39
+ return await work()
40
+ } finally {
41
+ if (report && !--open) report(performance.now() - began)
42
+ }
43
+ }
44
+ }
45
+
46
+ /// header({ groups: 5, hits: 2, misses: 1 }) -> 'compiler_groups;dur=5.000;desc="1 built, 2 kept"'
47
+ /** Fixed metric names keep compiler diagnostics distinct from host stages.
48
+ * The shared-group counts ride `groups` as its `desc`, saying whether its
49
+ * time went to building or to finding what was kept. */
50
+ export let header = (timing: Record<string, number>) =>
51
+ Object.entries(timing).filter(([name]) => name != 'hits' && name != 'misses')
52
+ .map(([name, ms]) =>
53
+ `compiler_${name};dur=${ms.toFixed(3)}` +
54
+ (name == 'groups' && 'hits' in timing
55
+ ? `;desc="${timing.misses} built, ${timing.hits} kept"`
56
+ : '')
57
+ ).join(', ')
58
+
59
+ /** Add compiler relay timings while streaming the original answer through. */
60
+ export let timed = (
61
+ response: Response,
62
+ timing: Record<string, number>,
63
+ ): Response => {
64
+ let headers = new Headers(response.headers)
65
+ headers.append('server-timing', header(timing))
66
+ return new Response(response.body, {
67
+ status: response.status,
68
+ statusText: response.statusText,
69
+ headers,
70
+ })
71
+ }
package/unpack.js ADDED
@@ -0,0 +1,40 @@
1
+ // A host's half of an npm package's home (./home.ts): one file out of the
2
+ // registry's tarball as it streams in, and the proof that it is the tarball
3
+ // the home names. A module of its own, so a host loads the hashing it needs
4
+ // only when it fills a home, never on start.
5
+ import { sha256 } from "@noble/hashes/sha2.js";
6
+ import { hex } from "./home.js";
7
+ import { rooted, untar } from "./tar.js";
8
+ /**
9
+ * Read a gzipped npm tarball as it streams in, keeping only the file at
10
+ * `want`, a path from the package's root. The whole tarball is read, since
11
+ * its SHA-256 is what says it is the one a home names; a host checks that
12
+ * before it serves the bytes.
13
+ */ export let unpacked = async (tgz, want)=>{
14
+ let hash = sha256.create();
15
+ let paths = [];
16
+ // The two entries `want` could be until the root is known: under the first
17
+ // entry's directory, where npm packs every file, or under none.
18
+ let first;
19
+ let found = new Map();
20
+ let push = untar((path, _, file)=>{
21
+ if (!file || !path) return false;
22
+ paths.push(path);
23
+ first ??= path.slice(0, path.indexOf('/') + 1);
24
+ return path == want || path == first + want;
25
+ }, (path, bytes)=>void found.set(path, bytes));
26
+ let inflated = tgz.pipeThrough(new TransformStream({
27
+ transform: (chunk, out)=>{
28
+ hash.update(chunk);
29
+ out.enqueue(chunk);
30
+ }
31
+ })).pipeThrough(new DecompressionStream('gzip'));
32
+ for await (let chunk of inflated)push(chunk);
33
+ let root = rooted(paths);
34
+ return {
35
+ sha256: hex(hash.digest()),
36
+ paths: paths.map((path)=>path.slice(root.length)),
37
+ bytes: found.get(root + want) ?? null
38
+ };
39
+ };
40
+ //# sourceMappingURL=unpack.js.map
package/unpack.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unpack.js","sources":["./unpack.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,4EAA4E;AAC5E,4EAA4E;AAC5E,6CAA6C;AAC7C,SAAS,MAAM,gCAAyC;AACxD,SAAS,GAAG,oBAAmB;AAC/B,SAAS,MAAM,EAAE,KAAK,mBAAkB;AAWxC;;;;;CAKC,GACD,OAAO,IAAI,WAAW,OACpB,KACA;EAEA,IAAI,OAAO,OAAO,MAAM;EACxB,IAAI,QAAkB,EAAE;EACxB,2EAA2E;EAC3E,gEAAgE;EAChE,IAAI;EACJ,IAAI,QAAQ,IAAI;EAChB,IAAI,OAAO,MACT,CAAC,MAAM,GAAG;IACR,IAAI,CAAC,QAAQ,CAAC,MAAM,OAAO;IAC3B,MAAM,IAAI,CAAC;IACX,UAAU,KAAK,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,OAAO;IAC5C,OAAO,QAAQ,QAAQ,QAAQ,QAAQ;EACzC,GACA,CAAC,MAAM,QAAU,KAAK,MAAM,GAAG,CAAC,MAAM;EAExC,IAAI,WAAW,IACZ,WAAW,CACV,IAAI,gBAAkE;IACpE,WAAW,CAAC,OAAO;MACjB,KAAK,MAAM,CAAC;MACZ,IAAI,OAAO,CAAC;IACd;EACF,IAED,WAAW,CAAC,IAAI,oBAAoB;EACvC,WAAW,IAAI,SAAS,SAAU,KAAK;EACvC,IAAI,OAAO,OAAO;EAClB,OAAO;IACL,QAAQ,IAAI,KAAK,MAAM;IACvB,OAAO,MAAM,GAAG,CAAC,CAAC,OAAS,KAAK,KAAK,CAAC,KAAK,MAAM;IACjD,OAAO,MAAM,GAAG,CAAC,OAAO,SAAS;EACnC;AACF,EAAC"}
package/unpack.ts ADDED
@@ -0,0 +1,60 @@
1
+ // A host's half of an npm package's home (./home.ts): one file out of the
2
+ // registry's tarball as it streams in, and the proof that it is the tarball
3
+ // the home names. A module of its own, so a host loads the hashing it needs
4
+ // only when it fills a home, never on start.
5
+ import { sha256 } from '@noble/hashes/sha2.js'
6
+ import { hex } from './home.js'
7
+ import { rooted, untar } from './tar.js'
8
+
9
+ /** What a tarball holds: its SHA-256, every file's path from the package's
10
+ * root, and the bytes of the one asked for, or null when it holds no such
11
+ * file. */
12
+ export type Unpacked = {
13
+ sha256: string
14
+ paths: string[]
15
+ bytes: Uint8Array | null
16
+ }
17
+
18
+ /**
19
+ * Read a gzipped npm tarball as it streams in, keeping only the file at
20
+ * `want`, a path from the package's root. The whole tarball is read, since
21
+ * its SHA-256 is what says it is the one a home names; a host checks that
22
+ * before it serves the bytes.
23
+ */
24
+ export let unpacked = async (
25
+ tgz: ReadableStream<Uint8Array<ArrayBuffer>>,
26
+ want: string,
27
+ ): Promise<Unpacked> => {
28
+ let hash = sha256.create()
29
+ let paths: string[] = []
30
+ // The two entries `want` could be until the root is known: under the first
31
+ // entry's directory, where npm packs every file, or under none.
32
+ let first: string | undefined
33
+ let found = new Map<string, Uint8Array>()
34
+ let push = untar(
35
+ (path, _, file) => {
36
+ if (!file || !path) return false
37
+ paths.push(path)
38
+ first ??= path.slice(0, path.indexOf('/') + 1)
39
+ return path == want || path == first + want
40
+ },
41
+ (path, bytes) => void found.set(path, bytes),
42
+ )
43
+ let inflated = tgz
44
+ .pipeThrough(
45
+ new TransformStream<Uint8Array<ArrayBuffer>, Uint8Array<ArrayBuffer>>({
46
+ transform: (chunk, out) => {
47
+ hash.update(chunk)
48
+ out.enqueue(chunk)
49
+ },
50
+ }),
51
+ )
52
+ .pipeThrough(new DecompressionStream('gzip'))
53
+ for await (let chunk of inflated) push(chunk)
54
+ let root = rooted(paths)
55
+ return {
56
+ sha256: hex(hash.digest()),
57
+ paths: paths.map((path) => path.slice(root.length)),
58
+ bytes: found.get(root + want) ?? null,
59
+ }
60
+ }
package/used.js ADDED
@@ -0,0 +1,91 @@
1
+ // Which exports of each shared npm specifier a page's consumers use, so that
2
+ // its shared module carries those and no more (./shared.ts), as a bundled copy
3
+ // did. esbuild answers, by shaking the consumers as it shook each copy: one
4
+ // build reads what each specifier exports, and a second builds every
5
+ // consumer's entries with each specifier read from a stand-in, which passes
6
+ // each export through a pure call carrying a mark. A call nothing uses is
7
+ // shaken out with its mark, so the marks left name what is used. A namespace
8
+ // that escapes (passed along, or read with a computed key) keeps every export.
9
+ // The stand-in passes the package's own export through, so what a shared
10
+ // package is used for decides what it uses of another; an import from inside
11
+ // the package is its own and reads the module itself.
12
+ import { bundle } from "./bundle.js";
13
+ import { owner } from "./common.js";
14
+ import { packageOf } from "./graph.js";
15
+ let MARK = 'yaks:used:';
16
+ let MARKS = /yaks:used:(\d+):(\d+)/g;
17
+ /** A module exporting what `path` exports, each export through a marked
18
+ * call: the `i`th specifier's `j`th export carries `yaks:used:i:j`.
19
+ *
20
+ * ```ts
21
+ * import { assertEquals } from '@std/assert'
22
+ * assertEquals(
23
+ * standIn('node_modules/a/index.js', ['default'], 0),
24
+ * 'let mark = (_, value) => value\n' +
25
+ * 'import { "default" as a0 } from "/node_modules/a/index.js"\n' +
26
+ * 'let b0 = /* @__PURE__ *\/ mark("yaks:used:0:0", a0)\n' +
27
+ * 'export { b0 as "default" }',
28
+ * )
29
+ * ```
30
+ */ export let standIn = (path, names, i)=>{
31
+ let from = JSON.stringify(`/${path}`);
32
+ let named = (as)=>names.map(as).join(', ');
33
+ return names.length ? [
34
+ 'let mark = (_, value) => value',
35
+ `import { ${named((n, j)=>`${JSON.stringify(n)} as a${j}`)} } ` + `from ${from}`,
36
+ ...names.map((_, j)=>`let b${j} = /* @__PURE__ */ mark("${MARK}${i}:${j}", a${j})`),
37
+ `export { ${named((n, j)=>`b${j} as ${JSON.stringify(n)}`)} }`
38
+ ].join('\n') : `import ${from}`;
39
+ };
40
+ let points = (paths)=>Object.fromEntries(paths.map((path, i)=>[
41
+ `entry-${i}`,
42
+ path
43
+ ]));
44
+ /** Every export of each shared specifier (`entries`, by the file it
45
+ * names). */ export let offered = async (fs, entries)=>{
46
+ let specs = Object.keys(entries).sort();
47
+ if (!specs.length) return {};
48
+ let { exports } = await bundle(fs, points(specs.map((s)=>entries[s])), {
49
+ graph: true
50
+ });
51
+ return Object.fromEntries(specs.map((spec, i)=>[
52
+ spec,
53
+ exports[`entry-${i}.js`]
54
+ ]));
55
+ };
56
+ /** The exports of each shared specifier (`entries`, by the file it names)
57
+ * that `files`, every consumer's entries, use once built with `options`.
58
+ * Each entry is built apart, so what files use together is the union of what
59
+ * each part of them uses; `all` is what {@link offered} answered, when the
60
+ * caller has it. */ export let used = async (fs, files, entries, options, all, outside = new Set())=>{
61
+ let specs = Object.keys(entries).sort();
62
+ if (!specs.length) return {};
63
+ all ??= await offered(fs, entries);
64
+ let names = specs.map((spec)=>all[spec]);
65
+ if (!files.length) return Object.fromEntries(specs.map((spec)=>[
66
+ spec,
67
+ []
68
+ ]));
69
+ let stands = Object.fromEntries(specs.map((spec, i)=>[
70
+ `__used/${i}.js`,
71
+ standIn(entries[spec], names[i], i)
72
+ ]));
73
+ let built = await bundle({
74
+ read: (path)=>stands[path] ?? fs.read(path)
75
+ }, points(files), {
76
+ ...options,
77
+ external: (spec)=>outside.has(packageOf(spec) ?? '') ? spec : undefined,
78
+ alias: (spec, importer)=>{
79
+ let i = specs.indexOf(spec);
80
+ return i < 0 || packageOf(spec) == owner(importer) ? undefined : `__used/${i}.js`;
81
+ }
82
+ });
83
+ let marks = new Set(Object.values(built.files).flatMap((text)=>[
84
+ ...text.matchAll(MARKS)
85
+ ].map((m)=>m[0])));
86
+ return Object.fromEntries(specs.map((spec, i)=>[
87
+ spec,
88
+ names[i].filter((_, j)=>marks.has(`${MARK}${i}:${j}`))
89
+ ]));
90
+ };
91
+ //# sourceMappingURL=used.js.map
package/used.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"used.js","sources":["./used.ts"],"names":[],"mappings":"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"}
package/used.ts ADDED
@@ -0,0 +1,116 @@
1
+ // Which exports of each shared npm specifier a page's consumers use, so that
2
+ // its shared module carries those and no more (./shared.ts), as a bundled copy
3
+ // did. esbuild answers, by shaking the consumers as it shook each copy: one
4
+ // build reads what each specifier exports, and a second builds every
5
+ // consumer's entries with each specifier read from a stand-in, which passes
6
+ // each export through a pure call carrying a mark. A call nothing uses is
7
+ // shaken out with its mark, so the marks left name what is used. A namespace
8
+ // that escapes (passed along, or read with a computed key) keeps every export.
9
+ // The stand-in passes the package's own export through, so what a shared
10
+ // package is used for decides what it uses of another; an import from inside
11
+ // the package is its own and reads the module itself.
12
+ import { bundle, type Options, type Source } from './bundle.js'
13
+ import { owner } from './common.js'
14
+ import { packageOf } from './graph.js'
15
+
16
+ let MARK = 'yaks:used:'
17
+ let MARKS = /yaks:used:(\d+):(\d+)/g
18
+
19
+ /** A module exporting what `path` exports, each export through a marked
20
+ * call: the `i`th specifier's `j`th export carries `yaks:used:i:j`.
21
+ *
22
+ * ```ts
23
+ * import { assertEquals } from '@std/assert'
24
+ * assertEquals(
25
+ * standIn('node_modules/a/index.js', ['default'], 0),
26
+ * 'let mark = (_, value) => value\n' +
27
+ * 'import { "default" as a0 } from "/node_modules/a/index.js"\n' +
28
+ * 'let b0 = /* @__PURE__ *\/ mark("yaks:used:0:0", a0)\n' +
29
+ * 'export { b0 as "default" }',
30
+ * )
31
+ * ```
32
+ */
33
+ export let standIn = (path: string, names: string[], i: number): string => {
34
+ let from = JSON.stringify(`/${path}`)
35
+ let named = (as: (name: string, j: number) => string) =>
36
+ names.map(as).join(', ')
37
+ return names.length
38
+ ? [
39
+ 'let mark = (_, value) => value',
40
+ `import { ${named((n, j) => `${JSON.stringify(n)} as a${j}`)} } ` +
41
+ `from ${from}`,
42
+ ...names.map((_, j) =>
43
+ `let b${j} = /* @__PURE__ */ mark("${MARK}${i}:${j}", a${j})`
44
+ ),
45
+ `export { ${named((n, j) => `b${j} as ${JSON.stringify(n)}`)} }`,
46
+ ].join('\n')
47
+ : `import ${from}`
48
+ }
49
+
50
+ let points = (paths: string[]) =>
51
+ Object.fromEntries(paths.map((path, i) => [`entry-${i}`, path]))
52
+
53
+ /** Every export of each shared specifier (`entries`, by the file it
54
+ * names). */
55
+ export let offered = async (
56
+ fs: Source,
57
+ entries: Record<string, string>,
58
+ ): Promise<Record<string, string[]>> => {
59
+ let specs = Object.keys(entries).sort()
60
+ if (!specs.length) return {}
61
+ let { exports } = await bundle(fs, points(specs.map((s) => entries[s])), {
62
+ graph: true,
63
+ })
64
+ return Object.fromEntries(
65
+ specs.map((spec, i) => [spec, exports![`entry-${i}.js`]]),
66
+ )
67
+ }
68
+
69
+ /** The exports of each shared specifier (`entries`, by the file it names)
70
+ * that `files`, every consumer's entries, use once built with `options`.
71
+ * Each entry is built apart, so what files use together is the union of what
72
+ * each part of them uses; `all` is what {@link offered} answered, when the
73
+ * caller has it. */
74
+ export let used = async (
75
+ fs: Source,
76
+ files: string[],
77
+ entries: Record<string, string>,
78
+ options: Options,
79
+ all?: Record<string, string[]>,
80
+ outside: Set<string> = new Set(),
81
+ ): Promise<Record<string, string[]>> => {
82
+ let specs = Object.keys(entries).sort()
83
+ if (!specs.length) return {}
84
+ all ??= await offered(fs, entries)
85
+ let names = specs.map((spec) => all[spec])
86
+ if (!files.length) return Object.fromEntries(specs.map((spec) => [spec, []]))
87
+ let stands: Record<string, string> = Object.fromEntries(
88
+ specs.map((spec, i) => [
89
+ `__used/${i}.js`,
90
+ standIn(entries[spec], names[i], i),
91
+ ]),
92
+ )
93
+ let built = await bundle(
94
+ { read: (path) => stands[path] ?? fs.read(path) },
95
+ points(files),
96
+ {
97
+ ...options,
98
+ external: (spec) => outside.has(packageOf(spec) ?? '') ? spec : undefined,
99
+ alias: (spec, importer) => {
100
+ let i = specs.indexOf(spec)
101
+ return i < 0 || packageOf(spec) == owner(importer)
102
+ ? undefined
103
+ : `__used/${i}.js`
104
+ },
105
+ },
106
+ )
107
+ let marks = new Set(
108
+ Object.values(built.files).flatMap((text) =>
109
+ [...text.matchAll(MARKS)].map((m) => m[0])
110
+ ),
111
+ )
112
+ return Object.fromEntries(specs.map((spec, i) => [
113
+ spec,
114
+ names[i].filter((_, j) => marks.has(`${MARK}${i}:${j}`)),
115
+ ]))
116
+ }