@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.
- package/LICENSE +202 -0
- package/README.md +450 -2
- package/_dist/bundle.d.ts +6 -0
- package/_dist/bundle.d.ts.map +1 -0
- package/_dist/compile.d.ts +72 -0
- package/_dist/compile.d.ts.map +1 -0
- package/_dist/dependencies.d.ts +15 -0
- package/_dist/dependencies.d.ts.map +1 -0
- package/_dist/file.d.ts +185 -0
- package/_dist/file.d.ts.map +1 -0
- package/_dist/graph.d.ts +104 -0
- package/_dist/graph.d.ts.map +1 -0
- package/_dist/home.d.ts +15 -0
- package/_dist/home.d.ts.map +1 -0
- package/_dist/link.d.ts +192 -0
- package/_dist/link.d.ts.map +1 -0
- package/_dist/lock.d.ts +30 -0
- package/_dist/lock.d.ts.map +1 -0
- package/_dist/mod.d.ts +6 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/pack.d.ts +42 -0
- package/_dist/pack.d.ts.map +1 -0
- package/_dist/package.d.ts +11 -0
- package/_dist/package.d.ts.map +1 -0
- package/_dist/plan.d.ts +135 -0
- package/_dist/plan.d.ts.map +1 -0
- package/_dist/platform.d.ts +27 -0
- package/_dist/platform.d.ts.map +1 -0
- package/_dist/resolve.d.ts +42 -0
- package/_dist/resolve.d.ts.map +1 -0
- package/_dist/shelf.d.ts +11 -0
- package/_dist/shelf.d.ts.map +1 -0
- package/_dist/strip.d.ts +51 -0
- package/_dist/strip.d.ts.map +1 -0
- package/_dist/timing.d.ts +6 -0
- package/_dist/timing.d.ts.map +1 -0
- package/_dist/unpack.d.ts +14 -0
- package/_dist/unpack.d.ts.map +1 -0
- package/analysis.js +72 -0
- package/analysis.js.map +1 -0
- package/analysis.ts +82 -0
- package/bundle.js +320 -0
- package/bundle.js.map +1 -0
- package/bundle.ts +415 -0
- package/common.js +129 -0
- package/common.js.map +1 -0
- package/common.ts +138 -0
- package/compile.js +500 -0
- package/compile.js.map +1 -0
- package/compile.ts +622 -0
- package/container.js +142 -0
- package/container.js.map +1 -0
- package/container.ts +183 -0
- package/deno.json +1 -0
- package/dependencies.js +31 -0
- package/dependencies.js.map +1 -0
- package/dependencies.ts +40 -0
- package/file.js +303 -0
- package/file.js.map +1 -0
- package/file.ts +443 -0
- package/forward.ts +49 -0
- package/graph.js +297 -0
- package/graph.js.map +1 -0
- package/graph.ts +360 -0
- package/home.js +40 -0
- package/home.js.map +1 -0
- package/home.ts +52 -0
- package/link.js +455 -0
- package/link.js.map +1 -0
- package/link.ts +596 -0
- package/lock.js +129 -0
- package/lock.js.map +1 -0
- package/lock.ts +161 -0
- package/mod.js +14 -0
- package/mod.js.map +1 -0
- package/mod.ts +43 -0
- package/npm.js +362 -0
- package/npm.js.map +1 -0
- package/npm.ts +429 -0
- package/pack.js +188 -0
- package/pack.js.map +1 -0
- package/pack.ts +225 -0
- package/package.js +199 -0
- package/package.js.map +1 -0
- package/package.json +60 -4
- package/package.ts +255 -0
- package/plan.js +273 -0
- package/plan.js.map +1 -0
- package/plan.ts +395 -0
- package/platform.js +160 -0
- package/platform.js.map +1 -0
- package/platform.ts +238 -0
- package/resolve.js +86 -0
- package/resolve.js.map +1 -0
- package/resolve.ts +144 -0
- package/said.js +44 -0
- package/said.js.map +1 -0
- package/said.ts +61 -0
- package/serve.ts +37 -0
- package/sha256.js +7 -0
- package/sha256.js.map +1 -0
- package/sha256.ts +10 -0
- package/shared.js +646 -0
- package/shared.js.map +1 -0
- package/shared.ts +813 -0
- package/shelf.js +73 -0
- package/shelf.js.map +1 -0
- package/shelf.ts +110 -0
- package/strip.js +114 -0
- package/strip.js.map +1 -0
- package/strip.ts +117 -0
- package/tar.js +87 -0
- package/tar.js.map +1 -0
- package/tar.ts +99 -0
- package/timing.js +37 -0
- package/timing.js.map +1 -0
- package/timing.ts +71 -0
- package/unpack.js +40 -0
- package/unpack.js.map +1 -0
- package/unpack.ts +60 -0
- package/used.js +91 -0
- package/used.js.map +1 -0
- package/used.ts +116 -0
package/compile.ts
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
// The compile itself: npm packages installed at the pinned versions
|
|
2
|
+
// (./npm.ts) alongside compiler-owned toolkit sources, then esbuild bundling
|
|
3
|
+
// the worker and each page script (./bundle.ts). esbuild is native, a process
|
|
4
|
+
// of its own beside this one, so the compile runs wherever a process can start
|
|
5
|
+
// one: under Deno, and for yaks.app in a container. `default` is that
|
|
6
|
+
// container's server: it takes a {@link Job} and answers an {@link Answer}.
|
|
7
|
+
//
|
|
8
|
+
// It is handed app files and the toolkit catalog, and caches shared browser
|
|
9
|
+
// modules across jobs. It holds no binding, secret or store; the npm registry
|
|
10
|
+
// is the one thing it reaches.
|
|
11
|
+
//
|
|
12
|
+
// What is left of an output's imports once esbuild is done is checked here,
|
|
13
|
+
// because a build leaves any import it cannot resolve as an import rather
|
|
14
|
+
// than failing: in a worker that is a module the upload refuses, and in a
|
|
15
|
+
// page it is a request the browser makes for nothing.
|
|
16
|
+
import { parse } from 'es-module-lexer/js'
|
|
17
|
+
import { isBuiltin } from 'node:module'
|
|
18
|
+
import { posix } from 'node:path'
|
|
19
|
+
import { bundle, type Options, packaged, Stopped } from './bundle.js'
|
|
20
|
+
import { PACKED_BY, REPLACED, sealed, UNKNOWN } from './container.js'
|
|
21
|
+
import { packageOf, relative, resolved, twins } from './graph.js'
|
|
22
|
+
import { lockfile, type Pins, pins, reached, split, wanted } from './lock.js'
|
|
23
|
+
import * as npm from './npm.js'
|
|
24
|
+
import { type Answer, type Ask, dependencies } from './plan.js'
|
|
25
|
+
import { said } from './said.js'
|
|
26
|
+
import {
|
|
27
|
+
external,
|
|
28
|
+
flat,
|
|
29
|
+
forget as forgetShared,
|
|
30
|
+
pack,
|
|
31
|
+
shared,
|
|
32
|
+
unexported,
|
|
33
|
+
} from './shared.js'
|
|
34
|
+
import { header, phase, type Report, type Timing } from './timing.js'
|
|
35
|
+
import { type Shelves, timed } from './shelf.js'
|
|
36
|
+
import { homes, REGISTRY } from './home.js'
|
|
37
|
+
import {
|
|
38
|
+
type Catalog,
|
|
39
|
+
located,
|
|
40
|
+
packageFor,
|
|
41
|
+
type Seed,
|
|
42
|
+
seed,
|
|
43
|
+
type Toolkit,
|
|
44
|
+
urlOf,
|
|
45
|
+
} from './platform.js'
|
|
46
|
+
import { packageKey, packageName, PACKER, Unexported } from './file.js'
|
|
47
|
+
import { type Compiled, packageModules } from './package.js'
|
|
48
|
+
import { type PackJob, packModules, Unpackable } from './pack.js'
|
|
49
|
+
/* @ts-types="npm:@types/semver@^7.8.0" */ import { valid } from 'semver'
|
|
50
|
+
export type { Catalog, Toolkit } from './platform.js'
|
|
51
|
+
export { Stopped } from './bundle.js'
|
|
52
|
+
|
|
53
|
+
/** What a host posts to the compiler's server: the app's ask, and beside it
|
|
54
|
+
* the toolkit catalog, which the host supplies and an app never does. */
|
|
55
|
+
export type Job = {
|
|
56
|
+
ask: Ask
|
|
57
|
+
catalog: Catalog
|
|
58
|
+
origin?: string
|
|
59
|
+
/** The host can store and serve content-addressed browser modules. */
|
|
60
|
+
shared?: boolean
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** What a host posts to have one package version compiled for the whole
|
|
64
|
+
* platform (D-499): an npm package at an exact version, or a toolkit
|
|
65
|
+
* package at its catalog version, with its sources. */
|
|
66
|
+
export type PackageJob = {
|
|
67
|
+
package: {
|
|
68
|
+
name: string
|
|
69
|
+
version: string
|
|
70
|
+
toolkit?: Toolkit
|
|
71
|
+
/** A specifier a pattern export matches, built alone. */
|
|
72
|
+
subpath?: string
|
|
73
|
+
}
|
|
74
|
+
origin: string
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A package compiled for the platform, and the tarball each npm package
|
|
78
|
+
* home its modules name is filled from, by its SHA-256 (./home.ts). */
|
|
79
|
+
export type CompiledPackage = Compiled & { tarballs: Record<string, string> }
|
|
80
|
+
|
|
81
|
+
/** Compile one package version on its own (./package.ts): nothing it
|
|
82
|
+
* imports is installed, since every import of another package stays bare.
|
|
83
|
+
* A toolkit package's resources are kept beside its modules, under its
|
|
84
|
+
* package's name; an npm package's are served from its home on `origin`. */
|
|
85
|
+
export let compilePackage = async (
|
|
86
|
+
{ package: { name, version, toolkit, subpath }, origin }: PackageJob,
|
|
87
|
+
{ get = fetch, shelves }: { get?: typeof fetch; shelves?: Shelves } = {},
|
|
88
|
+
): Promise<CompiledPackage> => {
|
|
89
|
+
let key = packageKey(name, version, subpath)
|
|
90
|
+
let fs = new npm.Files()
|
|
91
|
+
let root = `node_modules/${name}/`
|
|
92
|
+
if (toolkit) {
|
|
93
|
+
if (toolkit.version != version) {
|
|
94
|
+
throw new Error(`${name} is at ${toolkit.version} here, not ${version}`)
|
|
95
|
+
}
|
|
96
|
+
// Its resources are the version's, whichever build asks.
|
|
97
|
+
let base = await packageName(packageKey(name, version))
|
|
98
|
+
fs = new npm.Files(
|
|
99
|
+
Object.fromEntries(
|
|
100
|
+
Object.entries(toolkit.files).map(([path, text]) => [
|
|
101
|
+
root + path,
|
|
102
|
+
text,
|
|
103
|
+
]),
|
|
104
|
+
),
|
|
105
|
+
)
|
|
106
|
+
let built = await packageModules(fs, name, key, {
|
|
107
|
+
moved: (path) => urlOf(`./${base}/${path.slice(root.length)}`),
|
|
108
|
+
subpath,
|
|
109
|
+
})
|
|
110
|
+
for (let [path, text] of Object.entries(toolkit.resources ?? {})) {
|
|
111
|
+
built.modules[`${base}/${path}`] = text
|
|
112
|
+
}
|
|
113
|
+
return { ...built, tarballs: {} }
|
|
114
|
+
}
|
|
115
|
+
if (!valid(version)) {
|
|
116
|
+
throw new Error(`${name}@${version} is not an exact version`)
|
|
117
|
+
}
|
|
118
|
+
let { warnings } = await npm.install(fs, { [name]: version }, get, REGISTRY, {
|
|
119
|
+
shelf: shelves?.packages,
|
|
120
|
+
alone: true,
|
|
121
|
+
})
|
|
122
|
+
if (fs.read(`${root}package.json`) == null) {
|
|
123
|
+
throw new Error(warnings.join('; ') || `${key} did not install`)
|
|
124
|
+
}
|
|
125
|
+
let home = homes((n) => fs.tarball(n), origin)
|
|
126
|
+
let built = await packageModules(fs, name, key, {
|
|
127
|
+
moved: home.moved,
|
|
128
|
+
subpath,
|
|
129
|
+
})
|
|
130
|
+
return { ...built, tarballs: home.tarballs }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The module a compiled worker is uploaded as: its source's path, as
|
|
134
|
+
* JavaScript.
|
|
135
|
+
*
|
|
136
|
+
* ```ts
|
|
137
|
+
* import { assertEquals } from '@std/assert'
|
|
138
|
+
* assertEquals(compiledName('src/worker.ts'), 'src/worker.js')
|
|
139
|
+
* assertEquals(compiledName('worker.mjs'), 'worker.mjs')
|
|
140
|
+
* ```
|
|
141
|
+
*/
|
|
142
|
+
export let compiledName = (entry: string): string =>
|
|
143
|
+
entry.replace(/\.(?:ts|tsx|jsx|mts|cts|cjs)$/, '.js')
|
|
144
|
+
|
|
145
|
+
/** The specifiers still imported by a compiled module. */
|
|
146
|
+
let imports = (code: string) =>
|
|
147
|
+
parse(code)[0].map((i) => i.n).filter((n): n is string => !!n)
|
|
148
|
+
|
|
149
|
+
// A package the lock can be read from: its own package.json's dependencies.
|
|
150
|
+
let needs = (fs: npm.Files) => (name: string) => {
|
|
151
|
+
try {
|
|
152
|
+
let pkg = JSON.parse(fs.read(`node_modules/${name}/package.json`) ?? '{}')
|
|
153
|
+
return Object.keys(pkg.dependencies ?? {})
|
|
154
|
+
} catch {
|
|
155
|
+
return []
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Install what package.json asks at what the lock pins, and say the lock
|
|
160
|
+
* that results. Throws what the installer could not do. */
|
|
161
|
+
let install = async (
|
|
162
|
+
fs: npm.Files,
|
|
163
|
+
ask: Ask,
|
|
164
|
+
setup: Seed,
|
|
165
|
+
catalog: Catalog,
|
|
166
|
+
get?: typeof fetch,
|
|
167
|
+
report?: Report,
|
|
168
|
+
shelves?: Shelves,
|
|
169
|
+
) => {
|
|
170
|
+
let pkg = ask.files['package.json'] ?? null
|
|
171
|
+
let ranges = dependencies(pkg)
|
|
172
|
+
let want = wanted(
|
|
173
|
+
setup.dependencies,
|
|
174
|
+
pins(ask.files['package-lock.json'] ?? null),
|
|
175
|
+
)
|
|
176
|
+
let { installed, warnings } = await npm.install(
|
|
177
|
+
fs,
|
|
178
|
+
want,
|
|
179
|
+
get,
|
|
180
|
+
npm.REGISTRY,
|
|
181
|
+
{
|
|
182
|
+
report: report && ((ms) => report('registry', ms)),
|
|
183
|
+
shelf: shelves?.packages,
|
|
184
|
+
},
|
|
185
|
+
)
|
|
186
|
+
if (warnings.length) {
|
|
187
|
+
throw new Error(warnings.map((w) => `npm: ${w}`).join('\n'))
|
|
188
|
+
}
|
|
189
|
+
let all: Pins = {
|
|
190
|
+
...Object.fromEntries(installed.map(split)),
|
|
191
|
+
...setup.platform,
|
|
192
|
+
}
|
|
193
|
+
let needed = needs(fs)
|
|
194
|
+
let kept = reached(
|
|
195
|
+
Object.keys(ranges),
|
|
196
|
+
all,
|
|
197
|
+
(name) =>
|
|
198
|
+
name in setup.platform
|
|
199
|
+
? Object.keys(catalog[name].dependencies).flatMap((spec) =>
|
|
200
|
+
packageFor(setup, spec) ?? []
|
|
201
|
+
)
|
|
202
|
+
: needed(name),
|
|
203
|
+
)
|
|
204
|
+
let name = pkg == null ? undefined : JSON.parse(pkg).name
|
|
205
|
+
return {
|
|
206
|
+
installed: Object.entries(kept).map(([n, v]) => `${n}@${v}`).sort(),
|
|
207
|
+
lock: pkg == null ? undefined : lockfile(name, ranges, kept),
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// A `.js` import meaning a TypeScript file that was sent: esbuild's own
|
|
212
|
+
// resolver reads that convention, and ./bundle.ts, which resolves the
|
|
213
|
+
// extension it is given, does not.
|
|
214
|
+
let twin = (ask: Ask, at: string, spec: string) => {
|
|
215
|
+
let typed = twins(at).find((t) => t in ask.files)
|
|
216
|
+
return typed
|
|
217
|
+
? `imports ${spec}, which is ${typed}: write the import with the ` +
|
|
218
|
+
`file's own extension, or with none`
|
|
219
|
+
: null
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Why a worker's leftover import will not link, or null when it will.
|
|
223
|
+
let unlinked = (ask: Ask, main: string, catalog: Catalog) => (spec: string) => {
|
|
224
|
+
let { flags, carry } = ask.worker!
|
|
225
|
+
if (spec.startsWith('cloudflare:') || spec.startsWith('node:')) return null
|
|
226
|
+
if (flags.includes('nodejs_compat') && isBuiltin(spec)) return null
|
|
227
|
+
let name = packageOf(spec)
|
|
228
|
+
if (name?.startsWith('@yaks/')) {
|
|
229
|
+
let pkg = catalog[name]
|
|
230
|
+
let hit = pkg && packaged(
|
|
231
|
+
{
|
|
232
|
+
read: (path) =>
|
|
233
|
+
pkg.files[path.slice(`node_modules/${name}/`.length)] ?? null,
|
|
234
|
+
},
|
|
235
|
+
spec,
|
|
236
|
+
{ node: flags.includes('nodejs_compat') },
|
|
237
|
+
)
|
|
238
|
+
return hit
|
|
239
|
+
? `imports ${spec}. Add "${name}": "platform" to package.json dependencies and keep the @yaks/ import. A page's import map only applies to page scripts.`
|
|
240
|
+
: `imports ${spec}, which is unavailable to apps. Use an @yaks/ module exposed to apps or replace this import. A page's import map only applies to page scripts.`
|
|
241
|
+
}
|
|
242
|
+
if (name) {
|
|
243
|
+
return `imports ${spec}, which is not installed: name ${name} in ` +
|
|
244
|
+
'package.json dependencies'
|
|
245
|
+
}
|
|
246
|
+
if (!relative(spec)) return `imports ${spec}, which no worker can load`
|
|
247
|
+
let at = resolved(main, spec)
|
|
248
|
+
if (carry.includes(at)) return null
|
|
249
|
+
return twin(ask, at, spec) ?? `imports ${spec}, which names no file`
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// A page's leftover import is the browser's to fetch, the way every page
|
|
253
|
+
// fetches ./api/client.js, unless it meant a file that was compiled in.
|
|
254
|
+
let unfetched = (ask: Ask, entry: string) => (spec: string) =>
|
|
255
|
+
relative(spec) ? twin(ask, resolved(entry, spec), spec) : null
|
|
256
|
+
|
|
257
|
+
/// browserless('import"node:fs";import"https://o/a.js";import("node:os")') -> ['node:fs']
|
|
258
|
+
/** The modules a page imports statically that no browser has: Node's
|
|
259
|
+
* built-ins, which a module written for the toolkit's other hosts can reach.
|
|
260
|
+
* A browser links a page's whole static graph before it runs a line of it, so
|
|
261
|
+
* one such import anywhere in the graph stops the page (yak.sh v50, whose
|
|
262
|
+
* @yaks/cli/terminal reached node:fs). `code` is the page as served, with
|
|
263
|
+
* every shared module it reaches named ({@link flat}); a dynamic import is
|
|
264
|
+
* fetched only when it runs, so the code that asks for it decides. */
|
|
265
|
+
export let browserless = (code: string): string[] => [
|
|
266
|
+
...new Set(
|
|
267
|
+
parse(code)[0].flatMap((i) =>
|
|
268
|
+
i.d == -1 && i.n?.startsWith('node:') ? [i.n] : []
|
|
269
|
+
),
|
|
270
|
+
),
|
|
271
|
+
]
|
|
272
|
+
|
|
273
|
+
// Why a page will not link in a browser for a Node built-in it reaches, naming
|
|
274
|
+
// the page or the shared modules (by the specifier the page imports them by)
|
|
275
|
+
// that import it; empty when it reaches none.
|
|
276
|
+
let nodeOnly = (
|
|
277
|
+
entry: string,
|
|
278
|
+
code: string,
|
|
279
|
+
page: string,
|
|
280
|
+
shared: Record<string, string> = {},
|
|
281
|
+
urls: Record<string, string>,
|
|
282
|
+
origin: string,
|
|
283
|
+
): string[] => {
|
|
284
|
+
let node = browserless(page)
|
|
285
|
+
if (!node.length) return []
|
|
286
|
+
let names = new Map(Object.entries(urls).map(([spec, url]) => [url, spec]))
|
|
287
|
+
let reached = new Set(parse(page)[0].map((i) => i.n))
|
|
288
|
+
let from = [
|
|
289
|
+
...browserless(code).length ? [entry] : [],
|
|
290
|
+
...Object.entries(shared)
|
|
291
|
+
.filter(([path, text]) =>
|
|
292
|
+
reached.has(`${origin}/${path}`) && browserless(text).length
|
|
293
|
+
)
|
|
294
|
+
.map(([path]) => names.get(`${origin}/${path}`) ?? path),
|
|
295
|
+
]
|
|
296
|
+
return [
|
|
297
|
+
`imports ${node.join(', ')} through ${from.join(', ')}, and no browser ` +
|
|
298
|
+
'has it: a module the page loads is written for a server',
|
|
299
|
+
]
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/// realms(['a', 'b', 'c', 'w'], [['a', 'b'], ['b', 'c', 'x']]) -> [['a', 'b', 'c'], ['w']]
|
|
303
|
+
/// realms(['a', 'w'], undefined) -> [['a'], ['w']]
|
|
304
|
+
/** The pages that share one pack: those an HTML page loads together, joined
|
|
305
|
+
* through a page two HTML pages load. */
|
|
306
|
+
export let realms = (
|
|
307
|
+
pages: string[],
|
|
308
|
+
together: string[][] = [],
|
|
309
|
+
): string[][] => {
|
|
310
|
+
let of = new Map(pages.map((page) => [page, new Set([page])]))
|
|
311
|
+
for (let group of together) {
|
|
312
|
+
let joined = new Set(group.flatMap((page) => [...of.get(page) ?? []]))
|
|
313
|
+
for (let page of joined) of.set(page, joined)
|
|
314
|
+
}
|
|
315
|
+
return [...new Set(of.values())].map((realm) => [...realm])
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
let checked = (
|
|
319
|
+
entry: string,
|
|
320
|
+
code: string,
|
|
321
|
+
why: (spec: string) => string | null,
|
|
322
|
+
) =>
|
|
323
|
+
imports(code).map(why).filter((w): w is string => !!w).map((w) =>
|
|
324
|
+
`${entry} ${w}`
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
/** Compile what an ask names. Never throws for the app's own mistakes: those
|
|
328
|
+
* are the answer's `errors`. Throws {@link Stopped} when esbuild's process
|
|
329
|
+
* ends under a build, which is the compiler's room and not the app's code.
|
|
330
|
+
* The host supplies its toolkit catalog separately from the app's ask, and
|
|
331
|
+
* `get` is how the npm registry is fetched. */
|
|
332
|
+
export let compile = async (
|
|
333
|
+
ask: Ask,
|
|
334
|
+
catalog: Catalog = {},
|
|
335
|
+
origin = 'https://yaks.app',
|
|
336
|
+
options: {
|
|
337
|
+
shared?: boolean
|
|
338
|
+
get?: typeof fetch
|
|
339
|
+
timing?: boolean
|
|
340
|
+
shelves?: Shelves
|
|
341
|
+
} = {},
|
|
342
|
+
): Promise<Answer> => {
|
|
343
|
+
let timing: Timing | undefined = options.timing
|
|
344
|
+
? {
|
|
345
|
+
install: 0,
|
|
346
|
+
registry: 0,
|
|
347
|
+
shelf: 0,
|
|
348
|
+
worker: 0,
|
|
349
|
+
carried: 0,
|
|
350
|
+
used: 0,
|
|
351
|
+
groups: 0,
|
|
352
|
+
cache: 0,
|
|
353
|
+
pages: 0,
|
|
354
|
+
total: 0,
|
|
355
|
+
hits: 0,
|
|
356
|
+
misses: 0,
|
|
357
|
+
}
|
|
358
|
+
: undefined
|
|
359
|
+
let report: Report | undefined = timing
|
|
360
|
+
? (name, ms) => {
|
|
361
|
+
timing![name] += ms
|
|
362
|
+
}
|
|
363
|
+
: undefined
|
|
364
|
+
let total = phase(report, 'total')
|
|
365
|
+
let shelves = options.shelves &&
|
|
366
|
+
timed(options.shelves, report && ((ms) => report('shelf', ms)))
|
|
367
|
+
let done = (answer: Answer) => {
|
|
368
|
+
total()
|
|
369
|
+
return answer
|
|
370
|
+
}
|
|
371
|
+
origin = origin.replace(/\/$/, '')
|
|
372
|
+
let tarballs: Record<string, string> = {}
|
|
373
|
+
let answer: Answer = {
|
|
374
|
+
...(timing ? { timing } : {}),
|
|
375
|
+
pages: {},
|
|
376
|
+
assets: {},
|
|
377
|
+
tarballs,
|
|
378
|
+
installed: [],
|
|
379
|
+
notes: [],
|
|
380
|
+
errors: [],
|
|
381
|
+
}
|
|
382
|
+
let fs: npm.Files
|
|
383
|
+
let setup: Seed
|
|
384
|
+
let installing = phase(report, 'install')
|
|
385
|
+
try {
|
|
386
|
+
setup = seed(ask.files, catalog)
|
|
387
|
+
answer.notes.push(...setup.notes)
|
|
388
|
+
answer.assets = options.shared === false || ask.worker || !ask.pages.length
|
|
389
|
+
? setup.assets
|
|
390
|
+
: {}
|
|
391
|
+
fs = new npm.Files(setup.files)
|
|
392
|
+
Object.assign(
|
|
393
|
+
answer,
|
|
394
|
+
await install(fs, ask, setup, catalog, options.get, report, shelves),
|
|
395
|
+
)
|
|
396
|
+
} catch (e) {
|
|
397
|
+
installing()
|
|
398
|
+
return done({ ...answer, errors: said(e) })
|
|
399
|
+
} finally {
|
|
400
|
+
installing()
|
|
401
|
+
}
|
|
402
|
+
let locate = (entry: string | URL) => {
|
|
403
|
+
for (let [path, source] of Object.entries(located(setup.files, entry))) {
|
|
404
|
+
fs.write(path, source)
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
// One entry built, its package URLs located against `at` and its leftover
|
|
408
|
+
// imports judged by `why`; null when it failed, and the failure is among
|
|
409
|
+
// the answer's errors.
|
|
410
|
+
let built = async (
|
|
411
|
+
entry: string,
|
|
412
|
+
at: string | URL,
|
|
413
|
+
options: Options,
|
|
414
|
+
why: (spec: string) => string | null,
|
|
415
|
+
) => {
|
|
416
|
+
try {
|
|
417
|
+
locate(at)
|
|
418
|
+
let { code, warnings } = await bundle(fs, entry, {
|
|
419
|
+
packages: setup.aliases,
|
|
420
|
+
jsxImportSource: setup.jsxImportSource,
|
|
421
|
+
...options,
|
|
422
|
+
})
|
|
423
|
+
answer.errors.push(...checked(entry, code, why))
|
|
424
|
+
answer.notes.push(...warnings.map((w) => `${entry}: ${w}`))
|
|
425
|
+
return code
|
|
426
|
+
} catch (e) {
|
|
427
|
+
if (e instanceof Stopped) throw e
|
|
428
|
+
answer.errors.push(...said(e))
|
|
429
|
+
return null
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
// Shared modules are built before any entry locates the toolkit's sources
|
|
433
|
+
// for itself (`locate`), so they read them, and their kept analysis
|
|
434
|
+
// finds them, as seeded, whichever entries this compile builds.
|
|
435
|
+
let urls: Record<string, string> = {}
|
|
436
|
+
let unshared = false
|
|
437
|
+
if (ask.pages.length && options.shared !== false) {
|
|
438
|
+
try {
|
|
439
|
+
let modules = await shared(fs, setup, catalog, origin, ask.pages, {
|
|
440
|
+
timing: report,
|
|
441
|
+
shelves,
|
|
442
|
+
})
|
|
443
|
+
answer.shared = modules.files
|
|
444
|
+
Object.assign(tarballs, modules.tarballs)
|
|
445
|
+
urls = modules.urls
|
|
446
|
+
} catch (e) {
|
|
447
|
+
if (e instanceof Stopped) throw e
|
|
448
|
+
answer.errors.push(...said(e))
|
|
449
|
+
unshared = true
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (ask.worker) {
|
|
453
|
+
let finish = phase(report, 'worker')
|
|
454
|
+
try {
|
|
455
|
+
let { entry, flags, carry } = ask.worker
|
|
456
|
+
let main = compiledName(entry)
|
|
457
|
+
let separate = new Set(carry)
|
|
458
|
+
let code = await built(
|
|
459
|
+
entry,
|
|
460
|
+
// A workerd module name is not a URL. Its file URL is a logical
|
|
461
|
+
// identity, not a hosted asset address; a page keeps its browser's URL.
|
|
462
|
+
new URL(main, 'file:///'),
|
|
463
|
+
{
|
|
464
|
+
node: flags.includes('nodejs_compat'),
|
|
465
|
+
external: (spec, importer, attributes) => {
|
|
466
|
+
if (attributes.type == 'text' || !relative(spec)) return
|
|
467
|
+
let path = resolved(importer, spec)
|
|
468
|
+
if (!separate.has(path)) return
|
|
469
|
+
let moved = posix.relative(posix.dirname(main), path)
|
|
470
|
+
return relative(moved) ? moved : './' + moved
|
|
471
|
+
},
|
|
472
|
+
},
|
|
473
|
+
unlinked(ask, main, catalog),
|
|
474
|
+
)
|
|
475
|
+
if (code != null) answer.worker = { main, code }
|
|
476
|
+
} finally {
|
|
477
|
+
finish()
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
if (unshared) return done(answer)
|
|
481
|
+
// A page's npm package module is served from its package's home.
|
|
482
|
+
let pages = phase(report, 'pages')
|
|
483
|
+
let codes: Record<string, string> = {}
|
|
484
|
+
try {
|
|
485
|
+
let home = homes((name) => fs.tarball(name), origin)
|
|
486
|
+
for (let entry of ask.pages) {
|
|
487
|
+
let code = await built(entry, entry, {
|
|
488
|
+
minify: true,
|
|
489
|
+
moved: home.moved,
|
|
490
|
+
...options.shared !== false
|
|
491
|
+
? { external: external(urls, ask.mapped?.[entry]) }
|
|
492
|
+
: {},
|
|
493
|
+
// What a package written for bundlers asks of its environment.
|
|
494
|
+
define: { 'process.env.NODE_ENV': '"production"' },
|
|
495
|
+
}, unfetched(ask, entry))
|
|
496
|
+
if (code == null) continue
|
|
497
|
+
let missing = unexported(code, answer.shared ?? {}, origin, urls)
|
|
498
|
+
let page = flat(code, answer.shared ?? {}, origin)
|
|
499
|
+
missing.push(...nodeOnly(entry, code, page, answer.shared, urls, origin))
|
|
500
|
+
if (missing.length) {
|
|
501
|
+
answer.errors.push(...missing.map((line) => `${entry}: ${line}`))
|
|
502
|
+
} else codes[entry] = code
|
|
503
|
+
}
|
|
504
|
+
Object.assign(tarballs, home.tarballs)
|
|
505
|
+
// Scripts an HTML page loads together import one pack, so a module two
|
|
506
|
+
// of them import is one instance; another script, a module worker
|
|
507
|
+
// included, gets its own, and evaluates only what it imports.
|
|
508
|
+
for (let realm of realms(Object.keys(codes), ask.together)) {
|
|
509
|
+
let packed = await pack(
|
|
510
|
+
Object.fromEntries(realm.map((entry) => [entry, codes[entry]])),
|
|
511
|
+
answer.shared ?? {},
|
|
512
|
+
origin,
|
|
513
|
+
)
|
|
514
|
+
if (answer.shared) Object.assign(answer.shared, packed.files)
|
|
515
|
+
Object.assign(answer.pages, packed.pages)
|
|
516
|
+
}
|
|
517
|
+
} catch (e) {
|
|
518
|
+
if (e instanceof Stopped) throw e
|
|
519
|
+
answer.errors.push(...said(e))
|
|
520
|
+
} finally {
|
|
521
|
+
pages()
|
|
522
|
+
}
|
|
523
|
+
return done(answer)
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** Forget every cache memory holds, as a container that restarts does: the
|
|
527
|
+
* shelves are what is left. */
|
|
528
|
+
export let forget = (): void => {
|
|
529
|
+
npm.forget()
|
|
530
|
+
forgetShared()
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
type FetchJob = (req: Request) => Promise<Response>
|
|
534
|
+
|
|
535
|
+
/** The compiler's server, every answer sealed with its body's digest
|
|
536
|
+
* (./container.ts `sealed`). Losing the esbuild subprocess interrupts the job.
|
|
537
|
+
* esbuild's API reports a closed service channel without an exit reason.
|
|
538
|
+
* `shelves` keep what it fetches and builds beyond its container. */
|
|
539
|
+
export let serving = (
|
|
540
|
+
build: typeof compile = compile,
|
|
541
|
+
shelves?: Shelves,
|
|
542
|
+
): FetchJob =>
|
|
543
|
+
async (req) => sealed(await answered(build, shelves, req))
|
|
544
|
+
|
|
545
|
+
let answered = async (
|
|
546
|
+
build: typeof compile,
|
|
547
|
+
shelves: Shelves | undefined,
|
|
548
|
+
req: Request,
|
|
549
|
+
) => {
|
|
550
|
+
if (req.method != 'POST') return new Response('POST a job', { status: 405 })
|
|
551
|
+
let began = performance.now()
|
|
552
|
+
let job = await req.json() as Job | PackageJob | PackJob
|
|
553
|
+
if ('package' in job) return await packageAnswer(job, shelves)
|
|
554
|
+
if ('pack' in job) return await packAnswer(job)
|
|
555
|
+
if (!('ask' in job)) {
|
|
556
|
+
return new Response('the compiler knows no such job', { status: UNKNOWN })
|
|
557
|
+
}
|
|
558
|
+
let { ask, catalog, origin, shared } = job
|
|
559
|
+
let parsed = performance.now() - began
|
|
560
|
+
try {
|
|
561
|
+
let answer = await build(ask, catalog, origin, {
|
|
562
|
+
shared: shared === true,
|
|
563
|
+
timing: true,
|
|
564
|
+
shelves,
|
|
565
|
+
})
|
|
566
|
+
let at = performance.now()
|
|
567
|
+
let body = JSON.stringify(answer)
|
|
568
|
+
let serialized = performance.now() - at
|
|
569
|
+
return new Response(body, {
|
|
570
|
+
headers: {
|
|
571
|
+
'content-type': 'application/json',
|
|
572
|
+
'server-timing': [
|
|
573
|
+
header(answer.timing!),
|
|
574
|
+
`compiler_parse;dur=${parsed.toFixed(3)}`,
|
|
575
|
+
`compiler_serialize;dur=${serialized.toFixed(3)}`,
|
|
576
|
+
`compiler_request;dur=${(performance.now() - began).toFixed(3)}`,
|
|
577
|
+
].join(', '),
|
|
578
|
+
},
|
|
579
|
+
})
|
|
580
|
+
} catch (e) {
|
|
581
|
+
if (e instanceof Stopped) {
|
|
582
|
+
return new Response(e.message, { status: REPLACED })
|
|
583
|
+
}
|
|
584
|
+
throw e
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// A package job's answer: the compiled package, or what stopped it, as a
|
|
589
|
+
// line, with 422.
|
|
590
|
+
let packageAnswer = async (job: PackageJob, shelves?: Shelves) => {
|
|
591
|
+
try {
|
|
592
|
+
return Response.json(await compilePackage(job, { shelves }))
|
|
593
|
+
} catch (e) {
|
|
594
|
+
if (e instanceof Stopped) {
|
|
595
|
+
return new Response(e.message, { status: REPLACED })
|
|
596
|
+
}
|
|
597
|
+
if (e instanceof Unexported) {
|
|
598
|
+
return new Response(e.message, { status: 404 })
|
|
599
|
+
}
|
|
600
|
+
return new Response(said(e).join('\n'), { status: 422 })
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// A pack job's answer (./pack.ts): the pack, or why the modules are not
|
|
605
|
+
// packed, with 422, each naming the packer that made it.
|
|
606
|
+
let packAnswer = async (job: PackJob) => {
|
|
607
|
+
let headers = { [PACKED_BY]: String(PACKER) }
|
|
608
|
+
try {
|
|
609
|
+
return Response.json(await packModules(job.pack), { headers })
|
|
610
|
+
} catch (e) {
|
|
611
|
+
if (e instanceof Stopped) {
|
|
612
|
+
return new Response(e.message, { status: REPLACED })
|
|
613
|
+
}
|
|
614
|
+
if (e instanceof Unpackable) {
|
|
615
|
+
return new Response(e.message, { status: 422, headers })
|
|
616
|
+
}
|
|
617
|
+
throw e
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
let server: { fetch: FetchJob } = { fetch: serving() }
|
|
622
|
+
export default server
|