foldkit-plus 0.18.0 → 0.20.0

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.
@@ -1,10 +1,13 @@
1
1
  import { peer } from "./peer.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { Option, Schema } from "effect";
4
- import { watch } from "node:fs";
4
+ import { readFileSync, watch } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
- import { basename, dirname, join, relative, resolve } from "node:path";
7
- import { mkdir, rm, writeFile } from "node:fs/promises";
6
+ import { basename, dirname, extname, join, relative, resolve } from "node:path";
7
+ import { ChildProcess, spawn } from "node:child_process";
8
+ import { subscribe, unsubscribe } from "node:diagnostics_channel";
9
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
10
+ import { createInterface } from "node:readline";
8
11
  // src/testing/workers.ts
9
12
  /**
10
13
  * `foldkit-plus/testing/workers`: a Worker on a local workerd, configured by
@@ -17,13 +20,180 @@ import { mkdir, rm, writeFile } from "node:fs/promises";
17
20
  * condition into a directory of the stack's own, and the harness runs the
18
21
  * configuration with `main` pointed there.
19
22
  *
20
- * `wrangler` and `esbuild` are optional peers of `foldkit-plus`, loaded on the
21
- * first call; Miniflare is read from Wrangler's own copy, so the date check
22
- * asks the runtime Wrangler starts.
23
+ * `wrangler`, `esbuild` and `@foldkit/vite-plugin` are optional peers of
24
+ * `foldkit-plus`, loaded on the first call; Miniflare is read from Wrangler's
25
+ * own copy, so the date check asks the runtime Wrangler starts.
23
26
  */
24
27
  const SUBPATH = "testing/workers";
25
28
  const wrangler = () => peer(SUBPATH, "wrangler", () => import("wrangler"));
26
29
  const esbuild = () => peer(SUBPATH, "esbuild", () => import("esbuild"));
30
+ const foldkitVite = () => peer(SUBPATH, "@foldkit/vite-plugin", () => import("@foldkit/vite-plugin"));
31
+ const collecting = /* @__PURE__ */ new Set();
32
+ const isWorkerd = (child) => typeof child.spawnfile === "string" && /^workerd(\.exe)?$/.test(basename(child.spawnfile));
33
+ const onSpawn = (message) => {
34
+ if (typeof message !== "object" || message === null || !("process" in message)) return;
35
+ const child = message.process;
36
+ if (!(child instanceof ChildProcess)) return;
37
+ for (const spawned of collecting) spawned.processes.push(child);
38
+ };
39
+ /** Runs `step`, adding the processes it spawns to `into`. */
40
+ const collect = async (into, step) => {
41
+ if (collecting.size === 0) subscribe("child_process", onSpawn);
42
+ for (const other of collecting) other.shared = into.shared = true;
43
+ collecting.add(into);
44
+ try {
45
+ return await step();
46
+ } finally {
47
+ collecting.delete(into);
48
+ if (collecting.size === 0) unsubscribe("child_process", onSpawn);
49
+ }
50
+ };
51
+ const isRunning = (child) => child.exitCode === null && child.signalCode === null;
52
+ /** Milliseconds a Linux process's main thread has run, by the scheduler's nanoseconds. */
53
+ const linuxTime = async (pid) => Number((await readFile(`/proc/${pid}/task/${pid}/schedstat`, "utf8")).split(" ")[0]) / 1e6;
54
+ const linuxReader = () => ({
55
+ read: async (pids) => (await Promise.all(pids.map(linuxTime))).reduce((a, b) => a + b, 0),
56
+ close: () => {}
57
+ });
58
+ /**
59
+ * Windows has no `/proc`, and Node no call for another process's times, so
60
+ * one PowerShell kept open answers each read: started per read, it takes
61
+ * longer than the requests it measures. The main thread is the one that
62
+ * started first. Windows adds to a thread's time a scheduler tick (15.6 ms)
63
+ * at a time.
64
+ */
65
+ const windowsReader = () => {
66
+ const shell = spawn("powershell.exe", [
67
+ "-NoProfile",
68
+ "-NonInteractive",
69
+ "-Command",
70
+ "-"
71
+ ], {
72
+ stdio: [
73
+ "pipe",
74
+ "pipe",
75
+ "ignore"
76
+ ],
77
+ windowsHide: true
78
+ });
79
+ const waiting = [];
80
+ createInterface({ input: shell.stdout }).on("line", (line) => waiting.shift()?.(Option.some(line)));
81
+ const ended = () => waiting.splice(0).forEach((answer) => answer(Option.none()));
82
+ shell.on("error", ended).on("exit", ended);
83
+ return {
84
+ read: (pids) => new Promise((resolve, reject) => {
85
+ waiting.push((line) => {
86
+ const ticks = Number(Option.getOrElse(line, () => ""));
87
+ if (Option.isSome(line) && Number.isFinite(ticks)) resolve(ticks / 1e4);
88
+ else reject(/* @__PURE__ */ new Error(`workerd's CPU time could not be read: ${Option.getOrElse(line, () => "PowerShell ended")}`));
89
+ });
90
+ shell.stdin.write(`try { (@(${pids.join(",")}) | % { ([Diagnostics.Process]::GetProcessById($_).Threads | Sort-Object StartTime | Select-Object -First 1).TotalProcessorTime.Ticks } | Measure-Object -Sum).Sum } catch { "$_" }\n`);
91
+ }),
92
+ close: () => shell.kill()
93
+ };
94
+ };
95
+ const readerFor = () => {
96
+ if (process.platform === "linux") return linuxReader();
97
+ if (process.platform === "win32") return windowsReader();
98
+ throw new Error(`The stack reads workerd's CPU time on Linux and Windows, not ${process.platform}.`);
99
+ };
100
+ /** The CPU meter over a stack's workerd processes, its reader made on the first read. */
101
+ const workerdMeter = (origin, dispatch, spawned) => {
102
+ let reader = Option.none();
103
+ return {
104
+ meter: {
105
+ origin,
106
+ fetch: async (request) => dispatch(request.url, {
107
+ method: request.method,
108
+ headers: [...request.headers],
109
+ ...request.body === null ? {} : { body: await request.arrayBuffer() }
110
+ }),
111
+ spent: async () => {
112
+ if (spawned.shared) throw new Error("Another stack started in this process while this one did, so whose workerd is whose is unknown: start stacks one at a time to read a stack's CPU.");
113
+ const current = Option.getOrElse(reader, readerFor);
114
+ reader = Option.some(current);
115
+ return current.read(spawned.processes.filter((child) => isWorkerd(child) && isRunning(child)).flatMap((child) => child.pid === void 0 ? [] : [child.pid]));
116
+ }
117
+ },
118
+ close: () => Option.map(reader, (open) => open.close())
119
+ };
120
+ };
121
+ /**
122
+ * Asks each route once, then `runs` times more, one request at a time, each
123
+ * response read in full, and reads what each cost. Every warm request is
124
+ * checked, since a deployed Worker's limit applies to each rather than to
125
+ * their mean. Throws listing every reading when a route spends more than
126
+ * the budget, or answers a 5xx, whose cost says nothing of the route's.
127
+ */
128
+ const budget = async (meter, { routes, warm, cold, runs = 5 }) => {
129
+ if (!Number.isInteger(runs) || runs < 1) throw new Error(`Cpu.budget: runs must be a whole number from 1, not ${runs}.`);
130
+ const requestOf = (route) => typeof route === "string" ? new Request(new URL(route, meter.origin)) : route();
131
+ const readings = [];
132
+ for (const [name, route] of Object.entries(routes)) {
133
+ let status = 0;
134
+ const ask = async () => {
135
+ const response = await meter.fetch(requestOf(route));
136
+ await response.arrayBuffer();
137
+ status = response.status;
138
+ if (status >= 500) throw new Error(`Cpu.budget: ${name} answered ${status}.`);
139
+ };
140
+ const start = await meter.spent();
141
+ await ask();
142
+ const first = await meter.spent();
143
+ let warmest = 0;
144
+ let previous = first;
145
+ for (let run = 0; run < runs; run++) {
146
+ await ask();
147
+ const now = await meter.spent();
148
+ warmest = Math.max(warmest, now - previous);
149
+ previous = now;
150
+ }
151
+ readings.push({
152
+ route: name,
153
+ status,
154
+ cold: first - start,
155
+ warm: warmest
156
+ });
157
+ }
158
+ const over = readings.filter((reading) => reading.warm > warm || cold !== void 0 && reading.cold > cold);
159
+ if (over.length > 0) throw new Error(`Over the CPU budget (warm ${warm} ms${cold === void 0 ? "" : `, cold ${cold} ms`}): ${over.map((reading) => reading.route).join(", ")}\n` + readings.map((reading) => ` ${reading.route}: cold ${reading.cold.toFixed(2)} ms, warm ${reading.warm.toFixed(2)} ms (status ${reading.status})`).join("\n"));
160
+ return readings;
161
+ };
162
+ const pause = new Int32Array(new SharedArrayBuffer(4));
163
+ /**
164
+ * Milliseconds this thread has run. Linux books a running thread's time at
165
+ * each scheduler tick (4 ms at 250 Hz), and `threadCpuUsage` reads that
166
+ * book; a millisecond's sleep has the scheduler book the rest, and its own
167
+ * count is in nanoseconds. Read synchronously, so on this thread rather
168
+ * than the pool's.
169
+ */
170
+ const threadTime = () => {
171
+ if (process.platform === "linux") {
172
+ Atomics.wait(pause, 0, 0, 1);
173
+ return Number(readFileSync("/proc/thread-self/schedstat", "utf8").split(" ")[0]) / 1e6;
174
+ }
175
+ const { user, system } = process.threadCpuUsage();
176
+ return (user + system) / 1e3;
177
+ };
178
+ /**
179
+ * A meter over `answer` run in this process, by this thread's CPU time: for
180
+ * a Worker's handler Node can run (no D1 or other binding of workerd's),
181
+ * whose work happens on the thread that awaits it.
182
+ */
183
+ const inThread = (answer, origin = "http://localhost") => ({
184
+ origin,
185
+ fetch: answer,
186
+ spent: async () => threadTime()
187
+ });
188
+ /**
189
+ * What a request costs in CPU time, which Miniflare neither limits nor
190
+ * reports, while a deployed Worker fails past its plan's limit (error 1102).
191
+ * `Cpu.budget` reads routes through a meter: a stack's `cpu`, or `Cpu.inThread`.
192
+ */
193
+ const Cpu = {
194
+ budget,
195
+ inThread
196
+ };
27
197
  /**
28
198
  * The part of the configuration the stack reads itself. Wrangler validates
29
199
  * the whole of it when the harness loads it.
@@ -55,6 +225,103 @@ const readConfig = async (path) => {
55
225
  config
56
226
  };
57
227
  };
228
+ const scriptLoaders = {
229
+ ".ts": "ts",
230
+ ".mts": "ts",
231
+ ".tsx": "tsx",
232
+ ".js": "js",
233
+ ".mjs": "js",
234
+ ".jsx": "jsx"
235
+ };
236
+ const SCRIPT = /\.(?:ts|tsx|js|jsx|mts|mjs)$/;
237
+ const scripts = new Set(Object.values(scriptLoaders));
238
+ const isPackaged = (path) => /[\\/]node_modules[\\/]/.test(path);
239
+ /**
240
+ * The plugins, with the Worker's views branded as `@foldkit/vite-plugin`
241
+ * brands the page's build: each function's result named by its module's path
242
+ * from `root`. Foldkit adopts a served element only where that name is the
243
+ * one the browser's view gives it; unbranded, the Worker's page was rebuilt on
244
+ * every hydration, silently in production (#412).
245
+ *
246
+ * Vite brands what any load returns, but esbuild takes the first `onLoad`
247
+ * that answers, so each plugin's is wrapped and a module it loads (with
248
+ * `pnpm mutate`'s edits, say) is branded too. `foldkit/brand` resolves from
249
+ * `root`, as the page's does; a root that resolves none has no Foldkit page
250
+ * to match, and the Worker is bundled as written.
251
+ */
252
+ const viewIdentity = (root, plugins) => {
253
+ let brand = Option.none();
254
+ const resolving = Symbol("foldkit/brand");
255
+ const brands = ({ path, namespace }) => Option.isSome(brand) && namespace === "file" && SCRIPT.test(path) && !isPackaged(path);
256
+ /** `contents` branded, or none where nothing in them returns. */
257
+ const branded = async (contents, loader, path) => {
258
+ const { transform } = await esbuild();
259
+ const { transformViewIdentity } = await foldkitVite();
260
+ const { code } = await transform(contents, {
261
+ loader,
262
+ sourcefile: path
263
+ });
264
+ return Option.fromNullOr(transformViewIdentity(code, path, root)).pipe(Option.map((result) => result.code));
265
+ };
266
+ const brandedResult = async (result, args) => {
267
+ const loader = result.loader ?? scriptLoaders[extname(args.path)];
268
+ const { contents } = result;
269
+ if (!brands(args) || contents === void 0 || loader === void 0 || !scripts.has(loader)) return result;
270
+ return Option.match(await branded(contents, loader, args.path), {
271
+ onNone: () => result,
272
+ onSome: (contents) => ({
273
+ ...result,
274
+ contents,
275
+ loader: "js"
276
+ })
277
+ });
278
+ };
279
+ const wrapped = (plugin) => ({
280
+ ...plugin,
281
+ setup: (build) => plugin.setup({
282
+ ...build,
283
+ onLoad: (options, load) => build.onLoad(options, async (args) => {
284
+ const result = await load(args);
285
+ return result === null || result === void 0 ? result : brandedResult(result, args);
286
+ })
287
+ })
288
+ });
289
+ return [
290
+ {
291
+ name: "foldkit-view-identity",
292
+ setup: (build) => {
293
+ build.onStart(async () => {
294
+ const found = await build.resolve("foldkit/brand", {
295
+ kind: "import-statement",
296
+ resolveDir: root,
297
+ pluginData: resolving
298
+ });
299
+ brand = found.errors.length === 0 ? Option.some(found.path) : Option.none();
300
+ });
301
+ build.onResolve({ filter: /^foldkit\/brand$/ }, (args) => args.pluginData === resolving ? void 0 : Option.match(brand, {
302
+ onNone: () => void 0,
303
+ onSome: (path) => ({ path })
304
+ }));
305
+ }
306
+ },
307
+ ...plugins.map(wrapped),
308
+ {
309
+ name: "foldkit-view-identity-load",
310
+ setup: (build) => build.onLoad({ filter: SCRIPT }, async (args) => {
311
+ const loader = scriptLoaders[extname(args.path)];
312
+ if (!brands(args) || loader === void 0) return void 0;
313
+ const code = await branded(await readFile(args.path), loader, args.path);
314
+ return Option.match(code, {
315
+ onNone: () => void 0,
316
+ onSome: (contents) => ({
317
+ contents,
318
+ loader: "js"
319
+ })
320
+ });
321
+ })
322
+ }
323
+ ];
324
+ };
58
325
  /**
59
326
  * How the entry is bundled, for the stack and for `wrangler deploy`: the
60
327
  * script at `outfile`, and beside it any `.wasm` it imports, which `no_bundle`
@@ -69,7 +336,7 @@ const bundleOptions = (options, outfile) => ({
69
336
  conditions: ["foldkit-plus:source"],
70
337
  external: ["cloudflare:workers", "node:*"],
71
338
  loader: { ".wasm": "copy" },
72
- plugins: [...options.plugins ?? []],
339
+ plugins: viewIdentity(resolve(options.pageRoot ?? dirname(options.wrangler)), options.plugins ?? []),
73
340
  outdir: dirname(outfile),
74
341
  entryNames: basename(outfile, ".js"),
75
342
  write: false,
@@ -129,6 +396,15 @@ const start = async (options) => {
129
396
  const given = options.vars;
130
397
  let vars = typeof given === "function" ? void 0 : given;
131
398
  const harness = createTestHarness(optionsFor(raw, outfile, vars));
399
+ const spawned = {
400
+ processes: [],
401
+ shared: false
402
+ };
403
+ const trials = {
404
+ processes: [],
405
+ shared: false
406
+ };
407
+ let closeMeter = () => {};
132
408
  const kept = [];
133
409
  const drain = () => {
134
410
  const fresh = harness.getLogs();
@@ -149,6 +425,7 @@ const start = async (options) => {
149
425
  };
150
426
  const stopOnce = async () => {
151
427
  clearInterval(draining);
428
+ closeMeter();
152
429
  Option.map(rereading, clearTimeout);
153
430
  Option.map(configWatcher, (watcher) => watcher.close());
154
431
  try {
@@ -175,12 +452,14 @@ const start = async (options) => {
175
452
  });
176
453
  try {
177
454
  await writeOutputs(first);
178
- const { url } = await harness.listen();
455
+ const { url } = await collect(spawned, () => harness.listen());
179
456
  if (typeof given === "function") {
180
457
  vars = given(url.origin);
181
- await harness.update(optionsFor(raw, outfile, vars));
458
+ await collect(spawned, () => harness.update(optionsFor(raw, outfile, vars)));
182
459
  }
183
460
  const worker = harness.getWorker();
461
+ const metered = workerdMeter(url.origin, worker.fetch, spawned);
462
+ closeMeter = metered.close;
184
463
  await migrate(worker, config);
185
464
  const watch$1 = async (listener) => {
186
465
  if (Option.isSome(stopping)) throw new Error("This stack has stopped.");
@@ -203,7 +482,7 @@ const start = async (options) => {
203
482
  })));
204
483
  const trial = createTestHarness(optionsFor(next.raw, join(trialDirectory, basename(outfile)), vars));
205
484
  try {
206
- await trial.listen();
485
+ await collect(trials, () => trial.listen());
207
486
  await migrate(trial.getWorker(), next.config);
208
487
  } finally {
209
488
  await trial.close();
@@ -214,7 +493,7 @@ const start = async (options) => {
214
493
  }
215
494
  try {
216
495
  await writeOutputs(next.files);
217
- await harness.update(optionsFor(next.raw, outfile, vars));
496
+ await collect(spawned, () => harness.update(optionsFor(next.raw, outfile, vars)));
218
497
  } catch (error) {
219
498
  running = Option.none();
220
499
  listener.onStopped(errorText(error));
@@ -298,6 +577,7 @@ const start = async (options) => {
298
577
  env,
299
578
  dispatch: worker.fetch,
300
579
  logs,
580
+ cpu: metered.meter,
301
581
  watch: watch$1,
302
582
  stop
303
583
  };
@@ -315,6 +595,6 @@ const Stack = {
315
595
  start,
316
596
  writeBundle
317
597
  };
318
- export { Stack };
598
+ export { Cpu, Stack };
319
599
 
320
600
  //# sourceMappingURL=workers.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"workers.mjs","names":["watch","watchFile"],"sources":["../../src/testing/workers.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/workers`: a Worker on a local workerd, configured by\n * its own Wrangler configuration.\n *\n * Wrangler's test harness reads the configuration, so bindings, the\n * compatibility date and flags, `.dev.vars` and D1 migrations mean here what\n * they mean to `wrangler deploy`. This module owns only what Wrangler cannot\n * know: the bundle. esbuild builds the entry with the workspace's source\n * condition into a directory of the stack's own, and the harness runs the\n * configuration with `main` pointed there.\n *\n * `wrangler` and `esbuild` are optional peers of `foldkit-plus`, loaded on the\n * first call; Miniflare is read from Wrangler's own copy, so the date check\n * asks the runtime Wrangler starts.\n */\nimport { Option, Schema } from 'effect'\nimport type { BuildContext, BuildOptions, OutputFile, Plugin } from 'esbuild'\nimport type { TestHarness, WorkerHandle } from 'wrangler'\nimport { watch as watchFile, type FSWatcher } from 'node:fs'\nimport { mkdir, rm, writeFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { tmpdir } from 'node:os'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\nimport { peer } from './peer.js'\n\nconst SUBPATH = 'testing/workers'\n\nconst wrangler = () => peer(SUBPATH, 'wrangler', () => import('wrangler'))\nconst esbuild = () => peer(SUBPATH, 'esbuild', () => import('esbuild'))\n\nexport interface StackOptions {\n /** The Worker's Wrangler configuration (`wrangler.toml`, `.json` or `.jsonc`). */\n readonly wrangler: string\n /** The source esbuild bundles into what `main` names. */\n readonly entry: string\n /**\n * Local values for vars the deployed Worker is given elsewhere. As a\n * function, of the origin the stack answers at: the Worker has them from\n * its first request (`origin => ({ ORIGIN: origin })`).\n */\n readonly vars?: Vars | ((origin: string) => Vars)\n /** Local values for secrets, over any in `.dev.vars`. */\n readonly secrets?: Readonly<Record<string, string>>\n /** esbuild plugins for the bundle, the deploy's and the stack's alike. */\n readonly plugins?: ReadonlyArray<Plugin>\n /**\n * Whether each line the Worker writes to its console is printed here, by\n * its level, as it arrives (`'print'`, the default). `logs()` keeps them either way.\n */\n readonly console?: 'print' | 'quiet'\n}\n\ntype Vars = Readonly<Record<string, string>>\n\n/** A line the Worker wrote to its console. An `Error` logged carries its stack in `message`. */\nexport interface WorkerLog {\n /** As workerd names it: `debug`, `info`, `log`, `warn` or `error`. */\n readonly level: string\n readonly message: string\n readonly timestamp: number\n}\n\n/**\n * What a watched stack reports after each change to the bundle's sources or\n * to the Wrangler configuration.\n */\nexport interface WatchListener {\n /** The new Worker answers at the same origin, over the same storage. */\n readonly onSwap: () => void\n /**\n * The change was not swapped in, and the Worker running keeps answering\n * over the same storage. It did not build, built no code (as an entry saved\n * in place reads for a moment), did not start when tried on a workerd of\n * its own, or is a configuration the stack refuses. Or it was swapped in,\n * and a D1 migration then failed on the running database; the message says so.\n */\n readonly onRefused: (message: string) => void\n /**\n * A Worker that started when tried did not start in the stack. Wrangler's\n * harness tears its runtime down with it, storage included, so the stack\n * has stopped answering and watches no more: call `stop`, and start again.\n */\n readonly onStopped: (message: string) => void\n}\n\nexport interface Stack<Env> {\n /** Where the Worker answers over real HTTP. */\n readonly origin: string\n /**\n * The Worker's bindings, as the Worker sees them. A swap retires the ones\n * read before it (Miniflare's \"poisoned stub\"), so read them after.\n */\n readonly env: () => Promise<Env>\n /** A request straight to the Worker; an upgrade answers with its socket. */\n readonly dispatch: WorkerHandle['fetch']\n /**\n * Takes what the Worker wrote to its console since the last call, oldest\n * first. The lines come from workerd beside the response, not on it, so a\n * line written for a request may arrive after it: poll.\n */\n readonly logs: () => ReadonlyArray<WorkerLog>\n /**\n * Rebuilds on every change to a file the bundle read, and rereads the\n * Wrangler configuration when it changes. Each change is first started on\n * a workerd of its own, then swapped in at the same origin, and the D1\n * migrations not yet applied are applied. D1, R2 and Durable Object storage stay.\n */\n readonly watch: (listener: WatchListener) => Promise<void>\n /**\n * Stops watching, stops workerd and removes the bundle's directory, each\n * even when one before it failed. A change not yet being tried swaps\n * nothing and reports nothing; one being tried finishes first. A second\n * call returns the first one's promise.\n */\n readonly stop: () => Promise<void>\n}\n\n/**\n * The part of the configuration the stack reads itself. Wrangler validates\n * the whole of it when the harness loads it.\n */\nconst Config = Schema.Struct({\n main: Schema.String,\n compatibility_date: Schema.String,\n // The stack bundles; Wrangler bundling `main` again would deploy other code.\n no_bundle: Schema.Literal(true),\n d1_databases: Schema.optional(Schema.Array(Schema.Struct({ binding: Schema.String }))),\n})\n\n/**\n * The newest date the workerd Wrangler starts supports, from Wrangler's own\n * Miniflare: an application's own `miniflare` may be another release. Call it\n * after `wrangler()`, which says so when Wrangler is missing.\n */\nconst supportedDate = (): string => {\n const fromWrangler = createRequire(createRequire(import.meta.url).resolve('wrangler'))\n return Schema.decodeUnknownSync(Schema.Struct({ supportedCompatibilityDate: Schema.String }))(\n fromWrangler('miniflare'),\n ).supportedCompatibilityDate\n}\n\nconst readConfig = async (path: string) => {\n const { experimental_readRawConfig } = await wrangler()\n const { rawConfig: raw } = experimental_readRawConfig({ config: path })\n if ('env' in raw)\n throw new Error(`${path}: the local stack runs the top-level Worker; [env.*] is not read.`)\n const config = Schema.decodeUnknownSync(Config)(raw)\n // Miniflare would run a date it does not know at its own latest, with a\n // warning nobody reads, and the tests would pass on a runtime the deploy does not get.\n const supported = supportedDate()\n if (config.compatibility_date > supported)\n throw new Error(\n `${path} asks for compatibility_date ${config.compatibility_date}, but the installed ` +\n `workerd supports up to ${supported}. Move wrangler to a release that knows it.`,\n )\n return { raw, config }\n}\n\n/**\n * How the entry is bundled, for the stack and for `wrangler deploy`: the\n * script at `outfile`, and beside it any `.wasm` it imports, which `no_bundle`\n * Wrangler loads as a compiled module. `node:*` stays external for\n * `nodejs_compat`.\n */\nconst bundleOptions = (options: StackOptions, outfile: string) =>\n ({\n entryPoints: [options.entry],\n bundle: true,\n format: 'esm',\n platform: 'browser',\n conditions: ['foldkit-plus:source'],\n external: ['cloudflare:workers', 'node:*'],\n loader: { '.wasm': 'copy' },\n plugins: [...(options.plugins ?? [])],\n outdir: dirname(outfile),\n entryNames: basename(outfile, '.js'),\n write: false,\n logLevel: 'silent',\n }) satisfies BuildOptions\n\ntype OutputFiles = ReadonlyArray<OutputFile>\n\nconst writeOutputs = async (\n files: ReadonlyArray<{ readonly path: string; readonly contents: Uint8Array }>,\n) => {\n for (const file of files) {\n await mkdir(dirname(file.path), { recursive: true })\n await writeFile(file.path, file.contents)\n }\n}\n\nconst identityOf = (files: OutputFiles) => files.map(file => `${file.path}:${file.hash}`).join()\n\n/** Node's console method for each level workerd writes; any other prints as a log. */\nconst printers = new Map<string, (line: string) => void>([\n ['debug', line => console.debug(line)],\n ['info', line => console.info(line)],\n ['warn', line => console.warn(line)],\n ['error', line => console.error(line)],\n])\n\nconst print = (log: WorkerLog) =>\n (printers.get(log.level) ?? (line => console.log(line)))(`[worker] ${log.message}`)\n\nconst errorText = (error: unknown) => (error instanceof Error ? error.message : String(error))\n\n/** Writes the bundle where `main` says, for `wrangler deploy`. */\nconst writeBundle = async (options: Omit<StackOptions, 'vars' | 'secrets'>): Promise<void> => {\n const { config } = await readConfig(options.wrangler)\n const outfile = resolve(dirname(options.wrangler), config.main)\n const { build } = await esbuild()\n await writeOutputs((await build(bundleOptions(options, outfile))).outputFiles)\n}\n\ntype Raw = Awaited<ReturnType<typeof readConfig>>['raw']\n\n/** What the stack runs: a configuration and a bundle, swapped in together. */\ninterface Running {\n readonly raw: Raw\n readonly config: typeof Config.Type\n readonly files: OutputFiles\n}\n\nconst migrate = async (worker: WorkerHandle, config: typeof Config.Type) => {\n for (const database of config.d1_databases ?? []) await worker.applyD1Migrations(database.binding)\n}\n\n/**\n * Starts the Worker with a fresh, migrated D1 for each `[[d1_databases]]`,\n * and empty R2 and Durable Object storage. Each call is a stack of its own,\n * so test files running side by side share nothing.\n */\nconst start = async <Env>(options: StackOptions): Promise<Stack<Env>> => {\n const { raw, config } = await readConfig(options.wrangler)\n const { build, context } = await esbuild()\n const { createTestHarness } = await wrangler()\n const directory = join(tmpdir(), `foldkit-workers-${crypto.randomUUID()}`)\n const outfile = join(directory, basename(config.main))\n // Where a change is started on a workerd of its own before the swap.\n const trialDirectory = join(directory, 'trial')\n const bundle = bundleOptions(options, outfile)\n // In memory: a source that does not build fails here, before anything exists to clean up.\n const first = (await build(bundle)).outputFiles\n\n const optionsFor = (raw: Raw, main: string, vars: Vars | undefined) => ({\n root: dirname(options.wrangler),\n workers: [{ config: { ...raw, main }, vars, secrets: options.secrets }],\n })\n const given = options.vars\n // Given here, or once the stack knows its origin.\n let vars = typeof given === 'function' ? undefined : given\n const harness: TestHarness = createTestHarness(optionsFor(raw, outfile, vars))\n // The harness keeps workerd's console and offers no handler, so it is drained:\n // read and cleared in one synchronous step, nothing is read twice or missed.\n const kept: Array<WorkerLog> = []\n const drain = () => {\n const fresh = harness.getLogs()\n harness.clearLogs()\n if (options.console !== 'quiet') fresh.forEach(print)\n kept.push(...fresh)\n }\n const draining = setInterval(drain, 100)\n draining.unref()\n let watching = Option.none<Promise<BuildContext>>()\n let configWatcher = Option.none<FSWatcher>()\n let rereading = Option.none<ReturnType<typeof setTimeout>>()\n // Swaps run one at a time, in the order their changes arrived.\n let swaps: Promise<void> = Promise.resolve()\n let stopping = Option.none<Promise<void>>()\n const dispose = async (watcher: Promise<BuildContext>) => {\n // A context that never opened has nothing to dispose; its failure was the watch's to report.\n const opened = await watcher.then(Option.some, () => Option.none<BuildContext>())\n if (Option.isSome(opened)) await opened.value.dispose()\n }\n // Each step runs however the one before it ended: a step skipped leaves\n // workerd running, or the bundle's directory behind.\n const stopOnce = async () => {\n clearInterval(draining)\n Option.map(rereading, clearTimeout)\n Option.map(configWatcher, watcher => watcher.close())\n try {\n const watcher = watching\n watching = Option.none()\n // Waits for a rebuild in flight, whose step sees `stopping`.\n if (Option.isSome(watcher)) await dispose(watcher.value)\n await swaps\n } finally {\n try {\n await harness.close()\n } finally {\n // What the Worker wrote since the last drain, up to its end, is printed and kept.\n drain()\n await rm(directory, { recursive: true, force: true })\n }\n }\n }\n const stop = () =>\n Option.getOrElse(stopping, () => {\n const once = stopOnce()\n stopping = Option.some(once)\n return once\n })\n\n try {\n await writeOutputs(first)\n const { url } = await harness.listen()\n // A reload at the same origin, as a swap is, before any request of the caller's.\n if (typeof given === 'function') {\n vars = given(url.origin)\n await harness.update(optionsFor(raw, outfile, vars))\n }\n const worker = harness.getWorker()\n await migrate(worker, config)\n\n const watch = async (listener: WatchListener) => {\n if (Option.isSome(stopping)) throw new Error('This stack has stopped.')\n if (Option.isSome(watching)) throw new Error('This stack is already watching.')\n // None once a swap failed after its trial and took the runtime with it.\n let running = Option.some<Running>({ raw, config, files: first })\n\n /**\n * Starts `next` on a workerd of its own, then swaps it in. A Worker\n * that does not start is refused there, and the stack's harness, which\n * a failed update tears down with its storage, never sees it.\n */\n const swap = async (next: Running) => {\n try {\n await writeOutputs(\n next.files.map(file => ({\n path: join(trialDirectory, relative(directory, file.path)),\n contents: file.contents,\n })),\n )\n const trial = createTestHarness(\n optionsFor(next.raw, join(trialDirectory, basename(outfile)), vars),\n )\n try {\n await trial.listen()\n await migrate(trial.getWorker(), next.config)\n } finally {\n await trial.close()\n }\n } catch (error) {\n listener.onRefused(errorText(error))\n return\n }\n try {\n await writeOutputs(next.files)\n await harness.update(optionsFor(next.raw, outfile, vars))\n } catch (error) {\n running = Option.none()\n listener.onStopped(errorText(error))\n return\n }\n running = Option.some(next)\n try {\n await migrate(harness.getWorker(), next.config)\n } catch (error) {\n listener.onRefused(\n `The Worker was swapped in, but a migration failed: ${errorText(error)}`,\n )\n return\n }\n listener.onSwap()\n }\n /** Queues a swap of what `change` makes of the running stack, which may be none. */\n const enqueue = (change: (now: Running) => Promise<Option.Option<Running>>) => {\n const step = swaps.then(async () => {\n // A step that runs once `stop` began swaps nothing: `stop` waits for\n // it before closing the harness, so it would swap into a closing stack.\n if (Option.isNone(running) || Option.isSome(stopping)) return\n const next = await change(running.value)\n if (Option.isSome(next)) await swap(next.value)\n })\n // A listener that throws fails its own step, not the ones after it.\n swaps = step.catch(() => undefined)\n return step\n }\n\n const watcher = context({\n ...bundle,\n plugins: [\n ...bundle.plugins,\n {\n name: 'foldkit-swap',\n setup: build =>\n build.onEnd(result =>\n enqueue(async now => {\n if (result.errors.length > 0) {\n listener.onRefused(result.errors.map(error => error.text).join('\\n'))\n return Option.none()\n }\n const files = result.outputFiles ?? []\n // An editor saving in place empties the file before writing it, and a\n // rebuild can read it then; the write's own rebuild swaps.\n if (files.some(file => file.path === outfile && file.contents.length === 0)) {\n listener.onRefused(\n `${options.entry} bundles to no code, so no Worker could start.`,\n )\n return Option.none()\n }\n return identityOf(files) === identityOf(now.files)\n ? Option.none()\n : Option.some({ ...now, files })\n }),\n ),\n },\n ],\n })\n watching = Option.some(watcher)\n try {\n await (await watcher).watch()\n } catch (error) {\n // Not watching after all: `stop` must not wait on this context, nor a second `watch` be refused.\n if (Option.contains(watching, watcher)) {\n watching = Option.none()\n await dispose(watcher)\n }\n throw error\n }\n // A `stop` that began while the context opened would close no watcher made now.\n if (Option.isSome(stopping)) return\n\n const reread = () =>\n enqueue(async now => {\n const read = await readConfig(options.wrangler).then(Option.some, (error: unknown) => {\n listener.onRefused(errorText(error))\n return Option.none<Awaited<ReturnType<typeof readConfig>>>()\n })\n // A save that changed nothing the configuration says.\n return read.pipe(\n Option.filter(({ raw }) => JSON.stringify(raw) !== JSON.stringify(now.raw)),\n Option.map(({ raw, config }) => ({ ...now, raw, config })),\n )\n })\n // The directory, not the file: an editor that renames a temporary over the\n // file replaces what a file watcher watches.\n const name = basename(options.wrangler)\n configWatcher = Option.some(\n watchFile(dirname(options.wrangler), (_, changed) => {\n if (changed !== name) return\n // One reread for the burst of events a single save makes.\n Option.map(rereading, clearTimeout)\n rereading = Option.some(setTimeout(() => void reread(), 50))\n }).on('error', error =>\n listener.onRefused(`The configuration is no longer watched: ${errorText(error)}`),\n ),\n )\n }\n\n const env = () => harness.getWorker<Env>().getEnv()\n const logs = () => {\n drain()\n return kept.splice(0)\n }\n return { origin: url.origin, env, dispatch: worker.fetch, logs, watch, stop }\n } catch (error) {\n // The start's failure is the one to report; a failure cleaning up after it would hide it.\n await stop().catch(() => undefined)\n throw error\n }\n}\n\n/**\n * The local Workers stack. `Stack.start` runs the Worker for tests and\n * development; `Stack.writeBundle` writes what `wrangler deploy` uploads,\n * bundled the same way.\n */\nexport const Stack = { start, writeBundle } as const\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,UAAU;AAEhB,MAAM,iBAAiB,KAAK,SAAS,kBAAkB,OAAO,WAAW;AACzE,MAAM,gBAAgB,KAAK,SAAS,iBAAiB,OAAO,UAAU;;;;;AA6FtE,MAAM,SAAS,OAAO,OAAO;CAC3B,MAAM,OAAO;CACb,oBAAoB,OAAO;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;GAAK,UAAU,OAAO;GAAO;GAAM,OAAA;GAAO;EAAK;CAC9E,SAAS,OAAO;EAEd,MAAM,KAAK,CAAC,CAAC,YAAY,KAAA,CAAS;EAClC,MAAM;CACR;AACF;;;;;;AAOA,MAAa,QAAQ;CAAE;CAAO;AAAY"}
1
+ {"version":3,"file":"workers.mjs","names":["watch","watchFile"],"sources":["../../src/testing/workers.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/workers`: a Worker on a local workerd, configured by\n * its own Wrangler configuration.\n *\n * Wrangler's test harness reads the configuration, so bindings, the\n * compatibility date and flags, `.dev.vars` and D1 migrations mean here what\n * they mean to `wrangler deploy`. This module owns only what Wrangler cannot\n * know: the bundle. esbuild builds the entry with the workspace's source\n * condition into a directory of the stack's own, and the harness runs the\n * configuration with `main` pointed there.\n *\n * `wrangler`, `esbuild` and `@foldkit/vite-plugin` are optional peers of\n * `foldkit-plus`, loaded on the first call; Miniflare is read from Wrangler's\n * own copy, so the date check asks the runtime Wrangler starts.\n */\nimport { Option, Schema } from 'effect'\nimport type {\n BuildContext,\n BuildOptions,\n Loader,\n OnLoadArgs,\n OnLoadResult,\n OutputFile,\n Plugin,\n} from 'esbuild'\nimport type { TestHarness, WorkerHandle } from 'wrangler'\nimport { ChildProcess, spawn } from 'node:child_process'\nimport { subscribe, unsubscribe } from 'node:diagnostics_channel'\nimport { readFileSync, watch as watchFile, type FSWatcher } from 'node:fs'\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { createInterface } from 'node:readline'\nimport { createRequire } from 'node:module'\nimport { tmpdir } from 'node:os'\nimport { basename, dirname, extname, join, relative, resolve } from 'node:path'\nimport { peer } from './peer.js'\n\nconst SUBPATH = 'testing/workers'\n\nconst wrangler = () => peer(SUBPATH, 'wrangler', () => import('wrangler'))\nconst esbuild = () => peer(SUBPATH, 'esbuild', () => import('esbuild'))\nconst foldkitVite = () =>\n peer(SUBPATH, '@foldkit/vite-plugin', () => import('@foldkit/vite-plugin'))\n\nexport interface StackOptions {\n /** The Worker's Wrangler configuration (`wrangler.toml`, `.json` or `.jsonc`). */\n readonly wrangler: string\n /** The source esbuild bundles into what `main` names. */\n readonly entry: string\n /**\n * Local values for vars the deployed Worker is given elsewhere. As a\n * function, of the origin the stack answers at: the Worker has them from\n * its first request (`origin => ({ ORIGIN: origin })`).\n */\n readonly vars?: Vars | ((origin: string) => Vars)\n /** Local values for secrets, over any in `.dev.vars`. */\n readonly secrets?: Readonly<Record<string, string>>\n /**\n * esbuild plugins for the bundle, the deploy's and the stack's alike. A\n * module one loads is branded with view identities as one read from disk is.\n */\n readonly plugins?: ReadonlyArray<Plugin>\n /**\n * The Vite root of the page the Worker renders; by default the folder of\n * the Wrangler configuration. Each view is named by its module's path from\n * here, as `@foldkit/vite-plugin` names the page's.\n */\n readonly pageRoot?: string\n /**\n * Whether each line the Worker writes to its console is printed here, by\n * its level, as it arrives (`'print'`, the default). `logs()` keeps them either way.\n */\n readonly console?: 'print' | 'quiet'\n}\n\ntype Vars = Readonly<Record<string, string>>\n\n/** A line the Worker wrote to its console. An `Error` logged carries its stack in `message`. */\nexport interface WorkerLog {\n /** As workerd names it: `debug`, `info`, `log`, `warn` or `error`. */\n readonly level: string\n readonly message: string\n readonly timestamp: number\n}\n\n/**\n * What a watched stack reports after each change to the bundle's sources or\n * to the Wrangler configuration.\n */\nexport interface WatchListener {\n /** The new Worker answers at the same origin, over the same storage. */\n readonly onSwap: () => void\n /**\n * The change was not swapped in, and the Worker running keeps answering\n * over the same storage. It did not build, built no code (as an entry saved\n * in place reads for a moment), did not start when tried on a workerd of\n * its own, or is a configuration the stack refuses. Or it was swapped in,\n * and a D1 migration then failed on the running database; the message says so.\n */\n readonly onRefused: (message: string) => void\n /**\n * A Worker that started when tried did not start in the stack. Wrangler's\n * harness tears its runtime down with it, storage included, so the stack\n * has stopped answering and watches no more: call `stop`, and start again.\n */\n readonly onStopped: (message: string) => void\n}\n\nexport interface Stack<Env> {\n /** Where the Worker answers over real HTTP. */\n readonly origin: string\n /**\n * The Worker's bindings, as the Worker sees them. A swap retires the ones\n * read before it (Miniflare's \"poisoned stub\"), so read them after.\n */\n readonly env: () => Promise<Env>\n /** A request straight to the Worker; an upgrade answers with its socket. */\n readonly dispatch: WorkerHandle['fetch']\n /**\n * Takes what the Worker wrote to its console since the last call, oldest\n * first. The lines come from workerd beside the response, not on it, so a\n * line written for a request may arrive after it: poll.\n */\n readonly logs: () => ReadonlyArray<WorkerLog>\n /**\n * Requests sent straight to the Worker, metered for `Cpu.budget` by how\n * long workerd's main thread runs, read from the operating system since\n * workerd reports no CPU (Linux and Windows). That counts the Worker's code\n * and what workerd does on the thread around it, D1's SQLite included,\n * which a deployed Worker's CPU time leaves out.\n */\n readonly cpu: CpuMeter\n /**\n * Rebuilds on every change to a file the bundle read, and rereads the\n * Wrangler configuration when it changes. Each change is first started on\n * a workerd of its own, then swapped in at the same origin, and the D1\n * migrations not yet applied are applied. D1, R2 and Durable Object storage stay.\n */\n readonly watch: (listener: WatchListener) => Promise<void>\n /**\n * Stops watching, stops workerd and removes the bundle's directory, each\n * even when one before it failed. A change not yet being tried swaps\n * nothing and reports nothing; one being tried finishes first. A second\n * call returns the first one's promise.\n */\n readonly stop: () => Promise<void>\n}\n\n/** What a meter answers: a `Response`, or Miniflare's own. */\nexport type CpuAnswer = Pick<Response, 'status' | 'arrayBuffer'>\n\n/** Answers requests, and reads how much CPU time the code answering them has spent. */\nexport interface CpuMeter {\n /** What a route given as a path is resolved against. */\n readonly origin: string\n readonly fetch: (request: Request) => Promise<CpuAnswer>\n /** Milliseconds of CPU time spent so far, from a fixed point of the meter's own. */\n readonly spent: () => Promise<number>\n}\n\n/**\n * A route `Cpu.budget` asks: a path or URL to `GET`, or a function making\n * a new request for each run, since a request's body is read once.\n */\nexport type CpuRoute = string | (() => Request)\n\n/** What one route cost, in milliseconds of CPU time. */\nexport interface CpuReading {\n readonly route: string\n /** The last response's status. */\n readonly status: number\n /** The route's first request in this call: in a fresh stack, a cold isolate's. */\n readonly cold: number\n /**\n * The most a request after the first spent, in milliseconds. A deployed\n * Worker's limit applies to each request, not to their mean.\n */\n readonly warm: number\n}\n\nexport interface CpuBudget {\n /** The routes, by the name a failure reports them with. */\n readonly routes: Readonly<Record<string, CpuRoute>>\n /**\n * Milliseconds each request after the first may spend. A meter's own\n * resolution bounds how small this can be: Windows books a thread's CPU\n * time in 15.6 ms ticks, so a budget near that reads one request's cost\n * as a tick whether it spent it or not.\n */\n readonly warm: number\n /** Milliseconds the first request may spend; unchecked when not given. */\n readonly cold?: number\n /** Requests after the first, each answered in full before the next; default 5. */\n readonly runs?: number\n}\n\n/** The processes spawned while a stack's harness starts or reloads; workerd among them. */\ninterface Spawned {\n readonly processes: Array<ChildProcess>\n /** Another stack spawned at the same time, so whose process is whose is unknown. */\n shared: boolean\n}\n\nconst collecting = new Set<Spawned>()\n\n// Named once spawned: Node publishes a process before it starts it.\nconst isWorkerd = (child: ChildProcess) =>\n typeof child.spawnfile === 'string' && /^workerd(\\.exe)?$/.test(basename(child.spawnfile))\n\n// Node publishes every `spawn` here, workerd's by Miniflare included; the\n// harness offers no other way to find the process.\nconst onSpawn = (message: unknown) => {\n if (typeof message !== 'object' || message === null || !('process' in message)) return\n const child = message.process\n if (!(child instanceof ChildProcess)) return\n for (const spawned of collecting) spawned.processes.push(child)\n}\n\n/** Runs `step`, adding the processes it spawns to `into`. */\nconst collect = async <A>(into: Spawned, step: () => Promise<A>): Promise<A> => {\n if (collecting.size === 0) subscribe('child_process', onSpawn)\n for (const other of collecting) other.shared = into.shared = true\n collecting.add(into)\n try {\n return await step()\n } finally {\n collecting.delete(into)\n if (collecting.size === 0) unsubscribe('child_process', onSpawn)\n }\n}\n\nconst isRunning = (child: ChildProcess) => child.exitCode === null && child.signalCode === null\n\n/** Milliseconds a Linux process's main thread has run, by the scheduler's nanoseconds. */\nconst linuxTime = async (pid: number): Promise<number> =>\n Number((await readFile(`/proc/${pid}/task/${pid}/schedstat`, 'utf8')).split(' ')[0]) / 1e6\n\n/**\n * Reads how long processes' main threads have run, where workerd runs\n * JavaScript. V8's helper threads, which collect garbage and compile beside\n * it, are left out: on a server-rendered page they added half as much again.\n */\ninterface CpuReader {\n readonly read: (pids: ReadonlyArray<number>) => Promise<number>\n readonly close: () => void\n}\n\nconst linuxReader = (): CpuReader => ({\n read: async pids => (await Promise.all(pids.map(linuxTime))).reduce((a, b) => a + b, 0),\n close: () => {},\n})\n\n/**\n * Windows has no `/proc`, and Node no call for another process's times, so\n * one PowerShell kept open answers each read: started per read, it takes\n * longer than the requests it measures. The main thread is the one that\n * started first. Windows adds to a thread's time a scheduler tick (15.6 ms)\n * at a time.\n */\nconst windowsReader = (): CpuReader => {\n const shell = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '-'], {\n stdio: ['pipe', 'pipe', 'ignore'],\n windowsHide: true,\n })\n const waiting: Array<(line: Option.Option<string>) => void> = []\n createInterface({ input: shell.stdout }).on('line', line => waiting.shift()?.(Option.some(line)))\n // A shell that could not start, or ended, answers no read waiting on it.\n const ended = () => waiting.splice(0).forEach(answer => answer(Option.none()))\n shell.on('error', ended).on('exit', ended)\n return {\n read: pids =>\n new Promise((resolve, reject) => {\n waiting.push(line => {\n const ticks = Number(Option.getOrElse(line, () => ''))\n if (Option.isSome(line) && Number.isFinite(ticks)) resolve(ticks / 1e4)\n else\n reject(\n new Error(\n `workerd's CPU time could not be read: ${Option.getOrElse(line, () => 'PowerShell ended')}`,\n ),\n )\n })\n shell.stdin.write(\n `try { (@(${pids.join(',')}) | % { ([Diagnostics.Process]::GetProcessById($_).Threads | Sort-Object StartTime | Select-Object -First 1).TotalProcessorTime.Ticks } | Measure-Object -Sum).Sum } catch { \"$_\" }\\n`,\n )\n }),\n close: () => shell.kill(),\n }\n}\n\nconst readerFor = (): CpuReader => {\n if (process.platform === 'linux') return linuxReader()\n if (process.platform === 'win32') return windowsReader()\n throw new Error(\n `The stack reads workerd's CPU time on Linux and Windows, not ${process.platform}.`,\n )\n}\n\n/** The CPU meter over a stack's workerd processes, its reader made on the first read. */\nconst workerdMeter = (origin: string, dispatch: WorkerHandle['fetch'], spawned: Spawned) => {\n let reader = Option.none<CpuReader>()\n const meter: CpuMeter = {\n origin,\n // Straight to the Worker: over `origin` a second workerd, which proxies\n // what the harness serves, would spend time of its own on every request.\n fetch: async request =>\n dispatch(request.url, {\n method: request.method,\n headers: [...request.headers],\n ...(request.body === null ? {} : { body: await request.arrayBuffer() }),\n }),\n spent: async () => {\n if (spawned.shared)\n throw new Error(\n 'Another stack started in this process while this one did, so whose workerd is ' +\n \"whose is unknown: start stacks one at a time to read a stack's CPU.\",\n )\n const current = Option.getOrElse(reader, readerFor)\n reader = Option.some(current)\n return current.read(\n spawned.processes\n .filter(child => isWorkerd(child) && isRunning(child))\n .flatMap(child => (child.pid === undefined ? [] : [child.pid])),\n )\n },\n }\n return { meter, close: () => Option.map(reader, open => open.close()) }\n}\n\n/**\n * Asks each route once, then `runs` times more, one request at a time, each\n * response read in full, and reads what each cost. Every warm request is\n * checked, since a deployed Worker's limit applies to each rather than to\n * their mean. Throws listing every reading when a route spends more than\n * the budget, or answers a 5xx, whose cost says nothing of the route's.\n */\nconst budget = async (\n meter: CpuMeter,\n { routes, warm, cold, runs = 5 }: CpuBudget,\n): Promise<ReadonlyArray<CpuReading>> => {\n if (!Number.isInteger(runs) || runs < 1)\n throw new Error(`Cpu.budget: runs must be a whole number from 1, not ${runs}.`)\n const requestOf = (route: CpuRoute) =>\n typeof route === 'string' ? new Request(new URL(route, meter.origin)) : route()\n const readings: Array<CpuReading> = []\n for (const [name, route] of Object.entries(routes)) {\n let status = 0\n const ask = async () => {\n const response = await meter.fetch(requestOf(route))\n await response.arrayBuffer()\n status = response.status\n if (status >= 500) throw new Error(`Cpu.budget: ${name} answered ${status}.`)\n }\n const start = await meter.spent()\n await ask()\n const first = await meter.spent()\n let warmest = 0\n let previous = first\n for (let run = 0; run < runs; run++) {\n await ask()\n const now = await meter.spent()\n warmest = Math.max(warmest, now - previous)\n previous = now\n }\n readings.push({ route: name, status, cold: first - start, warm: warmest })\n }\n const over = readings.filter(\n reading => reading.warm > warm || (cold !== undefined && reading.cold > cold),\n )\n if (over.length > 0)\n throw new Error(\n `Over the CPU budget (warm ${warm} ms${cold === undefined ? '' : `, cold ${cold} ms`}): ` +\n `${over.map(reading => reading.route).join(', ')}\\n` +\n readings\n .map(\n reading =>\n ` ${reading.route}: cold ${reading.cold.toFixed(2)} ms, ` +\n `warm ${reading.warm.toFixed(2)} ms (status ${reading.status})`,\n )\n .join('\\n'),\n )\n return readings\n}\n\nconst pause = new Int32Array(new SharedArrayBuffer(4))\n\n/**\n * Milliseconds this thread has run. Linux books a running thread's time at\n * each scheduler tick (4 ms at 250 Hz), and `threadCpuUsage` reads that\n * book; a millisecond's sleep has the scheduler book the rest, and its own\n * count is in nanoseconds. Read synchronously, so on this thread rather\n * than the pool's.\n */\nconst threadTime = (): number => {\n if (process.platform === 'linux') {\n Atomics.wait(pause, 0, 0, 1)\n return Number(readFileSync('/proc/thread-self/schedstat', 'utf8').split(' ')[0]) / 1e6\n }\n const { user, system } = process.threadCpuUsage()\n return (user + system) / 1000\n}\n\n/**\n * A meter over `answer` run in this process, by this thread's CPU time: for\n * a Worker's handler Node can run (no D1 or other binding of workerd's),\n * whose work happens on the thread that awaits it.\n */\nconst inThread = (\n answer: (request: Request) => Promise<CpuAnswer>,\n origin = 'http://localhost',\n): CpuMeter => ({ origin, fetch: answer, spent: async () => threadTime() })\n\n/**\n * What a request costs in CPU time, which Miniflare neither limits nor\n * reports, while a deployed Worker fails past its plan's limit (error 1102).\n * `Cpu.budget` reads routes through a meter: a stack's `cpu`, or `Cpu.inThread`.\n */\nexport const Cpu = { budget, inThread } as const\n\n/**\n * The part of the configuration the stack reads itself. Wrangler validates\n * the whole of it when the harness loads it.\n */\nconst Config = Schema.Struct({\n main: Schema.String,\n compatibility_date: Schema.String,\n // The stack bundles; Wrangler bundling `main` again would deploy other code.\n no_bundle: Schema.Literal(true),\n d1_databases: Schema.optional(Schema.Array(Schema.Struct({ binding: Schema.String }))),\n})\n\n/**\n * The newest date the workerd Wrangler starts supports, from Wrangler's own\n * Miniflare: an application's own `miniflare` may be another release. Call it\n * after `wrangler()`, which says so when Wrangler is missing.\n */\nconst supportedDate = (): string => {\n const fromWrangler = createRequire(createRequire(import.meta.url).resolve('wrangler'))\n return Schema.decodeUnknownSync(Schema.Struct({ supportedCompatibilityDate: Schema.String }))(\n fromWrangler('miniflare'),\n ).supportedCompatibilityDate\n}\n\nconst readConfig = async (path: string) => {\n const { experimental_readRawConfig } = await wrangler()\n const { rawConfig: raw } = experimental_readRawConfig({ config: path })\n if ('env' in raw)\n throw new Error(`${path}: the local stack runs the top-level Worker; [env.*] is not read.`)\n const config = Schema.decodeUnknownSync(Config)(raw)\n // Miniflare would run a date it does not know at its own latest, with a\n // warning nobody reads, and the tests would pass on a runtime the deploy does not get.\n const supported = supportedDate()\n if (config.compatibility_date > supported)\n throw new Error(\n `${path} asks for compatibility_date ${config.compatibility_date}, but the installed ` +\n `workerd supports up to ${supported}. Move wrangler to a release that knows it.`,\n )\n return { raw, config }\n}\n\n// The modules Vite's view-identity transform reads, and the loader each is read with.\nconst scriptLoaders: Readonly<Record<string, Loader>> = {\n '.ts': 'ts',\n '.mts': 'ts',\n '.tsx': 'tsx',\n '.js': 'js',\n '.mjs': 'js',\n '.jsx': 'jsx',\n}\nconst SCRIPT = /\\.(?:ts|tsx|js|jsx|mts|mjs)$/\nconst scripts = new Set(Object.values(scriptLoaders))\n// Vite skips installed packages: Foldkit's own, whose brand would stamp every vnode as it is made.\nconst isPackaged = (path: string) => /[\\\\/]node_modules[\\\\/]/.test(path)\n\n/**\n * The plugins, with the Worker's views branded as `@foldkit/vite-plugin`\n * brands the page's build: each function's result named by its module's path\n * from `root`. Foldkit adopts a served element only where that name is the\n * one the browser's view gives it; unbranded, the Worker's page was rebuilt on\n * every hydration, silently in production (#412).\n *\n * Vite brands what any load returns, but esbuild takes the first `onLoad`\n * that answers, so each plugin's is wrapped and a module it loads (with\n * `pnpm mutate`'s edits, say) is branded too. `foldkit/brand` resolves from\n * `root`, as the page's does; a root that resolves none has no Foldkit page\n * to match, and the Worker is bundled as written.\n */\nconst viewIdentity = (root: string, plugins: ReadonlyArray<Plugin>): Array<Plugin> => {\n // Found at each build's start, so a watched stack sees Foldkit installed.\n let brand = Option.none<string>()\n const resolving = Symbol('foldkit/brand')\n const brands = ({ path, namespace }: OnLoadArgs) =>\n Option.isSome(brand) && namespace === 'file' && SCRIPT.test(path) && !isPackaged(path)\n /** `contents` branded, or none where nothing in them returns. */\n const branded = async (\n contents: string | Uint8Array,\n loader: Loader,\n path: string,\n ): Promise<Option.Option<string>> => {\n const { transform } = await esbuild()\n const { transformViewIdentity } = await foldkitVite()\n // The brand reads JavaScript, as Vite hands it over after its own TypeScript pass.\n const { code } = await transform(contents, { loader, sourcefile: path })\n return Option.fromNullOr(transformViewIdentity(code, path, root)).pipe(\n Option.map(result => result.code),\n )\n }\n const brandedResult = async (result: OnLoadResult, args: OnLoadArgs): Promise<OnLoadResult> => {\n const loader = result.loader ?? scriptLoaders[extname(args.path)]\n const { contents } = result\n if (!brands(args) || contents === undefined || loader === undefined || !scripts.has(loader))\n return result\n return Option.match(await branded(contents, loader, args.path), {\n onNone: () => result,\n onSome: contents => ({ ...result, contents, loader: 'js' }),\n })\n }\n const wrapped = (plugin: Plugin): Plugin => ({\n ...plugin,\n setup: build =>\n plugin.setup({\n ...build,\n onLoad: (options, load) =>\n build.onLoad(options, async args => {\n const result = await load(args)\n return result === null || result === undefined ? result : brandedResult(result, args)\n }),\n }),\n })\n return [\n {\n name: 'foldkit-view-identity',\n setup: build => {\n build.onStart(async () => {\n const found = await build.resolve('foldkit/brand', {\n kind: 'import-statement',\n resolveDir: root,\n pluginData: resolving,\n })\n brand = found.errors.length === 0 ? Option.some(found.path) : Option.none()\n })\n build.onResolve({ filter: /^foldkit\\/brand$/ }, args =>\n args.pluginData === resolving\n ? undefined\n : Option.match(brand, { onNone: () => undefined, onSome: path => ({ path }) }),\n )\n },\n },\n ...plugins.map(wrapped),\n {\n // Last: a module no plugin loaded, read from disk.\n name: 'foldkit-view-identity-load',\n setup: build =>\n build.onLoad({ filter: SCRIPT }, async args => {\n const loader = scriptLoaders[extname(args.path)]\n if (!brands(args) || loader === undefined) return undefined\n const code = await branded(await readFile(args.path), loader, args.path)\n return Option.match(code, {\n onNone: () => undefined,\n onSome: contents => ({ contents, loader: 'js' as const }),\n })\n }),\n },\n ]\n}\n\n/**\n * How the entry is bundled, for the stack and for `wrangler deploy`: the\n * script at `outfile`, and beside it any `.wasm` it imports, which `no_bundle`\n * Wrangler loads as a compiled module. `node:*` stays external for\n * `nodejs_compat`.\n */\nconst bundleOptions = (options: StackOptions, outfile: string) =>\n ({\n entryPoints: [options.entry],\n bundle: true,\n format: 'esm',\n platform: 'browser',\n conditions: ['foldkit-plus:source'],\n external: ['cloudflare:workers', 'node:*'],\n loader: { '.wasm': 'copy' },\n plugins: viewIdentity(\n resolve(options.pageRoot ?? dirname(options.wrangler)),\n options.plugins ?? [],\n ),\n outdir: dirname(outfile),\n entryNames: basename(outfile, '.js'),\n write: false,\n logLevel: 'silent',\n }) satisfies BuildOptions\n\ntype OutputFiles = ReadonlyArray<OutputFile>\n\nconst writeOutputs = async (\n files: ReadonlyArray<{ readonly path: string; readonly contents: Uint8Array }>,\n) => {\n for (const file of files) {\n await mkdir(dirname(file.path), { recursive: true })\n await writeFile(file.path, file.contents)\n }\n}\n\nconst identityOf = (files: OutputFiles) => files.map(file => `${file.path}:${file.hash}`).join()\n\n/** Node's console method for each level workerd writes; any other prints as a log. */\nconst printers = new Map<string, (line: string) => void>([\n ['debug', line => console.debug(line)],\n ['info', line => console.info(line)],\n ['warn', line => console.warn(line)],\n ['error', line => console.error(line)],\n])\n\nconst print = (log: WorkerLog) =>\n (printers.get(log.level) ?? (line => console.log(line)))(`[worker] ${log.message}`)\n\nconst errorText = (error: unknown) => (error instanceof Error ? error.message : String(error))\n\n/** Writes the bundle where `main` says, for `wrangler deploy`. */\nconst writeBundle = async (options: Omit<StackOptions, 'vars' | 'secrets'>): Promise<void> => {\n const { config } = await readConfig(options.wrangler)\n const outfile = resolve(dirname(options.wrangler), config.main)\n const { build } = await esbuild()\n await writeOutputs((await build(bundleOptions(options, outfile))).outputFiles)\n}\n\ntype Raw = Awaited<ReturnType<typeof readConfig>>['raw']\n\n/** What the stack runs: a configuration and a bundle, swapped in together. */\ninterface Running {\n readonly raw: Raw\n readonly config: typeof Config.Type\n readonly files: OutputFiles\n}\n\nconst migrate = async (worker: WorkerHandle, config: typeof Config.Type) => {\n for (const database of config.d1_databases ?? []) await worker.applyD1Migrations(database.binding)\n}\n\n/**\n * Starts the Worker with a fresh, migrated D1 for each `[[d1_databases]]`,\n * and empty R2 and Durable Object storage. Each call is a stack of its own,\n * so test files running side by side share nothing.\n */\nconst start = async <Env>(options: StackOptions): Promise<Stack<Env>> => {\n const { raw, config } = await readConfig(options.wrangler)\n const { build, context } = await esbuild()\n const { createTestHarness } = await wrangler()\n const directory = join(tmpdir(), `foldkit-workers-${crypto.randomUUID()}`)\n const outfile = join(directory, basename(config.main))\n // Where a change is started on a workerd of its own before the swap.\n const trialDirectory = join(directory, 'trial')\n const bundle = bundleOptions(options, outfile)\n // In memory: a source that does not build fails here, before anything exists to clean up.\n const first = (await build(bundle)).outputFiles\n\n const optionsFor = (raw: Raw, main: string, vars: Vars | undefined) => ({\n root: dirname(options.wrangler),\n workers: [{ config: { ...raw, main }, vars, secrets: options.secrets }],\n })\n const given = options.vars\n // Given here, or once the stack knows its origin.\n let vars = typeof given === 'function' ? undefined : given\n const harness: TestHarness = createTestHarness(optionsFor(raw, outfile, vars))\n const spawned: Spawned = { processes: [], shared: false }\n // Where a trial's workerd goes: collected only so that a stack starting beside it knows.\n const trials: Spawned = { processes: [], shared: false }\n let closeMeter = () => {}\n // The harness keeps workerd's console and offers no handler, so it is drained:\n // read and cleared in one synchronous step, nothing is read twice or missed.\n const kept: Array<WorkerLog> = []\n const drain = () => {\n const fresh = harness.getLogs()\n harness.clearLogs()\n if (options.console !== 'quiet') fresh.forEach(print)\n kept.push(...fresh)\n }\n const draining = setInterval(drain, 100)\n draining.unref()\n let watching = Option.none<Promise<BuildContext>>()\n let configWatcher = Option.none<FSWatcher>()\n let rereading = Option.none<ReturnType<typeof setTimeout>>()\n // Swaps run one at a time, in the order their changes arrived.\n let swaps: Promise<void> = Promise.resolve()\n let stopping = Option.none<Promise<void>>()\n const dispose = async (watcher: Promise<BuildContext>) => {\n // A context that never opened has nothing to dispose; its failure was the watch's to report.\n const opened = await watcher.then(Option.some, () => Option.none<BuildContext>())\n if (Option.isSome(opened)) await opened.value.dispose()\n }\n // Each step runs however the one before it ended: a step skipped leaves\n // workerd running, or the bundle's directory behind.\n const stopOnce = async () => {\n clearInterval(draining)\n closeMeter()\n Option.map(rereading, clearTimeout)\n Option.map(configWatcher, watcher => watcher.close())\n try {\n const watcher = watching\n watching = Option.none()\n // Waits for a rebuild in flight, whose step sees `stopping`.\n if (Option.isSome(watcher)) await dispose(watcher.value)\n await swaps\n } finally {\n try {\n await harness.close()\n } finally {\n // What the Worker wrote since the last drain, up to its end, is printed and kept.\n drain()\n await rm(directory, { recursive: true, force: true })\n }\n }\n }\n const stop = () =>\n Option.getOrElse(stopping, () => {\n const once = stopOnce()\n stopping = Option.some(once)\n return once\n })\n\n try {\n await writeOutputs(first)\n const { url } = await collect(spawned, () => harness.listen())\n // A reload at the same origin, as a swap is, before any request of the caller's.\n if (typeof given === 'function') {\n vars = given(url.origin)\n await collect(spawned, () => harness.update(optionsFor(raw, outfile, vars)))\n }\n const worker = harness.getWorker()\n const metered = workerdMeter(url.origin, worker.fetch, spawned)\n closeMeter = metered.close\n await migrate(worker, config)\n\n const watch = async (listener: WatchListener) => {\n if (Option.isSome(stopping)) throw new Error('This stack has stopped.')\n if (Option.isSome(watching)) throw new Error('This stack is already watching.')\n // None once a swap failed after its trial and took the runtime with it.\n let running = Option.some<Running>({ raw, config, files: first })\n\n /**\n * Starts `next` on a workerd of its own, then swaps it in. A Worker\n * that does not start is refused there, and the stack's harness, which\n * a failed update tears down with its storage, never sees it.\n */\n const swap = async (next: Running) => {\n try {\n await writeOutputs(\n next.files.map(file => ({\n path: join(trialDirectory, relative(directory, file.path)),\n contents: file.contents,\n })),\n )\n const trial = createTestHarness(\n optionsFor(next.raw, join(trialDirectory, basename(outfile)), vars),\n )\n try {\n await collect(trials, () => trial.listen())\n await migrate(trial.getWorker(), next.config)\n } finally {\n await trial.close()\n }\n } catch (error) {\n listener.onRefused(errorText(error))\n return\n }\n try {\n await writeOutputs(next.files)\n await collect(spawned, () => harness.update(optionsFor(next.raw, outfile, vars)))\n } catch (error) {\n running = Option.none()\n listener.onStopped(errorText(error))\n return\n }\n running = Option.some(next)\n try {\n await migrate(harness.getWorker(), next.config)\n } catch (error) {\n listener.onRefused(\n `The Worker was swapped in, but a migration failed: ${errorText(error)}`,\n )\n return\n }\n listener.onSwap()\n }\n /** Queues a swap of what `change` makes of the running stack, which may be none. */\n const enqueue = (change: (now: Running) => Promise<Option.Option<Running>>) => {\n const step = swaps.then(async () => {\n // A step that runs once `stop` began swaps nothing: `stop` waits for\n // it before closing the harness, so it would swap into a closing stack.\n if (Option.isNone(running) || Option.isSome(stopping)) return\n const next = await change(running.value)\n if (Option.isSome(next)) await swap(next.value)\n })\n // A listener that throws fails its own step, not the ones after it.\n swaps = step.catch(() => undefined)\n return step\n }\n\n const watcher = context({\n ...bundle,\n plugins: [\n ...bundle.plugins,\n {\n name: 'foldkit-swap',\n setup: build =>\n build.onEnd(result =>\n enqueue(async now => {\n if (result.errors.length > 0) {\n listener.onRefused(result.errors.map(error => error.text).join('\\n'))\n return Option.none()\n }\n const files = result.outputFiles ?? []\n // An editor saving in place empties the file before writing it, and a\n // rebuild can read it then; the write's own rebuild swaps.\n if (files.some(file => file.path === outfile && file.contents.length === 0)) {\n listener.onRefused(\n `${options.entry} bundles to no code, so no Worker could start.`,\n )\n return Option.none()\n }\n return identityOf(files) === identityOf(now.files)\n ? Option.none()\n : Option.some({ ...now, files })\n }),\n ),\n },\n ],\n })\n watching = Option.some(watcher)\n try {\n await (await watcher).watch()\n } catch (error) {\n // Not watching after all: `stop` must not wait on this context, nor a second `watch` be refused.\n if (Option.contains(watching, watcher)) {\n watching = Option.none()\n await dispose(watcher)\n }\n throw error\n }\n // A `stop` that began while the context opened would close no watcher made now.\n if (Option.isSome(stopping)) return\n\n const reread = () =>\n enqueue(async now => {\n const read = await readConfig(options.wrangler).then(Option.some, (error: unknown) => {\n listener.onRefused(errorText(error))\n return Option.none<Awaited<ReturnType<typeof readConfig>>>()\n })\n // A save that changed nothing the configuration says.\n return read.pipe(\n Option.filter(({ raw }) => JSON.stringify(raw) !== JSON.stringify(now.raw)),\n Option.map(({ raw, config }) => ({ ...now, raw, config })),\n )\n })\n // The directory, not the file: an editor that renames a temporary over the\n // file replaces what a file watcher watches.\n const name = basename(options.wrangler)\n configWatcher = Option.some(\n watchFile(dirname(options.wrangler), (_, changed) => {\n if (changed !== name) return\n // One reread for the burst of events a single save makes.\n Option.map(rereading, clearTimeout)\n rereading = Option.some(setTimeout(() => void reread(), 50))\n }).on('error', error =>\n listener.onRefused(`The configuration is no longer watched: ${errorText(error)}`),\n ),\n )\n }\n\n const env = () => harness.getWorker<Env>().getEnv()\n const logs = () => {\n drain()\n return kept.splice(0)\n }\n return {\n origin: url.origin,\n env,\n dispatch: worker.fetch,\n logs,\n cpu: metered.meter,\n watch,\n stop,\n }\n } catch (error) {\n // The start's failure is the one to report; a failure cleaning up after it would hide it.\n await stop().catch(() => undefined)\n throw error\n }\n}\n\n/**\n * The local Workers stack. `Stack.start` runs the Worker for tests and\n * development; `Stack.writeBundle` writes what `wrangler deploy` uploads,\n * bundled the same way.\n */\nexport const Stack = { start, writeBundle } as const\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,UAAU;A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