@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/platform.ts ADDED
@@ -0,0 +1,238 @@
1
+ // @ts-types="@types/semver"
2
+ // Compiler-owned toolkit sources, seeded as npm-shaped packages. Only declared
3
+ // toolkit roots and their catalog dependency closure enter a build; their source
4
+ // digests describe what was compiled, never a version to ask the registry for.
5
+ /* @ts-types="npm:@types/semver@^7.8.0" */ import { gt, intersects, minVersion, Range } from 'semver'
6
+ import { parse } from 'es-module-lexer/js'
7
+ import { packageOf, script } from './graph.js'
8
+ import { dependencies } from './plan.js'
9
+
10
+ /** A compiler's toolkit package: paths relative to its package root, including
11
+ * package.json, normalized source imports, runtime dependencies and source SHA. */
12
+ export type Toolkit = {
13
+ files: Record<string, string>
14
+ dependencies: Record<string, string>
15
+ /** Runtime text files, relative to the package root. */
16
+ resources?: Record<string, string>
17
+ renderer?: Renderer
18
+ version: string
19
+ }
20
+
21
+ /** The import aliases a renderer supplies to apps that select it. */
22
+ export type Renderer = {
23
+ dependency: string
24
+ unless?: string
25
+ aliases: Record<string, string>
26
+ }
27
+
28
+ /** Supplied by the compiler's wrapper, never by an app. */
29
+ export type Catalog = Record<string, Toolkit>
30
+
31
+ export type Seed = {
32
+ assets: Record<string, string>
33
+ files: Record<string, string>
34
+ /** npm roots, including toolkit externals whose transitives the installer
35
+ * would otherwise skip when it finds a preseeded toolkit package. */
36
+ dependencies: Record<string, string>
37
+ /** Toolkit package to the exact source digest used by this compiler. */
38
+ platform: Record<string, string>
39
+ /** What the app should know about how its asks were met. */
40
+ notes: string[]
41
+ aliases?: Readonly<Record<string, string>>
42
+ jsxImportSource?: string
43
+ }
44
+
45
+ /** The package supplying an import after the app's renderer is selected. */
46
+ export let packageFor = (setup: Seed, spec: string): string | undefined =>
47
+ packageOf(setup.aliases?.[spec] ?? spec) ?? undefined
48
+
49
+ /** Runtime resources stay outside the app's own paths. */
50
+ export let ASSETS = '__packages/'
51
+
52
+ let toolkit = (name: string) => name.startsWith('@yaks/')
53
+ let safe = (path: string) =>
54
+ !!path && !path.startsWith('/') &&
55
+ !path.split('/').some((p) => !p || p == '.' || p == '..') &&
56
+ !/[\\?#%]/.test(path)
57
+
58
+ // The lexer identifies import.meta outside comments, strings and regexps.
59
+ let urlProp =
60
+ /^(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*(?:\n|$))*\.(?:\s|\/\*[\s\S]*?\*\/)*url\b/
61
+
62
+ /** Preserve a package module's URL when its source is bundled into an entry.
63
+ * Page paths resolve against the browser's entry URL. A server entry supplies
64
+ * its absolute logical module URL, since workerd names modules without an origin. */
65
+ export let located = (
66
+ files: Record<string, string>,
67
+ entry: string | URL,
68
+ baseFor?: (path: string) => string,
69
+ ) => {
70
+ let out: Record<string, string> = {}
71
+ let path = typeof entry == 'string' ? entry : entry.pathname.slice(1)
72
+ let up = '../'.repeat(path.split('/').length - 1)
73
+ for (let [path, source] of Object.entries(files)) {
74
+ if (!path.startsWith('node_modules/@yaks/') || !script(path)) continue
75
+ let base = baseFor?.(path) ??
76
+ up + ASSETS + path.slice('node_modules/'.length)
77
+ out[path] = moved(
78
+ source,
79
+ () =>
80
+ typeof entry == 'string'
81
+ ? urlOf(base)
82
+ : JSON.stringify(new URL(base, entry).href),
83
+ )
84
+ }
85
+ return out
86
+ }
87
+
88
+ /** The expression for `base`, a path from the module that is running. */
89
+ export let urlOf = (base: string) =>
90
+ `new URL(${JSON.stringify(base)}, import.meta.url).href`
91
+
92
+ /** A module's source with each `import.meta.url` read replaced by `value()`,
93
+ * an expression for the address the module is served from. `value` is asked
94
+ * only of a module that reads its URL, and none leaves the module as it is. */
95
+ export let moved = (source: string, value: () => string | undefined) => {
96
+ let to: string | undefined
97
+ for (let imp of parse(source)[0].toReversed()) {
98
+ if (imp.d != -2) continue
99
+ let tail = urlProp.exec(source.slice(imp.e))
100
+ if (!tail) continue
101
+ to ??= value()
102
+ if (to == null) return source
103
+ source = source.slice(0, imp.s) + to +
104
+ source.slice(imp.e + tail[0].length)
105
+ }
106
+ return source
107
+ }
108
+
109
+ // The lowest version a range allows, or null for a tag or a URL.
110
+ let least = (range: string) => {
111
+ try {
112
+ return minVersion(range)?.version ?? null
113
+ } catch {
114
+ return null
115
+ }
116
+ }
117
+
118
+ /** One version for a flat install that two consumers ask for: what both
119
+ * ranges allow, else the higher of two that semver calls compatible, as when
120
+ * a release pins the marked its toolkit used before the toolkit moved on.
121
+ * `noted` hears that choice; different majors cannot share one install. */
122
+ export let together = (
123
+ name: string,
124
+ a: string,
125
+ b: string,
126
+ noted: (note: string) => void = () => {},
127
+ ) => {
128
+ if (a == b) return a
129
+ try {
130
+ if (intersects(a, b)) {
131
+ let choices = new Range(a).set.flatMap((left) =>
132
+ new Range(b).set.map((right) =>
133
+ [...left, ...right].map((c) => c.value).filter(Boolean).join(' ')
134
+ )
135
+ )
136
+ return choices.join(' || ')
137
+ }
138
+ let [low, high] = [least(a), least(b)]
139
+ if (low && high && intersects(`^${low}`, `^${high}`)) {
140
+ let [kept, left] = gt(low, high) ? [a, b] : [b, a]
141
+ noted(
142
+ `package.json: ${name} ${left} and ${kept} are both asked for; ` +
143
+ `the one install is ${kept}`,
144
+ )
145
+ return kept
146
+ }
147
+ } catch {
148
+ // Different tags and URLs cannot express a shared version constraint.
149
+ }
150
+ throw new Error(
151
+ `package.json: ${name} has incompatible versions ${a} and ${b}`,
152
+ )
153
+ }
154
+
155
+ /** Seed declared platform packages and their dependency closure without I/O.
156
+ * @yaks packages must use "platform"; none is fetched from a registry. */
157
+ export let seed = (files: Record<string, string>, catalog: Catalog): Seed => {
158
+ for (let path of Object.keys(files)) {
159
+ if (/^(?:\.\/)*node_modules(?:\/|$)/.test(path)) {
160
+ throw new Error(
161
+ `${path}: node_modules is the compiler's reserved package namespace`,
162
+ )
163
+ }
164
+ }
165
+ let out: Seed = {
166
+ files: { ...files },
167
+ assets: {},
168
+ dependencies: {},
169
+ platform: {},
170
+ notes: [],
171
+ }
172
+ let noted = (note: string) => out.notes.push(note)
173
+ let roots = dependencies(files['package.json'] ?? null)
174
+ let npm: [string, string][] = []
175
+ let visit = (name: string, version: string) => {
176
+ if (!toolkit(name)) {
177
+ if (version == 'platform') {
178
+ throw new Error(`${name}: only @yaks toolkit packages use "platform"`)
179
+ }
180
+ npm.push([name, version])
181
+ return
182
+ }
183
+ if (version != 'platform') {
184
+ throw new Error(
185
+ `${name}: use "platform", not ${version}, in dependencies`,
186
+ )
187
+ }
188
+ if (name in out.platform) return
189
+ let pkg = catalog[name]
190
+ if (!pkg) {
191
+ throw new Error(`${name}: missing from this compiler's platform catalog`)
192
+ }
193
+ if (!/^sha256:[a-f0-9]{64}$/.test(pkg.version)) {
194
+ throw new Error(
195
+ `${name}: platform catalog version must be a source SHA256`,
196
+ )
197
+ }
198
+ if (!('package.json' in pkg.files)) {
199
+ throw new Error(`${name}: platform catalog is missing package.json`)
200
+ }
201
+ out.platform[name] = pkg.version
202
+ for (let [path, source] of Object.entries(pkg.files)) {
203
+ if (!safe(path)) {
204
+ throw new Error(
205
+ `${name}: platform catalog path ${path} is not package-relative`,
206
+ )
207
+ }
208
+ out.files[`node_modules/${name}/${path}`] = source
209
+ }
210
+ for (let [path, text] of Object.entries(pkg.resources ?? {})) {
211
+ if (!safe(path)) {
212
+ throw new Error(`${name}: resource ${path} is not package-relative`)
213
+ }
214
+ out.assets[`${ASSETS}${name}/${path}`] = text
215
+ out.files[`node_modules/${name}/${path}`] = text
216
+ }
217
+ for (let [dep, range] of Object.entries(pkg.dependencies)) visit(dep, range)
218
+ }
219
+ for (let [name, range] of Object.entries(roots)) visit(name, range)
220
+ let npmNames = new Set(npm.map(([name]) => name))
221
+ let renderer = Object.values(catalog).map((p) => p.renderer).find((r) =>
222
+ r && npmNames.has(r.dependency) && (!r.unless || !roots[r.unless])
223
+ )
224
+ if (renderer) {
225
+ out.aliases = renderer.aliases
226
+ out.jsxImportSource = renderer.dependency
227
+ } else if (roots.preact && !roots.react) {
228
+ out.jsxImportSource = 'preact'
229
+ } else if (roots.react) out.jsxImportSource = 'react'
230
+ for (let [name, version] of npm) {
231
+ if (out.aliases?.[name] && !roots[name]) continue
232
+ let prior = out.dependencies[name]
233
+ out.dependencies[name] = prior
234
+ ? together(name, prior, version, noted)
235
+ : version
236
+ }
237
+ return out
238
+ }
package/resolve.js ADDED
@@ -0,0 +1,86 @@
1
+ // Which version of each npm package a lock pins, as an install chooses them,
2
+ // read from the registry's documents alone: one version of each name, flat,
3
+ // a range read as npm reads it. ./npm.ts installs what these name; a host
4
+ // with no installer (a Worker) pins an app's packages with `resolved` and
5
+ // leaves the tarballs to the compile that first needs each.
6
+ /* @ts-types="npm:@types/semver@^7.8.0" */ import { maxSatisfying } from "semver";
7
+ import { REGISTRY } from "./home.js";
8
+ // How long the registry has to answer, in ms.
9
+ export let WAIT = 30_000;
10
+ /** The version a range asks for, as npm reads it: a tag, an exact version or
11
+ * the newest the range allows. */ export let resolve = (range, meta)=>range == 'latest' || range == '*' ? meta['dist-tags'].latest : range in meta.versions ? range : meta['dist-tags'][range] ?? maxSatisfying(Object.keys(meta.versions), range) ?? undefined;
12
+ /** A package's document at the registry. */ export let documentAt = (registry, name)=>`${registry}/${name.startsWith('@') ? `@${encodeURIComponent(name.slice(1))}` : name}`;
13
+ /** `url`'s answer read by `read`, or a line saying the registry did not
14
+ * answer within `WAIT`. */ export let asked = async (get, url, read, init = {})=>{
15
+ try {
16
+ return await read(await get(url, {
17
+ ...init,
18
+ signal: AbortSignal.timeout(WAIT)
19
+ }));
20
+ } catch (e) {
21
+ if (e.name != 'TimeoutError') throw e;
22
+ throw new Error(`the registry did not answer ${url} within ${WAIT / 1000}s`);
23
+ }
24
+ };
25
+ /** The registry's document for `name`, its abbreviated form. */ export let metadata = (ask, url, name)=>ask(url, async (r)=>{
26
+ if (r.ok) return await r.json();
27
+ await r.body?.cancel();
28
+ throw new Error(`the registry answered ${r.status} for "${name}"` + (r.status == 404 ? ' (no such package: check its name in package.json)' : ''));
29
+ }, {
30
+ headers: {
31
+ accept: 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8'
32
+ }
33
+ });
34
+ /** The version of each package `want` names (name to range) and of each it
35
+ * needs, one of each name, as ./npm.ts `install` chooses them, asking the
36
+ * registry for documents and never a tarball. `warnings` names each package
37
+ * no version of satisfies its range, or that could not be read.
38
+ *
39
+ * ```ts
40
+ * import { assertEquals } from '@std/assert'
41
+ * let docs: Record<string, unknown> = {
42
+ * a: { 'dist-tags': { latest: '1.2.0' }, versions: {
43
+ * '1.1.0': {}, '1.2.0': { dependencies: { b: '^2.0.0' } },
44
+ * } },
45
+ * b: { 'dist-tags': { latest: '3.0.0' }, versions: { '2.1.0': {}, '3.0.0': {} } },
46
+ * }
47
+ * let get = (url: string | URL | Request) =>
48
+ * Promise.resolve(Response.json(docs[String(url).split('/').pop()!]))
49
+ * assertEquals(
50
+ * await resolved({ a: '^1.0.0' }, get as typeof fetch, 'https://r.test'),
51
+ * { pins: { a: '1.2.0', b: '2.1.0' }, warnings: [] },
52
+ * )
53
+ * ```
54
+ */ export let resolved = async (want, get = fetch, registry = REGISTRY)=>{
55
+ let pins = {};
56
+ let warnings = [];
57
+ let pending = new Map();
58
+ let ask = (url, read, init)=>asked(get, url, read, init);
59
+ let one = (name, range)=>{
60
+ let running = pending.get(name);
61
+ if (running) return running;
62
+ let work = (async ()=>{
63
+ try {
64
+ let meta = await metadata(ask, documentAt(registry, name), name);
65
+ let version = resolve(range, meta);
66
+ let release = version ? meta.versions[version] : undefined;
67
+ if (!version || !release) {
68
+ warnings.push(`no version of ${name} satisfies ${range}`);
69
+ return;
70
+ }
71
+ pins[name] = version;
72
+ await Promise.all(Object.entries(release.dependencies ?? {}).map(([dep, r])=>one(dep, r)));
73
+ } catch (e) {
74
+ warnings.push(`could not resolve ${name}: ${e.message}`);
75
+ }
76
+ })();
77
+ pending.set(name, work);
78
+ return work;
79
+ };
80
+ await Promise.all(Object.entries(want).map(([name, range])=>one(name, range)));
81
+ return {
82
+ pins,
83
+ warnings
84
+ };
85
+ };
86
+ //# sourceMappingURL=resolve.js.map
package/resolve.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve.js","sources":["./resolve.ts"],"names":[],"mappings":"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"}
package/resolve.ts ADDED
@@ -0,0 +1,144 @@
1
+ // Which version of each npm package a lock pins, as an install chooses them,
2
+ // read from the registry's documents alone: one version of each name, flat,
3
+ // a range read as npm reads it. ./npm.ts installs what these name; a host
4
+ // with no installer (a Worker) pins an app's packages with `resolved` and
5
+ // leaves the tarballs to the compile that first needs each.
6
+ /* @ts-types="npm:@types/semver@^7.8.0" */ import { maxSatisfying } from 'semver'
7
+ import { REGISTRY } from './home.js'
8
+
9
+ // How long the registry has to answer, in ms.
10
+ export let WAIT = 30_000
11
+
12
+ export type Version = {
13
+ dependencies?: Record<string, string>
14
+ dist?: { tarball?: string }
15
+ }
16
+ export type Metadata = {
17
+ 'dist-tags': Record<string, string>
18
+ versions: Record<string, Version>
19
+ }
20
+
21
+ /** The version a range asks for, as npm reads it: a tag, an exact version or
22
+ * the newest the range allows. */
23
+ export let resolve = (range: string, meta: Metadata): string | undefined =>
24
+ range == 'latest' || range == '*'
25
+ ? meta['dist-tags'].latest
26
+ : range in meta.versions
27
+ ? range
28
+ : meta['dist-tags'][range] ??
29
+ maxSatisfying(Object.keys(meta.versions), range) ?? undefined
30
+
31
+ /** A package's document at the registry. */
32
+ export let documentAt = (registry: string, name: string): string =>
33
+ `${registry}/${
34
+ name.startsWith('@') ? `@${encodeURIComponent(name.slice(1))}` : name
35
+ }`
36
+
37
+ /** `url`'s answer read by `read`, or a line saying the registry did not
38
+ * answer within `WAIT`. */
39
+ export let asked = async <T>(
40
+ get: typeof fetch,
41
+ url: string,
42
+ read: (response: Response) => Promise<T>,
43
+ init: RequestInit = {},
44
+ ): Promise<T> => {
45
+ try {
46
+ return await read(
47
+ await get(url, { ...init, signal: AbortSignal.timeout(WAIT) }),
48
+ )
49
+ } catch (e) {
50
+ if ((e as Error).name != 'TimeoutError') throw e
51
+ throw new Error(`the registry did not answer ${url} within ${WAIT / 1000}s`)
52
+ }
53
+ }
54
+
55
+ /** The registry's document for `name`, its abbreviated form. */
56
+ export let metadata = (
57
+ ask: <T>(
58
+ url: string,
59
+ read: (response: Response) => Promise<T>,
60
+ init?: RequestInit,
61
+ ) => Promise<T>,
62
+ url: string,
63
+ name: string,
64
+ ): Promise<Metadata> =>
65
+ ask(url, async (r) => {
66
+ if (r.ok) return await r.json() as Metadata
67
+ await r.body?.cancel()
68
+ throw new Error(
69
+ `the registry answered ${r.status} for "${name}"` +
70
+ (r.status == 404
71
+ ? ' (no such package: check its name in package.json)'
72
+ : ''),
73
+ )
74
+ }, {
75
+ headers: {
76
+ accept:
77
+ 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8',
78
+ },
79
+ })
80
+
81
+ /** The version of each package `want` names (name to range) and of each it
82
+ * needs, one of each name, as ./npm.ts `install` chooses them, asking the
83
+ * registry for documents and never a tarball. `warnings` names each package
84
+ * no version of satisfies its range, or that could not be read.
85
+ *
86
+ * ```ts
87
+ * import { assertEquals } from '@std/assert'
88
+ * let docs: Record<string, unknown> = {
89
+ * a: { 'dist-tags': { latest: '1.2.0' }, versions: {
90
+ * '1.1.0': {}, '1.2.0': { dependencies: { b: '^2.0.0' } },
91
+ * } },
92
+ * b: { 'dist-tags': { latest: '3.0.0' }, versions: { '2.1.0': {}, '3.0.0': {} } },
93
+ * }
94
+ * let get = (url: string | URL | Request) =>
95
+ * Promise.resolve(Response.json(docs[String(url).split('/').pop()!]))
96
+ * assertEquals(
97
+ * await resolved({ a: '^1.0.0' }, get as typeof fetch, 'https://r.test'),
98
+ * { pins: { a: '1.2.0', b: '2.1.0' }, warnings: [] },
99
+ * )
100
+ * ```
101
+ */
102
+ export let resolved = async (
103
+ want: Record<string, string>,
104
+ get: typeof fetch = fetch,
105
+ registry: string = REGISTRY,
106
+ ): Promise<{ pins: Record<string, string>; warnings: string[] }> => {
107
+ let pins: Record<string, string> = {}
108
+ let warnings: string[] = []
109
+ let pending = new Map<string, Promise<void>>()
110
+ let ask = <T>(
111
+ url: string,
112
+ read: (response: Response) => Promise<T>,
113
+ init?: RequestInit,
114
+ ) => asked(get, url, read, init)
115
+ let one = (name: string, range: string): Promise<void> => {
116
+ let running = pending.get(name)
117
+ if (running) return running
118
+ let work = (async () => {
119
+ try {
120
+ let meta = await metadata(ask, documentAt(registry, name), name)
121
+ let version = resolve(range, meta)
122
+ let release = version ? meta.versions[version] : undefined
123
+ if (!version || !release) {
124
+ warnings.push(`no version of ${name} satisfies ${range}`)
125
+ return
126
+ }
127
+ pins[name] = version
128
+ await Promise.all(
129
+ Object.entries(release.dependencies ?? {}).map(([dep, r]) =>
130
+ one(dep, r)
131
+ ),
132
+ )
133
+ } catch (e) {
134
+ warnings.push(`could not resolve ${name}: ${(e as Error).message}`)
135
+ }
136
+ })()
137
+ pending.set(name, work)
138
+ return work
139
+ }
140
+ await Promise.all(
141
+ Object.entries(want).map(([name, range]) => one(name, range)),
142
+ )
143
+ return { pins, warnings }
144
+ }
package/said.js ADDED
@@ -0,0 +1,44 @@
1
+ // What a failed build says, as lines an agent can act on: esbuild's own
2
+ // messages at the place they point, `file:line:column: message` and the line
3
+ // itself beneath, the way a compiler prints them. esbuild names a file by the
4
+ // namespace it loaded it from (`virtual:worker.ts`); the namespace is
5
+ // ./bundle.ts's, not the app's, so it goes.
6
+ /** One esbuild message, the part of it read here. */ /** How many messages a refusal carries: the first ones are the cause, and the
7
+ * rest are usually the same mistake again. */ export let SHOWN = 10;
8
+ let missingExport = /^No matching export in "([^"]+)" for import "([^"]+)"$/;
9
+ /** One message as the agent reads it; the column counts from 1, as an editor
10
+ * does.
11
+ *
12
+ * ```ts
13
+ * import { assertEquals } from '@std/assert'
14
+ * assertEquals(
15
+ * line({ text: 'Unexpected "}"', location: { file: 'virtual:worker.ts',
16
+ * line: 2, column: 49, lineText: ' fetch: () => ok( }' } }),
17
+ * 'worker.ts:2:50: Unexpected "}"\n fetch: () => ok( }',
18
+ * )
19
+ * ```
20
+ */ export let line = ({ text, location: at })=>{
21
+ let missing = missingExport.exec(text);
22
+ if (missing) {
23
+ let [, file, name] = missing;
24
+ file = file.replace(/^virtual:/, '');
25
+ text = `No matching export in "${file}" for import "${name}". Export ${name} from ` + `${file}, or change the import to use a name that file exports.`;
26
+ }
27
+ return at ? `${at.file.replace(/^[a-z-]+:/, '')}:${at.line}:${at.column + 1}: ` + text + (at.lineText ? `\n ${at.lineText}` : '') : text;
28
+ };
29
+ /** What a thrown build error says: esbuild's messages when it carries them,
30
+ * else its own message. */ export let said = (e)=>{
31
+ let errors = e?.errors;
32
+ if (Array.isArray(errors) && errors.length) {
33
+ let shown = errors.slice(0, SHOWN).map(line);
34
+ let more = errors.length - shown.length;
35
+ return more ? [
36
+ ...shown,
37
+ `… and ${more} more`
38
+ ] : shown;
39
+ }
40
+ return [
41
+ e instanceof Error ? e.message : String(e)
42
+ ];
43
+ };
44
+ //# sourceMappingURL=said.js.map
package/said.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"said.js","sources":["./said.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,6EAA6E;AAC7E,8EAA8E;AAC9E,sEAAsE;AACtE,4CAA4C;AAE5C,mDAAmD,GAWnD;4CAC4C,GAC5C,OAAO,IAAI,QAAQ,GAAE;AAErB,IAAI,gBAAgB;AAEpB;;;;;;;;;;;CAWC,GACD,OAAO,IAAI,OAAO,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,EAAW;EAChD,IAAI,UAAU,cAAc,IAAI,CAAC;EACjC,IAAI,SAAS;IACX,IAAI,GAAG,MAAM,KAAK,GAAG;IACrB,OAAO,KAAK,OAAO,CAAC,aAAa;IACjC,OACE,CAAC,uBAAuB,EAAE,KAAK,cAAc,EAAE,KAAK,UAAU,EAAE,KAAK,MAAM,CAAC,GAC5E,GAAG,KAAK,uDAAuD,CAAC;EACpE;EACA,OAAO,KACH,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,CAAC,EAAE,GAAG,MAAM,GAAG,EAAE,EAAE,CAAC,GACnE,OAAO,CAAC,GAAG,QAAQ,GAAG,CAAC,IAAI,EAAE,GAAG,QAAQ,EAAE,GAAG,EAAE,IAC/C;AACN,EAAC;AAED;yBACyB,GACzB,OAAO,IAAI,OAAO,CAAC;EACjB,IAAI,SAAU,GAA8B;EAC5C,IAAI,MAAM,OAAO,CAAC,WAAW,OAAO,MAAM,EAAE;IAC1C,IAAI,QAAQ,OAAO,KAAK,CAAC,GAAG,OAAO,GAAG,CAAC;IACvC,IAAI,OAAO,OAAO,MAAM,GAAG,MAAM,MAAM;IACvC,OAAO,OAAO;SAAI;MAAO,CAAC,MAAM,EAAE,KAAK,KAAK,CAAC;KAAC,GAAG;EACnD;EACA,OAAO;IAAC,aAAa,QAAQ,EAAE,OAAO,GAAG,OAAO;GAAG;AACrD,EAAC"}
package/said.ts ADDED
@@ -0,0 +1,61 @@
1
+ // What a failed build says, as lines an agent can act on: esbuild's own
2
+ // messages at the place they point, `file:line:column: message` and the line
3
+ // itself beneath, the way a compiler prints them. esbuild names a file by the
4
+ // namespace it loaded it from (`virtual:worker.ts`); the namespace is
5
+ // ./bundle.ts's, not the app's, so it goes.
6
+
7
+ /** One esbuild message, the part of it read here. */
8
+ export type Message = {
9
+ text: string
10
+ location?: {
11
+ file: string
12
+ line: number
13
+ column: number
14
+ lineText?: string
15
+ } | null
16
+ }
17
+
18
+ /** How many messages a refusal carries: the first ones are the cause, and the
19
+ * rest are usually the same mistake again. */
20
+ export let SHOWN = 10
21
+
22
+ let missingExport = /^No matching export in "([^"]+)" for import "([^"]+)"$/
23
+
24
+ /** One message as the agent reads it; the column counts from 1, as an editor
25
+ * does.
26
+ *
27
+ * ```ts
28
+ * import { assertEquals } from '@std/assert'
29
+ * assertEquals(
30
+ * line({ text: 'Unexpected "}"', location: { file: 'virtual:worker.ts',
31
+ * line: 2, column: 49, lineText: ' fetch: () => ok( }' } }),
32
+ * 'worker.ts:2:50: Unexpected "}"\n fetch: () => ok( }',
33
+ * )
34
+ * ```
35
+ */
36
+ export let line = ({ text, location: at }: Message) => {
37
+ let missing = missingExport.exec(text)
38
+ if (missing) {
39
+ let [, file, name] = missing
40
+ file = file.replace(/^virtual:/, '')
41
+ text =
42
+ `No matching export in "${file}" for import "${name}". Export ${name} from ` +
43
+ `${file}, or change the import to use a name that file exports.`
44
+ }
45
+ return at
46
+ ? `${at.file.replace(/^[a-z-]+:/, '')}:${at.line}:${at.column + 1}: ` +
47
+ text + (at.lineText ? `\n ${at.lineText}` : '')
48
+ : text
49
+ }
50
+
51
+ /** What a thrown build error says: esbuild's messages when it carries them,
52
+ * else its own message. */
53
+ export let said = (e: unknown): string[] => {
54
+ let errors = (e as { errors?: Message[] })?.errors
55
+ if (Array.isArray(errors) && errors.length) {
56
+ let shown = errors.slice(0, SHOWN).map(line)
57
+ let more = errors.length - shown.length
58
+ return more ? [...shown, `… and ${more} more`] : shown
59
+ }
60
+ return [e instanceof Error ? e.message : String(e)]
61
+ }
package/serve.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { serving } from './compile.ts'
2
+ import { hex } from './home.ts'
3
+ import { shelf, under } from './shelf.ts'
4
+
5
+ // What this compiler is: its own sources and pins, and the Deno running them.
6
+ // What it builds is kept on the shelf under this, so another compiler never
7
+ // takes a build it might make differently.
8
+ let release = async (dir: URL) => {
9
+ let texts = [`deno ${Deno.version.deno}`]
10
+ let names = [...Deno.readDirSync(dir)].map((entry) => entry.name)
11
+ .filter((name) =>
12
+ /\.(?:ts|json)$/.test(name) && !name.endsWith('_test.ts') &&
13
+ name != 'deno.lock'
14
+ ).sort()
15
+ for (let name of names) {
16
+ texts.push(name, await Deno.readTextFile(new URL(name, dir)))
17
+ }
18
+ let bytes = new TextEncoder().encode(texts.join('\0'))
19
+ return hex(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)))
20
+ .slice(0, 16)
21
+ }
22
+
23
+ // The host names its shelf when it starts the container (./container.ts).
24
+ let at = Deno.env.get('SHELF')
25
+ let kept = at ? shelf(at) : undefined
26
+ let shelves = kept && {
27
+ packages: under(kept, 'npm'),
28
+ builds: under(kept, `builds/${await release(new URL('.', import.meta.url))}`),
29
+ }
30
+
31
+ // Cloudflare sends SIGTERM before replacing the container. Finish the jobs
32
+ // already accepted so a rollout need not make their callers build twice.
33
+ let server = Deno.serve({ port: 8080 }, serving(undefined, shelves))
34
+ let stop = () => void server.shutdown()
35
+ Deno.addSignalListener('SIGTERM', stop)
36
+ await server.finished
37
+ Deno.removeSignalListener('SIGTERM', stop)
package/sha256.js ADDED
@@ -0,0 +1,7 @@
1
+ // Bytes named by their SHA-256, with nothing else imported, so the compiler's
2
+ // container, the Worker in front of it and the kernel share it.
3
+ /** Bytes as lowercase hex. */ export let hex = (bytes)=>[
4
+ ...bytes
5
+ ].map((n)=>n.toString(16).padStart(2, '0')).join('');
6
+ /** The SHA-256 of some bytes, as lowercase hex. */ export let sha256 = async (bytes)=>hex(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)));
7
+ //# sourceMappingURL=sha256.js.map
package/sha256.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sha256.js","sources":["./sha256.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,gEAAgE;AAEhE,4BAA4B,GAC5B,OAAO,IAAI,MAAM,CAAC,QAChB;OAAI;GAAM,CAAC,GAAG,CAAC,CAAC,IAAM,EAAE,QAAQ,CAAC,IAAI,QAAQ,CAAC,GAAG,MAAM,IAAI,CAAC,IAAG;AAEjE,iDAAiD,GACjD,OAAO,IAAI,SAAS,OAAO,QACzB,IAAI,IAAI,WAAW,MAAM,OAAO,MAAM,CAAC,MAAM,CAAC,WAAW,SAAQ"}
package/sha256.ts ADDED
@@ -0,0 +1,10 @@
1
+ // Bytes named by their SHA-256, with nothing else imported, so the compiler's
2
+ // container, the Worker in front of it and the kernel share it.
3
+
4
+ /** Bytes as lowercase hex. */
5
+ export let hex = (bytes: Uint8Array) =>
6
+ [...bytes].map((n) => n.toString(16).padStart(2, '0')).join('')
7
+
8
+ /** The SHA-256 of some bytes, as lowercase hex. */
9
+ export let sha256 = async (bytes: Uint8Array<ArrayBuffer>) =>
10
+ hex(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)))