@guren/core 1.13.0 → 1.13.1

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.
@@ -3,48 +3,22 @@ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path
3
3
  import { fileURLToPath } from "node:url";
4
4
  //#region src/internal/deploy-build.ts
5
5
  /**
6
- * Build-time helpers shared by the deploy plugins (`@guren/plugin-cloudflare`,
7
- * `@guren/plugin-lambda`, `@guren/plugin-vercel`).
8
- *
9
- * Internal by the rules in `contributing/api-stability.md`: reachable only
10
- * through a deep import under `internal/`, never re-exported from
11
- * `@guren/core`'s index. No stability guarantee — it exists so the three
12
- * plugins stop carrying three copies of the same knowledge, not as a public
13
- * extension point.
14
- *
15
- * Deliberately imports nothing from the framework itself: a plugin's build
16
- * step should not drag the runtime into a developer's build process. Only
17
- * `node:` builtins belong here, and `deploy-build.test.ts` asserts it of the
18
- * built artifact — the property would otherwise break silently the day the bundler
19
- * splits a shared chunk out of this entry.
20
- *
21
- * What does *not* belong here: anything a platform legitimately decides for
22
- * itself. The message naming a platform and its replacement API, where a
23
- * rendered stub is delivered (Workers resolves an alias to a file on disk,
24
- * Lambda hands source to its bundler plugin), whether a missing `build` script
25
- * is fatal, and how an SSR bundle's renderer export is verified are all
26
- * per-plugin by design.
27
- *
28
- * One rule holds across the helpers here: a helper that *relates* two paths —
29
- * a containment test, a relative specifier — canonicalizes both first, because
30
- * whatever consumes the answer resolves links too. A helper that merely reads
31
- * or writes one path passes it through, since the OS follows the links itself.
32
- * That is why `resolveSsrEntryFile` compares raw strings (both operands derive
33
- * from one `ssrDir`, so no link can come between them) and why the plugins'
34
- * own `relative(root, out)` for `wrangler.jsonc` must stay lexical: that path
35
- * is read by wrangler, not by a bundler resolving a module from its real path.
6
+ * Build-time helpers shared by the deploy plugins (cloudflare, lambda, vercel).
7
+ * Internal (`contributing/api-stability.md`): deep import only, never re-exported
8
+ * from `@guren/core`. Imports only `node:` builtins so a plugin build never drags
9
+ * the runtime in; `deploy-build.test.ts` asserts that of the built artifact.
10
+ * Platform decisions (messages, stub delivery, whether a missing `build` script is
11
+ * fatal, SSR renderer verification) stay per-plugin. A helper that *relates* two
12
+ * paths canonicalizes both first; one that reads or writes a single path does not.
36
13
  */
37
14
  function resolvePathLike(value) {
38
15
  return value instanceof URL ? fileURLToPath(value) : resolve(String(value));
39
16
  }
40
17
  /**
41
- * Read the first manifest that parses, tolerating both Vite layouts
42
- * (`.vite/manifest.json` and the flat `manifest.json` older configs emit), and
43
- * report which path it was. A malformed file is skipped rather than fatal —
44
- * the caller decides what a missing manifest means for its platform. The path
45
- * is part of the result because a caller publishing the manifest location to
46
- * the runtime has to name the file that was actually parsed: testing which one
47
- * *exists* picks the malformed one that was just skipped.
18
+ * Read the first manifest that parses, in either Vite layout (`.vite/manifest.json`,
19
+ * then flat `manifest.json`), and report its path: a caller publishing the location
20
+ * must name the file actually parsed, not the malformed one that was skipped. What a
21
+ * missing manifest means is the caller's call.
48
22
  */
49
23
  function readManifest(...paths) {
50
24
  for (const path of paths) {
@@ -60,39 +34,27 @@ function readManifest(...paths) {
60
34
  }
61
35
  }
62
36
  /**
63
- * The two layouts `readManifest` accepts, in preference order: `.vite/` first,
64
- * because Vite >= 5 writes it there and a flat `manifest.json` beside it is
65
- * most likely stale output of an older config. `@guren/server`'s runtime
66
- * lookup (`clientManifestCandidates` in `http/vite-manifest.ts`) prefers the
67
- * same layout — the orders must agree, or an app with both files resolves
68
- * different asset versions locally than after a deploy; the server's
69
- * `tests/http/vite-manifest.test.ts` pins the agreement (the rule cannot be
70
- * shared as code, since this module imports nothing beyond node builtins).
37
+ * Layouts `readManifest` accepts, `.vite/` first (Vite >= 5 writes it there; a flat
38
+ * file beside it is likely stale). Must agree with `clientManifestCandidates` in
39
+ * @guren/server's http/vite-manifest.ts, pinned by tests/http/vite-manifest.test.ts,
40
+ * or local and deployed asset versions diverge.
71
41
  */
72
42
  function manifestPaths(dir) {
73
43
  return [resolve(dir, ".vite/manifest.json"), resolve(dir, "manifest.json")];
74
44
  }
75
45
  /**
76
- * The one statement of where an app's *client* manifest lives: under
77
- * `<publicDir>/assets`, in either Vite layout. `resolveClientAssetEnv` and
78
- * `clientManifestJson` both answer from this read — stating the composition
79
- * twice is how the two would come to look in different places.
46
+ * The one statement of where the client manifest lives: `<publicDir>/assets`, either
47
+ * layout. `resolveClientAssetEnv` and `clientManifestJson` both read through here.
80
48
  */
81
49
  function readClientManifest(publicDir) {
82
50
  return readManifest(...manifestPaths(resolve(publicDir, "assets")))?.manifest;
83
51
  }
84
52
  /**
85
- * Resolve symlinks in the parts of `path` that exist, keeping the trailing
86
- * components that do not. `realpathSync` throws on a path that is not there
87
- * yet, and an output directory usually is not on a first build.
88
- *
89
- * A sibling of `realpathNearestExisting` in `@guren/cli`'s plugin-manifest.ts,
90
- * kept as a copy because this module must not import beyond node builtins and
91
- * cli cannot be imported from core. Only ENOENT walks up, matching the twin:
92
- * any other failure (an unreadable or non-directory ancestor) is surfaced
93
- * rather than silently treated as nonexistent — both callers relate two paths
94
- * (a deletion guard, an import specifier) and neither may answer from a path
95
- * it could not actually resolve.
53
+ * Resolve symlinks in the existing parts of `path`, keeping trailing components that
54
+ * do not exist yet (`realpathSync` throws on a first build's output dir). Twin of
55
+ * `realpathNearestExisting` in @guren/cli's plugin-manifest.ts, copied because this
56
+ * module imports only node builtins. Only ENOENT walks up; any other failure
57
+ * surfaces, since both callers relate two paths and must not answer from a guess.
96
58
  */
97
59
  function realpathOfNearestExisting(path) {
98
60
  try {
@@ -105,25 +67,11 @@ function realpathOfNearestExisting(path) {
105
67
  return resolve(realpathOfNearestExisting(parent), basename(path));
106
68
  }
107
69
  /**
108
- * Throw unless `out` is safe to delete: it must be neither the app root nor a
109
- * directory containing it.
110
- *
111
- * Relates two paths, so it canonicalizes both: comparing lexically would
112
- * accept `outputDir` values that reach the app root the long way, and the
113
- * delete that follows resolves the links regardless.
114
- *
115
- * Containment is then decided with `relative` rather than a string prefix
116
- * because `out + sep` is `//` at the filesystem root, which no absolute path
117
- * is prefixed by — a prefix test lets `outputDir: '/'` through. The escape
118
- * test is `'..'` exactly or a `'../'` prefix, not `startsWith('..')`: a
119
- * directory legitimately named `..-source` inside `out` yields the relative
120
- * path `..-source`, which the looser test would read as an escape.
121
- *
122
- * Exported separately from `resetOutputDir` so a caller can validate the
123
- * option early and delete later, but the delete itself should always go
124
- * through `resetOutputDir`.
125
- *
126
- * @param label Platform name for the error message, e.g. `'Lambda build'`.
70
+ * Throw unless `out` is safe to delete: neither the app root nor a directory
71
+ * containing it. Both paths are canonicalized (a lexical compare accepts an
72
+ * `outputDir` that reaches the root through links). Containment uses `relative`,
73
+ * not a prefix test (`out + sep` is `//` at the root, letting `'/'` through), and
74
+ * escape means `'..'` or a `'../'` prefix, so `..-source` inside `out` is not one.
127
75
  */
128
76
  function assertOutputDirOutsideRoot(out, root, label) {
129
77
  const outToRoot = relative(realpathOfNearestExisting(out), realpathOfNearestExisting(root));
@@ -131,13 +79,8 @@ function assertOutputDirOutsideRoot(out, root, label) {
131
79
  if (outToRoot === "" || rootIsInsideOut) throw new Error(`${label}: outputDir (${out}) must be a directory outside or below the app root, never the root itself or a parent of it — it is deleted on every build.`);
132
80
  }
133
81
  /**
134
- * Delete the output directory so the build starts from a clean slate, after
135
- * checking it is safe to delete.
136
- *
137
- * The check and the delete are one call on purpose: they were separate
138
- * statements in each plugin, and a plugin that had only the delete has already
139
- * shipped.
140
- *
82
+ * Delete the output directory after checking it is safe to delete. One call on
83
+ * purpose: a plugin that carried only the delete has already shipped.
141
84
  * @param label Platform name for the error message, e.g. `'Lambda build'`.
142
85
  */
143
86
  function resetOutputDir(out, root, label) {
@@ -148,13 +91,10 @@ function resetOutputDir(out, root, label) {
148
91
  });
149
92
  }
150
93
  /**
151
- * Relative specifier for importing `target` from a module written into
152
- * `fromDir`, in POSIX form so the emitted source is platform-agnostic.
153
- *
154
- * Relates two paths, so it canonicalizes both: the bundler resolves the
155
- * emitted module from its real path, and a link that changes depth would
156
- * otherwise leave the specifier short a `..` segment.
157
- *
94
+ * POSIX relative specifier for importing `target` from a module written into
95
+ * `fromDir`. Both paths are canonicalized: the bundler resolves the emitted module
96
+ * from its real path, and a link that changes depth would leave the specifier a
97
+ * `..` short.
158
98
  * @param label Platform name for the error message, e.g. `'Lambda build'`.
159
99
  */
160
100
  function importSpecifier(fromDir, target, label) {
@@ -164,12 +104,9 @@ function importSpecifier(fromDir, target, label) {
164
104
  return specifier.startsWith(".") ? specifier : `./${specifier}`;
165
105
  }
166
106
  /**
167
- * Locate the built client entry and its CSS in the Vite client manifest, as
168
- * the `/assets/`-prefixed URLs the Inertia head expects.
169
- *
170
- * Takes the public directory rather than the app root so a caller passing a
171
- * custom `publicDir` is honoured.
172
- *
107
+ * Locate the built client entry and its CSS in the Vite client manifest, as the
108
+ * `/assets/`-prefixed URLs the Inertia head expects. Takes the public directory so
109
+ * a custom `publicDir` is honoured.
173
110
  * @param label Platform name for the warning message, e.g. `'Lambda build'`.
174
111
  */
175
112
  function resolveClientAssetEnv(publicDir, clientEntryKey, label) {
@@ -184,27 +121,11 @@ function resolveClientAssetEnv(publicDir, clientEntryKey, label) {
184
121
  };
185
122
  }
186
123
  /**
187
- * The client build manifest as JSON text, for the deploy targets' runtime
188
- * manifest injection (`GUREN_VITE_MANIFEST`): `viteAsset()` resolves
189
- * content-page asset URLs from the client manifest at render time, and a
190
- * bundled function or worker has no `public/assets/manifest.json` to read.
191
- * How the payload reaches the runtime is per-plugin (a generated-entry
192
- * assignment, a bundler `define`); *what* the payload is, is this.
193
- *
194
- * Separate from `resolveClientAssetEnv` because that helper answers only for
195
- * the client *entry*: a content-page app can have a manifest of CSS build
196
- * inputs and no `resources/js/app.tsx` at all, and its `viteAsset()` calls
197
- * still need the whole manifest.
198
- *
199
- * The payload is trimmed to the fields the runtime rule reads — `file` and
200
- * `css` per entry (`getManifestFile`/`getManifestCss` in @guren/server's
201
- * vite-manifest.ts) — because it ships inside executable code: a large app's
202
- * manifest is dominated by per-chunk `imports`/`dynamicImports` graph
203
- * metadata nothing consumes, and Workers caps bundle size. Trimming also
204
- * validates the shape at build time, so a parseable-but-not-a-manifest file
205
- * (`null`, an array) is reported as "no manifest" here instead of being baked
206
- * in to fail at first render. String and array entry forms pass through
207
- * untrimmed — the runtime accepts them, and the two paths must not diverge.
124
+ * The client manifest as JSON for runtime injection (`GUREN_VITE_MANIFEST`): a
125
+ * bundled function has no `public/assets/manifest.json`. Separate from
126
+ * `resolveClientAssetEnv`, which answers only for the client entry. Trimmed to
127
+ * `file`/`css` per entry (all the runtime reads; chunk graph metadata dominates
128
+ * size and Workers caps bundles); a parseable non-manifest is rejected here.
208
129
  */
209
130
  function clientManifestJson(publicDir) {
210
131
  const manifest = readClientManifest(publicDir);
@@ -225,11 +146,9 @@ function clientManifestJson(publicDir) {
225
146
  return JSON.stringify(trimmed);
226
147
  }
227
148
  /**
228
- * Absolute path of the built SSR entry chunk, or undefined when the app has no
229
- * SSR build. Verifying that the chunk actually exports a renderer is left to
230
- * the caller: the platforms disagree on whether importing it during a build is
231
- * acceptable.
232
- *
149
+ * Absolute path of the built SSR entry chunk, or undefined without an SSR build.
150
+ * Whether the chunk exports a renderer is the caller's check: platforms disagree
151
+ * on importing it during a build.
233
152
  * @param label Platform name for the error messages, e.g. `'Lambda build'`.
234
153
  */
235
154
  function resolveSsrEntryFile(ssrDir, ssrEntryKey, label) {
@@ -241,18 +160,11 @@ function resolveSsrEntryFile(ssrDir, ssrEntryKey, label) {
241
160
  return file;
242
161
  }
243
162
  /**
244
- * Runtime locations of a staged SSR bundle, for platforms that copy `ssrDir`
245
- * under the function root and hand the layout to the server through
246
- * environment variables. `prefix` is where the caller stages the directory —
247
- * it cannot be derived here because staging happens later in the caller's own
248
- * flow.
249
- *
250
- * The manifest path is derived from the file that parsed rather than the
251
- * first one that exists: both Vite layouts occur in the wild, and a malformed
252
- * `.vite/manifest.json` alongside a valid flat one would otherwise publish the
253
- * path to the file that was skipped. It is optional only for the mid-build
254
- * race where the manifest vanishes between `resolveSsrEntryFile` and this
255
- * call — callers already hold a chunk path that manifest produced.
163
+ * Runtime locations of a staged SSR bundle, for platforms that copy `ssrDir` under
164
+ * the function root; `prefix` is where the caller stages it. The manifest path is
165
+ * the file that parsed, not the first that exists (a malformed `.vite/` file beside
166
+ * a valid flat one). Optional only for the race where the manifest vanishes after
167
+ * `resolveSsrEntryFile`.
256
168
  */
257
169
  function ssrRuntimePaths(ssrDir, ssrFile, prefix) {
258
170
  const under = (target) => `${prefix}/${relative(ssrDir, target).split(sep).join("/")}`;
@@ -263,46 +175,36 @@ function ssrRuntimePaths(ssrDir, ssrFile, prefix) {
263
175
  };
264
176
  }
265
177
  /**
266
- * Copy `public/` into a platform's static-asset staging directory.
267
- *
268
- * Two pieces of Guren-specific knowledge, not platform policy, which is why
269
- * this is shared: the dev-mode `index.html` shell must never ship (it would
270
- * shadow the app's root route on any host that serves static files first), and
271
- * built assets self-reference the Vite plugin's derived base `/public/assets/`
272
- * while HTML references use `/assets/` — so on a host without rewrites the
273
- * built-assets directory has to appear under both prefixes.
178
+ * Delete the dev-mode `index.html` shell from a statically served directory: every
179
+ * deploy target answers for its static directory before the function runs, so the
180
+ * shell shadows the app's root route. Exact name only (the framework writes it).
181
+ * Separate from `stageStaticAssets` because `@guren/plugin-vercel` stages `public/`
182
+ * itself and needs this rule alone.
183
+ */
184
+ function removeShadowingIndex(assetsOut) {
185
+ const shadowingIndex = resolve(assetsOut, "index.html");
186
+ if (existsSync(shadowingIndex)) rmSync(shadowingIndex);
187
+ }
188
+ /**
189
+ * Copy `public/` into a platform's static staging directory. Built assets
190
+ * self-reference `/public/assets/` while HTML uses `/assets/`, so on a host without
191
+ * rewrites the assets directory must appear under both prefixes. Also applies
192
+ * `removeShadowingIndex`.
274
193
  */
275
194
  function stageStaticAssets(publicDir, assetsOut) {
276
195
  mkdirSync(assetsOut, { recursive: true });
277
196
  if (!existsSync(publicDir)) return;
278
197
  cpSync(publicDir, assetsOut, { recursive: true });
279
- const shadowingIndex = resolve(assetsOut, "index.html");
280
- if (existsSync(shadowingIndex)) rmSync(shadowingIndex);
198
+ removeShadowingIndex(assetsOut);
281
199
  const clientAssetsDir = resolve(publicDir, "assets");
282
200
  if (existsSync(clientAssetsDir)) cpSync(clientAssetsDir, resolve(assetsOut, "public/assets"), { recursive: true });
283
201
  }
284
202
  /**
285
- * Extensions a browser renders as a *document* in the serving origin, for a
286
- * platform that answers for `public/` before the app ever runs.
287
- *
288
- * Exactly the set `@guren/server`'s `rendersAsDocument` matches over Hono's
289
- * mime table — the same two inputs the framework's own static guard reads, so
290
- * a file that downloads locally downloads on a deploy target too. Written out
291
- * rather than derived because this module imports nothing from the framework
292
- * (see the header); `packages/server/tests/http/static-documents.test.ts`
293
- * recomputes it from that table and fails when the two disagree, so a document
294
- * type Hono adds cannot pass unnoticed.
295
- *
296
- * Two things the list does not reach, both of them the framework's own
297
- * blind spots rather than new ones. `text/xsl` is a document type
298
- * `rendersAsDocument` matches, but Hono's table names no extension for it, so
299
- * `getMimeType` returns nothing for a `.xsl` file and the framework serves it
300
- * unguarded too — adding it here would make a deploy target stricter than the
301
- * app it deployed. And extension *case*: `getMimeType` lowercases before its
302
- * lookup, so the framework guard does fire for `logo.SVG`, and a platform
303
- * matching a literal pattern does not. Each plugin closes that where its own
304
- * matcher allows, and the three answers differ — see each one's own comment
305
- * rather than a list here that goes stale on the next target.
203
+ * Extensions a browser renders as a document, for platforms serving `public/`
204
+ * before the app runs: exactly what `@guren/server`'s `rendersAsDocument` matches
205
+ * over Hono's mime table (`tests/http/static-documents.test.ts` fails on drift).
206
+ * Like the framework it misses `.xsl` (Hono names no extension) and extension
207
+ * case, which each plugin closes as its own matcher allows.
306
208
  */
307
209
  const DOCUMENT_ASSET_EXTENSIONS = [
308
210
  "htm",
@@ -312,38 +214,20 @@ const DOCUMENT_ASSET_EXTENSIONS = [
312
214
  "xml"
313
215
  ];
314
216
  /**
315
- * The pair `applyDocumentDisposition` sets, for a platform to set on the same
316
- * files. Same reasoning as the framework's: `attachment` is honoured for
317
- * navigations and ignored for subresource loads, so `<img src="/logo.svg">`
318
- * and a CSS `url()` keep working while the URL opened directly downloads;
319
- * `nosniff` stops the promotion a browser would otherwise do on its own.
217
+ * The headers `applyDocumentDisposition` sets: `attachment` is honoured for
218
+ * navigations and ignored for subresource loads, so `<img>` and CSS `url()` keep
219
+ * working while a directly opened URL downloads; `nosniff` stops browser promotion.
320
220
  */
321
221
  const DOCUMENT_ASSET_HEADERS = {
322
222
  "Content-Disposition": "attachment",
323
223
  "X-Content-Type-Options": "nosniff"
324
224
  };
325
225
  /**
326
- * Modules that cannot run off Bun but sit in the graph of any app importing
327
- * `@guren/core`, reached only through dev-time branches. Core aggregates
328
- * `@guren/server` and `@guren/orm`, where these imports actually live, so it
329
- * is the one package that sees the whole set — which is why the list lives
330
- * here rather than in each plugin, where two copies had already drifted apart.
331
- *
332
- * Bundlers follow these imports even when they are dynamic, so without stubs
333
- * the build either fails to resolve them or ships megabytes of dev tooling.
334
- *
335
- * - `sqlite` — the local sqlite ORM factory, opposite the platform's own
336
- * database branch in `config/database.ts`.
337
- * - `vite` — the dev asset server `Application` starts when serving locally.
338
- * - `mcp` — the opt-in MCP endpoint's lazy imports, which drag the CLI
339
- * generators (and Babel) plus the MCP SDK in behind them.
340
- *
341
- * SQL client libraries are deliberately *not* here: they are dev-only on
342
- * Workers, where D1 is the only database, and load-bearing on Lambda and
343
- * Vercel, which connect to Postgres. See `SQL_CLIENT_MODULES`.
344
- *
345
- * `as const` so a consumer can key an exhaustive table on the specifiers and
346
- * have a new entry here surface as a compile error there.
226
+ * Dev-only modules in the graph of any app importing `@guren/core`, listed here
227
+ * because core alone sees the whole set (two plugin copies had drifted). Bundlers
228
+ * follow even dynamic imports, so unstubbed they fail the build or ship dev tooling.
229
+ * SQL clients are deliberately elsewhere (`SQL_CLIENT_MODULES`): dev-only on
230
+ * Workers, load-bearing on Lambda/Vercel. `as const` keys consumers' exhaustive tables.
347
231
  */
348
232
  const DEV_ONLY_MODULES = [
349
233
  {
@@ -373,34 +257,18 @@ const DEV_ONLY_MODULES = [
373
257
  }
374
258
  ];
375
259
  /**
376
- * The specifier `@guren/plugin-mcp` dynamically imports to serve the App MCP
377
- * endpoint (RFC 0016 §7). Named here rather than inline in three plugins
378
- * because it is the one entry of `DEV_ONLY_MODULES` whose stubbing is
379
- * conditional, and each platform has to recognise it.
260
+ * The specifier `@guren/plugin-mcp` lazily imports for the App MCP endpoint (RFC
261
+ * 0016 §7): the one `DEV_ONLY_MODULES` entry whose stubbing is conditional.
380
262
  */
381
263
  const MCP_TRANSPORT_SPECIFIER = "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
382
264
  /** The package an app declares to opt into the App MCP endpoint. */
383
265
  const MCP_PLUGIN_PACKAGE = "@guren/plugin-mcp";
384
266
  /**
385
- * Whether the app has opted into the App MCP endpoint (RFC 0016 §7).
386
- *
387
- * Resolves the RFC's Open Question 5 — how a build learns that an app wants
388
- * the MCP transport — as **dependency sniffing**: declaring
389
- * `@guren/plugin-mcp` in `dependencies` *is* the opt-in. Nothing else is
390
- * asked of the developer, because there is nothing else to ask: an app that
391
- * installed the plugin and mounted it wants the endpoint to work, and a build
392
- * flag it must also remember to pass is a way for the endpoint to be silently
393
- * compiled shut on a platform. The build does not *enable* anything here — it
394
- * stops sabotaging what the app already configured.
395
- *
396
- * `dependencies` only, never `devDependencies`: a devDependency does not ship,
397
- * so an app that has one has no MCP endpoint at runtime to protect. Reading
398
- * both would keep the transport in the bundle of every app that merely
399
- * develops against the plugin.
400
- *
401
- * Absent, unreadable, or malformed manifest answers `false` — no opt-in
402
- * evidence is not the same as opt-in, and the false direction is the safe
403
- * one: the transport stays stubbed, which is exactly today's behaviour.
267
+ * Whether the app opted into the App MCP endpoint (RFC 0016 §7, Open Question 5):
268
+ * declaring `@guren/plugin-mcp` in `dependencies` is the opt-in, so no build flag
269
+ * can silently compile the endpoint shut. `devDependencies` do not count (they do
270
+ * not ship). An absent, unreadable, or malformed manifest answers `false`: the
271
+ * transport stays stubbed, which is the safe direction.
404
272
  */
405
273
  function appUsesMcpPlugin(root) {
406
274
  try {
@@ -411,53 +279,21 @@ function appUsesMcpPlugin(root) {
411
279
  }
412
280
  }
413
281
  /**
414
- * The dev-only modules that must stay stubbed for this app.
415
- *
416
- * The policy layer over `DEV_ONLY_MODULES`, which stays exported and
417
- * unchanged: it is the full inventory, and other consumers (the wrangler
418
- * bundle probe, the stub-filename table) read it as such. What varies per app
419
- * is only whether the *transport* entry is in force.
420
- *
421
- * `@guren/plugin-mcp` reaches the App MCP endpoint through exactly one lazy
422
- * import — `MCP_TRANSPORT_SPECIFIER` — plus static imports of the SDK's
423
- * `server/index.js` and `types.js`, which no entry here names. Stubbing the
424
- * transport therefore compiles the endpoint shut on every platform, which is
425
- * what the three deploy plugins did until RFC 0016 Phase 4a. Dropping the
426
- * entry for an app that declared the plugin is the whole of the fix.
427
- *
428
- * `@modelcontextprotocol/sdk/server/mcp.js` stays stubbed regardless, and the
429
- * distinction matters: that is the **Dev** MCP's `McpServer`, reached from
430
- * `@guren/server`'s `McpServiceProvider`, which drives the CLI's code
431
- * generators against the filesystem. It is compiled shut by the `NODE_ENV`
432
- * define anyway; the stub is the second guard, and a deployed app has no use
433
- * for it either way. Same for `@guren/cli` behind it, and for `bun:sqlite`
434
- * and `vite`, none of which the App MCP endpoint touches.
435
- *
436
- * The return type keeps each entry's narrow `kind` so that a platform can
437
- * index its `Record<kind, message>` table with `module.kind` at all. What
438
- * makes those tables exhaustive is not this function — each is keyed off
439
- * `DEV_ONLY_MODULES` directly (on Workers, that list plus
440
- * `SQL_CLIENT_MODULES`), which is what turns a new kind there into a compile
441
- * error there. Widening the return to `readonly DevOnlyModule[]` would leave
442
- * that exhaustiveness untouched and instead break every one of the lookups,
443
- * since `DevOnlyModuleKind` includes `'sql-driver'` — a kind Lambda's and
444
- * Vercel's tables deliberately omit, because those two platforms decide the
445
- * SQL clients per app rather than per platform.
282
+ * The dev-only modules that must stay stubbed for this app: `DEV_ONLY_MODULES`
283
+ * minus the transport entry when the app declared `@guren/plugin-mcp` (stubbing
284
+ * `MCP_TRANSPORT_SPECIFIER` compiled the endpoint shut everywhere before RFC 0016
285
+ * Phase 4a). `server/mcp.js` stays stubbed: that is the Dev MCP. Each entry keeps
286
+ * its narrow `kind` so platform `Record<kind, message>` tables stay indexable.
446
287
  */
447
288
  function stubbableDevOnlyModules(options) {
448
289
  if (!options.mcpPlugin) return DEV_ONLY_MODULES;
449
290
  return DEV_ONLY_MODULES.filter((module) => module.specifier !== MCP_TRANSPORT_SPECIFIER);
450
291
  }
451
292
  /**
452
- * The `@guren/orm` factory names an app's database config calls, and the
453
- * dialect each one declares.
454
- *
455
- * Taken from `@guren/core`'s export allowlist rather than from the ORM's
456
- * implementation files, and pinned there by a test: a list built from the
457
- * implementation admits names that were never exported and misses the aliases
458
- * that were. The spelling is `createMySqlDatabase`, not `createMysqlDatabase`
459
- * — a build that filters on a name nobody exports detects nothing and stubs
460
- * nothing, which is silent.
293
+ * The `@guren/orm` factory names an app's config calls, with each one's dialect.
294
+ * Taken from `@guren/core`'s export allowlist (pinned by a test), not the ORM's
295
+ * files: it is `createMySqlDatabase`, and a filter on a name nobody exports stubs
296
+ * nothing, silently.
461
297
  */
462
298
  const DATABASE_FACTORIES = {
463
299
  createPostgresDatabase: "postgres",
@@ -467,29 +303,11 @@ const DATABASE_FACTORIES = {
467
303
  createD1Database: "d1"
468
304
  };
469
305
  /**
470
- * The database client libraries `@guren/orm`'s Postgres, MySQL and Aurora
471
- * Data API factories reach for.
472
- *
473
- * They sit apart from `DEV_ONLY_MODULES` because whether they are dead weight
474
- * depends on the platform: on Workers, D1 is the only database there is, so
475
- * every one of these is unreachable; on Lambda and Vercel the app connects to
476
- * Postgres through them and stubbing them would break a working deploy.
477
- *
478
- * That makes the list itself the wrong granularity for a platform that hosts
479
- * more than one dialect. Workers stubs all of it; Lambda and Vercel stub the
480
- * entries whose `dialect` the app's config does not declare, which is what
481
- * `unusedSqlClients` decides.
482
- *
483
- * A platform where they are unreachable has to stub them rather than ignore
484
- * them. `@guren/orm` names them in *literal* dynamic imports, which a bundler
485
- * follows whether or not the branch can be taken — so a D1 app failed to
486
- * bundle on `Could not resolve "postgres"`, naming a database its author had
487
- * deliberately not chosen. Both the client and the drizzle entry point that
488
- * imports it need stubbing: aliasing only the client leaves drizzle's own
489
- * `import pgClient from "postgres"` to resolve.
490
- *
491
- * Export names are read off drizzle-orm's driver and session modules, which
492
- * is what a bundler checks a stub against.
306
+ * Client libraries the Postgres, MySQL and Aurora Data API factories reach for.
307
+ * Apart from `DEV_ONLY_MODULES` because their fate is per platform: unreachable on
308
+ * Workers (D1 only), load-bearing on Lambda/Vercel, which stub only undeclared
309
+ * dialects (`unusedSqlClients`). Stub the client *and* drizzle's entry importing it,
310
+ * or a D1 app fails on `Could not resolve "postgres"`; export names mirror drizzle-orm's.
493
311
  */
494
312
  const SQL_CLIENT_MODULES = [
495
313
  {
@@ -524,32 +342,17 @@ const SQL_CLIENT_MODULES = [
524
342
  }
525
343
  ];
526
344
  /**
527
- * Where an app declares its database, in the order it is looked for.
528
- *
529
- * The same pair `guren doctor` checks, kept as a copy for the same reason
530
- * `realpathOfNearestExisting` above is one: this module must not import
531
- * beyond node builtins, and cli cannot be imported from core. If the two ever
532
- * disagree, a build would stub clients for an app whose config the doctor
533
- * says is fine — so a change to either belongs in both.
345
+ * Where an app declares its database, in lookup order. Same pair `guren doctor`
346
+ * checks, copied because this module imports only node builtins; a change to
347
+ * either belongs in both.
534
348
  */
535
349
  const DATABASE_CONFIG_CANDIDATES = ["config/database.ts", "db/config.ts"];
536
350
  /**
537
- * Which databases an app connects to, read off its database config.
538
- *
539
- * A *union*, never a single answer: an app legitimately names two factories in
540
- * one file, picking between them at runtime — the Workers app in this
541
- * repository declares D1 for the deployed worker and sqlite for local
542
- * development, and a Lambda app can pair Postgres with sqlite the same way.
543
- * Taking the first match would stub a client the app really does reach for.
544
- *
545
- * Matching is a scan for the factory names, not a parse: every way of being
546
- * wrong about a name that *is* in the file — mentioned in a comment, imported
547
- * but never called, called in a branch this deploy will not take — errs
548
- * toward reporting a dialect the app might not use, and the caller stubs
549
- * fewer clients as a result. The opposite error is the dangerous one, so the
550
- * cheap reading is the right one. A config that reaches a factory without
551
- * naming it (a re-export, an indirection through another module) reports
552
- * nothing, and the caller stubs nothing.
351
+ * Which databases an app connects to, read off its config. A union, never a single
352
+ * answer: a config may name two factories and pick at runtime (D1 plus sqlite).
353
+ * A name scan, not a parse: every way of being wrong about a name that is in the
354
+ * file errs toward reporting an unused dialect, which only stubs fewer clients.
355
+ * A factory reached without being named reports nothing, and nothing is stubbed.
553
356
  */
554
357
  function detectDatabaseDialects(root) {
555
358
  for (const candidate of DATABASE_CONFIG_CANDIDATES) {
@@ -573,23 +376,11 @@ function detectDatabaseDialects(root) {
573
376
  /** Every dialect name `databaseDialects` accepts, for validation and messages. */
574
377
  const DATABASE_DIALECTS = [...new Set(Object.values(DATABASE_FACTORIES))];
575
378
  /**
576
- * Reject a dialect list that names nothing, or names something that is not a
577
- * dialect.
578
- *
579
- * Both are rejected rather than dropped because both mean the same thing to
580
- * the filter downstream — a dialect it never sees is a dialect whose client it
581
- * stubs. An empty list stubs *every* client, and `['postgress']` stubs the
582
- * Postgres one; either way the bundle builds clean and the deployed function
583
- * cannot reach its own database. That is the failure the caller reached for
584
- * this option to avoid, so it fails here, at build time, with the typo in the
585
- * message.
586
- *
587
- * Deliberately not a fail-open: the surrounding code stubs nothing when it
588
- * cannot *read* an app's dialects, but this input is a caller stating them.
589
- * Falling back to detection would discard the override and then stub according
590
- * to the very config the caller was overriding.
591
- *
592
- * @param label Platform name for the error message, e.g. `'Lambda build'`.
379
+ * Reject a dialect list that is empty or names a non-dialect: either stubs the
380
+ * client the app needs (`[]` stubs every one, `['postgress']` the Postgres one),
381
+ * and the bundle builds clean but cannot reach its database. Not fail-open: this
382
+ * is a caller's explicit override, and falling back to detection would stub by the
383
+ * very config being overridden.
593
384
  */
594
385
  function assertDatabaseDialects(names, label, quoted) {
595
386
  const unknown = names.filter((name) => !DATABASE_DIALECTS.includes(name));
@@ -605,22 +396,11 @@ function parseDatabaseDialects(value, label) {
605
396
  return assertDatabaseDialects(value.split(",").map((name) => name.trim()).filter((name) => name.length > 0), label, JSON.stringify(value));
606
397
  }
607
398
  /**
608
- * The database clients an app does not connect through, for a platform where
609
- * the ones it *does* connect through are load-bearing — Lambda and Vercel,
610
- * as opposed to Workers, where D1 is the only database and every client in
611
- * `SQL_CLIENT_MODULES` is unreachable regardless of what the config says.
612
- *
613
- * Fails open: when the dialects cannot be read, this warns and returns
614
- * nothing to stub. The two errors are not symmetric. Under-stubbing leaves
615
- * today's behaviour — the build fails to resolve a client the app never
616
- * installed, loudly, at build time. Over-stubbing produces a bundle that
617
- * builds clean and then cannot reach its own database, at runtime, in
618
- * production. Only the second is worth protecting against, so anything less
619
- * than positive evidence means stub nothing.
620
- *
621
- * @param dialects Overrides detection when the caller already knows, for an
622
- * app whose config the scan cannot read.
623
- * @param label Platform name for the messages, e.g. `'Lambda build'`.
399
+ * The database clients an app does not connect through, for Lambda and Vercel
400
+ * (on Workers every client is unreachable). Fails open: unreadable dialects warn
401
+ * and stub nothing, because under-stubbing fails loudly at build time while
402
+ * over-stubbing ships a bundle that cannot reach its database in production.
403
+ * @param dialects Overrides detection when the caller already knows.
624
404
  */
625
405
  function unusedSqlClients(input) {
626
406
  const { root, label } = input;
@@ -637,25 +417,17 @@ function unusedSqlClients(input) {
637
417
  }));
638
418
  }
639
419
  /**
640
- * A JavaScript string literal for `value`.
641
- *
642
- * `JSON.stringify` alone is not one: JSON and JavaScript disagree about
643
- * U+2028 and U+2029, which JSON leaves raw while JavaScript reads them as
644
- * line terminators — so a message containing either ends the statement it was
645
- * embedded in on any target below ES2019.
420
+ * A JavaScript string literal for `value`. `JSON.stringify` alone is not one: it
421
+ * leaves U+2028/U+2029 raw, which JavaScript below ES2019 reads as line terminators.
646
422
  */
647
423
  function toJsStringLiteral(value) {
648
424
  return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
649
425
  }
650
426
  /**
651
- * Source for a stub replacing one dev-only module. Shared because what it
652
- * encodes is a bundler constraint, not a platform choice: every name the
653
- * importer destructures must be present or the bundle fails with "no matching
654
- * export", and each is emitted as a throwing *function* because the stubbed
655
- * names mix constructors (`new Database()`) with plain calls
656
- * (`createServer()`) — a class invoked without `new` reports "Class
657
- * constructor cannot be invoked without 'new'" instead of the real reason.
658
- *
427
+ * Source for a stub replacing one dev-only module. Every destructured name must be
428
+ * present or the bundle fails with "no matching export", and each is a throwing
429
+ * *function* because stubbed names mix constructors and plain calls (a class
430
+ * called without `new` would hide the real reason).
659
431
  * @param message Platform-specific explanation, including the replacement API.
660
432
  */
661
433
  function renderDevOnlyStub(module, message) {
@@ -666,12 +438,10 @@ function renderDevOnlyStub(module, message) {
666
438
  return `// ${comment}\n${throwing}\n${`function unavailable() { ${error} }`}\nexport default Object.assign(unavailable${named})\n`;
667
439
  }
668
440
  /**
669
- * The MCP SDK is only ever reached through subpaths, and a bundler alias on a
670
- * package name does not cover them — which is why `DEV_ONLY_MODULES` lists
671
- * each one. A platform whose aliasing supports prefixes should also route
672
- * unlisted subpaths under this prefix to a stub, so a new subpath added
673
- * upstream cannot pull the real SDK into a deployed bundle.
441
+ * The MCP SDK is reached only through subpaths, which a package-name alias does not
442
+ * cover (hence each one in `DEV_ONLY_MODULES`). A platform whose aliasing supports
443
+ * prefixes should route unlisted subpaths under this prefix to a stub too.
674
444
  */
675
445
  const MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
676
446
  //#endregion
677
- export { DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, MCP_PLUGIN_PACKAGE, MCP_SDK_SUBPATH_PREFIX, MCP_TRANSPORT_SPECIFIER, SQL_CLIENT_MODULES, appUsesMcpPlugin, assertOutputDirOutsideRoot, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, stubbableDevOnlyModules, unusedSqlClients };
447
+ export { DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, MCP_PLUGIN_PACKAGE, MCP_SDK_SUBPATH_PREFIX, MCP_TRANSPORT_SPECIFIER, SQL_CLIENT_MODULES, appUsesMcpPlugin, assertOutputDirOutsideRoot, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, removeShadowingIndex, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, stubbableDevOnlyModules, unusedSqlClients };