@guren/core 1.13.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,48 +3,29 @@ 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
  */
14
+ /**
15
+ * The agent registry (RFC 0017 §3), at a path neither side may choose. Shared
16
+ * rather than spelled twice: `guren check` reads it as source and a deploy build
17
+ * reads it to generate the worker's Durable Object exports, so a second spelling
18
+ * is a deploy exporting no agents while the check calls them registered.
19
+ */
20
+ const AGENTS_CONFIG_FILE = "config/agents.ts";
37
21
  function resolvePathLike(value) {
38
22
  return value instanceof URL ? fileURLToPath(value) : resolve(String(value));
39
23
  }
40
24
  /**
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.
25
+ * Read the first manifest that parses, in either Vite layout (`.vite/manifest.json`,
26
+ * then flat `manifest.json`), and report its path: a caller publishing the location
27
+ * must name the file actually parsed, not the malformed one that was skipped. What a
28
+ * missing manifest means is the caller's call.
48
29
  */
49
30
  function readManifest(...paths) {
50
31
  for (const path of paths) {
@@ -60,39 +41,27 @@ function readManifest(...paths) {
60
41
  }
61
42
  }
62
43
  /**
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).
44
+ * Layouts `readManifest` accepts, `.vite/` first (Vite >= 5 writes it there; a flat
45
+ * file beside it is likely stale). Must agree with `clientManifestCandidates` in
46
+ * @guren/server's http/vite-manifest.ts, pinned by tests/http/vite-manifest.test.ts,
47
+ * or local and deployed asset versions diverge.
71
48
  */
72
49
  function manifestPaths(dir) {
73
50
  return [resolve(dir, ".vite/manifest.json"), resolve(dir, "manifest.json")];
74
51
  }
75
52
  /**
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.
53
+ * The one statement of where the client manifest lives: `<publicDir>/assets`, either
54
+ * layout. `resolveClientAssetEnv` and `clientManifestJson` both read through here.
80
55
  */
81
56
  function readClientManifest(publicDir) {
82
57
  return readManifest(...manifestPaths(resolve(publicDir, "assets")))?.manifest;
83
58
  }
84
59
  /**
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.
60
+ * Resolve symlinks in the existing parts of `path`, keeping trailing components that
61
+ * do not exist yet (`realpathSync` throws on a first build's output dir). Twin of
62
+ * `realpathNearestExisting` in @guren/cli's plugin-manifest.ts, copied because this
63
+ * module imports only node builtins. Only ENOENT walks up; any other failure
64
+ * surfaces, since both callers relate two paths and must not answer from a guess.
96
65
  */
97
66
  function realpathOfNearestExisting(path) {
98
67
  try {
@@ -105,25 +74,11 @@ function realpathOfNearestExisting(path) {
105
74
  return resolve(realpathOfNearestExisting(parent), basename(path));
106
75
  }
107
76
  /**
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'`.
77
+ * Throw unless `out` is safe to delete: neither the app root nor a directory
78
+ * containing it. Both paths are canonicalized (a lexical compare accepts an
79
+ * `outputDir` that reaches the root through links). Containment uses `relative`,
80
+ * not a prefix test (`out + sep` is `//` at the root, letting `'/'` through), and
81
+ * escape means `'..'` or a `'../'` prefix, so `..-source` inside `out` is not one.
127
82
  */
128
83
  function assertOutputDirOutsideRoot(out, root, label) {
129
84
  const outToRoot = relative(realpathOfNearestExisting(out), realpathOfNearestExisting(root));
@@ -131,13 +86,8 @@ function assertOutputDirOutsideRoot(out, root, label) {
131
86
  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
87
  }
133
88
  /**
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
- *
89
+ * Delete the output directory after checking it is safe to delete. One call on
90
+ * purpose: a plugin that carried only the delete has already shipped.
141
91
  * @param label Platform name for the error message, e.g. `'Lambda build'`.
142
92
  */
143
93
  function resetOutputDir(out, root, label) {
@@ -148,13 +98,10 @@ function resetOutputDir(out, root, label) {
148
98
  });
149
99
  }
150
100
  /**
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
- *
101
+ * POSIX relative specifier for importing `target` from a module written into
102
+ * `fromDir`. Both paths are canonicalized: the bundler resolves the emitted module
103
+ * from its real path, and a link that changes depth would leave the specifier a
104
+ * `..` short.
158
105
  * @param label Platform name for the error message, e.g. `'Lambda build'`.
159
106
  */
160
107
  function importSpecifier(fromDir, target, label) {
@@ -164,12 +111,9 @@ function importSpecifier(fromDir, target, label) {
164
111
  return specifier.startsWith(".") ? specifier : `./${specifier}`;
165
112
  }
166
113
  /**
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
- *
114
+ * Locate the built client entry and its CSS in the Vite client manifest, as the
115
+ * `/assets/`-prefixed URLs the Inertia head expects. Takes the public directory so
116
+ * a custom `publicDir` is honoured.
173
117
  * @param label Platform name for the warning message, e.g. `'Lambda build'`.
174
118
  */
175
119
  function resolveClientAssetEnv(publicDir, clientEntryKey, label) {
@@ -184,27 +128,11 @@ function resolveClientAssetEnv(publicDir, clientEntryKey, label) {
184
128
  };
185
129
  }
186
130
  /**
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.
131
+ * The client manifest as JSON for runtime injection (`GUREN_VITE_MANIFEST`): a
132
+ * bundled function has no `public/assets/manifest.json`. Separate from
133
+ * `resolveClientAssetEnv`, which answers only for the client entry. Trimmed to
134
+ * `file`/`css` per entry (all the runtime reads; chunk graph metadata dominates
135
+ * size and Workers caps bundles); a parseable non-manifest is rejected here.
208
136
  */
209
137
  function clientManifestJson(publicDir) {
210
138
  const manifest = readClientManifest(publicDir);
@@ -225,11 +153,9 @@ function clientManifestJson(publicDir) {
225
153
  return JSON.stringify(trimmed);
226
154
  }
227
155
  /**
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
- *
156
+ * Absolute path of the built SSR entry chunk, or undefined without an SSR build.
157
+ * Whether the chunk exports a renderer is the caller's check: platforms disagree
158
+ * on importing it during a build.
233
159
  * @param label Platform name for the error messages, e.g. `'Lambda build'`.
234
160
  */
235
161
  function resolveSsrEntryFile(ssrDir, ssrEntryKey, label) {
@@ -241,18 +167,11 @@ function resolveSsrEntryFile(ssrDir, ssrEntryKey, label) {
241
167
  return file;
242
168
  }
243
169
  /**
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.
170
+ * Runtime locations of a staged SSR bundle, for platforms that copy `ssrDir` under
171
+ * the function root; `prefix` is where the caller stages it. The manifest path is
172
+ * the file that parsed, not the first that exists (a malformed `.vite/` file beside
173
+ * a valid flat one). Optional only for the race where the manifest vanishes after
174
+ * `resolveSsrEntryFile`.
256
175
  */
257
176
  function ssrRuntimePaths(ssrDir, ssrFile, prefix) {
258
177
  const under = (target) => `${prefix}/${relative(ssrDir, target).split(sep).join("/")}`;
@@ -263,46 +182,36 @@ function ssrRuntimePaths(ssrDir, ssrFile, prefix) {
263
182
  };
264
183
  }
265
184
  /**
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.
185
+ * Delete the dev-mode `index.html` shell from a statically served directory: every
186
+ * deploy target answers for its static directory before the function runs, so the
187
+ * shell shadows the app's root route. Exact name only (the framework writes it).
188
+ * Separate from `stageStaticAssets` because `@guren/plugin-vercel` stages `public/`
189
+ * itself and needs this rule alone.
190
+ */
191
+ function removeShadowingIndex(assetsOut) {
192
+ const shadowingIndex = resolve(assetsOut, "index.html");
193
+ if (existsSync(shadowingIndex)) rmSync(shadowingIndex);
194
+ }
195
+ /**
196
+ * Copy `public/` into a platform's static staging directory. Built assets
197
+ * self-reference `/public/assets/` while HTML uses `/assets/`, so on a host without
198
+ * rewrites the assets directory must appear under both prefixes. Also applies
199
+ * `removeShadowingIndex`.
274
200
  */
275
201
  function stageStaticAssets(publicDir, assetsOut) {
276
202
  mkdirSync(assetsOut, { recursive: true });
277
203
  if (!existsSync(publicDir)) return;
278
204
  cpSync(publicDir, assetsOut, { recursive: true });
279
- const shadowingIndex = resolve(assetsOut, "index.html");
280
- if (existsSync(shadowingIndex)) rmSync(shadowingIndex);
205
+ removeShadowingIndex(assetsOut);
281
206
  const clientAssetsDir = resolve(publicDir, "assets");
282
207
  if (existsSync(clientAssetsDir)) cpSync(clientAssetsDir, resolve(assetsOut, "public/assets"), { recursive: true });
283
208
  }
284
209
  /**
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.
210
+ * Extensions a browser renders as a document, for platforms serving `public/`
211
+ * before the app runs: exactly what `@guren/server`'s `rendersAsDocument` matches
212
+ * over Hono's mime table (`tests/http/static-documents.test.ts` fails on drift).
213
+ * Like the framework it misses `.xsl` (Hono names no extension) and extension
214
+ * case, which each plugin closes as its own matcher allows.
306
215
  */
307
216
  const DOCUMENT_ASSET_EXTENSIONS = [
308
217
  "htm",
@@ -312,38 +221,20 @@ const DOCUMENT_ASSET_EXTENSIONS = [
312
221
  "xml"
313
222
  ];
314
223
  /**
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.
224
+ * The headers `applyDocumentDisposition` sets: `attachment` is honoured for
225
+ * navigations and ignored for subresource loads, so `<img>` and CSS `url()` keep
226
+ * working while a directly opened URL downloads; `nosniff` stops browser promotion.
320
227
  */
321
228
  const DOCUMENT_ASSET_HEADERS = {
322
229
  "Content-Disposition": "attachment",
323
230
  "X-Content-Type-Options": "nosniff"
324
231
  };
325
232
  /**
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.
233
+ * Dev-only modules in the graph of any app importing `@guren/core`, listed here
234
+ * because core alone sees the whole set (two plugin copies had drifted). Bundlers
235
+ * follow even dynamic imports, so unstubbed they fail the build or ship dev tooling.
236
+ * SQL clients are deliberately elsewhere (`SQL_CLIENT_MODULES`): dev-only on
237
+ * Workers, load-bearing on Lambda/Vercel. `as const` keys consumers' exhaustive tables.
347
238
  */
348
239
  const DEV_ONLY_MODULES = [
349
240
  {
@@ -373,34 +264,18 @@ const DEV_ONLY_MODULES = [
373
264
  }
374
265
  ];
375
266
  /**
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.
267
+ * The specifier `@guren/plugin-mcp` lazily imports for the App MCP endpoint (RFC
268
+ * 0016 §7): the one `DEV_ONLY_MODULES` entry whose stubbing is conditional.
380
269
  */
381
270
  const MCP_TRANSPORT_SPECIFIER = "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
382
271
  /** The package an app declares to opt into the App MCP endpoint. */
383
272
  const MCP_PLUGIN_PACKAGE = "@guren/plugin-mcp";
384
273
  /**
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.
274
+ * Whether the app opted into the App MCP endpoint (RFC 0016 §7, Open Question 5):
275
+ * declaring `@guren/plugin-mcp` in `dependencies` is the opt-in, so no build flag
276
+ * can silently compile the endpoint shut. `devDependencies` do not count (they do
277
+ * not ship). An absent, unreadable, or malformed manifest answers `false`: the
278
+ * transport stays stubbed, which is the safe direction.
404
279
  */
405
280
  function appUsesMcpPlugin(root) {
406
281
  try {
@@ -411,53 +286,21 @@ function appUsesMcpPlugin(root) {
411
286
  }
412
287
  }
413
288
  /**
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.
289
+ * The dev-only modules that must stay stubbed for this app: `DEV_ONLY_MODULES`
290
+ * minus the transport entry when the app declared `@guren/plugin-mcp` (stubbing
291
+ * `MCP_TRANSPORT_SPECIFIER` compiled the endpoint shut everywhere before RFC 0016
292
+ * Phase 4a). `server/mcp.js` stays stubbed: that is the Dev MCP. Each entry keeps
293
+ * its narrow `kind` so platform `Record<kind, message>` tables stay indexable.
446
294
  */
447
295
  function stubbableDevOnlyModules(options) {
448
296
  if (!options.mcpPlugin) return DEV_ONLY_MODULES;
449
297
  return DEV_ONLY_MODULES.filter((module) => module.specifier !== MCP_TRANSPORT_SPECIFIER);
450
298
  }
451
299
  /**
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.
300
+ * The `@guren/orm` factory names an app's config calls, with each one's dialect.
301
+ * Taken from `@guren/core`'s export allowlist (pinned by a test), not the ORM's
302
+ * files: it is `createMySqlDatabase`, and a filter on a name nobody exports stubs
303
+ * nothing, silently.
461
304
  */
462
305
  const DATABASE_FACTORIES = {
463
306
  createPostgresDatabase: "postgres",
@@ -467,29 +310,11 @@ const DATABASE_FACTORIES = {
467
310
  createD1Database: "d1"
468
311
  };
469
312
  /**
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.
313
+ * Client libraries the Postgres, MySQL and Aurora Data API factories reach for.
314
+ * Apart from `DEV_ONLY_MODULES` because their fate is per platform: unreachable on
315
+ * Workers (D1 only), load-bearing on Lambda/Vercel, which stub only undeclared
316
+ * dialects (`unusedSqlClients`). Stub the client *and* drizzle's entry importing it,
317
+ * or a D1 app fails on `Could not resolve "postgres"`; export names mirror drizzle-orm's.
493
318
  */
494
319
  const SQL_CLIENT_MODULES = [
495
320
  {
@@ -524,32 +349,17 @@ const SQL_CLIENT_MODULES = [
524
349
  }
525
350
  ];
526
351
  /**
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.
352
+ * Where an app declares its database, in lookup order. Same pair `guren doctor`
353
+ * checks, copied because this module imports only node builtins; a change to
354
+ * either belongs in both.
534
355
  */
535
356
  const DATABASE_CONFIG_CANDIDATES = ["config/database.ts", "db/config.ts"];
536
357
  /**
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.
358
+ * Which databases an app connects to, read off its config. A union, never a single
359
+ * answer: a config may name two factories and pick at runtime (D1 plus sqlite).
360
+ * A name scan, not a parse: every way of being wrong about a name that is in the
361
+ * file errs toward reporting an unused dialect, which only stubs fewer clients.
362
+ * A factory reached without being named reports nothing, and nothing is stubbed.
553
363
  */
554
364
  function detectDatabaseDialects(root) {
555
365
  for (const candidate of DATABASE_CONFIG_CANDIDATES) {
@@ -573,23 +383,11 @@ function detectDatabaseDialects(root) {
573
383
  /** Every dialect name `databaseDialects` accepts, for validation and messages. */
574
384
  const DATABASE_DIALECTS = [...new Set(Object.values(DATABASE_FACTORIES))];
575
385
  /**
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'`.
386
+ * Reject a dialect list that is empty or names a non-dialect: either stubs the
387
+ * client the app needs (`[]` stubs every one, `['postgress']` the Postgres one),
388
+ * and the bundle builds clean but cannot reach its database. Not fail-open: this
389
+ * is a caller's explicit override, and falling back to detection would stub by the
390
+ * very config being overridden.
593
391
  */
594
392
  function assertDatabaseDialects(names, label, quoted) {
595
393
  const unknown = names.filter((name) => !DATABASE_DIALECTS.includes(name));
@@ -605,22 +403,11 @@ function parseDatabaseDialects(value, label) {
605
403
  return assertDatabaseDialects(value.split(",").map((name) => name.trim()).filter((name) => name.length > 0), label, JSON.stringify(value));
606
404
  }
607
405
  /**
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'`.
406
+ * The database clients an app does not connect through, for Lambda and Vercel
407
+ * (on Workers every client is unreachable). Fails open: unreadable dialects warn
408
+ * and stub nothing, because under-stubbing fails loudly at build time while
409
+ * over-stubbing ships a bundle that cannot reach its database in production.
410
+ * @param dialects Overrides detection when the caller already knows.
624
411
  */
625
412
  function unusedSqlClients(input) {
626
413
  const { root, label } = input;
@@ -637,25 +424,17 @@ function unusedSqlClients(input) {
637
424
  }));
638
425
  }
639
426
  /**
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.
427
+ * A JavaScript string literal for `value`. `JSON.stringify` alone is not one: it
428
+ * leaves U+2028/U+2029 raw, which JavaScript below ES2019 reads as line terminators.
646
429
  */
647
430
  function toJsStringLiteral(value) {
648
431
  return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
649
432
  }
650
433
  /**
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
- *
434
+ * Source for a stub replacing one dev-only module. Every destructured name must be
435
+ * present or the bundle fails with "no matching export", and each is a throwing
436
+ * *function* because stubbed names mix constructors and plain calls (a class
437
+ * called without `new` would hide the real reason).
659
438
  * @param message Platform-specific explanation, including the replacement API.
660
439
  */
661
440
  function renderDevOnlyStub(module, message) {
@@ -666,12 +445,10 @@ function renderDevOnlyStub(module, message) {
666
445
  return `// ${comment}\n${throwing}\n${`function unavailable() { ${error} }`}\nexport default Object.assign(unavailable${named})\n`;
667
446
  }
668
447
  /**
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.
448
+ * The MCP SDK is reached only through subpaths, which a package-name alias does not
449
+ * cover (hence each one in `DEV_ONLY_MODULES`). A platform whose aliasing supports
450
+ * prefixes should route unlisted subpaths under this prefix to a stub too.
674
451
  */
675
452
  const MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
676
453
  //#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 };
454
+ export { AGENTS_CONFIG_FILE, 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 };