@uniflowed/vite 0.0.0-alpha.4 → 0.0.0-alpha.40

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/driver.js CHANGED
@@ -2,13 +2,34 @@
2
2
  //
3
3
  // Plain JavaScript: the host runs this file directly.
4
4
  //
5
- // The driver `uf dev`, `uf build` and `uf preview` spawn.
5
+ // The driver `uf dev`, `uf build`, `uf build --compile`, `uf preview` and
6
+ // `uf start` spawn.
6
7
  //
7
- // <host> driver.js dev --root <dir> [--host <h>] [--port <n>] [--strict-port]
8
- // <host> driver.js build --root <dir> [--out-dir <dir>] [--mode <m>]
9
- // <host> driver.js preview --root <dir> [--host <h>] [--port <n>]
8
+ // <host> driver.js dev --root <dir> [--mode <m>] [--host <h>] [--port <n>] [--strict-port]
9
+ // [--uf-env-file <file>]...
10
+ // <host> driver.js build --root <dir> [--mode <m>] [--out-dir <dir>] [--target <target>]
11
+ // [--prerender everything|possible|nothing]
12
+ // [--static-build] [--because <sentence>]
13
+ // <host> driver.js library --root <dir> [--mode <m>] [--out-dir <dir>]
14
+ // --entry <file>... --format <es|cjs>... [--external <name>]...
15
+ // <host> driver.js compile --root <dir> [--mode <m>] [--out-dir <dir>] --assets <file> --bundle <dir>
16
+ // <host> driver.js deploy --root <dir> [--mode <m>] [--out-dir <dir>] --adapter <name> --work <dir> --output <dir>
17
+ // <host> driver.js preview --root <dir> [--mode <m>] [--out-dir <dir>] [--host <h>] [--port <n>]
18
+ // <host> driver.js start --root <dir> [--out-dir <dir>] [--host <h>] [--port <n>]
10
19
  // <host> driver.js config --root <dir>
11
20
  //
21
+ // `--mode` is what `uf` resolved from `--mode`, `.uniflowed/profile` and
22
+ // `env.active`; it is Vite's mode, so it is `import.meta.env.MODE`. The `.env`
23
+ // files it selected have already been read, by `uf`, into this process's
24
+ // environment — see `viteConfig` below and `crates/uf_config/src/env_files.rs`.
25
+ // `start` has no Vite in it and therefore no mode.
26
+ //
27
+ // `--uf-env-file` names those files, one flag each, so `dev` can watch them and
28
+ // say when one moved; nothing here reads their contents. The prefix is load
29
+ // bearing: node claims `--env-file` for itself and honours it wherever it
30
+ // appears on the command line, script arguments included, so a driver argument
31
+ // by that name is an argument node eats and then exits 9 over.
32
+ //
12
33
  // `uf` in Rust owns the terminal; this process owns Vite. They talk over
13
34
  // stdout, one JSON event per line (see `./internal/events.js`), and the driver
14
35
  // exits when its stdin closes so it cannot outlive the command that started
@@ -18,21 +39,63 @@
18
39
  // Rust side reads a config that may hold functions and plugin instances: the
19
40
  // one host that can evaluate the file evaluates it.
20
41
 
21
- import { register } from "node:module";
22
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
42
+ import { randomUUID } from "node:crypto";
43
+ import { createServer as createHttpServer } from "node:http";
44
+ import { builtinModules, register } from "node:module";
45
+ import { installFlowHooks } from "@uniflowed/host/internal/sync-hooks.js";
46
+ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
23
47
  import path from "node:path";
24
48
  import { pathToFileURL } from "node:url";
25
49
 
50
+ import { COMPILE_ASSETS_ID, compileAssetsPlugin } from "./internal/compile-assets.js";
51
+ import {
52
+ survivingImports,
53
+ unavailableOnWorkers,
54
+ workerBuiltinWarnings,
55
+ } from "./internal/worker-builtins.js";
26
56
  import { emit, errorEvent, eventLogger } from "./internal/events.js";
27
57
  import { loadUfConfig, projectConfig } from "./internal/config.js";
58
+ import { send, toAddressRequest, toRequest } from "./internal/http.js";
59
+ import { createOpenApiDocument } from "./internal/openapi.js";
28
60
  import { withProjectConfig } from "./merge.js";
29
- import { VIRTUAL, scanRoutes } from "./internal/routes.js";
61
+ import { FLIGHT_VIRTUAL, RSC_ENVIRONMENT } from "./internal/flight.js";
62
+ import { MODULE_GRAPH_FILE, createModuleGraphCollector } from "./internal/module-graph.js";
63
+ import { VIRTUAL, resolveRouteTarget, routingRulesOf, scanRoutes } from "./internal/routes.js";
64
+ import {
65
+ BUILD_ID_FILE,
66
+ DOCUMENT_ASSETS_FILE,
67
+ REGENERATED_DIRECTORY,
68
+ REGENERATION_FILE,
69
+ answerRouting,
70
+ answersInFrontOfFiles,
71
+ assetsFromManifest,
72
+ buildIdentity,
73
+ createPrerenderGate,
74
+ createServeHandler,
75
+ documentAssetsFor,
76
+ forViteBase,
77
+ loadBuild,
78
+ nodeListener,
79
+ providerSpecifier,
80
+ readRegeneration,
81
+ withRequest,
82
+ } from "./internal/serve.js";
30
83
 
31
84
  function argument(name) {
32
85
  const at = process.argv.indexOf(name);
33
86
  return at === -1 ? null : process.argv[at + 1];
34
87
  }
35
88
 
89
+ /** Every value of a repeated argument, in the order they were given. */
90
+ function argumentAll(name) {
91
+ const values = [];
92
+ for (let at = 0; at < process.argv.length; at += 1) {
93
+ if (process.argv[at] === name && process.argv[at + 1] != null)
94
+ values.push(process.argv[at + 1]);
95
+ }
96
+ return values;
97
+ }
98
+
36
99
  function flag(name) {
37
100
  return process.argv.includes(name);
38
101
  }
@@ -47,11 +110,23 @@ process.env.UF_PROJECT_ROOT = root;
47
110
  // hooks for that; Bun is started with `--preload` on the same package's
48
111
  // preload instead, and has no `register`.
49
112
  //
113
+ // Deno has no `register` either, and it gets its hooks *here* rather than from
114
+ // a preload, for a reason that is about order. While a Deno `load` hook is
115
+ // registered, `require()` of a native addon fails — and Vite requires one,
116
+ // Rolldown's binding. The static imports above have already loaded Vite by
117
+ // this line, binding included, so hooks installed now see only what is
118
+ // imported after them: the config, and the `@uniflowed/*` modules this driver
119
+ // reaches dynamically. They are the in-thread hooks a new enough Node takes
120
+ // through `@uniflowed/host/register` too; see
121
+ // `@uniflowed/host/internal/sync-hooks.js`.
122
+ //
50
123
  // The hooks live in `@uniflowed/host` rather than here: they are how Flow runs
51
124
  // on a Capability JS Host, and nothing in them is Vite's. `uf test` reaches for
52
125
  // the same package, which is what stopped a test run from depending on a
53
126
  // bundler it never loads.
54
- if (typeof Bun === "undefined" && typeof Deno === "undefined") {
127
+ if (typeof Deno !== "undefined") {
128
+ installFlowHooks(root);
129
+ } else if (typeof Bun === "undefined") {
55
130
  register("@uniflowed/host/internal/node-hooks.js", import.meta.url, { data: { root } });
56
131
  }
57
132
 
@@ -59,7 +134,7 @@ process.stdin.on("end", () => process.exit(0));
59
134
  process.stdin.on("error", () => process.exit(0));
60
135
  process.stdin.resume();
61
136
 
62
- const commands = { dev, build, preview, config: printConfig };
137
+ const commands = { dev, build, library, compile, deploy, preview, start, config: printConfig };
63
138
  const run = commands[command];
64
139
  if (run == null) {
65
140
  emit("error", { message: `unknown driver command ${JSON.stringify(command)}` });
@@ -71,6 +146,33 @@ run().catch((error) => {
71
146
  process.exit(1);
72
147
  });
73
148
 
149
+ /**
150
+ * What this build is called, for anything that outlives it.
151
+ *
152
+ * `UF_BUILD_ID` when it is set, and a fresh random name otherwise — which is
153
+ * `crates/uf_rsc`'s `BuildId::from_env_or_generate` exactly, reading the same
154
+ * variable, because it is the same question asked by a different half of the
155
+ * toolchain. Two artefacts that have to *be* one build say so with the
156
+ * variable; everything else gets a name no other build has.
157
+ *
158
+ * Minted once per build and written into the build, never per process. Four
159
+ * servers started from one artefact are one build and must share one cache;
160
+ * generating this where the server starts would give them four, which is worse
161
+ * than none at all — four copies of everything written into one directory and
162
+ * none of them read.
163
+ *
164
+ * Not a hash of the output. A content hash would be reproducible, which is
165
+ * appealing and wrong here: two builds with identical client bundles can have
166
+ * different server behaviour — a loader's body moves and no asset hash does —
167
+ * and a cache keyed by one would serve the old loader's documents. A name that
168
+ * changes whenever the build ran is the conservative direction to be wrong in.
169
+ */
170
+ function mintBuildId() {
171
+ const named = process.env.UF_BUILD_ID;
172
+ if (typeof named === "string" && named.trim() !== "") return named.trim();
173
+ return randomUUID().replaceAll("-", "");
174
+ }
175
+
74
176
  /** Load `uf.config.js`, reporting where it was found. */
75
177
  async function loadConfig() {
76
178
  const { config, file } = await loadUfConfig(root);
@@ -78,6 +180,15 @@ async function loadConfig() {
78
180
  return config;
79
181
  }
80
182
 
183
+ /**
184
+ * `app.router.basePath` as the driver uses it: `""` at the root, `"/docs"`
185
+ * otherwise. Read where the build writes asset URLs and file names, because a
186
+ * prerendered document is written outside Vite's HTML transform.
187
+ */
188
+ function basePathOf(config) {
189
+ return routingRulesOf(config.app?.router).basePath;
190
+ }
191
+
81
192
  /** The Vite inline config a uf config describes. */
82
193
  async function viteConfig(config, mode) {
83
194
  const { default: uniflowed } = await import("./index.js");
@@ -88,19 +199,59 @@ async function viteConfig(config, mode) {
88
199
  const port = Number(argument("--port") ?? dev.port ?? 5173);
89
200
  const allowedHosts =
90
201
  Array.isArray(dev.allowedHosts) && dev.allowedHosts.length > 0 ? dev.allowedHosts : undefined;
202
+ const routeTarget = resolveRouteTarget(config, argument("--target"));
91
203
 
92
204
  // What uf generates from the semantics it owns: where the project is, which
93
205
  // plugins make Flow compile, and the few settings uf enforces rather than
94
206
  // merely passes on — `allowedHosts` gates binding a routable address, and
95
207
  // `manifest` is how the prerender finds its assets.
208
+ //
209
+ // `envDir: false` turns off Vite's *file* loading, and only that. uf reads
210
+ // the `.env` cascade itself, in Rust, before this process starts — one
211
+ // parser, one precedence, one answer for `uf dev`, `uf build`, `uf start`,
212
+ // `uf test` and `uf run` — and sets what it read in this process's
213
+ // environment. Vite's `loadEnv` still runs with `envDir: false` and still
214
+ // picks every `envPrefix`-matching name out of `process.env`, so the client
215
+ // half is Vite's own, unchanged: the prefixed subset becomes
216
+ // `import.meta.env.*` in the browser bundle and nothing else does. See
217
+ // `crates/uf_config/src/env_files.rs`, `docs/app/guide/env` and #259.
218
+ //
219
+ // A project that would rather Vite read the files can still say
220
+ // `vite: { envDir: "." }` — its own configuration is merged over this one —
221
+ // and then both parsers run, uf's answer still standing. `loadEnv` takes the
222
+ // prefixed names out of the files it read and then copies every prefixed name
223
+ // in `process.env` over the top, and uf put its own there before this process
224
+ // started; so the second parser adds prefixed names uf did not set and
225
+ // changes none that it did.
96
226
  const generated = {
97
227
  root,
98
228
  configFile: false,
99
- envFile: false,
229
+ envDir: false,
100
230
  mode,
231
+ // Vite's dependency cache, kept in the project whatever is above it.
232
+ // Vite's own default is the nearest `package.json`'s `node_modules/.vite`,
233
+ // and a uf project needs no `package.json`. One inside another repository
234
+ // pre-bundled into that repository's `node_modules`, in one directory
235
+ // shared with every other such project there and emptied by each dev
236
+ // server that started — which is how two `uf dev` servers came to answer
237
+ // each other's pre-bundled files with `504 Outdated Optimize Dep`
238
+ // (ubugeeei-prod/uf#1141).
239
+ //
240
+ // This directory rather than `.vite` or `.uf/cache/vite`, because it is
241
+ // where Vite already puts the cache for a project with its own
242
+ // `package.json`, so nothing moves for one: the URLs stay
243
+ // `/node_modules/.vite/deps/…`, and the files stay under `node_modules`,
244
+ // which git ignores, Vite's watcher skips and Vite's sourcemap ignore list
245
+ // treats as somebody else's code. `cacheDir` is shared config, so every
246
+ // environment's optimizer follows it — `deps`, `deps_ssr`, `deps_rsc` —
247
+ // and a project's own `vite.cacheDir` is merged over it like any option.
248
+ cacheDir: path.join(root, "node_modules", ".vite"),
249
+ // `app.router.basePath`: where Vite serves the modules in development, and
250
+ // what it puts in front of every asset URL a build writes.
251
+ base: basePathOf(config) === "" ? "/" : `${basePathOf(config)}/`,
101
252
  clearScreen: false,
102
253
  customLogger: eventLogger(argument("--log-level") ?? "info"),
103
- plugins: [uniflowed({ root, config })],
254
+ plugins: [uniflowed({ root, config, target: routeTarget })],
104
255
  server: {
105
256
  host,
106
257
  port,
@@ -111,7 +262,17 @@ async function viteConfig(config, mode) {
111
262
  deny: dev.fs?.deny,
112
263
  },
113
264
  },
114
- preview: { host, port },
265
+ // Not `server`, and not `dev.port` either. Vite's own default for a
266
+ // preview is 4173 rather than 5173, and the reason is the case this
267
+ // command exists for: somebody comparing a build against the dev server
268
+ // they left running. Taking `dev.port` would have made the two collide,
269
+ // and Vite would have moved the preview to the next free port and served
270
+ // it somewhere nobody was looking.
271
+ preview: {
272
+ host: argument("--host") ?? "127.0.0.1",
273
+ port: Number(argument("--port") ?? 4173),
274
+ strictPort: flag("--strict-port"),
275
+ },
115
276
  build: {
116
277
  outDir: argument("--out-dir") ?? build.outDir ?? "dist",
117
278
  sourcemap: build.sourcemap ?? true,
@@ -135,72 +296,43 @@ async function viteConfig(config, mode) {
135
296
  * Vite in middleware mode serves nothing on its own: with no `index.html` at
136
297
  * the project root it answers every navigation with "Cannot GET /", which is
137
298
  * what `uf dev` used to do for every project it started. A uf project has no
138
- * `index.html` — the document comes from a layout — so the server has to render
139
- * it, which is what this middleware does:
299
+ * `index.html` — the document comes from a layout — so the server has to
300
+ * render it.
140
301
  *
141
- * 1. load the server entry through `ssrLoadModule`, so it is transformed the
142
- * same way the browser's copy is and picks up edits without a restart;
143
- * 2. render the URL, pointing the client script at the dev entry rather than
144
- * at a built asset;
145
- * 3. hand the HTML to `transformIndexHtml`, which is what injects the HMR
146
- * client and lets any Vite plugin see the document.
302
+ * That rendering is **not** here. It is one middleware, in `./index.js`'s
303
+ * `configureServer`, and this function installs none of its own. It used to
304
+ * install a second one, and two middlewares rendering the same request is how
305
+ * `uf dev` came to answer a route handler with a page and a redirect without
306
+ * its `Location`: `configureServer`'s post hook runs inside `createServer`,
307
+ * and anything added here runs after it returns, so of the two the plugin's
308
+ * was always the one that decided. See ubugeeei-prod/uf#349 and #338, and the
309
+ * comment above that middleware for what it now has to do.
147
310
  *
148
- * Anything Vite already serves — a module, a public file — never reaches this,
149
- * because the middleware runs after Vite's own.
311
+ * What is left here is the half that is genuinely the driver's: the Vite
312
+ * config, the socket, the event channel back to `uf`, and the two watchers
313
+ * below.
150
314
  */
151
315
  async function dev() {
152
316
  const { createServer } = await import("vite");
153
317
  const config = await loadConfig();
154
- const inline = await viteConfig(config, "development");
318
+ const routeTarget = resolveRouteTarget(config, argument("--target"));
319
+ // The mode is uf's to decide, not this file's: `uf dev` resolves `--mode`,
320
+ // the profile `uf env use` wrote and `env.active` before it starts anything,
321
+ // and always passes the answer. The fallback is for a driver started by hand.
322
+ const inline = await viteConfig(config, argument("--mode") ?? "development");
155
323
  const server = await createServer({ ...inline, appType: "custom" });
156
324
 
157
- // In dev the browser loads the client entry from Vite, not from a manifest;
158
- // its stylesheets arrive through that module rather than as <link> tags.
159
- const assets = { scripts: [`/@id/${VIRTUAL.client}`], styles: [], preloads: [] };
160
-
161
- server.middlewares.use(async (request, response, next) => {
162
- const url = request.originalUrl ?? request.url ?? "/";
163
- try {
164
- const entry = await server.ssrLoadModule(VIRTUAL.server);
165
-
166
- // Route handlers first, and for every method: a handler is the only
167
- // thing that answers a POST, and it may also answer a GET for a path
168
- // that has no page.
169
- const handled = await entry.dispatch(await toRequest(request, server.config));
170
- if (handled != null) {
171
- await send(response, handled);
172
- return;
173
- }
174
-
175
- // Only a navigation reaches the renderer. A page cannot answer a POST,
176
- // and letting one try would turn a missing handler into a rendered page
177
- // with a 200 rather than a 404.
178
- if (request.method !== "GET" && request.method !== "HEAD") {
179
- next();
180
- return;
181
- }
182
-
183
- const result = await entry.render(url, assets);
184
- const html = await server.transformIndexHtml(url, result.html);
185
- response.statusCode = result.status ?? 200;
186
- response.setHeader("content-type", "text/html; charset=utf-8");
187
- response.end(html);
188
- } catch (error) {
189
- // Map the stack back onto the Flow source before it reaches the overlay.
190
- if (error instanceof Error) server.ssrFixStacktrace(error);
191
- next(error);
192
- }
193
- });
194
-
195
325
  await server.listen();
196
326
  const urls = server.resolvedUrls ?? { local: [], network: [] };
197
327
  emit("listening", {
198
328
  local: urls.local,
199
329
  network: urls.network,
200
- routes: scanRoutes(path.resolve(root, config.app?.router?.root ?? "app")).routes.map(
201
- (route) => route.path,
202
- ),
330
+ routes: scanRoutes(path.resolve(root, config.app?.router?.root ?? "app"), {
331
+ target: routeTarget,
332
+ }).routes.map((route) => route.path),
203
333
  });
334
+ watchSources(server);
335
+ watchEnvFiles(server);
204
336
 
205
337
  const shutdown = async () => {
206
338
  await server.close();
@@ -211,67 +343,252 @@ async function dev() {
211
343
  }
212
344
 
213
345
  /**
214
- * A Node request as a `Request`.
346
+ * Tell the Rust side when a module under the project root changed.
347
+ *
348
+ * `uf dev` answers questions Vite does not: whether a module is a Server
349
+ * Component, and whether a Server Component reaches for something that only
350
+ * exists in a browser. Those are whole-project answers, so they go stale on
351
+ * any edit and there is no module to recompute them *for* — which is why this
352
+ * event carries no path. What it carries is "ask again".
353
+ *
354
+ * Vite's watcher is the only watcher. A second one over the same tree, in
355
+ * Rust, would be a second answer to "did this file change", and two watchers
356
+ * disagree exactly when an editor writes through a temporary file — which is
357
+ * every editor, and which is not a thing anybody tests.
215
358
  *
216
- * The handler contract is the platform's, so the adapter belongs here rather
217
- * than in every handler. The body is read as a stream where the host supports
218
- * it, because a handler that accepts an upload should not need the whole thing
219
- * buffered before it starts.
359
+ * Debounced, because a `git checkout` is one intention and several hundred
360
+ * `change` events, and unrefed so a pending timer cannot keep this process
361
+ * alive after the server has closed.
220
362
  */
221
- async function toRequest(incoming, config) {
222
- const host = incoming.headers.host ?? "localhost";
223
- const protocol = config?.server?.https == null ? "http" : "https";
224
- const url = new URL(incoming.originalUrl ?? incoming.url ?? "/", `${protocol}://${host}`);
225
-
226
- const headers = new Headers();
227
- for (const [name, value] of Object.entries(incoming.headers)) {
228
- if (value == null) continue;
229
- for (const entry of Array.isArray(value) ? value : [value]) {
230
- headers.append(name, entry);
231
- }
232
- }
233
-
234
- const method = (incoming.method ?? "GET").toUpperCase();
235
- const init = { method, headers };
236
- if (method !== "GET" && method !== "HEAD") {
237
- // `duplex` is required by the specification whenever a body is a stream,
238
- // and Node throws without it.
239
- init.body = incoming;
240
- init.duplex = "half";
363
+ function watchSources(server) {
364
+ let timer = null;
365
+ const changed = () => {
366
+ if (timer != null) clearTimeout(timer);
367
+ timer = setTimeout(() => {
368
+ timer = null;
369
+ emit("source-changed");
370
+ }, 50);
371
+ timer.unref?.();
372
+ };
373
+ const isSource = (file) =>
374
+ (file.endsWith(".js") || file.endsWith(".jsx")) && !file.includes("node_modules");
375
+ for (const event of ["add", "change", "unlink"]) {
376
+ server.watcher.on(event, (file) => {
377
+ if (isSource(file)) changed();
378
+ });
241
379
  }
242
- return new Request(url, init);
243
380
  }
244
381
 
245
- /** Write a `Response` to a Node response. */
246
- async function send(outgoing, result) {
247
- outgoing.statusCode = result.status;
248
- if (result.statusText !== "") {
249
- outgoing.statusMessage = result.statusText;
250
- }
251
- for (const [name, value] of result.headers) {
252
- outgoing.setHeader(name, value);
253
- }
254
- if (result.body == null) {
255
- outgoing.end();
256
- return;
257
- }
258
- // Streamed rather than buffered, so a handler returning a large or
259
- // open-ended body is not read into memory first.
260
- const reader = result.body.getReader();
261
- while (true) {
262
- const { done, value } = await reader.read();
263
- if (done) break;
264
- outgoing.write(value);
382
+ /**
383
+ * Restart the server when one of the `.env` files uf read changes.
384
+ *
385
+ * uf reads the `.env` cascade itself, in Rust, before this process starts —
386
+ * one parser, one precedence, one answer for every command (see `viteConfig`
387
+ * above and `crates/uf_config/src/env_files.rs`) — and `envDir: false` turns
388
+ * Vite's own file loading off so there cannot be two answers. The cost of that
389
+ * was that nothing watched them: a value edited while `uf dev` ran changed
390
+ * nothing until somebody restarted the command by hand, and the guide had to
391
+ * document it as a limitation. See ubugeeei-prod/uf#428.
392
+ *
393
+ * `uf` passes the files it would consult with `--uf-env-file`, one per file, in
394
+ * cascade order, whether or not each exists today — a `.env.local` *created*
395
+ * while the server runs changes the answer exactly as much as an edit to one
396
+ * that was already there, and watching only what was read would have missed
397
+ * it. They are added to Vite's watcher explicitly because they are in no
398
+ * module graph, which is the same reason the RSC manifest is added in
399
+ * `index.js`.
400
+ *
401
+ * What is emitted is "these values are stale", and the Rust side restarts this
402
+ * process with the files re-read. A restart rather than a hot update is the
403
+ * honest granularity: a prefixed value reaches the browser by substitution
404
+ * into the bundle, so a new value has to be substituted again, and every
405
+ * module that read one has to be re-evaluated. Vite's watcher is still the
406
+ * only watcher — a second one over the same tree, in Rust, would be a second
407
+ * answer to "did this file change".
408
+ */
409
+ function watchEnvFiles(server) {
410
+ const files = argumentAll("--uf-env-file").map((file) => path.resolve(root, file));
411
+ if (files.length === 0) return;
412
+ const watched = new Set(files);
413
+ server.watcher.add(files);
414
+ for (const event of ["add", "change", "unlink"]) {
415
+ server.watcher.on(event, (file) => {
416
+ if (watched.has(path.resolve(file))) emit("env-changed", { file, change: event });
417
+ });
265
418
  }
266
- outgoing.end();
267
419
  }
268
420
 
421
+ /**
422
+ * The preview server: the build, as Vite serves it.
423
+ *
424
+ * Vite's `preview()` is a static file server, and a uf build is not only
425
+ * static files — a route handler answers a `POST` and a route with parameters
426
+ * and no `generateStaticParams` was never prerendered. On its own it would
427
+ * therefore 404 every request the interesting half of an application exists to
428
+ * answer, which is worse than having no preview at all, because a preview is
429
+ * checked and believed.
430
+ *
431
+ * So the application handler is mounted behind it, and `appType: "custom"` is
432
+ * what makes that reachable: with Vite's default `spa` it inserts an
433
+ * index.html fallback and a 404 middleware of its own, so every unmatched path
434
+ * would have been answered with the home page — a 200 for a path that does not
435
+ * exist — before anything of uf's ran.
436
+ *
437
+ * The static middleware still runs first, and that is deliberate rather than
438
+ * incidental; see `internal/serve.js` for why `uf start` orders itself the
439
+ * same way.
440
+ *
441
+ * One request is the exception, and it is the only thing uf mounts in *front*
442
+ * of Vite here: a request carrying the draft cookie, which no front door may
443
+ * answer from a prerendered document. `createStaticHandler` applies that rule
444
+ * and cannot reach a request Vite's file middleware answered first, so under
445
+ * `uf preview` draft mode appeared to be off while it worked under `uf dev`
446
+ * and `uf start` — ubugeeei-prod/uf#620. `configurePreviewServer` is where a
447
+ * middleware goes ahead of Vite's own; the hook's *body* runs before they are
448
+ * installed and a function it returns runs after, which is why this is a body
449
+ * and the handler below is a `use` on the started server.
450
+ */
269
451
  async function preview() {
270
452
  const { preview: startPreview } = await import("vite");
271
453
  const config = await loadConfig();
272
- const server = await startPreview(await viteConfig(config, "production"));
454
+ const routeTarget = resolveRouteTarget(config, argument("--target"));
455
+ const inline = await viteConfig(config, argument("--mode") ?? "production");
456
+ // A build that declared it emits no server has none to mount. `uf` refuses
457
+ // `uf start` for such a project and lets this one through, because a preview
458
+ // of files *is* the deployment: what a static host does with `dist/` is
459
+ // exactly what Vite's preview server does with it, and mounting a request
460
+ // handler behind it would make this preview right about a deployment that is
461
+ // not the one happening. See `uf_cli`'s `commands::serve`.
462
+ const staticBuild = flag("--static-build");
463
+ const build = staticBuild
464
+ ? null
465
+ : await loadBuild({
466
+ root,
467
+ outDir: inline.build.outDir,
468
+ serverDir: path.join(".uf", "build", "server"),
469
+ });
470
+
471
+ // One handler for both positions in the chain. A draft request meets it in
472
+ // front of Vite's file middleware and every other request meets it behind,
473
+ // and because it is the same handler the two give the same answer — which is
474
+ // the whole reason `uf preview` exists.
475
+ const handle =
476
+ build == null ? null : createServeHandler({ ...build, cache: config.app?.rendering?.cache });
477
+ const answer = (previewServer) => async (request, response, next) => {
478
+ try {
479
+ const asRequest = await toRequest(request, previewServer.config);
480
+ // The same lifecycle `uf start` gets from `nodeListener`, spelled out
481
+ // because this door is Vite's connect chain rather than a bare
482
+ // `node:http` server: the whole request runs inside it, and it settles
483
+ // once `send` has returned. A preview whose `after()` fired at a
484
+ // different moment from the production server's would be a preview that
485
+ // is checked and believed and wrong.
486
+ await withRequest(build.entry, asRequest, async () => {
487
+ await send(response, await handle(asRequest));
488
+ });
489
+ } catch (error) {
490
+ next(error);
491
+ }
492
+ };
493
+
494
+ const mayAnswerFromPrerender = createPrerenderGate();
495
+ const draftFirst = {
496
+ name: "uf:draft-before-files",
497
+ configurePreviewServer(previewServer) {
498
+ // `app.router.headers` and `redirects`, first of all: a redirect answers
499
+ // before a file is looked for, and a header is pinned on the response so
500
+ // it survives the `writeHead` Vite's file middleware writes its own
501
+ // with. `uf start` and every adapter put the same two in front of their
502
+ // static half; the application's own answers get them from
503
+ // `createServeHandler` behind. See `internal/serve.js`'s `answerRouting`.
504
+ const routing = build?.entry?.routing;
505
+ if (answersInFrontOfFiles(routing)) {
506
+ previewServer.middlewares.use((request, response, next) => {
507
+ answerRouting(routing, toAddressRequest(request), response)
508
+ .then((answered) => {
509
+ if (answered) return;
510
+ // The bare base path is the root, which Vite only knows as
511
+ // `/docs/`; see `forViteBase`.
512
+ forViteBase(routing, request);
513
+ next();
514
+ })
515
+ .catch(next);
516
+ });
517
+ }
518
+ // A prerendered payload is a file whose extension Vite's static middleware
519
+ // knows no type for, and the router hands bytes to React only when they
520
+ // are answered as a payload — so a navigation on a preview would silently
521
+ // become a document load. Set here, in front of the file server, which
522
+ // keeps a type it did not choose.
523
+ previewServer.middlewares.use((request, response, next) => {
524
+ if ((request.url ?? "").split("?")[0].endsWith("/__uf.flight")) {
525
+ response.setHeader("content-type", "text/x-component");
526
+ }
527
+ next();
528
+ });
529
+ if (handle == null) return;
530
+ const run = answer(previewServer);
531
+ previewServer.middlewares.use((request, response, next) => {
532
+ // Not `await`ed by connect, which takes no promise: the gate is
533
+ // resolved inside and `next()` is called from there. A rejection is a
534
+ // `next(error)` for the same reason.
535
+ mayAnswerFromPrerender(request.headers.cookie ?? null)
536
+ .then((mayAnswer) => (mayAnswer ? next() : run(request, response, next)))
537
+ .catch(next);
538
+ });
539
+ },
540
+ };
541
+
542
+ const server = await startPreview({
543
+ ...inline,
544
+ appType: "custom",
545
+ plugins: [...(inline.plugins ?? []), draftFirst],
546
+ });
547
+ if (handle != null) {
548
+ server.middlewares.use(answer(server));
549
+ }
550
+ // The rewrite rule a single-page deployment needs, in the one place uf can
551
+ // apply one. A `["csr"]` build writes `index.html` and nothing else that is a
552
+ // page, so a file server answers `/` and 404s every other URL — and this
553
+ // preview exists to be believed about the deployment. A host serving that
554
+ // build has to send unmatched paths to the shell, so a preview that did not
555
+ // would be right about a deployment nobody is doing.
556
+ //
557
+ // Behind the static middleware, which is what makes it a *fallback*: a real
558
+ // file still wins, so `/assets/client.js` is still the chunk and not the
559
+ // shell. And `Accept: text/html` only, so a `fetch` for a missing JSON file
560
+ // gets a 404 rather than a document — the failure mode of a fallback that
561
+ // answers everything is a parse error two layers away from the missing file.
562
+ if (flag("--spa-fallback")) {
563
+ const shell = path.resolve(root, inline.build.outDir, "index.html");
564
+ server.middlewares.use((request, response, next) => {
565
+ if (request.method !== "GET" && request.method !== "HEAD") return next();
566
+ if (!(request.headers.accept ?? "").includes("text/html")) return next();
567
+ if (!existsSync(shell)) return next();
568
+ response.statusCode = 200;
569
+ response.setHeader("content-type", "text/html; charset=utf-8");
570
+ response.end(request.method === "HEAD" ? undefined : readFileSync(shell));
571
+ return undefined;
572
+ });
573
+ }
574
+
273
575
  const urls = server.resolvedUrls ?? { local: [], network: [] };
274
- emit("listening", { local: urls.local, network: urls.network, routes: [] });
576
+ emit("listening", {
577
+ local: urls.local,
578
+ network: urls.network,
579
+ // From the filesystem when there is no bundle to ask, which is the same
580
+ // scan `dev` reports from. The count is what a reader checks the build
581
+ // against, so answering "0 routes" for a static site that has thirty would
582
+ // be the report being wrong about the thing it exists to report.
583
+ routes:
584
+ build == null
585
+ ? scanRoutes(path.resolve(root, config.app?.router?.root ?? "app"), {
586
+ target: routeTarget,
587
+ }).routes.map((route) => route.path)
588
+ : build.entry.routes.map((route) => route.path),
589
+ handlers: build == null ? [] : build.entry.handlers.map((handler) => handler.path),
590
+ });
591
+
275
592
  const shutdown = async () => {
276
593
  await server.close();
277
594
  process.exit(0);
@@ -280,6 +597,70 @@ async function preview() {
280
597
  process.on("SIGTERM", shutdown);
281
598
  }
282
599
 
600
+ /**
601
+ * The production server: the build, with no bundler in the process.
602
+ *
603
+ * `preview` proves the build works through Vite. This is the thing that is
604
+ * actually deployed, and it imports `vite` nowhere — a host running a built
605
+ * application should not need the bundler that produced it, and the moment it
606
+ * does, "portable output" is a claim rather than a property.
607
+ *
608
+ * There is no `--strict-port` here and there is nothing to add: this server
609
+ * binds the port it was given or fails, where Vite's would have quietly moved
610
+ * to the next free one. `PORT` and `HOST` are read from the environment
611
+ * because that is how every process manager and container platform says which
612
+ * socket to take, and a production server that could only be told on the
613
+ * command line would need a wrapper script everywhere it ran.
614
+ *
615
+ * It is not the only thing that can be deployed. `uf build --compile` puts
616
+ * this same application behind this same resolution order inside a single
617
+ * executable, for a host that should not have to have a JavaScript runtime
618
+ * installed at all; see [`compile`] for what that costs and what it shares.
619
+ */
620
+ async function start() {
621
+ const config = await loadConfig();
622
+ const outDir = argument("--out-dir") ?? config.build?.outDir ?? "dist";
623
+ const build = await loadBuild({
624
+ root,
625
+ outDir,
626
+ serverDir: path.join(".uf", "build", "server"),
627
+ });
628
+
629
+ const host = argument("--host") ?? process.env.HOST ?? "0.0.0.0";
630
+ const port = Number(argument("--port") ?? process.env.PORT ?? 3000);
631
+ const server = createHttpServer(
632
+ nodeListener(
633
+ createServeHandler({ ...build, cache: config.app?.rendering?.cache }),
634
+ build.entry,
635
+ ),
636
+ );
637
+
638
+ await new Promise((resolve, reject) => {
639
+ server.once("error", reject);
640
+ server.listen(port, host, resolve);
641
+ });
642
+
643
+ const bound = server.address();
644
+ // `0.0.0.0` is not a URL anybody can open, so the loopback spelling is what
645
+ // is printed as `local` and the bound address is reported as the network
646
+ // one — the same split `uf dev` prints, and for the same reason: one of the
647
+ // two is a link and the other is a fact about the socket.
648
+ const shown = `${bound.address}:${bound.port}`;
649
+ const wildcard = bound.address === "0.0.0.0" || bound.address === "::";
650
+ emit("listening", {
651
+ local: [`http://${wildcard ? `localhost:${bound.port}` : shown}/`],
652
+ network: wildcard ? [`http://${shown}/`] : [],
653
+ routes: build.entry.routes.map((route) => route.path),
654
+ handlers: build.entry.handlers.map((handler) => handler.path),
655
+ });
656
+
657
+ const shutdown = () => {
658
+ server.close(() => process.exit(0));
659
+ };
660
+ process.on("SIGINT", shutdown);
661
+ process.on("SIGTERM", shutdown);
662
+ }
663
+
283
664
  async function build() {
284
665
  const vite = await import("vite");
285
666
  const config = await loadConfig();
@@ -287,18 +668,70 @@ async function build() {
287
668
  const inline = await viteConfig(config, mode);
288
669
  const outDir = path.resolve(root, inline.build.outDir);
289
670
  const serverDir = path.join(root, ".uf", "build", "server");
671
+ // How much of the route table to prerender, and whether the server bundle
672
+ // survives the build. Both are `uf`'s answer rather than this file's: they
673
+ // come from two settings in `uf.config.js` that only mean something read
674
+ // together, and `uf_config`'s `RenderingPlan` is where they are. A driver
675
+ // started by hand gets the behaviour every uf build had before either
676
+ // setting was read.
677
+ const prerender = argument("--prerender") ?? "possible";
678
+ const staticBuild = flag("--static-build");
679
+ const because = argument("--because") ?? "this build prerenders every route";
680
+
681
+ // 0. The rsc graph, for an application React Server Components render: the
682
+ // route table and every server component, resolved under `react-server`.
683
+ // First, because it is what finds the client modules the next pass has
684
+ // to build; `./internal/flight.js` has the order and the reason for it.
685
+ const flight = flightStateOf(inline);
686
+ // `uf build --analyze`: the graph every bundle below is built from, for uf
687
+ // to attribute to routes; see `./internal/module-graph.js`. A client module
688
+ // is an entry the browser loads because a server component names it, not on
689
+ // every page, so it is not one of the client bundle's shared entries.
690
+ const graph = flag("--analyze")
691
+ ? createModuleGraphCollector(root, {
692
+ isReference: (file) => flight?.clientModules.has(file) ?? false,
693
+ })
694
+ : null;
695
+ if (graph != null) {
696
+ inline.plugins = [...(inline.plugins ?? []), graph.plugin];
697
+ }
698
+ const rscDir = path.join(root, ".uf", "build", "rsc");
699
+ if (flight != null) {
700
+ emit("phase", { name: "rsc" });
701
+ await buildRscGraph(vite, inline, flight, { outDir: rscDir, conditions: null });
702
+ }
290
703
 
291
704
  // 1. The client: everything the browser loads, with a manifest so the
292
- // server render knows which script and stylesheet tags to write.
705
+ // server render knows which script and stylesheet tags to write. Under
706
+ // React Server Components that is the entry and one entry per client
707
+ // module, each keeping its export names, because a payload asks for a
708
+ // chunk by its URL and for a component by its export.
293
709
  emit("phase", { name: "client" });
710
+ const references = flight == null ? [] : [...flight.clientModules].sort();
711
+ const input = { client: VIRTUAL.client };
712
+ references.forEach((file, index) => {
713
+ input[`client-reference-${index}`] = file;
714
+ });
294
715
  await vite.build({
295
716
  ...inline,
296
717
  build: {
297
718
  ...inline.build,
298
- rollupOptions: { input: { client: VIRTUAL.client } },
719
+ rollupOptions:
720
+ flight == null ? { input } : { input, preserveEntrySignatures: "exports-only" },
299
721
  },
300
722
  });
301
723
  const manifest = readManifest(outDir);
724
+ if (flight != null) {
725
+ recordClientChunks(flight, manifest, references, rscDir, basePathOf(config));
726
+ // What the summary's "pages in the client bundle" reads. None: a browser
727
+ // that hydrates a payload imports no page, whichever route it is on.
728
+ emit("rsc-split", {
729
+ pages: 0,
730
+ routes: scanRoutes(path.resolve(root, config.app?.router?.root ?? "app"), {
731
+ target: resolveRouteTarget(config, argument("--target")),
732
+ }).routes.length,
733
+ });
734
+ }
302
735
 
303
736
  // 2. The server entry, bundled for the host, outside `dist/` so it is never
304
737
  // deployed by accident.
@@ -318,129 +751,1746 @@ async function build() {
318
751
  },
319
752
  },
320
753
  });
754
+ // What this build is, beside the bundle it is about. One line, written by
755
+ // every build and read by nothing unless a project turned a durable cache on
756
+ // — at which point it is the thing that stops a deploy answering the new
757
+ // build's URLs with the previous build's documents. See
758
+ // `packages/server/internal/cache-key.js`, which argues the whole of it, and
759
+ // `internal/serve.js`'s `buildIdentity`, which is what reads this.
760
+ writeFileSync(path.join(serverDir, BUILD_ID_FILE), `${mintBuildId()}\n`);
321
761
 
322
- // 3. Every static route, rendered to an HTML document.
762
+ // Every bundle is built by here, and the prerender below builds none.
763
+ graph?.write(path.join(root, ".uf", "build", "meta", MODULE_GRAPH_FILE));
764
+
765
+ // 3. Which routes this build renders when, and every route it renders now.
766
+ //
767
+ // The decision comes from `uf.config.js` and is made in Rust — see
768
+ // `uf_config`'s `RenderingPlan` — because `app.rendering.modes` and
769
+ // `build.staticBuild` are two settings that have to be read together. It
770
+ // arrives here as one word, and this is where it meets the route table.
323
771
  emit("phase", { name: "prerender" });
324
772
  const server = await import(pathToFileURL(path.join(serverDir, "server.js")).href);
325
- const assets = assetsFromManifest(manifest);
326
- const pages = await staticPaths(server.routes);
773
+ const assets =
774
+ flight == null
775
+ ? assetsFromManifest(manifest, basePathOf(config))
776
+ : flightAssets(manifest, references, rscDir, outDir, basePathOf(config));
777
+ // Recorded beside the server bundle, because whatever serves this build
778
+ // later cannot recompute them from the client manifest alone; see
779
+ // `documentAssetsFor`.
780
+ writeFileSync(path.join(serverDir, DOCUMENT_ASSETS_FILE), `${JSON.stringify(assets, null, 2)}\n`);
781
+ const openapi = await createOpenApiDocument(server.handlers);
782
+ const openapiFile = path.join(root, ".uf", "build", "meta", "openapi.json");
783
+ mkdirSync(path.dirname(openapiFile), { recursive: true });
784
+ writeFileSync(openapiFile, `${JSON.stringify(openapi, null, 2)}\n`);
785
+ const plan = await renderingPlan(server, prerender);
786
+ emit("rendering", {
787
+ prerender,
788
+ prerendered: plan.urls.length,
789
+ perRequest: plan.perRequest.map((route) => route.path),
790
+ });
791
+ // A build that has to prerender everything, and a route it cannot: the
792
+ // refusal ubugeeei-prod/uf#336 and ubugeeei-prod/uf#385 are both about.
793
+ // Before the loop below, so no document is written for a build that is not
794
+ // going to be one, and with the whole list rather than the first item — a
795
+ // project that has just narrowed `rendering.modes` wants to see every route
796
+ // the narrowing costs it, not one per rebuild.
797
+ if (prerender === "everything" && plan.perRequest.length > 0) {
798
+ const listed = plan.perRequest.map((entry) => ` ${entry.path} — ${entry.why}`).join("\n");
799
+ emit("error", {
800
+ message:
801
+ `${plan.perRequest.length} ${plural(plan.perRequest.length, "route")} in this project ` +
802
+ `can only be answered by a server, and ${because}\n${listed}\n\n` +
803
+ "Give each page a `generateStaticParams` and take out the handlers and middleware, or " +
804
+ 'allow `"ssr"` in `app.rendering.modes` and deploy a server.',
805
+ });
806
+ process.exit(1);
807
+ }
808
+ const pages = plan.urls;
809
+
810
+ // A route that throws fails *that route*, and the rest of the build still
811
+ // happens. This loop had no `try`: the first page to throw rejected out of
812
+ // `build()`, `run().catch` reported the exception, and which URL was being
813
+ // rendered was a local variable nobody could see. One broken page was the
814
+ // whole build, and the message named a stack rather than a route.
815
+ //
816
+ // The render itself no longer throws for an ordinary component failure —
817
+ // `createRenderer` renders the error boundary and reports the exception on
818
+ // the result — so both are checked here. Neither writes a file: an error
819
+ // page written into `dist/` is a build that shipped its own failure.
820
+ //
821
+ // `prerender`, not `render`: a build wants the document React produces once
822
+ // every boundary has resolved, with the content where the fallback was. The
823
+ // streaming renderer would write a file whose slow parts are `<template>`
824
+ // elements waiting for a script — correct in a browser, blank to a crawler
825
+ // and to `curl`, which is most of what a static file is for.
826
+ const failures = [];
827
+ const failed = (url, error) => {
828
+ failures.push(url);
829
+ emit("page-failed", { url, ...errorEvent(error) });
830
+ };
831
+ //
832
+ // Each prerender runs inside a fill that stores nothing, so what a page states
833
+ // with `cacheLife`, `cacheTag` and `noStore` is something this loop can read
834
+ // rather than a call that throws for want of a scope.
835
+ //
836
+ // A page is written for regeneration when `uf` passed `--regenerate` — `isr`
837
+ // allowed in `app.rendering.modes`, `rendering.cache.route` on, and a server
838
+ // deployed to regenerate it — and the page stated a lifetime, called no
839
+ // `noStore`, and answered 200. Its document goes under
840
+ // `REGENERATED_DIRECTORY` rather than at its own URL, so no static half
841
+ // answers the page: the server does, starting from this document, until the
842
+ // lifetime has passed. What it stated goes into `REGENERATION_FILE` beside the
843
+ // server bundle. Every other page is the document it has always been.
844
+ //
845
+ // A tag without a lifetime is not enough, for the route cache's own reason:
846
+ // an entry with no end is one another process could serve from its memory
847
+ // for ever after `revalidateTag` took it out of the shared store.
848
+ const { collectCacheDeclarations } = await import("@uniflowed/server/cache");
849
+ const regenerate = flag("--regenerate");
850
+ const regenerated = {};
327
851
  for (const url of pages) {
328
- const result = await server.render(url, assets);
329
- const file = htmlPathFor(outDir, url);
852
+ let declared;
853
+ const renderedAt = Date.now();
854
+ try {
855
+ declared = await collectCacheDeclarations(() => server.prerender(url, assets));
856
+ } catch (error) {
857
+ failed(url, error);
858
+ continue;
859
+ }
860
+ const result = declared.value;
861
+ if (result.error != null) {
862
+ failed(url, result.error);
863
+ continue;
864
+ }
865
+ const lifetime = declared.lifetime;
866
+ const regenerates =
867
+ regenerate && result.status === 200 && declared.denied == null && lifetime != null;
868
+ // The trailing-slash policy decides a served page's file name; a page the
869
+ // build regenerates keeps the one layout the regeneration reads.
870
+ const file = regenerates
871
+ ? htmlPathFor(path.join(outDir, REGENERATED_DIRECTORY), url)
872
+ : htmlPathFor(outDir, url, routingRulesOf(config.app?.router).trailingSlash);
330
873
  mkdirSync(path.dirname(file), { recursive: true });
331
874
  writeFileSync(file, result.html);
875
+ // The payload the document was rendered from, beside it: what a browser
876
+ // navigating to this route fetches, from whatever serves the files. Beside
877
+ // the document wherever the document went, so a page written for
878
+ // regeneration leaves no file at its route's own payload URL answering with
879
+ // the build's copy for ever; the server answers that URL instead.
880
+ if (result.payload != null) {
881
+ // Beside the route's directory whatever the document is called:
882
+ // `guide/index.html` and `guide.html` both put it at `guide/__uf.flight`.
883
+ const payloadDirectory =
884
+ path.basename(file) === "index.html" ? path.dirname(file) : file.slice(0, -".html".length);
885
+ mkdirSync(payloadDirectory, { recursive: true });
886
+ writeFileSync(path.join(payloadDirectory, "__uf.flight"), result.payload);
887
+ }
888
+ if (regenerates) {
889
+ regenerated[url] = {
890
+ document: regeneratedDocumentUrl(url),
891
+ renderedAt,
892
+ revalidate: lifetime.revalidate,
893
+ expire: lifetime.expire ?? null,
894
+ tags: declared.tags,
895
+ };
896
+ }
332
897
  emit("page", {
333
898
  url,
334
899
  file: path.relative(root, file),
335
900
  status: result.status,
336
901
  bytes: Buffer.byteLength(result.html),
902
+ regenerates,
337
903
  });
338
904
  }
339
- if (server.notFound != null) {
340
- const result = await server.render("/__uf_not_found__", assets);
341
- const file = path.join(outDir, "404.html");
342
- writeFileSync(file, result.html);
343
- emit("page", {
344
- url: "/404",
345
- file: path.relative(root, file),
346
- status: 404,
347
- bytes: Buffer.byteLength(result.html),
905
+ if (Object.keys(regenerated).length > 0) {
906
+ writeFileSync(
907
+ path.join(serverDir, REGENERATION_FILE),
908
+ `${JSON.stringify({ pages: regenerated }, null, 2)}\n`,
909
+ );
910
+ }
911
+ // One `404.html`, from the boundary at the router root: a static host serves
912
+ // a single error document for the whole site, so the nested boundaries a
913
+ // project declares are the server's and the client's to render, not
914
+ // something this loop can write a file for.
915
+ //
916
+ // The condition is "there is a root boundary", not "there is any boundary",
917
+ // because `/__uf_not_found__` is a path at the root: a project whose only
918
+ // `$not-found.js` is in `app/guide/` would otherwise get a `404.html`
919
+ // rendered from the framework's bare default, which is worse than the file
920
+ // it used to write, which was none.
921
+ //
922
+ // Through the same two checks as the loop, and for the same reason. A
923
+ // not-found boundary is a component like any other: it can throw, and when it
924
+ // does `prerender` answers with the *error* page's HTML and a non-null
925
+ // `error` rather than rejecting. Writing that HTML and emitting `page` was a
926
+ // build publishing its own failure as `404.html` and exiting 0 — the static
927
+ // host would then serve uf's error page to every visitor who mistyped a URL,
928
+ // and nothing between the throw and the deploy would have mentioned it.
929
+ let attempted = pages.length;
930
+ // The single-page build's whole output, written here because it is the one
931
+ // document this build has and the loop above had no route to write it for.
932
+ //
933
+ // Twice, to two names, and the second is the load-bearing one. `index.html`
934
+ // is what a host serves for `/`; `404.html` is what a static host serves for
935
+ // every path it has no file for, which under this plan is *every other URL
936
+ // in the application*. Without it a deployment of `dist/` answers `/` and
937
+ // 404s `/orders` — a build with a hole in it, found from a 404, which is the
938
+ // failure ubugeeei-prod/uf#336 is about wearing a different hat.
939
+ //
940
+ // It is still the host's rewrite rule that makes this correct, and the two
941
+ // files are what uf can do without one: a host with a proper SPA fallback
942
+ // serves `index.html` and never looks at `404.html`, and a host with only an
943
+ // error document (Pages, Netlify, an S3 bucket) serves `404.html` and gets
944
+ // the same bytes with a 404 status — which is the right status for a URL
945
+ // this application does not have, and the not-found boundary is what the
946
+ // browser then renders into it.
947
+ if (prerender === "shell") {
948
+ const html = server.shellDocument(assets);
949
+ for (const [file, url, status] of [
950
+ ["index.html", "/", 200],
951
+ ["404.html", "/404", 404],
952
+ ]) {
953
+ const target = path.join(outDir, file);
954
+ writeFileSync(target, html);
955
+ attempted += 1;
956
+ emit("page", {
957
+ url,
958
+ file: path.relative(root, target),
959
+ status,
960
+ bytes: Buffer.byteLength(html),
961
+ });
962
+ }
963
+ }
964
+ // Not for a build that prerenders nothing. `404.html` is a file a static
965
+ // host serves for every path it has no file for, and a project whose
966
+ // `rendering.modes` allows only `ssr` has no such host: its not-found
967
+ // boundary is rendered per request, by the server, with the right status.
968
+ //
969
+ // Nor for a shell build, which has just written its own: the boundary this
970
+ // would render is one the *browser* renders in that plan, and a document
971
+ // holding the framework's 404 markup would be served in place of the shell
972
+ // for every URL the host could not match.
973
+ else if (prerender !== "nothing" && server.notFound.some((boundary) => boundary.path === "/")) {
974
+ attempted += 1;
975
+ // `/404` rather than `/__uf_not_found__`: the internal path is how the
976
+ // router is asked, and the file the reader is looking for is `404.html`.
977
+ let result;
978
+ try {
979
+ result = await server.prerender("/__uf_not_found__", assets);
980
+ } catch (error) {
981
+ failed("/404", error);
982
+ result = null;
983
+ }
984
+ if (result != null && result.error != null) {
985
+ failed("/404", result.error);
986
+ result = null;
987
+ }
988
+ if (result != null) {
989
+ const file = path.join(outDir, "404.html");
990
+ writeFileSync(file, result.html);
991
+ emit("page", {
992
+ url: "/404",
993
+ file: path.relative(root, file),
994
+ status: 404,
995
+ bytes: Buffer.byteLength(result.html),
996
+ });
997
+ }
998
+ }
999
+
1000
+ if (failures.length > 0) {
1001
+ // Emitted rather than thrown, so the message is the routes and not the
1002
+ // last exception: each one has already been reported with its own frame.
1003
+ //
1004
+ // The first line stands on its own, because it is the one `uf build` uses
1005
+ // as the headline and the one a CI log's last line will be. It read
1006
+ // `... failed:` with the routes below it, and the headline was then a
1007
+ // sentence ending in a colon and nothing.
1008
+ // `attempted`, not `pages.length`: the root 404 is prerendered too, and
1009
+ // counting a failure of it against a total that excludes it produced
1010
+ // "1 of 12" for a build that rendered thirteen things.
1011
+ emit("error", {
1012
+ message: `${failures.length} of ${attempted} prerendered ${plural(
1013
+ attempted,
1014
+ "route",
1015
+ )} failed\n${failures.map((url) => ` ${url}`).join("\n")}`,
348
1016
  });
1017
+ process.exit(1);
349
1018
  }
350
1019
 
1020
+ // `build.staticBuild` is "prerender everything and emit no server bundle",
1021
+ // and this is the second half of it. The bundle is still *built*: the
1022
+ // prerender renders through it, so a build with no server bundle at any
1023
+ // point would be a build with no documents either. What the declaration is
1024
+ // about is what is left behind — so it goes once the last document is
1025
+ // written, and `uf start`, `uf preview` and every server adapter then find
1026
+ // nothing to serve, which is the honest outcome for a project that said it
1027
+ // deploys files.
1028
+ if (staticBuild) rmSync(serverDir, { recursive: true, force: true });
1029
+
351
1030
  emit("done", { outDir: path.relative(root, outDir), pages: pages.length });
352
1031
  process.exit(0);
353
1032
  }
354
1033
 
355
- async function printConfig() {
1034
+ /**
1035
+ * The library build, for a project whose `app.router.enabled` is false.
1036
+ *
1037
+ * `build` above is an application build and has no other mode: it links
1038
+ * `virtual:uf/client`, which imports the router and the project's `app.js`.
1039
+ * A library has neither, so `uf build` in a project `uf create lib`
1040
+ * scaffolded failed at the first pass with `Could not resolve '<root>/app.js'`
1041
+ * — a file a library does not have and never had. See ubugeeei-prod/uf#268.
1042
+ *
1043
+ * This is the fourth thing the driver does, beside `dev`, `build` and
1044
+ * `compile`, and it is one pass per format over one input list. Which of the
1045
+ * two builds runs is **not decided here**: `uf` resolves it from the config
1046
+ * (`uf_config`'s `LibraryPlan`) and spawns this subcommand, the same way
1047
+ * `--prerender` arrives as one word rather than as two settings for this file
1048
+ * to read together.
1049
+ *
1050
+ * # The three ways it differs from the application build
1051
+ *
1052
+ * * **Every dependency stays an import.** `--external` names them, and
1053
+ * `uf` computes the list from the project's own manifest —
1054
+ * `dependencies`, `peerDependencies`, `optionalDependencies` — so a
1055
+ * library ships its own modules and nobody else's. That is the opposite
1056
+ * of the application build, which inlines what it can because an
1057
+ * application is the end of the line and a library is not: a bundled copy
1058
+ * of React inside a library is a second React in every application that
1059
+ * installs it.
1060
+ * * **One output per entry, named after the entry.** `index.js` becomes
1061
+ * `dist/index.js`; `internal/parse.js` becomes `dist/internal/parse.js`.
1062
+ * The path rather than the basename, so two entries cannot collide at the
1063
+ * moment one would overwrite the other.
1064
+ * * **No manifest, no prerender, no server bundle.** There is no document to
1065
+ * write and no route table to write it from.
1066
+ *
1067
+ * Vite's own `build.lib` does the work. uf owns *that* a library is a
1068
+ * different build and what goes into it; how this builder performs one is the
1069
+ * builder's, which is the same line `build` draws around `rollupOptions`.
1070
+ */
1071
+ async function library() {
1072
+ const vite = await import("vite");
356
1073
  const config = await loadConfig();
357
- emit("config", { config: projectConfig(config) });
1074
+ const inline = await viteConfig(config, argument("--mode") ?? "production");
1075
+ const outDir = path.resolve(root, inline.build.outDir);
1076
+ const entries = argumentAll("--entry");
1077
+ const formats = argumentAll("--format");
1078
+ const external = argumentAll("--external");
1079
+ if (entries.length === 0) {
1080
+ throw new Error("uf: `driver.js library` needs at least one --entry");
1081
+ }
1082
+ if (formats.length === 0) {
1083
+ throw new Error("uf: `driver.js library` needs at least one --format");
1084
+ }
1085
+
1086
+ // Keyed by the entry's path without its extension, which is what Vite's lib
1087
+ // mode turns into the output file name.
1088
+ const input = {};
1089
+ for (const entry of entries) {
1090
+ input[entryName(entry)] = path.resolve(root, entry);
1091
+ }
1092
+
1093
+ const isExternal = externalTest(external);
1094
+ // One pass per format rather than one build with several outputs: Vite's
1095
+ // lib mode writes a whole `outDir` per format, and the second pass must not
1096
+ // empty what the first wrote. So `emptyOutDir` is true exactly once, on the
1097
+ // first, which is also what makes a build that dropped an entry leave no
1098
+ // stale copy of it behind.
1099
+ let first = true;
1100
+ for (const format of formats) {
1101
+ emit("phase", { name: `library (${format})` });
1102
+ await vite.build({
1103
+ ...inline,
1104
+ build: {
1105
+ ...inline.build,
1106
+ // Vite's `manifest` maps source modules to hashed browser assets. A
1107
+ // library has neither — its file names are its API — and writing one
1108
+ // would put a `.vite/` directory into a published tarball.
1109
+ manifest: false,
1110
+ outDir,
1111
+ emptyOutDir: first,
1112
+ lib: {
1113
+ entry: input,
1114
+ formats: [format],
1115
+ fileName: (_format, name) => `${name}.${format === "cjs" ? "cjs" : "js"}`,
1116
+ },
1117
+ rollupOptions: { external: isExternal },
1118
+ },
1119
+ });
1120
+ first = false;
1121
+ }
1122
+
1123
+ emit("done", { outDir: path.relative(root, outDir), pages: 0 });
358
1124
  process.exit(0);
359
1125
  }
360
1126
 
361
- function readManifest(outDir) {
362
- const file = path.join(outDir, ".vite", "manifest.json");
363
- if (!existsSync(file)) throw new Error(`uf: the client build wrote no manifest at ${file}`);
364
- return JSON.parse(readFileSync(file, "utf8"));
1127
+ /**
1128
+ * The output name for one entry: its path, without the extension.
1129
+ *
1130
+ * Not the basename. `index.js` and `internal/index.js` are two entries a
1131
+ * library can reasonably have, and under a basename they are one file written
1132
+ * twice — the second silently winning, which is a published package whose
1133
+ * subpath export is somebody else's module.
1134
+ */
1135
+ function entryName(entry) {
1136
+ const normalised = entry.replace(/\\/g, "/").replace(/^\.\//, "");
1137
+ const dot = normalised.lastIndexOf(".");
1138
+ const slash = normalised.lastIndexOf("/");
1139
+ return dot > slash ? normalised.slice(0, dot) : normalised;
365
1140
  }
366
1141
 
367
1142
  /**
368
- * Script, stylesheet and preload URLs for the client entry chunk.
1143
+ * Whether an import is somebody else's module.
1144
+ *
1145
+ * Three checks, and only the one over `names` is a policy uf decided. `names`
1146
+ * is what `uf` read out of the project's manifest and passed as `--external`,
1147
+ * and a subpath of one of those names — `@scope/pkg/deep` for `@scope/pkg` —
1148
+ * is the same package. The other two are the host's built-in modules, and they
1149
+ * are a fact rather than a decision: `node:fs` has no bytes to inline.
369
1150
  *
370
- * The entry is found by its `isEntry` flag rather than by key, because a
371
- * virtual module's manifest key is an implementation detail of the bundler.
1151
+ * A bare relative or absolute id is never external, which is the rule that
1152
+ * makes this a library build at all: what the author wrote is bundled, and
1153
+ * what they installed is imported.
372
1154
  */
1155
+ function externalTest(names) {
1156
+ const declared = new Set(names);
1157
+ // The host's built-in module names, unprefixed. `node:`-prefixed ids are
1158
+ // caught by the first check whatever the host is; this set is for the bare
1159
+ // spellings — `fs`, `path`, `stream` — which a dependency written before the
1160
+ // prefix existed still uses. Read from the running host rather than written
1161
+ // down, because the list grows and a stale copy of it here would be a
1162
+ // bundled `node:worker_threads` that cannot be bundled.
1163
+ const builtins = new Set(builtinModules ?? []);
1164
+ return (id) => {
1165
+ if (id.startsWith("node:")) return true;
1166
+ if (builtins.has(id)) return true;
1167
+ if (declared.has(id)) return true;
1168
+ for (const name of declared) {
1169
+ if (id.startsWith(`${name}/`)) return true;
1170
+ }
1171
+ return false;
1172
+ };
1173
+ }
1174
+
373
1175
  /**
374
- * The tags a prerendered document needs.
1176
+ * Link the whole application into one JavaScript file, for `uf build --compile`.
1177
+ *
1178
+ * This runs after `build`, on a `dist/` that is already complete, and produces
1179
+ * the module a runtime is wrapped around. It differs from the server build in
1180
+ * `build()` in exactly three ways, and each of them is what "one file" means:
1181
+ *
1182
+ * * `ssr.noExternal: true` — the server build leaves `react`, `react-dom`
1183
+ * and every other dependency as bare imports, because the host it runs on
1184
+ * has `node_modules` beside it. A binary does not, so they come in.
1185
+ * * `codeSplitting: false` — a route is a lazy `import()` so that the browser
1186
+ * can fetch one chunk per page. On the server that split buys nothing and
1187
+ * costs everything: chunks are separate files, and separate files are the
1188
+ * one thing this output may not have.
1189
+ * * the native-addon guard below, which turns "cannot resolve" into a
1190
+ * sentence naming the package that cannot be compiled.
1191
+ *
1192
+ * The embedded copy of `dist/` is *not* built here. `uf` writes it (see
1193
+ * `uf_bundle::embed`) and passes its path in `--assets`, because walking an
1194
+ * output directory and encoding every file in it is bulk work over the whole
1195
+ * build, which belongs in Rust rather than in the host process.
375
1196
  *
376
- * Two walks over the manifest, because the two answers are different. A
377
- * `modulepreload` is worth emitting only for a chunk this document will
378
- * certainly load, which is the entry's *static* imports. A stylesheet has to
379
- * be emitted for anything the page might render, and the router loads every
380
- * route module dynamically — so a stylesheet imported by a layout is reached
381
- * through `dynamicImports` and through nothing else. Following only the static
382
- * graph, as this did, meant a layout could import a stylesheet and the built
383
- * HTML would silently ship without it.
1197
+ * # Three front doors onto one build, and why they are not one function
384
1198
  *
385
- * The cost is that a project with per-route stylesheets links all of them on
386
- * every page. Narrowing that needs the route table to say which chunk each
387
- * route came from, which the manifest alone cannot tell us.
1199
+ * `preview` and `start` above serve `dist/` from disk, and they share a single
1200
+ * handler in `./internal/serve.js` for the express purpose of being unable to
1201
+ * answer differently. What is linked here is a third front door onto the same
1202
+ * build, and it deliberately does *not* import that module. Two reasons, and
1203
+ * either would be enough: `internal/serve.js` answers by opening files under
1204
+ * `dist/`, and a compiled binary has no `dist/` to open — it carries the bytes
1205
+ * — so the half that reads a request would arrive with a half that cannot run;
1206
+ * and it lives in `@uniflowed/vite`, so linking it would put the package named
1207
+ * after the bundler inside the artefact a deployment runs, which is the one
1208
+ * thing `start` exists to avoid.
1209
+ *
1210
+ * What a binary uses instead is `@uniflowed/server/standalone`, and the thing
1211
+ * that is shared between the three is not code but the *answer*: an asset or a
1212
+ * prerendered document first, then a route handler, then a render for whatever
1213
+ * is left. That order is not a preference. `preview` cannot deviate from it —
1214
+ * Vite's preview server runs its own file middleware before anything uf mounts
1215
+ * behind it — so `start` matches Vite, and the binary matches `start`. A
1216
+ * compiled application that resolved a collision the other way would be the
1217
+ * trap `preview` exists to prevent, one deployment further along, and the only
1218
+ * copy nobody can check with `uf preview` first.
388
1219
  */
389
- function assetsFromManifest(manifest) {
390
- const entry = Object.values(manifest).find((chunk) => chunk.isEntry);
391
- if (entry == null) throw new Error("uf: the client manifest has no entry chunk");
1220
+ async function compile() {
1221
+ const vite = await import("vite");
1222
+ const config = await loadConfig();
1223
+ const inline = await viteConfig(config, argument("--mode") ?? "production");
1224
+ const outDir = path.resolve(root, inline.build.outDir);
1225
+ const assetsArgument = argument("--assets");
1226
+ const bundleArgument = argument("--bundle");
1227
+ if (assetsArgument == null || bundleArgument == null) {
1228
+ throw new Error("uf: `driver.js compile` needs both --assets and --bundle");
1229
+ }
1230
+ const assets = path.resolve(root, assetsArgument);
1231
+ const bundleDir = path.resolve(root, bundleArgument);
392
1232
 
393
- const styles = new Set(entry.css ?? []);
394
- const seen = new Set();
395
- const collectStyles = (chunk) => {
396
- for (const imported of [...(chunk.imports ?? []), ...(chunk.dynamicImports ?? [])]) {
397
- if (seen.has(imported)) continue;
398
- seen.add(imported);
399
- const dependency = manifest[imported];
400
- if (dependency == null) continue;
401
- for (const css of dependency.css ?? []) styles.add(css);
402
- collectStyles(dependency);
1233
+ emit("phase", { name: "standalone" });
1234
+
1235
+ // The entry is written to disk rather than served as another virtual module:
1236
+ // it is generated per build (it bakes in this build's document), and a real
1237
+ // file is the version a person can open when a compiled binary misbehaves.
1238
+ const entry = path.join(bundleDir, "entry.js");
1239
+ mkdirSync(bundleDir, { recursive: true });
1240
+ writeFileSync(
1241
+ entry,
1242
+ entrySource(
1243
+ path.relative(root, assets),
1244
+ await documentAssetsFor(path.join(root, ".uf", "build", "server"), readManifest(outDir)),
1245
+ ),
1246
+ );
1247
+
1248
+ // The rsc graph `uf build` built, and the client chunks its references name.
1249
+ const flight = flightStateOf(inline);
1250
+ if (flight != null) loadFlightBuild(flight, path.join(root, ".uf", "build", "rsc"));
1251
+
1252
+ await vite.build({
1253
+ ...inline,
1254
+ customLogger: eventLogger("warn"),
1255
+ plugins: [...inline.plugins, nativeAddonGuard(), compileAssetsPlugin(assets)],
1256
+ ssr: { ...(inline.ssr ?? {}), noExternal: true },
1257
+ build: {
1258
+ ...inline.build,
1259
+ manifest: false,
1260
+ // The map would describe this intermediate bundle rather than the
1261
+ // binary, and nothing downstream reads it. Turning it off is a smaller
1262
+ // `.uf/` and one less file to explain.
1263
+ sourcemap: false,
1264
+ ssr: true,
1265
+ outDir: bundleDir,
1266
+ emptyOutDir: false,
1267
+ rollupOptions: {
1268
+ input: { server: entry },
1269
+ output: { entryFileNames: "server.js", format: "es", codeSplitting: false },
1270
+ },
1271
+ },
1272
+ });
1273
+
1274
+ emit("done", { outDir: path.relative(root, bundleDir), pages: 0 });
1275
+ process.exit(0);
1276
+ }
1277
+
1278
+ /**
1279
+ * What each adapter links, and what it links it against.
1280
+ *
1281
+ * Every entry in this table produces the same `handler.js` — the application
1282
+ * as `Request` → `Response`, from `@uniflowed/server/fetch` — and differs only
1283
+ * in the file wrapped around it and, for a target whose dependencies have a
1284
+ * different build, in the export conditions that pick one. That is the whole
1285
+ * of what an adapter is, and keeping the differences in one object is what
1286
+ * stops a second one from quietly becoming a second application.
1287
+ *
1288
+ * `static` is deliberately absent; `uf_config`'s
1289
+ * `DeployAdapter::is_implemented` is the other half of that fact and
1290
+ * `docs/app/reference/cli/$page.mdx` says why.
1291
+ *
1292
+ * `regenerationStore` is where a target keeps the pages a build regenerates
1293
+ * when `rendering.cache.store` names nothing: a disk for a process with one,
1294
+ * Workers KV for a Worker, and `null` for a Lambda, which keeps nothing between
1295
+ * invocations and is refused by name instead. A regenerated page kept only in
1296
+ * memory would go back to the build's copy on every restart, which is a page
1297
+ * that travels back in time. See [`deploy`].
1298
+ */
1299
+ const ADAPTERS = {
1300
+ node: {
1301
+ entries: (document, cache, build, schedules, regeneration) => ({
1302
+ handler: handlerEntrySource(document, cache, NODE_CAPABILITIES, build, regeneration),
1303
+ server: nodeEntrySource("./handler.js", schedules),
1304
+ }),
1305
+ regenerationStore: "filesystem",
1306
+ },
1307
+ // The same two files as `node`, with `@uniflowed/server/bun` in place of
1308
+ // `@uniflowed/server/node`. That module is `./internal/static.js` for every
1309
+ // decision and `Bun.file` for the bytes, which is where the measured win is
1310
+ // — see ubugeeei-prod/uf#391 and the header of `packages/server/bun.js`.
1311
+ //
1312
+ // No `conditions` of its own, unlike `edge`. Bun honours a `bun` export
1313
+ // condition and this deliberately does not ask for it: the measured win is
1314
+ // `Bun.serve` and `Bun.file` and not resolution, so asking would trade a
1315
+ // `handler.js` that is byte-for-byte `node`'s — which is what
1316
+ // `every_adapter_answers_exactly_what_the_node_adapter_answers` checks, and
1317
+ // what makes an adapter one file rather than one application — for whichever
1318
+ // build a dependency happens to ship behind that condition, tested by
1319
+ // nobody here. `edge` pays that price because it must: there is no
1320
+ // `node:stream` in a Worker.
1321
+ bun: {
1322
+ entries: (document, cache, build, schedules, regeneration) => ({
1323
+ handler: handlerEntrySource(document, cache, BUN_CAPABILITIES, build, regeneration),
1324
+ server: bunEntrySource("./handler.js", schedules),
1325
+ }),
1326
+ regenerationStore: "filesystem",
1327
+ },
1328
+ deno: {
1329
+ entries: (document, cache, build, schedules, regeneration) => ({
1330
+ handler: handlerEntrySource(document, cache, DENO_CAPABILITIES, build, regeneration),
1331
+ server: denoEntrySource("./handler.js", schedules),
1332
+ }),
1333
+ regenerationStore: "filesystem",
1334
+ },
1335
+ // The same two files. What `--adapter container` adds is a `Dockerfile` and
1336
+ // a `.dockerignore`, and both are plain text that `uf` writes beside this
1337
+ // output rather than anything the bundler produces — see `uf_cli`'s
1338
+ // `commands::deploy`.
1339
+ container: {
1340
+ entries: (document, cache, build, schedules, regeneration) => ({
1341
+ handler: handlerEntrySource(document, cache, NODE_CAPABILITIES, build, regeneration),
1342
+ server: nodeEntrySource("./handler.js", schedules),
1343
+ }),
1344
+ regenerationStore: "filesystem",
1345
+ },
1346
+ edge: {
1347
+ entries: (document, cache, build, schedules, regeneration) => ({
1348
+ handler: handlerEntrySource(document, cache, EDGE_CAPABILITIES, build, regeneration),
1349
+ worker: workerEntrySource("./handler.js", schedules),
1350
+ }),
1351
+ // Workers KV, through the same module seam a project's own provider goes
1352
+ // through. `packages/server/cache-kv.js` argues KV over the Cache API: the
1353
+ // seam has to find every entry under a tag, and the Cache API cannot list
1354
+ // what it holds.
1355
+ regenerationStore: "@uniflowed/server/cache/kv",
1356
+ // `workerd` first, so React resolves to the build that has
1357
+ // `renderToReadableStream` and no `node:stream`. `browser` and `module`
1358
+ // after it are Vite's own SSR defaults, kept so a dependency with no
1359
+ // worker condition still resolves the way it does for every other target.
1360
+ conditions: ["workerd", "worker", "edge-light", "browser", "module", "import", "default"],
1361
+ // A Worker has no filesystem, so uf's built-in durable provider cannot run
1362
+ // here. Refused by name at the build rather than linked into a bundle that
1363
+ // fails on its first `node:fs` import — the deployment rule is that a
1364
+ // target which cannot provide a durable store says so, and this is the one
1365
+ // target that cannot.
1366
+ filesystem: false,
1367
+ // And the Node built-ins it has only as stubs, which the link reports by
1368
+ // module and importer. See `./internal/worker-builtins.js`.
1369
+ workerBuiltins: true,
1370
+ },
1371
+ serverless: {
1372
+ entries: (document, cache, build, _schedules, regeneration) => ({
1373
+ handler: handlerEntrySource(document, cache, SERVERLESS_CAPABILITIES, build, regeneration),
1374
+ lambda: lambdaEntrySource("./handler.js"),
1375
+ }),
1376
+ // A Lambda's memory lasts one instance and its disk is that instance's
1377
+ // `/tmp`, so neither is somewhere a regenerated page survives. A build that
1378
+ // regenerates pages has to name a provider module; see [`deploy`].
1379
+ regenerationStore: null,
1380
+ },
1381
+ };
1382
+
1383
+ /**
1384
+ * How each target says what it can do: the module, and the name to call.
1385
+ *
1386
+ * A pair of strings rather than a value, because this is the module that
1387
+ * *writes* `handler.js` and never imports what it writes: the capabilities
1388
+ * belong to the deployed application's copy of `@uniflowed/server`, not to the
1389
+ * driver's. It is the same reason `beginRequest` is re-exported from the
1390
+ * generated file rather than reached for here — see `handlerEntrySource`.
1391
+ *
1392
+ * Nothing is passed for `websocket` or `queue`, and that is not an oversight:
1393
+ * uf defines both and implements neither, so a generated file that invented
1394
+ * one would be inventing an upgrade for a runtime it cannot see. What the call
1395
+ * does supply is the target's name and its two facts, which is what turns "an
1396
+ * upgrade is not available" into "the serverless host cannot hold a socket
1397
+ * open" and what lets `@uniflowed/server/lambda` refuse a queue that would be
1398
+ * dropped.
1399
+ */
1400
+ const NODE_CAPABILITIES = { module: "@uniflowed/server/node", name: "nodeCapabilities" };
1401
+ const BUN_CAPABILITIES = { module: "@uniflowed/server/bun", name: "bunCapabilities" };
1402
+ const DENO_CAPABILITIES = { module: "@uniflowed/server/deno", name: "denoCapabilities" };
1403
+ const EDGE_CAPABILITIES = { module: "@uniflowed/server/edge", name: "edgeCapabilities" };
1404
+ const SERVERLESS_CAPABILITIES = { module: "@uniflowed/server/lambda", name: "lambdaCapabilities" };
1405
+
1406
+ /**
1407
+ * Link the application into a directory that can be copied, for
1408
+ * `uf build --adapter`.
1409
+ *
1410
+ * `uf start` serves a build and `uf build --compile` puts one inside an
1411
+ * executable, and between them is the shape most hosts actually want: a
1412
+ * directory that carries everything and nothing that is still in the checkout
1413
+ * — no `node_modules`, no source, no `uf`. That is what this writes, for
1414
+ * whichever of [`ADAPTERS`] was asked for.
1415
+ *
1416
+ * It differs from the server build in [`build`] in one way, and that one way
1417
+ * is the whole of the difference between a build artefact and a checkout:
1418
+ * `ssr.noExternal: true`. The ordinary server build leaves `react`,
1419
+ * `react-dom` and every other dependency as bare imports, because the host it
1420
+ * runs on has `node_modules` beside it; a copied directory does not, so they
1421
+ * come in. (`@uniflowed/*` was never external — `index.js` sets
1422
+ * `ssr.noExternal: [/^@uniflowed\//]` because Node cannot import Flow — which
1423
+ * is why serving a build has never needed `uf transform` alive, and why the
1424
+ * blocker ubugeeei-prod/uf#335 records was not one.)
1425
+ *
1426
+ * # Two entries, because an adapter is exactly one of them
1427
+ *
1428
+ * `handler.js` is the application as a Web-standard `fetch` export: a
1429
+ * `Request` in, a `Response` out, no filesystem, no socket, no `node:` import
1430
+ * that a worker does not already have. That is the seam, and it is the same
1431
+ * file for every target in [`ADAPTERS`].
1432
+ *
1433
+ * The second entry is the wrapper for *this* target — `node:http` for `node`
1434
+ * and `container`, `export default { fetch }` for a Worker, `export const
1435
+ * handler` for a Lambda — and each of them is a handful of lines around an
1436
+ * import from `@uniflowed/server`. That is the point: the work is in the
1437
+ * handler, and what a new adapter has to write is the handful of lines, not
1438
+ * the application.
1439
+ *
1440
+ * Both are ordinary entries of one Rolldown build, so the wrapper imports the
1441
+ * emitted `handler.js` rather than a second copy of the application.
1442
+ *
1443
+ * The `static/` directory is *not* written here. `uf` copies it (see
1444
+ * `uf_cli`'s `commands::deploy`), because walking an output directory and
1445
+ * copying every file in it is bulk work over the whole build, which belongs in
1446
+ * Rust rather than in the host process — the same division `--compile` makes
1447
+ * with its embedded assets.
1448
+ *
1449
+ * # `--adapter static` never reaches this function
1450
+ *
1451
+ * It is the one implemented target with no application to link: a static host
1452
+ * returns files, and `uf build` has already written them. So `uf` copies the
1453
+ * output directory itself and never spawns this driver for it, which is why
1454
+ * [`ADAPTERS`] has six rows and not seven. What that target does instead of
1455
+ * linking is refuse a project whose route handlers, middleware, unprerendered
1456
+ * routes or server actions a static host cannot answer — in Rust, because the
1457
+ * facts it needs are the route table and what the prerender reported.
1458
+ */
1459
+ async function deploy() {
1460
+ const vite = await import("vite");
1461
+ const config = await loadConfig();
1462
+ const inline = await viteConfig(config, argument("--mode") ?? "production");
1463
+ const outDir = path.resolve(root, inline.build.outDir);
1464
+ const adapter = argument("--adapter");
1465
+ const workArgument = argument("--work");
1466
+ const outputArgument = argument("--output");
1467
+ if (adapter == null || workArgument == null || outputArgument == null) {
1468
+ throw new Error("uf: `driver.js deploy` needs --adapter, --work and --output");
1469
+ }
1470
+ // What the project declared, read by `uf`'s own walk of the route handlers
1471
+ // and handed over rather than found again here — one reading of a module,
1472
+ // and the same list `wrangler.json`'s `triggers.crons` is written from.
1473
+ // Absent on an older `uf` spawning a newer driver, which is a build with no
1474
+ // schedules rather than an error. See ubugeeei-prod/uf#531.
1475
+ const schedules = JSON.parse(argument("--schedules") ?? "[]");
1476
+ // The Rust side has already refused every adapter it has no implementation
1477
+ // for, by name and with the issue that tracks it. This is the second half of
1478
+ // that fact rather than a duplicate of it: the driver may be spawned by a
1479
+ // future `uf` that knows an adapter this copy does not, and answering "one
1480
+ // moment, here is a directory" for a target nobody wrote would be the silent
1481
+ // wrong answer the whole issue is about.
1482
+ const shape = ADAPTERS[adapter];
1483
+ if (shape == null) {
1484
+ throw new Error(
1485
+ `uf: this driver implements ${Object.keys(ADAPTERS)
1486
+ .map((name) => JSON.stringify(name))
1487
+ .join(", ")} and was asked for ${JSON.stringify(adapter)}`,
1488
+ );
1489
+ }
1490
+ const work = path.resolve(root, workArgument);
1491
+ const output = path.resolve(root, outputArgument);
1492
+
1493
+ emit("phase", { name: adapter });
1494
+
1495
+ // Written to disk rather than served as virtual modules: they are generated
1496
+ // per build — `handler.js` names this build's hashed assets — and a real
1497
+ // file is the version a person can open when a deployed directory
1498
+ // misbehaves.
1499
+ mkdirSync(work, { recursive: true });
1500
+ const document = await documentAssetsFor(
1501
+ path.join(root, ".uf", "build", "server"),
1502
+ readManifest(outDir),
1503
+ );
1504
+ // Whatever `build` above minted, so a durable cache in the deployed artefact
1505
+ // is keyed by the build that produced it and not by the moment it was
1506
+ // packaged. Read rather than minted again for exactly that reason: a second
1507
+ // `randomUUID()` here would key the adapter's copy differently from the one
1508
+ // `uf start` serves out of `.uf/build/`, which is two caches for one build.
1509
+ const buildId = await buildIdentity(root, path.join(".uf", "build", "server"));
1510
+ const declaredCache = config.app?.rendering?.cache;
1511
+ if (shape.filesystem === false && declaredCache?.store === "filesystem") {
1512
+ throw new Error(
1513
+ `uf: rendering.cache.store is "filesystem" and \`--adapter ${adapter}\` has no ` +
1514
+ "filesystem. Name a module exporting `createCacheProvider` instead — a KV " +
1515
+ "namespace or a Redis behind the same seam — or leave the store in memory. See " +
1516
+ "docs/app/guide/cache.",
1517
+ );
1518
+ }
1519
+ // The pages this build regenerates, and where this target keeps what it
1520
+ // regenerates when the project named no store: the adapter's
1521
+ // `regenerationStore`. A target with nowhere refuses by name and lists the
1522
+ // pages, rather than deploying pages that every cold start takes back to the
1523
+ // build's copy.
1524
+ const regeneration = await readRegeneration(path.join(root, ".uf", "build", "server"));
1525
+ let cacheConfig = declaredCache;
1526
+ if (regeneration != null && declaredCache?.store == null) {
1527
+ if (shape.regenerationStore == null) {
1528
+ const pages = Object.keys(regeneration.pages);
1529
+ throw new Error(
1530
+ `uf: this build regenerates ${pages.length} ${plural(pages.length, "page")} ` +
1531
+ `(${pages.join(", ")}), and \`--adapter ${adapter}\` has nowhere of its own to keep ` +
1532
+ "a regenerated page: an instance's memory and its /tmp both go with the instance. " +
1533
+ "Name a module exporting `createCacheProvider` in rendering.cache.store, or leave " +
1534
+ "`isr` out of app.rendering.modes to prerender those pages as documents that do not " +
1535
+ "change. See docs/app/guide/rendering.",
1536
+ );
403
1537
  }
404
- };
405
- collectStyles(entry);
406
-
407
- const preloads = new Set();
408
- const collectPreloads = (chunk) => {
409
- for (const imported of chunk.imports ?? []) {
410
- const dependency = manifest[imported];
411
- if (dependency == null || preloads.has(dependency.file)) continue;
412
- preloads.add(dependency.file);
413
- collectPreloads(dependency);
1538
+ cacheConfig = { ...declaredCache, store: shape.regenerationStore };
1539
+ }
1540
+ const entries = shape.entries(document, cacheConfig, buildId, schedules, regeneration);
1541
+ const input = {};
1542
+ for (const name of Object.keys(entries)) {
1543
+ writeFileSync(path.join(work, `${name}.js`), entries[name]);
1544
+ input[name] = path.join(work, `${name}.js`);
1545
+ }
1546
+
1547
+ // An application React Server Components render bundles the rsc graph into
1548
+ // its server, and a target with export conditions of its own needs that graph
1549
+ // resolved under them as well: React's Flight server has a Node build and a
1550
+ // worker build, exactly as its HTML renderer does.
1551
+ const flight = flightStateOf(inline);
1552
+ if (flight != null) {
1553
+ loadFlightBuild(flight, path.join(root, ".uf", "build", "rsc"));
1554
+ if (shape.conditions != null) {
1555
+ await buildRscGraph(vite, inline, flight, {
1556
+ outDir: path.join(work, "rsc"),
1557
+ conditions: shape.conditions,
1558
+ });
414
1559
  }
1560
+ }
1561
+
1562
+ const ssr = { ...(inline.ssr ?? {}), noExternal: true };
1563
+ if (shape.conditions != null) {
1564
+ // Which build of a dependency this target gets, and it is the difference
1565
+ // between a worker that renders and one that fails to link. React ships
1566
+ // `server.node.js` under the `node` condition and `server.edge.js` under
1567
+ // `workerd`; the first one imports `node:stream`, and the router picks its
1568
+ // renderer by asking whether `renderToPipeableStream` is there — so the
1569
+ // condition list is what decides that, not a flag in the application.
1570
+ ssr.resolve = { ...(inline.ssr?.resolve ?? {}), conditions: shape.conditions };
1571
+ }
1572
+
1573
+ await vite.build({
1574
+ ...inline,
1575
+ customLogger: eventLogger("warn"),
1576
+ plugins: [
1577
+ ...inline.plugins,
1578
+ nativeAddonGuard(),
1579
+ ...(shape.workerBuiltins === true ? [workerBuiltinGuard()] : []),
1580
+ ],
1581
+ // Fixed, because this bundle inlines every dependency and so both of each
1582
+ // React package's builds, and a runtime lookup of `NODE_ENV` in a worker
1583
+ // finds nothing and picks the development one. React's Flight client's
1584
+ // development build constructs a `WeakRef` for every response, which
1585
+ // workerd does not have: every document the edge artefact rendered was a
1586
+ // `ReferenceError`. The production build has none, and is the one a
1587
+ // deployment means.
1588
+ define: {
1589
+ ...(inline.define ?? {}),
1590
+ "process.env.NODE_ENV": JSON.stringify(
1591
+ inline.mode === "development" ? "development" : "production",
1592
+ ),
1593
+ },
1594
+ ssr,
1595
+ build: {
1596
+ ...inline.build,
1597
+ manifest: false,
1598
+ // The map would describe this bundle rather than the source, and nothing
1599
+ // downstream reads it. Off is a smaller directory to copy and one less
1600
+ // file to explain.
1601
+ sourcemap: false,
1602
+ ssr: true,
1603
+ outDir: output,
1604
+ // `uf` has already removed the directory, and `static/` is copied in
1605
+ // after this returns; letting Vite empty it would be Vite deciding when
1606
+ // that happens.
1607
+ emptyOutDir: false,
1608
+ rollupOptions: {
1609
+ input,
1610
+ output: {
1611
+ entryFileNames: "[name].js",
1612
+ // Route modules are lazy `import()`s, so the server bundle splits
1613
+ // whether or not anything asks it to, and the chunks have to land
1614
+ // somewhere. `chunks/` rather than the default `assets/`, because
1615
+ // `static/assets/` beside it is the *client's* — two directories
1616
+ // with one name in a directory whose whole purpose is to be copied
1617
+ // and read by a stranger.
1618
+ chunkFileNames: "chunks/[name]-[hash].js",
1619
+ format: "es",
1620
+ },
1621
+ },
1622
+ },
1623
+ });
1624
+
1625
+ emit("done", { outDir: path.relative(root, output), pages: 0 });
1626
+ process.exit(0);
1627
+ }
1628
+
1629
+ /**
1630
+ * The source of `handler.js`: the application, as one `fetch` export.
1631
+ *
1632
+ * `export default { fetch }` as well as the named export, because those are
1633
+ * the two spellings the hosts this shape exists for actually read — a worker
1634
+ * and Deno Deploy want the default export's `fetch`, and a Node or Bun entry
1635
+ * wants the name. Writing both costs a line and removes the one thing that
1636
+ * would make an otherwise portable file not portable.
1637
+ *
1638
+ * `beginRequest` is exported beside it, and it is not decoration. `fetch`
1639
+ * answers with a `Response`; it does not know when that response reached
1640
+ * anybody, and `after()` promises a callback once it has. So the host owns the
1641
+ * request: begin it, run `fetch` inside `run`, and `settle` when the bytes are
1642
+ * out — `server.js` below does exactly that through
1643
+ * `@uniflowed/server/node`, and a worker hands `settle` to `ctx.waitUntil`.
1644
+ * It comes from the bundle rather than from the host's own
1645
+ * `@uniflowed/server`, because the request store is shared only by copies of
1646
+ * one release of that package and the release the application reads is the one
1647
+ * inlined here. See ubugeeei-prod/uf#389.
1648
+ *
1649
+ * The document's script and stylesheet URLs are baked in here because they
1650
+ * come from the client manifest, which exists at this moment and not in the
1651
+ * directory that gets copied.
1652
+ *
1653
+ * `cache` is `rendering.cache` from `uf.config.js`, and this is where two of
1654
+ * its four switches stop being a field in a JSON file: a build that turned
1655
+ * `route` or `fetch` on constructs a store here and hands it to the handler,
1656
+ * and a build that turned neither on writes the file it always wrote, byte for
1657
+ * byte. The store is constructed in the *generated* module rather than reached
1658
+ * for inside `@uniflowed/server` for the same reason `beginRequest` is
1659
+ * re-exported above — a module-level singleton belongs to whichever copy of the
1660
+ * package a bundler happened to give it, and the copy that matters is the one
1661
+ * the application resolved. See ubugeeei-prod/uf#277 and #389.
1662
+ *
1663
+ * # And where a durable store is named
1664
+ *
1665
+ * `rendering.cache.store` is the fifth key, and it is the one that turns the
1666
+ * store into a shared one: `"filesystem"` links uf's built-in provider, and
1667
+ * anything else is a module specifier the project wrote, imported here by name
1668
+ * so the bundler links it like any other dependency of the application. Neither
1669
+ * appears at all when the key is absent, which is what a default project keeps.
1670
+ *
1671
+ * `build` is baked in beside it, and it is the reason this can be an `import`
1672
+ * at all rather than something read at boot: the build id is a fact about the
1673
+ * artefact being written, known here and nowhere later. `internal/serve.js`'s
1674
+ * `buildIdentity` is where it came from and
1675
+ * `packages/server/internal/cache-key.js` is why it exists.
1676
+ */
1677
+ function handlerEntrySource(document, cache, capabilities, build, regeneration) {
1678
+ const route = cache?.route === true;
1679
+ const fetchCache = cache?.fetch === true;
1680
+ // Nothing at all when both switches are off, so a default project's
1681
+ // `handler.js` is the file it has always been. A cache that appears in
1682
+ // generated output nobody asked for is the second half of the complaint
1683
+ // #277 makes about the first half.
1684
+ const store = route || fetchCache;
1685
+ const durable = store ? durableStoreSource(root, cache, build) : null;
1686
+ const options = [
1687
+ "app",
1688
+ `document: ${JSON.stringify(document)}`,
1689
+ ...(store ? ["cache"] : []),
1690
+ "capabilities",
1691
+ // The pages this build regenerates, baked in beside the document and for
1692
+ // the same reason: the manifest exists on the machine doing the build, and
1693
+ // the deployed directory has only what this file carries.
1694
+ ...(store && regeneration != null ? [`regeneration: ${JSON.stringify(regeneration)}`] : []),
1695
+ ].join(", ");
1696
+ const cacheImport = store ? 'import { createCacheStore } from "@uniflowed/server/cache";\n' : "";
1697
+ const providerImport = durable == null ? "" : `${durable.import}\n`;
1698
+ const from = JSON.stringify(capabilities.module);
1699
+ const capabilityImport = `import { ${capabilities.name} } from ${from};`;
1700
+ return `// Generated by \`uf build --adapter\`. Not checked in, not edited.
1701
+ import { createFetchHandler } from "@uniflowed/server/fetch";
1702
+ ${cacheImport}${providerImport}${capabilityImport}
1703
+ import * as app from ${JSON.stringify(VIRTUAL.server)};
1704
+
1705
+ ${
1706
+ store
1707
+ ? `// \`rendering.cache\` from uf.config.js. ${
1708
+ durable == null
1709
+ ? `One store per process: it is
1710
+ // emptied by a restart and is not shared with any other instance of this
1711
+ // application.`
1712
+ : `Entries are kept by ${durable.what},
1713
+ // under this build's identity, so a restart finds them where it left them and
1714
+ // every process of this deployment reads one store — and \`revalidateTag\` in
1715
+ // any of them takes an entry out of the store all of them fill from.`
1716
+ } See ubugeeei-prod/uf#277.
1717
+ const cache = { store: createCacheStore(${
1718
+ durable == null ? "" : `{ provider: ${durable.provider}, build: ${JSON.stringify(build)} }`
1719
+ }), route: ${String(route)}, fetch: ${String(fetchCache)} };
1720
+
1721
+ `
1722
+ : ""
1723
+ }// What this target can do, and it is not the same for all six: whether a
1724
+ // response body reaches the client as it is produced, and whether the process
1725
+ // is still there once it has. A route handler that streams events or takes a
1726
+ // socket asks through this rather than finding out in production. Nothing is
1727
+ // passed for the upgrade or the queue — uf defines both and implements
1728
+ // neither. See \`@uniflowed/server/socket\` and \`@uniflowed/server/queue\`.
1729
+ const capabilities = ${capabilities.name}();
1730
+
1731
+ export const fetch = createFetchHandler({ ${options} });
1732
+ export const beginRequest = app.beginRequest;
1733
+ // \`app.router\`'s redirects and headers, for the entry beside this file to put
1734
+ // in front of its static half. Rewrites are \`fetch\`'s own.
1735
+ export const routing = app.routing;
1736
+
1737
+ export default { fetch, beginRequest, routing };
1738
+ `;
1739
+ }
1740
+
1741
+ /**
1742
+ * The import and the expression that give a generated handler a durable store.
1743
+ *
1744
+ * `null` for `"memory"` and for a project that said nothing, which is every
1745
+ * project until one asks: persistence is a second opt-in on top of `route` and
1746
+ * `fetch`, not something a build decides on a project's behalf.
1747
+ *
1748
+ * The directory is baked in as written rather than resolved here, and that is
1749
+ * deliberate. This function runs on the machine doing the build; the path has
1750
+ * to mean something on the machine doing the *serving*, which may be a
1751
+ * container with one writable mount or a Lambda with only `/tmp`. A relative
1752
+ * one is resolved against the working directory at boot, by the provider, where
1753
+ * the answer is a fact rather than a guess.
1754
+ *
1755
+ * The specifier is resolved against the project for the same reason
1756
+ * `internal/serve.js`'s `providerSpecifier` does it: `"./cache/redis.js"` in
1757
+ * `uf.config.js` is relative to the project, and this file is written into
1758
+ * `.uf/deploy/work/`, where that path means nothing. Absolute is safe here
1759
+ * because the bundler inlines the module rather than emitting the specifier.
1760
+ *
1761
+ * @param {string} root
1762
+ * @param {{store?: string, storeDir?: string}} cache
1763
+ * @param {string | null} build
1764
+ */
1765
+ function durableStoreSource(root, cache, build) {
1766
+ const named = cache?.store ?? "memory";
1767
+ if (named === "memory") return null;
1768
+ if (build == null) {
1769
+ throw new Error(
1770
+ `uf: rendering.cache.store is ${JSON.stringify(named)}, which keeps entries between ` +
1771
+ "restarts, and this build has no identity to key them by. Run `uf build` so one is " +
1772
+ "written, or set UF_BUILD_ID. Without one the deployment would answer this build's " +
1773
+ "URLs with the previous build's documents.",
1774
+ );
1775
+ }
1776
+ const directory = JSON.stringify(cache?.storeDir ?? path.join(".uf", "cache", "route"));
1777
+ if (named === "filesystem") {
1778
+ return {
1779
+ import: 'import { createFilesystemCache } from "@uniflowed/server/cache/filesystem";',
1780
+ provider: `createFilesystemCache({ directory: ${directory} })`,
1781
+ what: "uf's filesystem provider",
1782
+ };
1783
+ }
1784
+ const from = JSON.stringify(providerSpecifier(root, named));
1785
+ return {
1786
+ import: `import { createCacheProvider } from ${from};`,
1787
+ provider: `createCacheProvider({ build: ${JSON.stringify(build)}, directory: ${directory} })`,
1788
+ what: `${named}'s provider`,
415
1789
  };
416
- collectPreloads(entry);
1790
+ }
417
1791
 
1792
+ /**
1793
+ * The lines a process entry needs to run what the project declared.
1794
+ *
1795
+ * Shared by `nodeEntrySource` and `bunEntrySource` because the two differ in
1796
+ * which module they take `serve` from and in nothing else — and a schedule
1797
+ * that behaved differently between them would be the drift the whole seam
1798
+ * exists to prevent. Empty strings when a project declared none, so the entry
1799
+ * a default project gets is the file it has always been.
1800
+ */
1801
+ function scheduleLines(module, schedules) {
1802
+ const declared = schedules ?? [];
1803
+ if (declared.length === 0) {
1804
+ return { imports: "", declarations: "", option: "" };
1805
+ }
1806
+ const built = declared
1807
+ .map(
1808
+ (schedule) =>
1809
+ ` routeSchedule({ handle: fetch, beginRequest, path: ${JSON.stringify(
1810
+ schedule.path,
1811
+ )}, cron: ${JSON.stringify(schedule.cron)} }),`,
1812
+ )
1813
+ .join("\n");
418
1814
  return {
419
- scripts: [`/${entry.file}`],
420
- styles: [...styles].map((file) => `/${file}`),
421
- preloads: [...preloads].map((file) => `/${file}`),
1815
+ imports: `import { routeSchedule } from ${JSON.stringify(module)};\n`,
1816
+ // A schedule runs the route by asking the application for it, so a
1817
+ // scheduled run and a request for the same path are one code path. See
1818
+ // ubugeeei-prod/uf#531.
1819
+ declarations: `\nconst schedules = [\n${built}\n];\n`,
1820
+ option: ", schedules",
422
1821
  };
423
1822
  }
424
1823
 
425
1824
  /**
426
- * The URLs to prerender: every route without parameters, plus every set of
427
- * parameters a page's `generateStaticParams` returns.
1825
+ * The source of `server.js`: the Node socket around that handler.
1826
+ *
1827
+ * Everything host-specific about serving a build is in
1828
+ * `@uniflowed/server/node`, which is the same module `uf start` reaches
1829
+ * through `./internal/serve.js` — so a request answered here and the same
1830
+ * request answered by `uf start` go through one implementation, not two that
1831
+ * agree today.
1832
+ */
1833
+ function nodeEntrySource(handlerSpecifier, schedules) {
1834
+ const cron = scheduleLines("@uniflowed/server/schedule", schedules);
1835
+ return `// Generated by \`uf build --adapter node\`. Not checked in, not edited.
1836
+ import path from "node:path";
1837
+ import { fileURLToPath } from "node:url";
1838
+
1839
+ import { serve } from "@uniflowed/server/node";
1840
+ ${cron.imports}
1841
+ // \`beginRequest\` comes from the handler beside this file rather than from
1842
+ // \`@uniflowed/server/node\` above, because the request has to be established in
1843
+ // the storage the *application* reads, which is the copy bundled into
1844
+ // \`handler.js\`. See ubugeeei-prod/uf#389.
1845
+ import { beginRequest, fetch, routing } from ${JSON.stringify(handlerSpecifier)};
1846
+
1847
+ // Resolved from this file and not from the working directory: a process
1848
+ // manager, a container entrypoint and a person in a shell each start a server
1849
+ // from wherever they happen to be, and a directory that only served its own
1850
+ // assets when it was started from inside itself would be a deployment with a
1851
+ // trap in it.
1852
+ const staticDir = path.join(path.dirname(fileURLToPath(import.meta.url)), "static");
1853
+ ${cron.declarations}
1854
+ // Not \`await serve(...)\` at the top level. uf parses that now
1855
+ // (ubugeeei-prod/uf#204) and this entry is a module, so it would work; \`.catch\`
1856
+ // is the better spelling regardless — a server that cannot take its port should
1857
+ // say so and exit non-zero, rather than die as an unhandled rejection.
1858
+ serve({ handle: fetch, staticDir, beginRequest, routing${cron.option} }).catch((error) => {
1859
+ process.stderr.write(\`uf: \${error?.message ?? String(error)}\\n\`);
1860
+ process.exit(1);
1861
+ });
1862
+ `;
1863
+ }
1864
+
1865
+ /**
1866
+ * The oldest Bun that can run what this adapter writes.
1867
+ *
1868
+ * Kept equal to `uf_runtime`'s `BUN_MINIMUM` by
1869
+ * `the_bun_entry_refuses_a_bun_older_than_the_declared_minimum`, which reads
1870
+ * the number out of the artefact rather than out of this file — two places
1871
+ * holding one version is exactly the shape that lets them disagree.
1872
+ *
1873
+ * Why there is a floor at all: React's published server build contains a
1874
+ * labelled statement in `else` position — `else a: if (…)`, in every
1875
+ * `react-dom-server*.production.js` including the `bun` one — and Bun's engine
1876
+ * rejects it with `Cannot find scope for the label 'a'` before this release.
1877
+ * Bun 1.3.13 rejects the built `handler.js`; 1.3.14 imports it and serves it.
1878
+ * It is ordinary ES that Node runs, uf does not emit it, and the `bun` export
1879
+ * condition does not avoid it, so there is nothing for uf to lower. See
1880
+ * ubugeeei-prod/uf#1048.
1881
+ */
1882
+ const MINIMUM_BUN = "1.3.14";
1883
+
1884
+ /**
1885
+ * The source of `server.js`: the Bun socket around that handler.
1886
+ *
1887
+ * `nodeEntrySource`'s twin, and identical but for the module it imports
1888
+ * `serve` from — `@uniflowed/server/bun` exports the same signature on
1889
+ * purpose, so that the two adapters are one contract and a project moving
1890
+ * between them changes a flag and nothing else.
1891
+ *
1892
+ * # Why the handler is imported dynamically
1893
+ *
1894
+ * The one place this is *not* `nodeEntrySource`'s twin. A static
1895
+ * `import … from "./handler.js"` is linked before a single statement of this
1896
+ * file runs, so a version check written above it would never execute: Bun
1897
+ * would fail parsing `handler.js` and the sentence explaining why would never
1898
+ * be reached. `await import()` puts the check first, which is the same move
1899
+ * `denoEntrySource` makes to get its globals in before the handler is
1900
+ * evaluated.
1901
+ */
1902
+ function bunEntrySource(handlerSpecifier, schedules) {
1903
+ const cron = scheduleLines("@uniflowed/server/schedule", schedules);
1904
+ return `// Generated by \`uf build --adapter bun\`. Not checked in, not edited.
1905
+ import path from "node:path";
1906
+ import { fileURLToPath } from "node:url";
1907
+
1908
+ import { serve } from "@uniflowed/server/bun";
1909
+ ${cron.imports}
1910
+ // The Bun this build needs. React's server build carries a labelled statement
1911
+ // in \`else\` position that Bun's engine rejects before this release, so an
1912
+ // older Bun cannot parse \`handler.js\` at all — see ubugeeei-prod/uf#1048.
1913
+ //
1914
+ // This runs *before* the handler is imported, and that ordering is the whole
1915
+ // point: a static import would be linked first and the parse would fail with
1916
+ // Bun's message rather than this one.
1917
+ const MINIMUM_BUN = ${JSON.stringify(MINIMUM_BUN)};
1918
+
1919
+ function ufBunIsOlderThanMinimum(version) {
1920
+ const actual = String(version).split(".");
1921
+ const floor = MINIMUM_BUN.split(".");
1922
+ for (let index = 0; index < floor.length; index += 1) {
1923
+ const mine = Number.parseInt(actual[index], 10);
1924
+ const want = Number.parseInt(floor[index], 10);
1925
+ if (!Number.isFinite(mine)) return true;
1926
+ if (mine !== want) return mine < want;
1927
+ }
1928
+ return false;
1929
+ }
1930
+
1931
+ if (typeof Bun !== "undefined" && ufBunIsOlderThanMinimum(Bun.version)) {
1932
+ process.stderr.write(
1933
+ \`uf: this build needs Bun \${MINIMUM_BUN} or newer, and this is Bun \${Bun.version}. \` +
1934
+ "React's server build uses a labelled statement Bun rejects before " +
1935
+ \`\${MINIMUM_BUN}, so \\\`handler.js\\\` beside this file cannot be parsed here. \` +
1936
+ "Upgrade with \`bun upgrade\`, or build with \`--adapter node\` and run it on Node.\\n",
1937
+ );
1938
+ process.exit(1);
1939
+ }
1940
+
1941
+ // \`beginRequest\` comes from the handler beside this file rather than from
1942
+ // \`@uniflowed/server/bun\` above, because the request has to be established in
1943
+ // the storage the *application* reads, which is the copy bundled into
1944
+ // \`handler.js\`. See ubugeeei-prod/uf#389.
1945
+ const { beginRequest, fetch, routing } = await import(${JSON.stringify(handlerSpecifier)});
1946
+
1947
+ // Resolved from this file and not from the working directory: a process
1948
+ // manager, a container entrypoint and a person in a shell each start a server
1949
+ // from wherever they happen to be, and a directory that only served its own
1950
+ // assets when it was started from inside itself would be a deployment with a
1951
+ // trap in it.
1952
+ const staticDir = path.join(path.dirname(fileURLToPath(import.meta.url)), "static");
1953
+ ${cron.declarations}
1954
+ serve({ handle: fetch, staticDir, beginRequest, routing${cron.option} }).catch((error) => {
1955
+ process.stderr.write(\`uf: \${error?.message ?? String(error)}\\n\`);
1956
+ process.exit(1);
1957
+ });
1958
+ `;
1959
+ }
1960
+
1961
+ /**
1962
+ * The source of `server.js`: the Deno socket around that handler.
1963
+ *
1964
+ * The same generated contract as Node and Bun, with `@uniflowed/server/deno`
1965
+ * owning the host-specific pieces. The static directory is resolved with
1966
+ * `import.meta.url` alone so the entry carries no `node:` imports.
428
1967
  */
429
- async function staticPaths(routes) {
1968
+ function denoEntrySource(handlerSpecifier, schedules) {
1969
+ const cron = scheduleLines("@uniflowed/server/schedule", schedules);
1970
+ return `// Generated by \`uf build --adapter deno\`. Not checked in, not edited.
1971
+ import { serve } from "@uniflowed/server/deno";
1972
+ ${cron.imports}
1973
+ // \`beginRequest\` comes from the handler beside this file rather than from
1974
+ // \`@uniflowed/server/deno\` above, because the request has to be established in
1975
+ // the storage the *application* reads, which is the copy bundled into
1976
+ // \`handler.js\`. See ubugeeei-prod/uf#389.
1977
+ //
1978
+ // Deno has no Node globals, but dependency bundles may still carry a CommonJS
1979
+ // production branch that expects a few of them. Establish the small environment
1980
+ // shape before \`handler.js\` is evaluated, which requires a dynamic import here
1981
+ // rather than a static one.
1982
+ globalThis.process ??= { env: {} };
1983
+ globalThis.process.env ??= {};
1984
+ globalThis.process.env.NODE_ENV ??= "production";
1985
+ globalThis.Buffer ??= {
1986
+ byteLength(value) {
1987
+ return new TextEncoder().encode(String(value)).byteLength;
1988
+ },
1989
+ };
1990
+ globalThis.setImmediate ??= (callback, ...args) => setTimeout(callback, 0, ...args);
1991
+ globalThis.clearImmediate ??= (handle) => clearTimeout(handle);
1992
+ const { beginRequest, fetch, routing } = await import(${JSON.stringify(handlerSpecifier)});
1993
+
1994
+ // Resolved from this file and not from the working directory: a process
1995
+ // manager and a person in a shell each start a server from wherever they
1996
+ // happen to be, and a directory that only served its own assets when it was
1997
+ // started from inside itself would be a deployment with a trap in it.
1998
+ const staticDir = decodeURIComponent(new URL("./static", import.meta.url).pathname);
1999
+ ${cron.declarations}
2000
+ serve({ handle: fetch, staticDir, beginRequest, routing${cron.option} }).catch((error) => {
2001
+ console.error(\`uf: \${error?.message ?? String(error)}\`);
2002
+ Deno.exit(1);
2003
+ });
2004
+ `;
2005
+ }
2006
+
2007
+ /**
2008
+ * The source of `worker.js`: the Cloudflare Workers entry around that handler.
2009
+ *
2010
+ * `export default { fetch }`, which is the modules-format Worker Cloudflare
2011
+ * runs, and everything host-specific is in `@uniflowed/server/edge` — the
2012
+ * asset lookup through the `ASSETS` binding `wrangler.json` declares, and the
2013
+ * `ctx.waitUntil` that keeps the isolate alive for `after()`.
2014
+ *
2015
+ * `beginRequest` comes from the handler beside this file for the reason
2016
+ * `nodeEntrySource` gives: the request has to be established in the storage the
2017
+ * *application* reads. See ubugeeei-prod/uf#389.
2018
+ */
2019
+ function workerEntrySource(handlerSpecifier, schedules) {
2020
+ const declared = schedules ?? [];
2021
+ // Nothing at all when the project declared none, so a `worker.js` without
2022
+ // schedules is the file it has always been — and `wrangler.json` carries no
2023
+ // `triggers` for it either, so there is nothing to call the export that
2024
+ // would not be there.
2025
+ if (declared.length === 0) {
2026
+ return `// Generated by \`uf build --adapter edge\`. Not checked in, not edited.
2027
+ import { createWorkerFetch, installWorkerLogger } from "@uniflowed/server/edge";
2028
+
2029
+ import { beginRequest, fetch as handle, routing } from ${JSON.stringify(handlerSpecifier)};
2030
+
2031
+ // After the imports, so a logger the application installed while it loaded is
2032
+ // the one that stays; see \`installWorkerLogger\`.
2033
+ installWorkerLogger();
2034
+
2035
+ export default { fetch: createWorkerFetch({ handle, beginRequest, routing }) };
2036
+ `;
2037
+ }
2038
+
2039
+ // The expression Cloudflare fires, mapped to the route that answers it.
2040
+ // `event.cron` arrives spelled exactly as `wrangler.json` spells it, and
2041
+ // `uf` writes both from one list, so the two cannot disagree.
2042
+ const routes = Object.fromEntries(declared.map((schedule) => [schedule.cron, schedule.path]));
2043
+ return `// Generated by \`uf build --adapter edge\`. Not checked in, not edited.
2044
+ import { createWorkerFetch, createWorkerScheduled, installWorkerLogger } from "@uniflowed/server/edge";
2045
+
2046
+ import { beginRequest, fetch as handle, routing } from ${JSON.stringify(handlerSpecifier)};
2047
+
2048
+ // After the imports, so a logger the application installed while it loaded is
2049
+ // the one that stays; see \`installWorkerLogger\`.
2050
+ installWorkerLogger();
2051
+
2052
+ // \`triggers.crons\` in the wrangler.json beside this file names these same
2053
+ // expressions. See ubugeeei-prod/uf#531.
2054
+ const routes = ${JSON.stringify(routes, null, 2)};
2055
+
2056
+ export default {
2057
+ fetch: createWorkerFetch({ handle, beginRequest, routing }),
2058
+ scheduled: createWorkerScheduled({ handle, beginRequest, routes }),
2059
+ };
2060
+ `;
2061
+ }
2062
+
2063
+ /**
2064
+ * The source of `lambda.js`: the AWS Lambda entry around that handler.
2065
+ *
2066
+ * `export const handler`, so the function's configured handler is
2067
+ * `lambda.handler`. Everything platform-specific — the payload format 2.0
2068
+ * event, the base64 rules, the `cookies` array — is in
2069
+ * `@uniflowed/server/lambda`.
2070
+ *
2071
+ * `staticDir` points at the `static/` copied beside this file, so an uploaded
2072
+ * package answers a prerendered document without any other infrastructure
2073
+ * existing. That is a starting point rather than a destination, and the module
2074
+ * it is passed to says so at length.
2075
+ */
2076
+ function lambdaEntrySource(handlerSpecifier) {
2077
+ return `// Generated by \`uf build --adapter serverless\`. Not checked in, not edited.
2078
+ import path from "node:path";
2079
+ import { fileURLToPath } from "node:url";
2080
+
2081
+ import { createLambdaHandler } from "@uniflowed/server/lambda";
2082
+
2083
+ import { beginRequest, fetch as handle, routing } from ${JSON.stringify(handlerSpecifier)};
2084
+
2085
+ // Resolved from this file and not from the working directory: Lambda sets the
2086
+ // working directory to the task root today and is under no obligation to keep
2087
+ // doing so, and a deployment that only found its own assets by accident is a
2088
+ // deployment with a trap in it.
2089
+ const staticDir = path.join(path.dirname(fileURLToPath(import.meta.url)), "static");
2090
+
2091
+ export const handler = createLambdaHandler({ handle, beginRequest, staticDir, routing });
2092
+ `;
2093
+ }
2094
+
2095
+ /**
2096
+ * The source of the module a runtime gets wrapped around.
2097
+ *
2098
+ * Three imports and one call: the shim that serves, the application, and the
2099
+ * bytes of `dist/`. The document's script and stylesheet URLs are baked in
2100
+ * here because they come from the client manifest, which exists at this moment
2101
+ * and not inside the binary.
2102
+ *
2103
+ * `assetsFile` is the generated payload's path, and it appears in a comment
2104
+ * rather than in the import: the module enters the graph under a virtual id so
2105
+ * that uf's Flow transform never meets eight megabytes of base64. The reason
2106
+ * that matters is `./internal/compile-assets.js`; naming the file here is what
2107
+ * keeps a reader of the generated entry able to find the bytes it carries.
2108
+ */
2109
+ function entrySource(assetsFile, document) {
2110
+ // Not `await serve(...)` at the top level. uf parses that now
2111
+ // (ubugeeei-prod/uf#204) and this entry is a module, so it would work;
2112
+ // `.catch` is the better spelling regardless: a binary that cannot take its
2113
+ // port should say which port and exit non-zero, rather than die as an
2114
+ // unhandled rejection.
2115
+ return `// Generated by \`uf build --compile\`. Not checked in, not edited.
2116
+ import { serve } from "@uniflowed/server/standalone";
2117
+ // Every file \`uf build\` wrote, base64 in one string. It is on disk at
2118
+ // ${assetsFile}, and it is imported under a virtual id so that uf's
2119
+ // Flow transform is never asked to parse it — see \`@uniflowed/vite\`'s
2120
+ // \`internal/compile-assets.js\` for why that matters.
2121
+ import { assets } from ${JSON.stringify(COMPILE_ASSETS_ID)};
2122
+ import * as app from ${JSON.stringify(VIRTUAL.server)};
2123
+
2124
+ serve({ app, assets, document: ${JSON.stringify(document)} }).catch((error) => {
2125
+ process.stderr.write(\`uf: \${error?.message ?? String(error)}\n\`);
2126
+ process.exit(1);
2127
+ });
2128
+ `;
2129
+ }
2130
+
2131
+ /**
2132
+ * Refuse a native addon by name instead of by stack trace.
2133
+ *
2134
+ * A `.node` file is a compiled shared object for one platform: it cannot be
2135
+ * inlined into a JavaScript bundle, and a binary that carried one would stop
2136
+ * being a single file. Without this, `ssr.noExternal: true` hands the addon to
2137
+ * Rolldown and the build fails somewhere inside the bundler with a message
2138
+ * about an unexpected character — which is true, and useless. Failing here
2139
+ * with the addon's path and the importer that reached it is the difference
2140
+ * between a feature and a trap.
2141
+ *
2142
+ * It catches what can be caught: a static `import` or `require` that resolves
2143
+ * to a `.node` file. An addon loaded through a runtime string — `process.dlopen`,
2144
+ * or `require(variable)` — is not visible to any bundler, so such a project
2145
+ * still compiles and still fails on the first request that reaches the addon.
2146
+ * That limit is real, it is not fixable from inside a bundler, and it is
2147
+ * written down in the CLI reference rather than papered over.
2148
+ */
2149
+ function nativeAddonGuard() {
2150
+ return {
2151
+ name: "uf:no-native-addons",
2152
+ enforce: "pre",
2153
+ resolveId(source, importer) {
2154
+ if (!source.endsWith(".node")) return null;
2155
+ const from = importer == null ? "the application" : path.relative(root, importer);
2156
+ throw new Error(
2157
+ `${from} loads the native addon ${source}, and \`uf build --compile\` cannot put one ` +
2158
+ "inside a single executable: a `.node` file is a shared object built for one " +
2159
+ "platform, and embedding it would make the output two files rather than one. " +
2160
+ "Build without `--compile` and deploy `dist/` with a runtime, or replace the " +
2161
+ "dependency with one that has no native addon.",
2162
+ );
2163
+ },
2164
+ };
2165
+ }
2166
+
2167
+ /**
2168
+ * Say which Node built-ins the Worker being linked reaches and does not have.
2169
+ *
2170
+ * `--adapter edge` only. Every import the bundler resolves passes through here,
2171
+ * and one naming a module `./internal/worker-builtins.js` measured as a stub at
2172
+ * the compatibility date uf writes is kept with the file that imported it. Only
2173
+ * the ones still in the output are reported — see `survivingImports` for the
2174
+ * fixture that showed why — and as warnings rather than a refusal, for the
2175
+ * reason that module gives: a deployment at a newer date may have the module,
2176
+ * and uf cannot see that deployment. What it can do is say, before anything is
2177
+ * uploaded, which request is going to answer 500 and why.
2178
+ */
2179
+ function workerBuiltinGuard() {
2180
+ const reached = [];
2181
+ return {
2182
+ name: "uf:worker-builtins",
2183
+ enforce: "pre",
2184
+ resolveId(source, importer) {
2185
+ if (importer != null && unavailableOnWorkers(source) != null) {
2186
+ reached.push({ specifier: source, importer });
2187
+ }
2188
+ return null;
2189
+ },
2190
+ generateBundle(_options, bundle) {
2191
+ const chunks = Object.values(bundle).filter((output) => output.type === "chunk");
2192
+ for (const warning of workerBuiltinWarnings(survivingImports(reached, chunks), root)) {
2193
+ this.warn(warning);
2194
+ }
2195
+ },
2196
+ };
2197
+ }
2198
+
2199
+ /** `word`, pluralised for `count`. */
2200
+ function plural(count, word) {
2201
+ return count === 1 ? word : `${word}s`;
2202
+ }
2203
+
2204
+ async function printConfig() {
2205
+ const config = await loadConfig();
2206
+ emit("config", { config: projectConfig(config) });
2207
+ process.exit(0);
2208
+ }
2209
+
2210
+ /**
2211
+ * The React Server Components state `@uniflowed/vite` shares with this driver,
2212
+ * or `null` for an application rendered from its modules.
2213
+ *
2214
+ * Read off the plugin rather than decided again here: `rendersFlight` in
2215
+ * `./internal/flight.js` decides from the same `uf.config.js`, and a second
2216
+ * reading of it would be the one that drifts.
2217
+ */
2218
+ function flightStateOf(inline) {
2219
+ const plugins = (inline.plugins ?? []).flat(Number.POSITIVE_INFINITY);
2220
+ return plugins.find((plugin) => plugin?.name === "uf:flow")?.api?.flight ?? null;
2221
+ }
2222
+
2223
+ /** What a later command needs of the rsc build, written beside its output. */
2224
+ const FLIGHT_BUILD_FILE = "uf-flight.json";
2225
+
2226
+ /**
2227
+ * Build the rsc graph into `outDir`.
2228
+ *
2229
+ * `conditions` are a deploy target's own, added to `react-server`; `null` is
2230
+ * the Node server `uf build` writes. Vite's builder rather than `vite.build`,
2231
+ * because the rsc graph is an environment of its own and `vite.build` builds
2232
+ * the two Vite always has.
2233
+ */
2234
+ async function buildRscGraph(vite, inline, state, { outDir, conditions }) {
2235
+ const environment = {
2236
+ build: {
2237
+ outDir,
2238
+ emptyOutDir: true,
2239
+ rollupOptions: {
2240
+ input: { index: FLIGHT_VIRTUAL.entry },
2241
+ output: { entryFileNames: "[name].js", format: "es" },
2242
+ },
2243
+ },
2244
+ };
2245
+ if (conditions != null) {
2246
+ environment.resolve = {
2247
+ conditions: ["react-server", ...conditions],
2248
+ externalConditions: ["react-server", ...conditions],
2249
+ };
2250
+ }
2251
+ const builder = await vite.createBuilder({
2252
+ ...inline,
2253
+ customLogger: eventLogger("warn"),
2254
+ environments: { [RSC_ENVIRONMENT]: environment },
2255
+ });
2256
+ await builder.build(builder.environments[RSC_ENVIRONMENT]);
2257
+ state.rscOutput = path.join(outDir, "index.js");
2258
+ }
2259
+
2260
+ /**
2261
+ * Record the chunk each client module was built into, and write it down.
2262
+ *
2263
+ * Written down because `uf build --adapter` and `uf build --compile` bundle
2264
+ * the server again in a process of their own, and a reference in the rsc
2265
+ * output names its module by path, which only this build's manifest turns
2266
+ * into a URL.
2267
+ */
2268
+ function recordClientChunks(state, manifest, references, rscDir, base = "") {
2269
+ for (const file of references) {
2270
+ const key = path.relative(root, file).split(path.sep).join("/");
2271
+ const chunk = manifest[key];
2272
+ if (chunk == null) {
2273
+ throw new Error(
2274
+ `uf: the client build wrote no chunk for ${key}, which a server component renders as a ` +
2275
+ "client component",
2276
+ );
2277
+ }
2278
+ state.chunkUrls.set(file, `${base}/${chunk.file}`);
2279
+ }
2280
+ writeFileSync(
2281
+ path.join(rscDir, FLIGHT_BUILD_FILE),
2282
+ `${JSON.stringify({ chunkUrls: [...state.chunkUrls] }, null, 2)}\n`,
2283
+ );
2284
+ }
2285
+
2286
+ /** What `recordClientChunks` wrote, for a command that runs after `uf build`. */
2287
+ function loadFlightBuild(state, rscDir) {
2288
+ const file = path.join(rscDir, FLIGHT_BUILD_FILE);
2289
+ if (!existsSync(file)) {
2290
+ throw new Error(
2291
+ `uf: ${path.relative(root, file)} is missing, so there is no rsc graph to render routes ` +
2292
+ "with; run `uf build` first",
2293
+ );
2294
+ }
2295
+ state.chunkUrls = new Map(JSON.parse(readFileSync(file, "utf8")).chunkUrls);
2296
+ state.rscOutput = path.join(rscDir, "index.js");
2297
+ }
2298
+
2299
+ /**
2300
+ * The tags a document React Server Components render needs.
2301
+ *
2302
+ * `assetsFromManifest`'s, with stylesheets from three places in the order they
2303
+ * cascade: the rsc graph's first — every layout's and every server component's
2304
+ * — then the client entry's, then each client module's own, which the client
2305
+ * build emits beside that module's chunk and no import from the entry reaches.
2306
+ *
2307
+ * The rsc build's emitted files are copied under `dist/` so those URLs resolve,
2308
+ * and only its assets: a server bundle's JavaScript is never a deployable file.
2309
+ */
2310
+ function flightAssets(manifest, references, rscDir, outDir, base = "") {
2311
+ const assets = assetsFromManifest(manifest, base);
2312
+ const styles = new Set();
2313
+ const rscManifest = path.join(rscDir, ".vite", "manifest.json");
2314
+ if (existsSync(rscManifest)) {
2315
+ const rscStyles = assetsFromManifest(
2316
+ JSON.parse(readFileSync(rscManifest, "utf8")),
2317
+ base,
2318
+ ).styles;
2319
+ for (const href of rscStyles) styles.add(href);
2320
+ }
2321
+ const rscAssets = path.join(rscDir, "assets");
2322
+ if (existsSync(rscAssets)) {
2323
+ cpSync(rscAssets, path.join(outDir, "assets"), {
2324
+ recursive: true,
2325
+ filter: (from) => !/\.(?:[cm]?js|map)$/.test(from),
2326
+ });
2327
+ }
2328
+ for (const href of assets.styles) styles.add(href);
2329
+ const seen = new Set();
2330
+ const visit = (key) => {
2331
+ if (seen.has(key)) return;
2332
+ seen.add(key);
2333
+ const chunk = manifest[key];
2334
+ if (chunk == null) return;
2335
+ for (const css of chunk.css ?? []) styles.add(`${base}/${css}`);
2336
+ for (const imported of chunk.imports ?? []) visit(imported);
2337
+ };
2338
+ for (const file of references) visit(path.relative(root, file).split(path.sep).join("/"));
2339
+ return { ...assets, styles: [...styles] };
2340
+ }
2341
+
2342
+ function readManifest(outDir) {
2343
+ const file = path.join(outDir, ".vite", "manifest.json");
2344
+ if (!existsSync(file)) throw new Error(`uf: the client build wrote no manifest at ${file}`);
2345
+ return JSON.parse(readFileSync(file, "utf8"));
2346
+ }
2347
+
2348
+ /**
2349
+ * What this build renders now, and what it leaves for a server.
2350
+ *
2351
+ * The rendering decision, per route, and it has three answers rather than the
2352
+ * two `staticPaths` used to have:
2353
+ *
2354
+ * * **prerender it** — a route with no parameters, or a route whose page
2355
+ * exports `generateStaticParams`, once per set of parameters it returns;
2356
+ * * **leave it to the server** — a route with parameters and no
2357
+ * `generateStaticParams`, or a page that has said `export const dynamic =
2358
+ * "force-dynamic"`;
2359
+ * * **refuse** — which is not decided here. This function reports what it
2360
+ * found and the caller, which knows whether the project allows a server,
2361
+ * is the one that turns "there is a route here a static host cannot
2362
+ * answer" into an error.
2363
+ *
2364
+ * `dynamic` is the spelling ubugeeei-prod/uf#336 asked for: a route with *no*
2365
+ * parameters whose content depends on the request had no way to say so, and
2366
+ * `generateStaticParams` cannot say it — there are no parameters to generate.
2367
+ * It is Next.js's name for the same declaration, because a person arriving
2368
+ * from `app/` should not have to learn a second word for a decision they have
2369
+ * already made once.
2370
+ *
2371
+ * Two of Next's four values are missing and are not silently accepted:
2372
+ * `"force-static"` and `"error"` are refused by name, because each is a
2373
+ * *constraint* on a page that uf does not yet check, and accepting one would
2374
+ * be reading a declaration and ignoring it — the failure the two issues behind
2375
+ * this function are about.
2376
+ *
2377
+ * Handlers and middleware are in the same list, and they belong there: this is
2378
+ * the list of things that need a process, and a `$route.js` needs one more
2379
+ * obviously than any page does. They carry no per-route render — the build has
2380
+ * never written a file for either — so they appear only when the answer might
2381
+ * be a refusal.
2382
+ *
2383
+ * @param {{routes: Route[], handlers: Handler[], middleware: Middleware[]}} server
2384
+ * @param {"everything" | "possible" | "nothing"} prerender
2385
+ */
2386
+ async function renderingPlan(server, prerender) {
430
2387
  const urls = [];
431
- for (const route of routes) {
2388
+ const perRequest = [];
2389
+
2390
+ // One document, and it is no route's, so there is no route to ask anything
2391
+ // about. `perRequest` is empty rather than "every route": nothing here is
2392
+ // left for a server — the browser answers all of it — and listing routes
2393
+ // under a heading that means "these need a process" would be a build
2394
+ // describing itself wrongly to `uf`, which prints that list.
2395
+ if (prerender === "shell") {
2396
+ return { urls: [], perRequest: [] };
2397
+ }
2398
+
2399
+ // Nothing is prerendered and nothing is refused, so no page module is
2400
+ // loaded: a project that renders everything per request should not pay for
2401
+ // a `generateStaticParams` this build will not call.
2402
+ if (prerender === "nothing") {
2403
+ return {
2404
+ urls,
2405
+ perRequest: server.routes.map((route) => ({
2406
+ path: route.path,
2407
+ why: "this build prerenders nothing",
2408
+ })),
2409
+ };
2410
+ }
2411
+
2412
+ for (const route of server.routes) {
2413
+ // Every page module, and not only the parameterised ones: `dynamic` is a
2414
+ // declaration any page can make. A module that cannot be imported at all
2415
+ // is a failure of *that route*, so a route with no parameters goes into
2416
+ // the prerender anyway and the loop below reports it the way it has always
2417
+ // reported a page that throws — named, with the rest of the build still
2418
+ // happening. A parameterised one still rejects out of the build, which is
2419
+ // what it did before there was anything else to load a page module for.
2420
+ let module;
2421
+ try {
2422
+ module = await route.page();
2423
+ } catch (error) {
2424
+ if (route.params.length > 0) throw error;
2425
+ urls.push(route.path);
2426
+ continue;
2427
+ }
2428
+ const declared = module.dynamic ?? "auto";
2429
+ if (declared !== "auto" && declared !== "force-dynamic") {
2430
+ throw new Error(
2431
+ `uf: ${route.file} exports \`dynamic = ${JSON.stringify(declared)}\`, and uf reads ` +
2432
+ '`"auto"` and `"force-dynamic"`. `"force-static"` and `"error"` are Next.js values ' +
2433
+ "for constraints uf does not check yet, and accepting one would be reading a " +
2434
+ "declaration and ignoring it.",
2435
+ );
2436
+ }
2437
+ if (declared === "force-dynamic") {
2438
+ perRequest.push({
2439
+ path: route.path,
2440
+ why: 'its page exports `dynamic = "force-dynamic"`',
2441
+ });
2442
+ continue;
2443
+ }
432
2444
  if (route.params.length === 0) {
433
2445
  urls.push(route.path);
434
2446
  continue;
435
2447
  }
436
- const module = await route.page();
437
2448
  const generate = module.generateStaticParams;
438
- if (typeof generate !== "function") continue;
2449
+ if (typeof generate !== "function") {
2450
+ perRequest.push({
2451
+ path: route.path,
2452
+ why: "it has parameters and its page exports no `generateStaticParams`",
2453
+ });
2454
+ continue;
2455
+ }
439
2456
  for (const params of await generate()) {
440
2457
  urls.push(fillParams(route.path, params));
441
2458
  }
442
2459
  }
443
- return urls;
2460
+
2461
+ for (const handler of server.handlers ?? []) {
2462
+ perRequest.push({
2463
+ path: handler.path,
2464
+ why: "it is a route handler, and a handler answers a request rather than producing a file",
2465
+ });
2466
+ }
2467
+ for (const entry of server.middleware ?? []) {
2468
+ // A middleware is reported by the path it guards rather than by the route
2469
+ // it guards, which is why it cannot be folded into the loop above: it runs
2470
+ // for a page, for a handler, and for a path under it that is neither, so
2471
+ // "which route is this" has no single answer.
2472
+ perRequest.push({
2473
+ path: `${entry.path === "/" ? "" : entry.path}/*`,
2474
+ why: "a middleware guards it, and a middleware runs once per request",
2475
+ });
2476
+ }
2477
+ // And `app.router`'s three lists, by the source each rule matches: a file
2478
+ // can be neither a redirect nor a rewrite, and a header a file is served
2479
+ // with is the host's to add rather than the file's.
2480
+ for (const [key, what] of [
2481
+ ["redirects", "a redirect"],
2482
+ ["rewrites", "a rewrite"],
2483
+ ["headers", "a response header"],
2484
+ ]) {
2485
+ for (const rule of server.routing?.[key] ?? []) {
2486
+ perRequest.push({
2487
+ path: rule.source,
2488
+ why: `\`app.router.${key}\` names it, and ${what} is answered when a request arrives`,
2489
+ });
2490
+ }
2491
+ }
2492
+
2493
+ return { urls, perRequest };
444
2494
  }
445
2495
 
446
2496
  function fillParams(routePath, params) {
@@ -460,9 +2510,36 @@ function fillParams(routePath, params) {
460
2510
  .join("/");
461
2511
  }
462
2512
 
463
- function htmlPathFor(outDir, url) {
464
- const pathname = url.split("?")[0].replace(/^\/+/, "");
465
- return pathname === ""
466
- ? path.join(outDir, "index.html")
2513
+ /**
2514
+ * The file a prerendered page is written to.
2515
+ *
2516
+ * `guide/index.html`, which every static host serves at `/guide/` and most at
2517
+ * `/guide`, unless `app.router.trailingSlash` is `"never"` — then `guide.html`,
2518
+ * which the same hosts serve at `/guide` without a redirect to the slash.
2519
+ * Next.js's static export makes the same choice from the same setting.
2520
+ */
2521
+ function htmlPathFor(outDir, url, trailingSlash = "ignore") {
2522
+ const pathname = url.split("?")[0].replace(/^\/+/, "").replace(/\/+$/, "");
2523
+ if (pathname === "") return path.join(outDir, "index.html");
2524
+ return trailingSlash === "never"
2525
+ ? path.join(outDir, `${pathname}.html`)
467
2526
  : path.join(outDir, pathname, "index.html");
468
2527
  }
2528
+
2529
+ /**
2530
+ * The URL path at which a static half answers the document `htmlPathFor`
2531
+ * wrote for `url` under `REGENERATED_DIRECTORY`.
2532
+ *
2533
+ * Ending in a slash, so every host answers it with that directory's
2534
+ * `index.html` in the same way: a Node static half tries `index.html` for such
2535
+ * a path, and a Worker's assets binding serves it without the redirect it
2536
+ * answers `…/index.html` with.
2537
+ */
2538
+ function regeneratedDocumentUrl(url) {
2539
+ const pathname = url.split("?")[0].replace(/^\/+/, "").replace(/\/+$/, "");
2540
+ const encoded = pathname
2541
+ .split("/")
2542
+ .map((segment) => encodeURIComponent(segment))
2543
+ .join("/");
2544
+ return pathname === "" ? `/${REGENERATED_DIRECTORY}/` : `/${REGENERATED_DIRECTORY}/${encoded}/`;
2545
+ }