@guren/plugin-cloudflare 0.4.0 → 0.6.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.
@@ -0,0 +1,867 @@
1
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { join, relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, MCP_PLUGIN_PACKAGE, MCP_TRANSPORT_SPECIFIER, SQL_CLIENT_MODULES, appUsesMcpPlugin, assertOutputDirOutsideRoot, clientManifestJson, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, stageStaticAssets, stubbableDevOnlyModules } from "@guren/core/internal/deploy-build";
5
+ //#region src/templates.ts
6
+ /**
7
+ * The OAuth consent flow this plugin scaffolds, shipped as **real source
8
+ * files** under `templates/mcp-oauth/` rather than string literals in
9
+ * `build.ts`.
10
+ *
11
+ * The layout mirrors `@guren/cli`'s `templates/scaffold/`, and the invariant
12
+ * is the same one: a template's path relative to `templates/mcp-oauth/` is
13
+ * exactly the path it is written to in the app, so the relative import from
14
+ * `routes/mcp-oauth.ts` into `app/Http/Controllers/` resolves in place — in
15
+ * the template tree *and* in the scaffolded app.
16
+ *
17
+ * They are real sources for the reason the CLI's are: a template literal is
18
+ * not TypeScript to any tool, so nothing typechecks it, nothing parses it, and
19
+ * an editor shows it as a string. These files are inside the root `tsconfig`
20
+ * program (`packages/**` less the explicitly excluded trees), so
21
+ * `bun run typecheck` compiles them as app-shaped code, and the
22
+ * `mcp-oauth templates` block in `src/mcp-oauth.test.ts` gates the rest.
23
+ *
24
+ * `templates/` is listed in this package's `files`, so it is published. It is
25
+ * outside `dist/`, which is why the URL below climbs one level — the same
26
+ * climb `@guren/cli`'s loader makes, and the reason both work from `dist/` and
27
+ * from `src/` alike.
28
+ */
29
+ const templateDir = fileURLToPath(new URL("../templates/mcp-oauth", import.meta.url));
30
+ /** The routes template, named once — the scaffold reports on it specifically. */
31
+ const MCP_OAUTH_ROUTES_FILE = "routes/mcp-oauth.ts";
32
+ /**
33
+ * Every file the consent-flow scaffold writes, in the order it writes them.
34
+ *
35
+ * A list rather than a directory walk: the scaffold's contract is "these
36
+ * files, at these paths", and a walk would silently start writing anything
37
+ * that landed in the template tree — a stray `.d.ts` from a mis-scoped
38
+ * declaration emit, for instance.
39
+ */
40
+ const MCP_OAUTH_TEMPLATE_FILES = [
41
+ "app/View/McpOAuthConsentPage.tsx",
42
+ "app/View/McpOAuthErrorPage.tsx",
43
+ "app/Http/Controllers/McpOAuthController.ts",
44
+ MCP_OAUTH_ROUTES_FILE
45
+ ];
46
+ /**
47
+ * The registrar the routes template exports. Named here because two places
48
+ * spell it — the template, and the wiring instruction the scaffold prints —
49
+ * and a rename that updated only one would print an import of a function that
50
+ * does not exist. The `mcp-oauth templates` block in `src/mcp-oauth.test.ts`
51
+ * pins the pair.
52
+ */
53
+ const MCP_OAUTH_REGISTRAR = "registerMcpOAuthRoutes";
54
+ /** Read one shipped template, `path` in POSIX form and relative to the tree. */
55
+ function loadMcpOAuthTemplate(path) {
56
+ return readFileSync(join(templateDir, ...path.split("/")), "utf8");
57
+ }
58
+ //#endregion
59
+ //#region src/build.ts
60
+ /**
61
+ * Assemble a deployable Cloudflare Workers directory (`.cloudflare/`) from a
62
+ * built Guren app: a generated worker entry that statically wires the SSR
63
+ * bundle, static assets for Workers Static Assets, and a one-time
64
+ * `wrangler.jsonc` scaffold. Deploy with `wrangler deploy`.
65
+ */
66
+ async function buildCloudflareOutput(options = {}) {
67
+ const root = resolvePathLike(options.rootDir ?? process.cwd());
68
+ const out = resolvePathLike(options.outputDir ?? resolve(root, ".cloudflare"));
69
+ const appEntry = resolvePathLike(options.appEntry ?? resolve(root, "src/app.ts"));
70
+ const publicDir = resolvePathLike(options.publicDir ?? resolve(root, "public"));
71
+ const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
72
+ const clientEntryKey = options.clientEntryKey ?? "resources/js/app.tsx";
73
+ const ssrEntryKey = options.ssrEntryKey ?? "resources/js/ssr.tsx";
74
+ assertOutputDirOutsideRoot(out, root, "Cloudflare build");
75
+ assertWranglerJsoncIsAuthoritative(root);
76
+ const packageJson = readPackageJson(root);
77
+ const mcpPlugin = appUsesMcpPlugin(root);
78
+ const mcpOAuth = options.mcpOAuth === true;
79
+ const mcpPath = options.mcpPath ?? DEFAULT_MCP_PATH;
80
+ assertMcpTransportNotAliased(root, mcpPlugin);
81
+ if (mcpOAuth) {
82
+ assertMcpOAuthUsable(root, mcpPlugin);
83
+ assertOAuthKvBound(root);
84
+ }
85
+ if (!options.skipAppBuild) runAppBuild(root, packageJson.scripts ?? {});
86
+ if (!existsSync(appEntry)) throw new Error(`Cloudflare build: app entry not found at ${appEntry}. Pass "appEntry" if your Application lives elsewhere.`);
87
+ const ssrImport = await resolveSsrImport(ssrDir, ssrEntryKey);
88
+ const assetEnv = resolveClientAssetEnv(publicDir, clientEntryKey, "Cloudflare build");
89
+ const viteManifest = clientManifestJson(publicDir);
90
+ resetOutputDir(out, root, "Cloudflare build");
91
+ stageStaticAssets(publicDir, resolve(out, "assets"));
92
+ writeAssetHeaders(resolve(out, "assets"));
93
+ const workerEnv = renderWorkerEnvModule({
94
+ assetEnv,
95
+ viteManifest
96
+ });
97
+ if (workerEnv) writeFileSync(resolve(out, "worker-env.js"), workerEnv);
98
+ writeFileSync(resolve(out, "worker.js"), renderWorkerModule({
99
+ out,
100
+ appEntry,
101
+ ssrImport,
102
+ hasEnvModule: workerEnv !== void 0,
103
+ mcpOAuth,
104
+ mcpPath
105
+ }));
106
+ flattenD1Migrations(resolve(root, "db/migrations"), resolve(out, "d1-migrations"));
107
+ writeDevOnlyStubs(out);
108
+ if (mcpOAuth) scaffoldConsentFlow(root);
109
+ scaffoldWranglerConfig(root, out, packageJson.name, mcpPlugin, mcpOAuth);
110
+ }
111
+ const MCP_UNAVAILABLE = "The MCP endpoint is unavailable on Cloudflare Workers — it generates files on disk.";
112
+ /** `mcpPlugin()`'s own default mount path — see `BuildCloudflareOutputOptions.mcpPath`. */
113
+ const DEFAULT_MCP_PATH = "/mcp";
114
+ /** The OAuth provider package the generated worker imports, installed by the app. */
115
+ const OAUTH_PROVIDER_PACKAGE = "@cloudflare/workers-oauth-provider";
116
+ /** The subpath of `@guren/plugin-mcp` carrying the principal seam. */
117
+ const MCP_OAUTH_SEAM_SPECIFIER = "@guren/plugin-mcp/oauth";
118
+ /** The KV binding name `OAuthProvider` requires, fixed by the provider. */
119
+ const OAUTH_KV_BINDING = "OAUTH_KV";
120
+ /** The three endpoints the provider owns or hands back, in one place. */
121
+ const OAUTH_ENDPOINTS = {
122
+ authorize: "/oauth/authorize",
123
+ token: "/oauth/token",
124
+ register: "/oauth/register"
125
+ };
126
+ /**
127
+ * Refuse `--mcp-oauth` on an app that cannot serve it, before anything is
128
+ * built or written.
129
+ *
130
+ * Two prerequisites, and both are the app's own declarations rather than
131
+ * anything this build can supply:
132
+ *
133
+ * - **`@guren/plugin-mcp`.** The flag's whole effect is to front the App MCP
134
+ * endpoint with an OAuth provider. An app that does not depend on the plugin
135
+ * has no such endpoint, so the wrapping would protect a route that answers
136
+ * 404 — and the generated worker would import a seam module that is not
137
+ * installed. Read through the same `appUsesMcpPlugin` rule the alias set
138
+ * uses, threaded in rather than re-derived.
139
+ * - **`@cloudflare/workers-oauth-provider`.** The generated worker imports it,
140
+ * and wrangler resolves that import from the *app's* `node_modules`. It is
141
+ * deliberately not a dependency of this plugin: it would then be installed
142
+ * by every app that deploys to Workers, the large majority of which will
143
+ * never front an OAuth provider, and the opt-in cost of an opt-in feature
144
+ * belongs to the people opting in.
145
+ *
146
+ * `dependencies` and not `devDependencies` for the provider, for the reason
147
+ * `appUsesMcpPlugin` gives: `wrangler deploy` resolves the import from
148
+ * whatever the deploy environment installed, and a production install has no
149
+ * devDependencies to resolve it from.
150
+ */
151
+ function assertMcpOAuthUsable(root, mcpPlugin) {
152
+ if (!mcpPlugin) throw new Error(`Cloudflare build: --mcp-oauth fronts the App MCP endpoint with an OAuth provider, but this app does not depend on ${MCP_PLUGIN_PACKAGE}, so it serves no such endpoint. Install and mount the plugin first:\n bun add ${MCP_PLUGIN_PACKAGE}\n # then add mcpPlugin() to createApp({ providers })
153
+ Or drop --mcp-oauth to build the worker without the OAuth wrapping.`);
154
+ if (!appDependsOn(root, OAUTH_PROVIDER_PACKAGE)) throw new Error(`Cloudflare build: --mcp-oauth generates a worker that imports ${OAUTH_PROVIDER_PACKAGE}, which this app does not depend on. Install it:\n bun add ${OAUTH_PROVIDER_PACKAGE}\nIt is not a dependency of @guren/plugin-cloudflare on purpose — only apps fronting the MCP endpoint with OAuth need it. A devDependency will not do: wrangler resolves the import at deploy time, from a production install.`);
155
+ }
156
+ /**
157
+ * `OAuthProvider` stores clients, grants and tokens in a KV namespace bound as
158
+ * `OAUTH_KV`, and there is no default: without the binding the worker deploys
159
+ * and then fails on its first authorize request.
160
+ *
161
+ * Build-owned **only while the flag is on**, which is why the caller and not
162
+ * this function decides whether to ask. A fresh scaffold gets the entry
163
+ * written for it; an app whose `wrangler.jsonc` already exists — the file this
164
+ * build never overwrites — is failed rather than warned, because unlike the
165
+ * warnings in {@link warnMissingBuildOwnedKeys} this one has a deploy-time
166
+ * consequence the developer cannot discover from the build output, and the fix
167
+ * is a paste of JSON this function can spell exactly.
168
+ *
169
+ * A config that does not parse is left alone, exactly as
170
+ * {@link assertMcpTransportNotAliased} leaves it: failing a build over a file
171
+ * this cannot read would be worse than the defect, and
172
+ * {@link warnMissingBuildOwnedKeys} already reports the unreadable file.
173
+ */
174
+ function assertOAuthKvBound(root) {
175
+ const configPath = resolve(root, "wrangler.jsonc");
176
+ if (!existsSync(configPath)) return;
177
+ let config;
178
+ try {
179
+ config = parseJsonc(readFileSync(configPath, "utf8"));
180
+ } catch {
181
+ return;
182
+ }
183
+ const bound = oauthKvBinding(config);
184
+ if (bound) {
185
+ if (bound.id === oauthKvNamespace().id) console.warn(`Cloudflare build: ${configPath} still has the scaffolded placeholder id for the ${OAUTH_KV_BINDING} binding, so a real deploy will be rejected. Create the namespace and paste its id in:\n wrangler kv namespace create ${OAUTH_KV_BINDING}`);
186
+ return;
187
+ }
188
+ throw new Error(`Cloudflare build: --mcp-oauth needs a KV namespace bound as ${OAUTH_KV_BINDING} — the OAuth provider stores its clients, grants and tokens there — and ${configPath} has none. Create one and add this entry, alongside whatever the file already has:\n "kv_namespaces": [\n ${JSON.stringify(oauthKvNamespace(), null, 2).split("\n").join("\n ")}\n ]\nGet the id from: wrangler kv namespace create ${OAUTH_KV_BINDING}`);
189
+ }
190
+ /**
191
+ * The KV namespace a parsed config binds under the provider's name, or
192
+ * `undefined`.
193
+ *
194
+ * Returns the entry rather than a boolean because two callers ask two
195
+ * questions of it — "is it bound at all" and "is its id still the
196
+ * placeholder" — and a predicate would have sent the second one back to
197
+ * re-walk the array with its own idea of what counts as a match.
198
+ */
199
+ function oauthKvBinding(config) {
200
+ const namespaces = config.kv_namespaces;
201
+ if (!Array.isArray(namespaces)) return;
202
+ return namespaces.find((entry) => typeof entry === "object" && entry !== null && entry.binding === OAUTH_KV_BINDING);
203
+ }
204
+ /** The binding entry, spelled once — the scaffold writes it, the guard quotes it. */
205
+ function oauthKvNamespace() {
206
+ return {
207
+ binding: OAUTH_KV_BINDING,
208
+ id: `TODO: wrangler kv namespace create ${OAUTH_KV_BINDING}`
209
+ };
210
+ }
211
+ /**
212
+ * Whether the app declares `name` under `dependencies`.
213
+ *
214
+ * The same question and the same answer-shape as `appUsesMcpPlugin` in
215
+ * `@guren/core/internal/deploy-build`, for a package that rule does not cover:
216
+ * absent, unreadable or malformed manifest answers `false`, because no
217
+ * evidence of a dependency is not evidence of one.
218
+ */
219
+ function appDependsOn(root, name) {
220
+ try {
221
+ const dependencies = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")).dependencies;
222
+ return typeof dependencies === "object" && dependencies !== null && name in dependencies;
223
+ } catch {
224
+ return false;
225
+ }
226
+ }
227
+ /**
228
+ * Both lists: on Workers the SQL clients are as unreachable as the dev-only
229
+ * modules, because D1 is the only database the platform has.
230
+ */
231
+ const STUBBED_MODULES = [...DEV_ONLY_MODULES, ...SQL_CLIENT_MODULES];
232
+ /**
233
+ * Why the stubbed modules cannot run here, worded for this platform: each
234
+ * names the Workers-appropriate replacement.
235
+ */
236
+ const UNAVAILABLE_ON_WORKERS = {
237
+ sqlite: "bun:sqlite is unavailable on Cloudflare Workers — use createD1Database().",
238
+ vite: "The Vite dev server is unavailable on Cloudflare Workers — assets are served by Workers Static Assets.",
239
+ mcp: MCP_UNAVAILABLE,
240
+ "sql-driver": "This database client is unavailable on Cloudflare Workers — use createD1Database(). It is stubbed because @guren/orm names it in a dynamic import that bundlers follow even when the branch cannot be taken."
241
+ };
242
+ /**
243
+ * Wrangler resolves an `alias` to a path on disk, so unlike a bundler plugin
244
+ * each stub needs a file of its own. The names are deliberately hand-written
245
+ * rather than derived: they are baked into every app's committed
246
+ * `wrangler.jsonc`, which the scaffold never overwrites, so deriving them
247
+ * would rename files out from under existing apps for no benefit.
248
+ *
249
+ * Keyed on `DevOnlySpecifier`, so adding an entry to `DEV_ONLY_MODULES` is a
250
+ * compile error here until it gets a filename — the drift a derived name would
251
+ * have prevented, caught by the type system instead.
252
+ */
253
+ const STUB_FILES = {
254
+ "bun:sqlite": "stub-bun-sqlite.js",
255
+ vite: "stub-vite.js",
256
+ "@guren/cli": "stub-guren-cli.js",
257
+ "@modelcontextprotocol/sdk/server/mcp.js": "stub-mcp-server.js",
258
+ "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js": "stub-mcp-transport.js",
259
+ postgres: "stub-postgres.js",
260
+ mysql2: "stub-mysql2.js",
261
+ "mysql2/promise": "stub-mysql2-promise.js",
262
+ "@aws-sdk/client-rds-data": "stub-rds-data.js"
263
+ };
264
+ function writeDevOnlyStubs(out) {
265
+ for (const module of STUBBED_MODULES) writeFileSync(resolve(out, STUB_FILES[module.specifier]), renderDevOnlyStub(module, UNAVAILABLE_ON_WORKERS[module.kind]));
266
+ }
267
+ /**
268
+ * A package-name alias does not cover subpaths, so every stubbed specifier —
269
+ * including each MCP SDK subpath — needs its own entry. Unlike the Lambda
270
+ * plugin's bundler hook, wrangler cannot match a prefix, so an SDK subpath
271
+ * added upstream needs a new `DEV_ONLY_MODULES` entry to stay stubbed here.
272
+ *
273
+ * `mcpPlugin` drops the App MCP transport's entry (RFC 0016 §7): an app that
274
+ * declares `@guren/plugin-mcp` serves the endpoint from the worker, and the
275
+ * adapter is workerd-compatible by construction — the alias was the only
276
+ * thing killing it. The Dev MCP's `McpServer` keeps its alias either way.
277
+ *
278
+ * The *files* are written unconditionally by `writeDevOnlyStubs`; only the
279
+ * alias set varies. A stub file costs nothing, and an app whose committed
280
+ * `wrangler.jsonc` still points at one must keep finding it.
281
+ */
282
+ function devOnlyAliases(outRelative, mcpPlugin) {
283
+ const stubbed = [...stubbableDevOnlyModules({ mcpPlugin }), ...SQL_CLIENT_MODULES];
284
+ return Object.fromEntries(stubbed.map((module) => [module.specifier, `./${outRelative}/${STUB_FILES[module.specifier]}`]));
285
+ }
286
+ /**
287
+ * Fail rather than deploy an app whose committed `wrangler.jsonc` still points
288
+ * the App MCP transport at a stub *this build generated*, while its manifest
289
+ * declares `@guren/plugin-mcp`.
290
+ *
291
+ * The scaffold writes `wrangler.jsonc` once and never overwrites it, so an
292
+ * app that adds the plugin later keeps an alias nothing in the build controls
293
+ * — and the endpoint stays compiled shut with every gate green, the failure
294
+ * appearing only as `tools/list` returning nothing against a deployed worker.
295
+ * A warning would be the wrong instrument: this is one line to delete, in a
296
+ * file the developer owns, and the build can name it exactly.
297
+ *
298
+ * The *value* is what decides, not the key. An alias on this specifier is only
299
+ * build residue when it names the stub file this build writes; pointing it at
300
+ * a shim of the developer's own is a deliberate override — an alternative
301
+ * transport, an instrumented wrapper — and none of this build's business.
302
+ * Failing on the key alone would refuse a config that has nothing wrong with
303
+ * it, while asserting in the message that a stub is there when it is not.
304
+ *
305
+ * The test is on the last path segment, not on the whole path: the output
306
+ * directory the alias points into is an option, so the same residue reads as
307
+ * `./.cloudflare/…` in one app and `./dist/cf/…` in the next. The filename
308
+ * comes from `STUB_FILES` rather than a re-spelled literal — it has exactly
309
+ * one definition, and a rename there must not leave a second spelling behind
310
+ * that silently stops matching. Both separators are split on: the value is a
311
+ * specifier wrangler resolves, so it is written with forward slashes, but a
312
+ * config hand-edited on Windows need not be. A developer shim that happens to
313
+ * be named `stub-mcp-transport.js` would be misread, which is the one false
314
+ * positive left and is a name this build generates.
315
+ *
316
+ * `mcpPlugin` arrives as an argument rather than being read here, so this and
317
+ * the alias set the scaffold writes cannot end up disagreeing about the same
318
+ * manifest.
319
+ *
320
+ * Read through `parseJsonc` rather than as text, for the same reason
321
+ * `warnMissingBuildOwnedKeys` does: a config carries comments, and a comment
322
+ * mentioning the specifier — including the one the failure message itself
323
+ * suggests writing — must not fail the build. A file that does not parse is
324
+ * left to that function's warning; failing a deploy on a file this build
325
+ * could not read would be worse than the defect.
326
+ */
327
+ function assertMcpTransportNotAliased(root, mcpPlugin) {
328
+ const configPath = resolve(root, "wrangler.jsonc");
329
+ if (!mcpPlugin || !existsSync(configPath)) return;
330
+ let config;
331
+ try {
332
+ config = parseJsonc(readFileSync(configPath, "utf8"));
333
+ } catch {
334
+ return;
335
+ }
336
+ const alias = config.alias;
337
+ if (typeof alias !== "object" || alias === null) return;
338
+ const target = alias[MCP_TRANSPORT_SPECIFIER];
339
+ if (typeof target !== "string" || target.split(/[\\/]/).pop() !== STUB_FILES[MCP_TRANSPORT_SPECIFIER]) return;
340
+ throw new Error(`Cloudflare build: ${configPath} aliases the App MCP transport to a stub, but this app depends on ${MCP_PLUGIN_PACKAGE} — the endpoint would deploy compiled shut. Delete this one line from "alias":\n ${JSON.stringify(MCP_TRANSPORT_SPECIFIER)}: ${JSON.stringify(target)}\nLeave every other alias entry in place; ${JSON.stringify("@modelcontextprotocol/sdk/server/mcp.js")} in particular must stay stubbed — that is the dev-only MCP server, which generates files on disk.`);
341
+ }
342
+ /**
343
+ * Wrangler's `migrations_dir` only discovers flat `*.sql` files, but
344
+ * drizzle-kit (1.x) emits one `<timestamp>_<name>/migration.sql` folder per
345
+ * migration. Flatten each folder into `<folder-name>.sql` (plain `*.sql`
346
+ * files pass through unchanged, `meta/` bookkeeping is skipped) so
347
+ * `wrangler d1 migrations apply` sees them in filename order. Regenerated on
348
+ * every build — run `cloudflare:build` after adding a migration.
349
+ */
350
+ function flattenD1Migrations(migrationsDir, outDir) {
351
+ if (!existsSync(migrationsDir)) return;
352
+ const entries = readdirSync(migrationsDir, { withFileTypes: true });
353
+ const copies = [];
354
+ for (const entry of entries) {
355
+ if (entry.isFile() && entry.name.endsWith(".sql")) {
356
+ copies.push({
357
+ from: resolve(migrationsDir, entry.name),
358
+ to: entry.name
359
+ });
360
+ continue;
361
+ }
362
+ if (entry.isDirectory() && entry.name !== "meta") {
363
+ const nested = resolve(migrationsDir, entry.name, "migration.sql");
364
+ if (existsSync(nested)) copies.push({
365
+ from: nested,
366
+ to: `${entry.name}.sql`
367
+ });
368
+ }
369
+ }
370
+ const seen = /* @__PURE__ */ new Map();
371
+ for (const copy of copies) {
372
+ const clash = seen.get(copy.to);
373
+ if (clash) throw new Error(`Cloudflare build: migrations "${clash}" and "${copy.from}" both flatten to "${copy.to}". Rename one so wrangler sees a stable order.`);
374
+ seen.set(copy.to, copy.from);
375
+ }
376
+ if (existsSync(outDir)) rmSync(outDir, {
377
+ recursive: true,
378
+ force: true
379
+ });
380
+ if (copies.length === 0) return;
381
+ mkdirSync(outDir, { recursive: true });
382
+ for (const copy of copies) cpSync(copy.from, resolve(outDir, copy.to));
383
+ }
384
+ /**
385
+ * Neutralize the document types staged under `assets/` with a `_headers`
386
+ * file, the platform's own mechanism for the job.
387
+ *
388
+ * Workers Static Assets answer a request for a staged file *before* the worker
389
+ * runs, so `guardStaticDocument` — which the framework applies on every mount
390
+ * that reaches `public/` — never sees one here. Without this the same app
391
+ * downloads an SVG locally and renders it inline, script and all, on its own
392
+ * origin in production.
393
+ *
394
+ * That `_headers` does not apply to worker-generated responses is what makes
395
+ * it the right mechanism rather than a limitation of it: those responses
396
+ * already go through the framework guard, and a rule reaching them would put
397
+ * `attachment` on a dynamic /sitemap.xml.
398
+ *
399
+ * One splat per pattern, and the extension is the only literal part: /*.svg
400
+ * compiles to an anchored regular expression whose splat is greedy across
401
+ * slashes, so it matches at any depth, while a second splat in one rule is a
402
+ * parse error the platform reports by *dropping the rule*.
403
+ */
404
+ function renderAssetHeaders(assetsOut) {
405
+ const headerLines = Object.entries(DOCUMENT_ASSET_HEADERS).map(([name, value]) => ` ${name}: ${value}`);
406
+ return [
407
+ "# Generated by `guren cloudflare:build`. Do not edit — regenerate instead.",
408
+ ...[...DOCUMENT_ASSET_EXTENSIONS.map((extension) => `/*.${extension}`), ...oddlyCasedDocumentPaths(assetsOut)].flatMap((pattern) => [
409
+ "",
410
+ pattern,
411
+ ...headerLines
412
+ ]),
413
+ ""
414
+ ].join("\n");
415
+ }
416
+ /**
417
+ * Staged document files whose extension is not already lowercase, as exact
418
+ * patterns.
419
+ *
420
+ * The one hole the `/*.<ext>` globs cannot reach. `getMimeType` lowercases
421
+ * before its lookup, so the framework serves `logo.SVG` as an attachment,
422
+ * and Cloudflare compiles a `_headers` pattern to an anchored, case-sensitive
423
+ * regular expression with no flag to say otherwise — measured against the
424
+ * asset worker, which serves that file as `image/svg+xml` with the glob in
425
+ * place. Enumerating the case variants is not an option either: one splat per
426
+ * rule, and `.svg` alone has eight spellings.
427
+ *
428
+ * What makes an exact rule the right answer here rather than a second
429
+ * mechanism to keep in step: on this platform the asset set is *closed*. Every
430
+ * file the deploy will ever serve is on disk at this moment, so a rule per
431
+ * offender is complete, and an app that names its files the ordinary way pays
432
+ * nothing — the normal result is an empty list.
433
+ */
434
+ function oddlyCasedDocumentPaths(assetsOut) {
435
+ const documents = new Set(DOCUMENT_ASSET_EXTENSIONS);
436
+ const paths = [];
437
+ const walk = (dir, prefix) => {
438
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
439
+ if (entry.isDirectory()) {
440
+ walk(resolve(dir, entry.name), `${prefix}/${entry.name}`);
441
+ continue;
442
+ }
443
+ const dot = entry.name.lastIndexOf(".");
444
+ const extension = dot === -1 ? "" : entry.name.slice(dot + 1);
445
+ if (extension && extension !== extension.toLowerCase() && documents.has(extension.toLowerCase())) paths.push(`${prefix}/${entry.name}`);
446
+ }
447
+ };
448
+ walk(assetsOut, "");
449
+ return paths.sort();
450
+ }
451
+ /**
452
+ * An app may ship a `_headers` of its own under `public/`, which
453
+ * `stageStaticAssets` has already copied here. Prepend rather than overwrite,
454
+ * and prepend rather than append: the platform applies every matching rule,
455
+ * but only the *first* rule naming a header sets it — a later one appends to
456
+ * the value it finds. Going second would turn an app's own
457
+ * `Content-Disposition` into "inline, attachment"; going first leaves the
458
+ * app's rules appending to ours, which is the harmless direction.
459
+ *
460
+ * The trade the direction costs: the platform parses at most 100 rules and
461
+ * *stops* at the hundredth, so these five push an app's own rules five closer
462
+ * to a cap past which the remainder is dropped rather than reported. Warned
463
+ * about here rather than resolved, because reordering to spend the budget on
464
+ * the app's rules first is the change that breaks the set-versus-append
465
+ * reasoning above.
466
+ */
467
+ function writeAssetHeaders(assetsOut) {
468
+ const headersFile = resolve(assetsOut, "_headers");
469
+ let existing = "";
470
+ try {
471
+ existing = readFileSync(headersFile, "utf8");
472
+ } catch (error) {
473
+ if (error.code !== "ENOENT") throw error;
474
+ }
475
+ const generated = renderAssetHeaders(assetsOut);
476
+ const merged = existing ? `${generated}\n${existing}` : generated;
477
+ warnHeaderRuleBudget(merged, existing);
478
+ writeFileSync(headersFile, merged);
479
+ }
480
+ /** What the platform parses before it stops. */
481
+ const HEADER_RULE_LIMIT = 100;
482
+ /**
483
+ * Say so when the rules added here push an app's own past what the platform
484
+ * reads.
485
+ *
486
+ * Cloudflare parses at most 100 rules and *stops* at the hundredth rather than
487
+ * reporting the rest, so going first — which the set-versus-append reasoning
488
+ * above requires — spends that budget on our rules and drops the app's last
489
+ * ones. Silently: the deploy succeeds and those responses simply stop carrying
490
+ * the headers the app wrote for them.
491
+ *
492
+ * Counted rather than resolved, because the resolution is a trade rather than
493
+ * a fix: ordering the app's rules first would restore them and hand an app's
494
+ * own `Content-Disposition` the power to turn ours into "inline, attachment".
495
+ */
496
+ function warnHeaderRuleBudget(merged, existing) {
497
+ if (!existing) return;
498
+ const rules = merged.split("\n").filter((line) => line.startsWith("/")).length;
499
+ if (rules <= HEADER_RULE_LIMIT) return;
500
+ console.warn(`Cloudflare build: the merged _headers has ${rules} rules and the platform reads only ${HEADER_RULE_LIMIT}, so the last ${rules - HEADER_RULE_LIMIT} of your app's own rules are dropped without an error. The generated document rules are placed first deliberately — the platform lets a later rule only append to a header an earlier one set, so going second would turn your own Content-Disposition into "inline, attachment". Trim public/_headers to fit.`);
501
+ }
502
+ function readPackageJson(root) {
503
+ const packageJsonPath = resolve(root, "package.json");
504
+ if (!existsSync(packageJsonPath)) return {};
505
+ try {
506
+ return JSON.parse(readFileSync(packageJsonPath, "utf8"));
507
+ } catch {
508
+ return {};
509
+ }
510
+ }
511
+ function runAppBuild(root, scripts) {
512
+ if (!scripts.build) throw new Error("Cloudflare build: no \"build\" script found in package.json. Add one (codegen + vite build + vite build --ssr) or pass --skip-app-build after building manually.");
513
+ if (Bun.spawnSync({
514
+ cmd: [
515
+ "bun",
516
+ "run",
517
+ "build"
518
+ ],
519
+ cwd: root,
520
+ stdout: "inherit",
521
+ stderr: "inherit"
522
+ }).exitCode !== 0) throw new Error("Cloudflare build: the app \"build\" script failed.");
523
+ }
524
+ async function resolveSsrImport(ssrDir, ssrEntryKey) {
525
+ const file = resolveSsrEntryFile(ssrDir, ssrEntryKey, "Cloudflare build");
526
+ if (!file) {
527
+ console.warn(`Cloudflare build: no SSR manifest entry for "${ssrEntryKey}" under ${ssrDir}; generating a CSR-only worker.`);
528
+ return;
529
+ }
530
+ const module = await import(pathToFileURL(file).href);
531
+ const rendererExport = ["render", "default"].find((name) => typeof module[name] === "function");
532
+ if (!rendererExport) throw new Error(`Cloudflare build: SSR entry ${file} does not export a renderer (expected a named "render" or default export).`);
533
+ return {
534
+ file,
535
+ rendererExport
536
+ };
537
+ }
538
+ /**
539
+ * Statements assigning the build-derived environment, emitted as a module of
540
+ * their own rather than as lines in worker.js: worker.js imports this module
541
+ * *first*, which is the only ordering ESM import hoisting cannot defeat. A
542
+ * statement in the worker body runs after the app's module graph has already
543
+ * evaluated, so a module-scope `viteAsset()` call in the app would see no
544
+ * manifest and throw before the worker could start. (The Lambda wrapper
545
+ * solves the same hazard by assigning env before dynamically importing the
546
+ * app.)
547
+ */
548
+ function renderWorkerEnvModule(input) {
549
+ const lines = [];
550
+ if (input.assetEnv.entry) lines.push(`process.env.GUREN_INERTIA_ENTRY = ${JSON.stringify(input.assetEnv.entry)}`);
551
+ if (input.assetEnv.styles) lines.push(`process.env.GUREN_INERTIA_STYLES = ${JSON.stringify(input.assetEnv.styles)}`);
552
+ if (input.viteManifest) lines.push(`process.env.GUREN_VITE_MANIFEST = ${JSON.stringify(input.viteManifest)}`);
553
+ if (lines.length === 0) return;
554
+ return [
555
+ "// Generated by `guren cloudflare:build`. Do not edit — regenerate instead.",
556
+ ...lines,
557
+ ""
558
+ ].join("\n");
559
+ }
560
+ function renderWorkerModule(input) {
561
+ const lines = ["// Generated by `guren cloudflare:build`. Do not edit — regenerate instead."];
562
+ if (input.hasEnvModule) lines.push("import './worker-env.js'");
563
+ lines.push("import { createWorkersHandler } from '@guren/plugin-cloudflare'");
564
+ if (input.mcpOAuth) lines.push(`import { OAuthProvider } from ${JSON.stringify(OAUTH_PROVIDER_PACKAGE)}`, `import { mcpOAuthPropsToAuth, presentExternalMcpAuth } from ${JSON.stringify(MCP_OAUTH_SEAM_SPECIFIER)}`);
565
+ if (input.ssrImport) lines.push("import { setInertiaSsrRenderer } from '@guren/core'", `import * as ssrModule from ${JSON.stringify(importSpecifier(input.out, input.ssrImport.file, "Cloudflare build"))}`);
566
+ lines.push(`import app from ${JSON.stringify(importSpecifier(input.out, input.appEntry, "Cloudflare build"))}`, "");
567
+ if (input.ssrImport) lines.push(`setInertiaSsrRenderer(ssrModule.${input.ssrImport.rendererExport})`, "");
568
+ if (!input.mcpOAuth) {
569
+ lines.push("export default createWorkersHandler(app)", "");
570
+ return lines.join("\n");
571
+ }
572
+ lines.push(renderOAuthWorker(input.mcpPath), "");
573
+ return lines.join("\n");
574
+ }
575
+ /**
576
+ * wrangler resolves its config as `wrangler.json` ?? `wrangler.jsonc` ??
577
+ * `wrangler.toml` — first match wins, silently (workers-sdk
578
+ * config-helpers.ts). This plugin manages `wrangler.jsonc`, which makes each
579
+ * neighbour a trap: a `wrangler.json` outranks everything the build scaffolds
580
+ * or checks, and scaffolding beside a lone `wrangler.toml` would make
581
+ * wrangler silently stop reading the user's own config. Neither state can be
582
+ * repaired here, so name the migration and stop before the app build spends
583
+ * minutes on output wrangler would never serve.
584
+ */
585
+ function assertWranglerJsoncIsAuthoritative(root) {
586
+ if (wranglerConfigExists(resolve(root, "wrangler.json"))) throw new Error("Cloudflare build: found wrangler.json. wrangler reads it before the wrangler.jsonc this plugin manages, so the build-owned keys would never reach a deploy. Rename it to wrangler.jsonc — every JSON file is already valid JSONC.");
587
+ if (!wranglerConfigExists(resolve(root, "wrangler.toml"))) return;
588
+ if (wranglerConfigExists(resolve(root, "wrangler.jsonc"))) {
589
+ console.warn("Cloudflare build: wrangler.toml is dead weight — wrangler reads wrangler.jsonc first. Port anything still missing into wrangler.jsonc, then delete wrangler.toml so edits to it stop looking like configuration.");
590
+ return;
591
+ }
592
+ throw new Error("Cloudflare build: found wrangler.toml, but this plugin manages wrangler.jsonc — it cannot read TOML to check the build-owned keys, and scaffolding wrangler.jsonc beside it would make wrangler silently ignore wrangler.toml. Move wrangler.toml aside, rerun the build to scaffold a reference wrangler.jsonc, then port your settings into it.");
593
+ }
594
+ /**
595
+ * `existsSync` folds an unreadable entry into "absent", and absent is the
596
+ * branch that scaffolds a config file beside it — only ENOENT may mean no.
597
+ */
598
+ function wranglerConfigExists(path) {
599
+ try {
600
+ statSync(path);
601
+ return true;
602
+ } catch (error) {
603
+ if (error.code === "ENOENT") return false;
604
+ throw error;
605
+ }
606
+ }
607
+ /**
608
+ * Serve a staged `.html` file at its own path and nowhere else.
609
+ *
610
+ * The platform default, `auto-trailing-slash`, serves `public/page.html` at
611
+ * `/page` and *redirects* `/page.html` there — measured against the asset
612
+ * worker, not assumed. Two consequences, and this setting is the only thing
613
+ * that answers either: the /*.html rule in `_headers` would otherwise only
614
+ * ever land on the redirect, leaving the document itself inline; and a file
615
+ * under `public/` would shadow the app's own route of that name, because
616
+ * assets answer before the worker does.
617
+ *
618
+ * A miss now falls through to the worker, which is where a Guren app's pages
619
+ * come from in the first place.
620
+ */
621
+ const HTML_HANDLING = "none";
622
+ /**
623
+ * The OAuth-fronted export: one `createWorkersHandler` threaded through both
624
+ * halves of the provider.
625
+ *
626
+ * **One handler, not two.** `createWorkersHandler` dedupes `boot()` per
627
+ * handler, while the env holder it captures into is module-global — so two
628
+ * handlers in one module would share the holder without sharing the boot slot,
629
+ * and neither could guard the other on a failed boot (see `handler.ts`). One
630
+ * handler keeps the topology that comment describes.
631
+ *
632
+ * **The seam, not a header.** `ctx.props` is what the provider decrypted from
633
+ * the access token it just validated; the glue maps it to a principal and
634
+ * presents it against the identity of the request it is about to dispatch.
635
+ * Nothing about that claim travels on the wire, so nothing about it can be
636
+ * forged by a caller who reaches the app another way. Props that do not map
637
+ * are refused here rather than passed on as a partial principal.
638
+ *
639
+ * `defaultHandler` is the same handler unwrapped: every route that is not the
640
+ * MCP endpoint — the consent screen included — is served by the application
641
+ * exactly as it would be without the provider.
642
+ */
643
+ function renderOAuthWorker(mcpPath) {
644
+ return `// One handler for both halves of the provider: it dedupes boot() per
645
+ // handler while the Workers env holder is module-global, so a second one
646
+ // would share the holder without sharing the boot slot.
647
+ const handler = createWorkersHandler(app)
648
+
649
+ export default new OAuthProvider({
650
+ apiRoute: ${JSON.stringify(mcpPath)},
651
+ apiHandler: {
652
+ fetch(request, env, ctx) {
653
+ // ctx.props is the grant the provider decrypted from the access
654
+ // token it has already validated. A shape the endpoint cannot read
655
+ // is refused here, never forwarded as a partial principal.
656
+ const auth = mcpOAuthPropsToAuth(ctx.props)
657
+ if (!auth) {
658
+ return new Response(
659
+ JSON.stringify({
660
+ error: 'unauthorized',
661
+ message: 'This access token carries no readable grant. Re-authorize the client.',
662
+ }),
663
+ { status: 401, headers: { 'Content-Type': 'application/json' } },
664
+ )
665
+ }
666
+ // The seam is keyed on this exact Request object — dispatch the one
667
+ // presentExternalMcpAuth returns, never a copy of it.
668
+ return handler.fetch(presentExternalMcpAuth(request, auth), env, ctx)
669
+ },
670
+ },
671
+ defaultHandler: handler,
672
+ authorizeEndpoint: ${JSON.stringify(OAUTH_ENDPOINTS.authorize)},
673
+ tokenEndpoint: ${JSON.stringify(OAUTH_ENDPOINTS.token)},
674
+ // Dynamic client registration (RFC 7591). Deprecated in the MCP
675
+ // 2026-07-28 line in favour of Client ID Metadata Documents, but it is
676
+ // what shipping MCP SDK 1.x clients use to register themselves today.
677
+ clientRegistrationEndpoint: ${JSON.stringify(OAUTH_ENDPOINTS.register)},
678
+ })`;
679
+ }
680
+ function scaffoldWranglerConfig(root, out, packageName, mcpPlugin, mcpOAuth) {
681
+ const configPath = resolve(root, "wrangler.jsonc");
682
+ const appName = (packageName ?? "guren-app").replace(/^@[^/]+\//, "");
683
+ const outRelative = relative(root, out).split(sep).join("/");
684
+ const config = {
685
+ name: appName,
686
+ main: `${outRelative}/worker.js`,
687
+ compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
688
+ compatibility_flags: ["nodejs_compat"],
689
+ alias: devOnlyAliases(outRelative, mcpPlugin),
690
+ define: {
691
+ "process.env.NODE_ENV": "\"production\"",
692
+ "import.meta.url": "\"file:///worker.js\""
693
+ },
694
+ assets: {
695
+ directory: `${outRelative}/assets`,
696
+ html_handling: HTML_HANDLING
697
+ },
698
+ d1_databases: [{
699
+ binding: "DB",
700
+ database_name: appName,
701
+ database_id: "TODO: wrangler d1 create",
702
+ migrations_dir: `${outRelative}/d1-migrations`
703
+ }],
704
+ ...mcpOAuth ? { kv_namespaces: [oauthKvNamespace()] } : {},
705
+ vars: { NODE_ENV: "production" }
706
+ };
707
+ try {
708
+ writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { flag: "wx" });
709
+ } catch (error) {
710
+ if (error.code === "EEXIST") {
711
+ warnMissingBuildOwnedKeys(configPath, outRelative, mcpPlugin, mcpOAuth);
712
+ return;
713
+ }
714
+ throw error;
715
+ }
716
+ const notes = ["fill in d1_databases[0].database_id"];
717
+ if (mcpOAuth) notes.push(`create the ${OAUTH_KV_BINDING} namespace (wrangler kv namespace create ${OAUTH_KV_BINDING}) and fill in its id`);
718
+ console.log(`Cloudflare build: scaffolded ${configPath} — ${notes.join(", and ")} before deploying.`);
719
+ }
720
+ /**
721
+ * The consent flow, written once into the app and never overwritten — the same
722
+ * contract `wrangler.jsonc` has, and for the same reason: these are the
723
+ * developer's files from the moment they exist, and a build that reasserted
724
+ * its own version of them would silently undo every edit.
725
+ *
726
+ * Only reached with `--mcp-oauth` on. An app that never asked for the flag
727
+ * gets no routes it did not ask for.
728
+ */
729
+ function scaffoldConsentFlow(root) {
730
+ const written = [];
731
+ for (const path of MCP_OAUTH_TEMPLATE_FILES) {
732
+ const target = resolve(root, ...path.split("/"));
733
+ mkdirSync(resolve(target, ".."), { recursive: true });
734
+ try {
735
+ writeFileSync(target, loadMcpOAuthTemplate(path), { flag: "wx" });
736
+ written.push(path);
737
+ } catch (error) {
738
+ if (error.code !== "EEXIST") throw error;
739
+ }
740
+ }
741
+ if (written.length === 0) return;
742
+ console.log(`Cloudflare build: scaffolded the OAuth consent flow — ${written.join(", ")}.`);
743
+ if (written.includes("routes/mcp-oauth.ts")) console.log(` Nothing mounts ${MCP_OAUTH_ROUTES_FILE} yet. Add these two lines to your routes entry (routes/web.ts):\n import { ${MCP_OAUTH_REGISTRAR} } from './mcp-oauth'\n ${MCP_OAUTH_REGISTRAR}(router) // inside your registrar, with its router parameter`);
744
+ }
745
+ /**
746
+ * `wrangler.jsonc` is JSONC by name and by habit — the scaffold writes plain
747
+ * JSON, but every app that has touched the file since has comments in it, and
748
+ * `JSON.parse` rejects the first one. Reading it with `JSON.parse` meant the
749
+ * upgrade warning below could not fire for the population it was written for.
750
+ *
751
+ * Only comments and trailing commas are stripped, which is the whole of what
752
+ * wrangler accepts beyond JSON. The scan tracks string literals rather than
753
+ * pattern-matching, because a config carries both hazards for real: `define`
754
+ * holds `"\"file:///worker.js\""`, where the `//` is inside a string and the
755
+ * quotes around it are escaped.
756
+ */
757
+ function parseJsonc(text) {
758
+ const out = [];
759
+ let index = 0;
760
+ while (index < text.length) {
761
+ const char = text[index];
762
+ if (char === "\"") {
763
+ const start = index;
764
+ index += 1;
765
+ while (index < text.length) {
766
+ if (text[index] === "\\") {
767
+ index += 2;
768
+ continue;
769
+ }
770
+ if (text[index] === "\"") {
771
+ index += 1;
772
+ break;
773
+ }
774
+ index += 1;
775
+ }
776
+ out.push(text.slice(start, index));
777
+ continue;
778
+ }
779
+ if (char === "/" && text[index + 1] === "/") {
780
+ while (index < text.length && text[index] !== "\n") index += 1;
781
+ continue;
782
+ }
783
+ if (char === "/" && text[index + 1] === "*") {
784
+ const end = text.indexOf("*/", index + 2);
785
+ index = end === -1 ? text.length : end + 2;
786
+ continue;
787
+ }
788
+ if (char === "}" || char === "]") {
789
+ let back = out.length - 1;
790
+ while (back >= 0 && /^\s+$/.test(out[back])) back -= 1;
791
+ if (back >= 0 && out[back] === ",") out.splice(back, 1);
792
+ }
793
+ out.push(char);
794
+ index += 1;
795
+ }
796
+ return JSON.parse(out.join(""));
797
+ }
798
+ /**
799
+ * The scaffold never overwrites an existing config, but `alias`, `define`,
800
+ * and `migrations_dir` are build-owned invariants pointing into the output
801
+ * directory — an app scaffolded before they existed deploys a worker that
802
+ * cannot resolve `bun:sqlite` or never applies its migrations. Name exactly
803
+ * what is missing rather than failing the build.
804
+ *
805
+ * Individual entries, never a whole `"alias"` or `"define"` object: apps keep
806
+ * their own entries under both keys — a `shiki` stub, a pinned `@guren/orm`,
807
+ * an extra `define` — and a suggestion shaped like a complete object reads as
808
+ * one to paste over what is there, which would drop them.
809
+ */
810
+ function warnMissingBuildOwnedKeys(configPath, outRelative, mcpPlugin, mcpOAuth) {
811
+ let config;
812
+ try {
813
+ config = parseJsonc(readFileSync(configPath, "utf8"));
814
+ } catch {
815
+ console.warn(`Cloudflare build: could not parse ${configPath}, so its build-owned keys went unchecked. Fix the file, or compare it against a config scaffolded in an empty directory.`);
816
+ return;
817
+ }
818
+ const missing = [];
819
+ const configAlias = config.alias;
820
+ const alias = typeof configAlias === "object" && configAlias !== null ? configAlias : {};
821
+ for (const [specifier, target] of Object.entries(devOnlyAliases(outRelative, mcpPlugin))) if (!(specifier in alias)) missing.push(`${JSON.stringify(specifier)}: ${JSON.stringify(target)} (inside "alias")`);
822
+ if (!config.define?.["process.env.NODE_ENV"]) missing.push("\"process.env.NODE_ENV\": \"\\\"production\\\"\" (inside \"define\")");
823
+ const d1 = config.d1_databases?.[0];
824
+ if (d1 && d1.migrations_dir !== `${outRelative}/d1-migrations`) missing.push(`"migrations_dir": "${outRelative}/d1-migrations" (inside d1_databases[0])`);
825
+ if (missing.length > 0) console.warn(`Cloudflare build: ${configPath} predates this plugin version. Add these entries, alongside whatever the file already has under the same keys, or the worker will fail to start or skip migrations:\n ${missing.join("\n ")}`);
826
+ warnMissingHtmlHandling(configPath, config);
827
+ warnOAuthDrift(configPath, config, mcpOAuth);
828
+ }
829
+ /**
830
+ * Kept out of `warnMissingBuildOwnedKeys` even though it fires beside it: the
831
+ * entries there are invariants pointing into the output directory, and their
832
+ * shared sentence ends "the worker will fail to start or skip migrations",
833
+ * which is not true of this one. What is true of it is the opposite kind of
834
+ * consequence — adding it *changes* how the app's own HTML is served — so it
835
+ * needs a message that says that rather than a line in that list.
836
+ *
837
+ * Warned only when the key is absent. Naming any other value is a decision an
838
+ * app had to type, and a config with no `assets` at all serves no static
839
+ * files, so it has nothing for the rules in `_headers` to protect.
840
+ */
841
+ function warnMissingHtmlHandling(configPath, config) {
842
+ const assets = config.assets;
843
+ if (!assets || assets.html_handling !== void 0) return;
844
+ console.warn(`Cloudflare build: ${configPath} does not set "html_handling" under "assets", so a document staged from public/ is still served at its extensionless path — where the /*.html rule in _headers does not reach it, and where it shadows any route of that name in your app. Add "html_handling": "${HTML_HANDLING}" to close both. Note this changes how those files are served: public/about.html stops answering at /about.`);
845
+ }
846
+ /**
847
+ * The drift `--mcp-oauth` leaves detectable in the other direction.
848
+ *
849
+ * The flag records itself nowhere: it is a build option, and passing it every
850
+ * time is the contract. So the way it goes wrong is a config that was
851
+ * scaffolded *with* the flag — carrying the `OAUTH_KV` binding a plain worker
852
+ * has no use for — while today's build omitted it. The worker that just
853
+ * replaced the deployed one has no `OAuthProvider` in it, `/oauth/token` and
854
+ * `/oauth/register` answer 404, and every already-authorized client stops
855
+ * working, with nothing in the build output mentioning OAuth at all.
856
+ *
857
+ * A warning and not a failure: a developer may be deliberately building a
858
+ * non-OAuth worker from a repository that also builds an OAuth one, and the
859
+ * binding is inert either way. What must not happen is the build passing in
860
+ * silence.
861
+ */
862
+ function warnOAuthDrift(configPath, config, mcpOAuth) {
863
+ if (mcpOAuth || !oauthKvBinding(config)) return;
864
+ console.warn(`Cloudflare build: ${configPath} binds ${OAUTH_KV_BINDING}, which only an OAuth-fronted worker uses, but this build ran without --mcp-oauth. The worker it produced has no OAuth provider in it: ${OAUTH_ENDPOINTS.token} and ${OAUTH_ENDPOINTS.register} will 404 and already-authorized clients will stop working. Pass --mcp-oauth, or remove the binding if this app no longer fronts its MCP endpoint with OAuth.`);
865
+ }
866
+ //#endregion
867
+ export { flattenD1Migrations as n, buildCloudflareOutput as t };