@guren/plugin-cloudflare 0.12.3 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,11 @@
1
+ import { i as WRANGLER_DEPLOY_CONFIG_FILE, n as D1_MIGRATIONS_DIR, o as outputDirFor, r as WORKER_MANIFEST_FILE } from "./worker-manifest-16SJawlX.js";
1
2
  import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
3
  import { dirname, join, relative, resolve, sep } from "node:path";
3
4
  import { fileURLToPath, pathToFileURL } from "node:url";
4
5
  import { AGENTS_CONFIG_FILE, DATABASE_FACTORIES, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, MCP_PLUGIN_PACKAGE, SQL_CLIENT_MODULES, assertOutputDirOutsideRoot, bundledRuntimeEnv, detectDatabaseDialects, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, stageStaticAssets } from "@guren/core/internal/deploy-build";
5
- import { reportDeployRuntimeHazards } from "@guren/core/internal/deploy-check";
6
+ import { inspectDeployRuntime } from "@guren/core/internal/deploy-check";
7
+ import { readScheduledTasks } from "@guren/core/internal/deploy-plan";
8
+ import { createHash } from "node:crypto";
6
9
  import { tmpdir } from "node:os";
7
10
  //#region src/templates.ts
8
11
  /**
@@ -37,47 +40,234 @@ function loadMcpOAuthTemplate(path) {
37
40
  return readFileSync(join(templateDir, ...path.split("/")), "utf8");
38
41
  }
39
42
  //#endregion
43
+ //#region src/backend.ts
44
+ /**
45
+ * RFC 0035 §7: `cf` when the app has `cloudflare.config.ts` and declares `cf`,
46
+ * otherwise Wrangler. The config without the package is refused rather than
47
+ * falling back, which would scaffold a wrangler.jsonc beside it.
48
+ */
49
+ function detectCloudflareBackend(root) {
50
+ if (!existsSync(resolve(root, "cloudflare.config.ts"))) return "wrangler";
51
+ if (!appDeclares(root, "cf")) throw new Error(`Cloudflare build: ${resolve(root, "cloudflare.config.ts")} exists, but this app does not declare the cf CLI that reads it. Install it:\n bun add -d cf wrangler
52
+ Or remove cloudflare.config.ts to keep deploying through wrangler.jsonc.`);
53
+ return "cf";
54
+ }
55
+ /** Whether the app declares `name` at all: a CLI like `cf` belongs in devDependencies. */
56
+ function appDeclares(root, name) {
57
+ const manifest = readPackageJson(root);
58
+ return (manifest.dependencies?.[name] ?? manifest.devDependencies?.[name]) !== void 0;
59
+ }
60
+ /** The app's package.json; an absent, unreadable or malformed one reads as `{}`, and a non-object field as absent. */
61
+ function readPackageJson(root) {
62
+ let manifest;
63
+ try {
64
+ manifest = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8"));
65
+ } catch {
66
+ return {};
67
+ }
68
+ if (!isRecord(manifest)) return {};
69
+ return {
70
+ name: typeof manifest.name === "string" ? manifest.name : void 0,
71
+ scripts: stringRecord(manifest.scripts),
72
+ dependencies: stringRecord(manifest.dependencies),
73
+ devDependencies: stringRecord(manifest.devDependencies)
74
+ };
75
+ }
76
+ /** The string-valued entries of an object field; anything else reads as absent. */
77
+ function stringRecord(value) {
78
+ if (!isRecord(value)) return void 0;
79
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
80
+ }
81
+ function isRecord(value) {
82
+ return typeof value === "object" && value !== null && !Array.isArray(value);
83
+ }
84
+ //#endregion
85
+ //#region src/inference.ts
86
+ function inferBindings(app) {
87
+ if (!app) return {
88
+ r2Buckets: [],
89
+ unread: "the build did not introspect the app"
90
+ };
91
+ if (app.status === "unread") return {
92
+ r2Buckets: [],
93
+ unread: app.reason
94
+ };
95
+ const r2Buckets = [];
96
+ const opaqueDisks = [];
97
+ const entries = isRecord(app.storage) && isRecord(app.storage.entries) ? app.storage.entries : {};
98
+ for (const [disk, entry] of Object.entries(entries)) {
99
+ if (!isRecord(entry)) continue;
100
+ if (entry.driver === "r2" && typeof entry.binding === "string") {
101
+ if (!r2Buckets.includes(entry.binding)) r2Buckets.push(entry.binding);
102
+ } else if (entry.driver === null || entry.driver === "r2") opaqueDisks.push(disk);
103
+ }
104
+ const databaseBinding = isRecord(app.database) && app.database.dialect === "d1" && typeof app.database.binding === "string" ? app.database.binding : void 0;
105
+ return {
106
+ r2Buckets: r2Buckets.sort(),
107
+ ...opaqueDisks.length > 0 ? { opaqueDisks: opaqueDisks.sort() } : {},
108
+ ...databaseBinding ? { databaseBinding } : {}
109
+ };
110
+ }
111
+ //#endregion
112
+ //#region src/deploy/migrations.ts
113
+ /**
114
+ * Which migration layout a D1 database is on, decided by what its tracker already
115
+ * records (RFC 0035 §6). Wrangler, and cf over the flattened copy, record
116
+ * `<folder>.sql`; cf over drizzle's nested layout records `<folder>/migration.sql`.
117
+ * Pointing a database at the other layout would make its whole history look pending.
118
+ */
119
+ const NESTED_SUFFIX = "/migration.sql";
120
+ /** The same entries `flattenD1Migrations()` copies, sorted the way cf and Wrangler apply them. */
121
+ function readLocalMigrations(migrationsDir) {
122
+ if (!existsSync(migrationsDir)) return {
123
+ folders: [],
124
+ files: []
125
+ };
126
+ const folders = [];
127
+ const files = [];
128
+ for (const entry of readdirSync(migrationsDir, { withFileTypes: true })) {
129
+ if (entry.isFile() && entry.name.endsWith(".sql")) files.push(entry.name);
130
+ if (entry.isDirectory() && entry.name !== "meta" && existsSync(join(migrationsDir, entry.name, "migration.sql"))) folders.push(entry.name);
131
+ }
132
+ return {
133
+ folders: folders.sort(),
134
+ files: files.sort()
135
+ };
136
+ }
137
+ /**
138
+ * `tracker` is `null` for a database with no tracker table, or one not created yet.
139
+ * A tracker with no rows takes the flat layout, which the guide's manual apply and
140
+ * Wrangler both use, so the two never record different names for one database.
141
+ * Wrangler applies only the flat copy (`appliesNested` false), where a nested history
142
+ * would all read as pending.
143
+ */
144
+ function decideLayout(local, tracker, appliesNested = true) {
145
+ const rows = tracker ?? [];
146
+ const nested = rows.filter((name) => name.endsWith(NESTED_SUFFIX));
147
+ const flat = rows.filter((name) => !name.endsWith(NESTED_SUFFIX));
148
+ if (nested.length > 0 && flat.length > 0) return {
149
+ ok: false,
150
+ nested,
151
+ flat
152
+ };
153
+ if (nested.length > 0 && !appliesNested) return {
154
+ ok: false,
155
+ unsupported: "nested",
156
+ nested
157
+ };
158
+ const layout = nested.length > 0 ? "nested" : "flat";
159
+ const recorded = (folder) => layout === "nested" ? `${folder}${NESTED_SUFFIX}` : `${folder}.sql`;
160
+ const applied = new Set(rows);
161
+ const pendingFolders = local.folders.filter((folder) => !applied.has(recorded(folder)));
162
+ const pendingFiles = local.files.filter((file) => !applied.has(file));
163
+ return {
164
+ ok: true,
165
+ layout,
166
+ pendingFolders,
167
+ pendingFiles,
168
+ pending: [...pendingFolders.map((folder) => ({
169
+ key: `${folder}.sql`,
170
+ name: folder
171
+ })), ...pendingFiles.map((file) => ({
172
+ key: file,
173
+ name: file
174
+ }))].sort((left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0).map((entry) => entry.name)
175
+ };
176
+ }
177
+ /** The `cf d1 migrations` arguments for a layout, after the database id. */
178
+ function migrationDirArgs(layout, flatDir) {
179
+ return layout === "nested" ? [
180
+ "--dir",
181
+ "db/migrations",
182
+ "--pattern",
183
+ "db/migrations/*/migration.sql"
184
+ ] : ["--dir", flatDir];
185
+ }
186
+ /** sha256 over each pending migration's name and text, in apply order. */
187
+ function fingerprintMigrations(migrationsDir, pending) {
188
+ const hash = createHash("sha256");
189
+ for (const name of pending) {
190
+ const path = name.endsWith(".sql") ? join(migrationsDir, name) : join(migrationsDir, name, "migration.sql");
191
+ hash.update(`${name}\0`).update(readFileSync(path)).update("\0");
192
+ }
193
+ return hash.digest("hex");
194
+ }
195
+ //#endregion
40
196
  //#region src/build.ts
41
197
  /**
42
- * Assemble a deployable Cloudflare Workers directory (`.cloudflare/`) from a
43
- * built Guren app: a generated worker entry that statically wires the SSR
44
- * bundle, static assets for Workers Static Assets, and a one-time
45
- * `wrangler.jsonc` scaffold. Deploy with `wrangler deploy`.
198
+ * Assemble a deployable Cloudflare Workers directory from a built Guren app: a
199
+ * generated worker entry that statically wires the SSR bundle, and static assets
200
+ * for Workers Static Assets. On the Wrangler backend it goes to `.cloudflare/` with
201
+ * a one-time `wrangler.jsonc` scaffold; on the cf backend to `.guren/cloudflare/`
202
+ * with the `guren-worker.json` manifest `gurenWorker()` reads (RFC 0035 §3).
46
203
  */
47
204
  async function buildCloudflareOutput(options = {}) {
205
+ await assembleCloudflareOutput(options);
206
+ }
207
+ /** {@link buildCloudflareOutput}, returning what it learnt about the app, which `cloudflare:deploy` plans from (RFC 0035 §2). */
208
+ async function assembleCloudflareOutput(options = {}) {
48
209
  const root = resolvePathLike(options.rootDir ?? process.cwd());
49
- const out = resolvePathLike(options.outputDir ?? resolve(root, ".cloudflare"));
210
+ const backend = detectCloudflareBackend(root);
211
+ const out = resolvePathLike(options.outputDir ?? resolve(root, outputDirFor(backend)));
50
212
  const appEntry = resolvePathLike(options.appEntry ?? resolve(root, "src/app.ts"));
51
213
  const publicDir = resolvePathLike(options.publicDir ?? resolve(root, "public"));
52
214
  const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
53
215
  const clientEntryKey = options.clientEntryKey ?? "resources/js/app.tsx";
54
216
  const ssrEntryKey = options.ssrEntryKey ?? "resources/js/ssr.tsx";
55
217
  assertOutputDirOutsideRoot(out, root, "Cloudflare build");
56
- assertWranglerJsoncIsAuthoritative(root);
57
- assertKeepsClassNames(root);
218
+ if (backend === "wrangler") {
219
+ assertWranglerJsoncIsAuthoritative(root);
220
+ assertKeepsClassNames(root);
221
+ warnPlaceholderIds(root);
222
+ }
58
223
  const packageJson = readPackageJson(root);
59
- const mcpOAuth = options.mcpOAuth === true;
60
- const mcpPath = options.mcpPath ?? DEFAULT_MCP_PATH;
224
+ const configFile = deployConfigPath(root);
225
+ const deployConfig = backend === "cf" && configFile ? await readDeployConfig(configFile) : void 0;
226
+ if (backend === "wrangler" && configFile) console.warn(`Cloudflare build: ${configFile} is read only on the cf backend (cloudflare.config.ts), so this build ignores it. Pass --mcp-oauth and --mcp-path here instead.`);
227
+ const configName = configFile ? relative(root, configFile).split(sep).join("/") : DEPLOY_CONFIG_FILE;
228
+ const mcpOAuth = (backend === "cf" ? resolveOption(configName, "mcpOAuth", "--mcp-oauth", deployConfig?.mcpOAuth, options.mcpOAuth) : options.mcpOAuth) === true;
229
+ const mcpPath = (backend === "cf" ? resolveOption(configName, "mcpPath", "--mcp-path", deployConfig?.mcpPath, options.mcpPath) : options.mcpPath) ?? DEFAULT_MCP_PATH;
61
230
  if (mcpOAuth) {
62
231
  assertMcpOAuthUsable(root);
63
- assertOAuthKvBound(root);
232
+ if (backend === "wrangler") assertOAuthKvBound(root);
64
233
  }
65
234
  const hostsAgents = existsSync(resolve(root, AGENTS_CONFIG_FILE));
66
235
  if (hostsAgents) assertAgentsPluginUsable(root);
67
236
  const agents = hostsAgents ? await readAgentRegistry(root) : NO_AGENTS;
68
- const agentBindings = assertAgentDurableObjects(root, agents.exports);
237
+ const agentBindings = backend === "cf" ? agents.exports.map((agent) => durableObjectBindingName(agent.export)) : assertAgentDurableObjects(root, agents.exports);
69
238
  warnUnroutedAgents(agents);
70
- await reportDeployRuntimeHazards({
239
+ const { app } = await inspectDeployRuntime({
71
240
  root,
72
- label: "Cloudflare build"
241
+ label: "Cloudflare build",
242
+ target: "cloudflare"
73
243
  });
244
+ const fresh = inferBindings(app);
245
+ const previousBuckets = readWorkerManifest(out).r2Buckets;
246
+ const inferred = fresh.unread && Array.isArray(previousBuckets) ? {
247
+ ...fresh,
248
+ r2Buckets: previousBuckets
249
+ } : fresh;
250
+ const schedule = backend === "cf" ? await cronTriggers(root) : { crons: [] };
74
251
  warnDatabaseWithoutD1(root);
75
- if (!options.skipAppBuild) runAppBuild(root, packageJson.scripts ?? {});
252
+ if (!options.skipAppBuild) runAppBuild(root, packageJson.scripts ?? {}, options.appBuildToStderr === true);
76
253
  if (!existsSync(appEntry)) throw new Error(`Cloudflare build: app entry not found at ${appEntry}. Pass "appEntry" if your Application lives elsewhere.`);
77
254
  const ssrImport = await resolveSsrImport(ssrDir, ssrEntryKey);
78
255
  const assetEnv = resolveClientAssetEnv(publicDir, clientEntryKey, "Cloudflare build");
79
256
  const bundledEnv = bundledRuntimeEnv(root, publicDir, "Cloudflare build");
257
+ const resolved = readResolvedResources(out);
80
258
  resetOutputDir(out, root, "Cloudflare build");
259
+ if (backend === "wrangler") writeResolvedOnly(out, resolved);
260
+ else writeWorkerManifest({
261
+ root,
262
+ out,
263
+ packageName: packageJson.name,
264
+ mcpOAuth,
265
+ agents: agents.exports,
266
+ resolved,
267
+ ...schedule,
268
+ resourceNames: deployConfig?.resourceNames ?? {},
269
+ inferred
270
+ });
81
271
  stageStaticAssets(publicDir, resolve(out, "assets"));
82
272
  writeAssetHeaders(resolve(out, "assets"));
83
273
  const workerEnv = renderWorkerEnvModule({
@@ -96,10 +286,132 @@ async function buildCloudflareOutput(options = {}) {
96
286
  agents: agents.exports,
97
287
  agentBindings
98
288
  }));
99
- flattenD1Migrations(resolve(root, "db/migrations"), resolve(out, "d1-migrations"));
289
+ flattenD1Migrations(resolve(root, "db/migrations"), resolve(out, D1_MIGRATIONS_DIR));
100
290
  writeDevOnlyStubs(out);
101
291
  if (mcpOAuth) scaffoldConsentFlow(root);
102
- scaffoldWranglerConfig(root, out, packageJson.name, mcpOAuth, agents.exports);
292
+ if (backend === "wrangler") scaffoldWranglerConfig(root, out, packageJson.name, mcpOAuth, agents.exports);
293
+ return { inference: inferred };
294
+ }
295
+ /** The manifest a build left in `out`, or an empty object when there is none to read. */
296
+ function readWorkerManifest(out) {
297
+ try {
298
+ const manifest = JSON.parse(readFileSync(resolve(out, WORKER_MANIFEST_FILE), "utf8"));
299
+ return isRecord(manifest) ? manifest : {};
300
+ } catch {
301
+ return {};
302
+ }
303
+ }
304
+ /** The previous build's `resolved` section, or nothing when there is no readable manifest. */
305
+ function readResolvedResources(out) {
306
+ const resolved = readWorkerManifest(out).resolved;
307
+ return isRecord(resolved) ? resolved : {};
308
+ }
309
+ /**
310
+ * One `* * * * *` trigger when the schedule kernel registers tasks: the worker runs
311
+ * whichever are due at each firing, so a coarser trigger would skip the finest task
312
+ * (RFC 0035 §2). None for the OAuth sweep alone, which `handler.scheduled` follows by
313
+ * throwing when no scheduler is bound. A kernel it cannot read is recorded, so the
314
+ * deploy plan can refuse to drop a trigger the Worker may already have.
315
+ */
316
+ async function cronTriggers(root) {
317
+ const tasks = await readScheduledTasks(root);
318
+ if (tasks.status === "unreadable") {
319
+ console.warn(`Cloudflare build: ${tasks.message}, so no cron trigger was added for scheduled tasks. Add triggers.scheduled() in cloudflare.config.ts if the app has any.`);
320
+ return {
321
+ crons: [],
322
+ scheduleUnreadable: tasks.message
323
+ };
324
+ }
325
+ if (tasks.status === "loaded") for (const warning of tasks.warnings) console.warn(`Cloudflare build: the schedule kernel loaded partly: ${warning}`);
326
+ return { crons: tasks.status === "loaded" && tasks.count > 0 ? [EVERY_MINUTE] : [] };
327
+ }
328
+ const EVERY_MINUTE = "* * * * *";
329
+ function writeWorkerManifest(input) {
330
+ const outRelative = relative(input.root, input.out).split(sep).join("/");
331
+ const manifest = {
332
+ version: 2,
333
+ entrypoint: `./${outRelative}/worker.js`,
334
+ assetsDirectory: `./${outRelative}/assets`,
335
+ compatibilityFlags: ["nodejs_compat"],
336
+ htmlHandling: HTML_HANDLING,
337
+ alias: devOnlyAliases(outRelative),
338
+ define: BUNDLE_DEFINES,
339
+ vars: WORKER_VARS,
340
+ d1: {
341
+ binding: "DB",
342
+ databaseName: input.resourceNames.DB ?? workerName(input.packageName)
343
+ },
344
+ kvNamespaces: input.mcpOAuth ? [OAUTH_KV_BINDING] : [],
345
+ crons: input.crons,
346
+ resourceNames: input.resourceNames,
347
+ ...input.scheduleUnreadable ? { scheduleUnreadable: input.scheduleUnreadable } : {},
348
+ agents: input.agents.map((agent) => ({
349
+ exportName: agent.export,
350
+ binding: durableObjectBindingName(agent.export)
351
+ })),
352
+ r2Buckets: input.inferred.r2Buckets,
353
+ resolved: input.resolved
354
+ };
355
+ mkdirSync(input.out, { recursive: true });
356
+ writeFileSync(resolve(input.out, WORKER_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`);
357
+ writeFileSync(resolve(input.out, ".gitignore"), "*\n");
358
+ }
359
+ /**
360
+ * The Wrangler backend's manifest holds only what `cloudflare:deploy` settled, since
361
+ * wrangler.jsonc is the rest. The ignore names only the files carrying ids, because
362
+ * an app may commit the rest of `.cloudflare/` for a host that deploys without building.
363
+ */
364
+ function writeResolvedOnly(out, resolved) {
365
+ mkdirSync(out, { recursive: true });
366
+ writeFileSync(resolve(out, WORKER_MANIFEST_FILE), `${JSON.stringify({
367
+ version: 2,
368
+ resolved
369
+ }, null, 2)}\n`);
370
+ writeFileSync(resolve(out, ".gitignore"), `${WORKER_MANIFEST_FILE}\n${WRANGLER_DEPLOY_CONFIG_FILE}\n.wrangler/\n`);
371
+ }
372
+ /** RFC 0035 §3: Guren's deploy settings on the cf backend, recorded nowhere else. */
373
+ const DEPLOY_CONFIG_FILE = "config/cloudflare.ts";
374
+ const DEPLOY_CONFIG_EXTENSIONS = [
375
+ ".ts",
376
+ ".mts",
377
+ ".js",
378
+ ".mjs"
379
+ ];
380
+ function deployConfigPath(root) {
381
+ return DEPLOY_CONFIG_EXTENSIONS.map((extension) => resolve(root, "config", `cloudflare${extension}`)).find((path) => existsSync(path));
382
+ }
383
+ async function readDeployConfig(path) {
384
+ let exported;
385
+ try {
386
+ exported = (await import(pathToFileURL(path).href)).default;
387
+ } catch (error) {
388
+ throw new Error(`Cloudflare build: ${path} failed to import: ${error instanceof Error ? error.message : String(error)}`);
389
+ }
390
+ const problems = deployConfigProblems(exported);
391
+ if (problems.length > 0) throw new Error(`Cloudflare build: ${path} must default-export defineCloudflareConfig({ ... }):\n ${problems.join("\n ")}`);
392
+ return exported;
393
+ }
394
+ function deployConfigProblems(config) {
395
+ if (!isRecord(config)) return ["the default export is not an object"];
396
+ const problems = [];
397
+ if (config.mcpOAuth !== void 0 && typeof config.mcpOAuth !== "boolean") problems.push("mcpOAuth is not a boolean");
398
+ if (config.mcpPath !== void 0 && (typeof config.mcpPath !== "string" || !config.mcpPath.startsWith("/"))) problems.push("mcpPath is not a path starting with /");
399
+ if (config.resourceNames !== void 0 && (!isRecord(config.resourceNames) || Object.values(config.resourceNames).some((name) => typeof name !== "string" || name === ""))) problems.push("resourceNames is not a record of non-empty names");
400
+ return problems;
401
+ }
402
+ /**
403
+ * The file is the record of a deploy setting on the cf backend; the flag, recorded
404
+ * nowhere, is accepted with a warning and refused when it contradicts the file.
405
+ */
406
+ function resolveOption(file, key, flag, fromFile, fromFlag) {
407
+ if (fromFlag === void 0 || fromFlag === false) return fromFile ?? fromFlag;
408
+ if (fromFile !== void 0 && fromFile !== fromFlag) throw new Error(`Cloudflare build: ${flag} contradicts ${key} in ${file}. Drop the flag; the file is what every build and deploy reads.`);
409
+ if (fromFile === void 0) console.warn(`Cloudflare build: ${flag} is recorded nowhere, so a build without it ships a different worker. Set ${key} in ${file} instead.`);
410
+ return fromFlag;
411
+ }
412
+ /** The Worker name, and the D1 database name a fresh binding gets. */
413
+ function workerName(packageName) {
414
+ return (packageName ?? "guren-app").replace(/^@[^/]+\//, "");
103
415
  }
104
416
  /** `mcpPlugin()`'s own default mount path — see `BuildCloudflareOutputOptions.mcpPath`. */
105
417
  const DEFAULT_MCP_PATH = "/mcp";
@@ -138,41 +450,25 @@ function assertOAuthKvBound(root) {
138
450
  const configPath = resolve(root, "wrangler.jsonc");
139
451
  const config = readWranglerConfig(configPath);
140
452
  if (!config) return;
141
- const bound = oauthKvBinding(config);
142
- if (bound) {
143
- 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}`);
144
- return;
145
- }
146
- 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}`);
453
+ if (bindsOAuthKv(config)) return;
454
+ 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. Add this entry, alongside whatever the file already has:\n "kv_namespaces": [\n ${JSON.stringify(OAUTH_KV_NAMESPACE, null, 2).split("\n").join("\n ")}\n ]\nWith no "id", \`wrangler deploy\` creates the namespace on the first deploy. To use one you created yourself, add its id from: wrangler kv namespace create ${OAUTH_KV_BINDING}`);
147
455
  }
148
- /**
149
- * The KV namespace a parsed config binds under the provider's name, or
150
- * `undefined`. Returns the entry rather than a boolean because callers ask both
151
- * "is it bound" and "is its id still the placeholder" of the same match.
152
- */
153
- function oauthKvBinding(config) {
456
+ /** Whether a parsed config binds a KV namespace under the provider's name. */
457
+ function bindsOAuthKv(config) {
154
458
  const namespaces = config.kv_namespaces;
155
- if (!Array.isArray(namespaces)) return;
156
- return namespaces.find((entry) => isRecord(entry) && entry.binding === OAUTH_KV_BINDING);
157
- }
158
- /** The binding entry, spelled once — the scaffold writes it, the guard quotes it. */
159
- function oauthKvNamespace() {
160
- return {
161
- binding: OAUTH_KV_BINDING,
162
- id: `TODO: wrangler kv namespace create ${OAUTH_KV_BINDING}`
163
- };
459
+ return Array.isArray(namespaces) && namespaces.some((entry) => isRecord(entry) && entry.binding === "OAUTH_KV");
164
460
  }
165
461
  /**
462
+ * The binding entry, spelled once — the scaffold writes it, the guard quotes it.
463
+ * No `id`: an id-less binding is what wrangler's own provisioning creates at deploy.
464
+ */
465
+ const OAUTH_KV_NAMESPACE = Object.freeze({ binding: OAUTH_KV_BINDING });
466
+ /**
166
467
  * Whether the app declares `name` under `dependencies` (devDependencies do not
167
468
  * ship). An absent, unreadable or malformed manifest answers `false`.
168
469
  */
169
470
  function appDependsOn(root, name) {
170
- try {
171
- const dependencies = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")).dependencies;
172
- return typeof dependencies === "object" && dependencies !== null && name in dependencies;
173
- } catch {
174
- return false;
175
- }
471
+ return readPackageJson(root).dependencies?.[name] !== void 0;
176
472
  }
177
473
  /** The package the generated worker imports the agent runtime and router from. */
178
474
  const AGENTS_PLUGIN_PACKAGE = "@guren/plugin-agents";
@@ -251,9 +547,6 @@ function isInside(root, target) {
251
547
  const rel = relative(root, target);
252
548
  return rel !== "" && !rel.startsWith("..") && !rel.startsWith(`..${sep}`);
253
549
  }
254
- function isRecord(value) {
255
- return typeof value === "object" && value !== null && !Array.isArray(value);
256
- }
257
550
  /**
258
551
  * Refuse an app hosting agents that did not install the plugin, before anything
259
552
  * is built. Same shape as {@link assertMcpOAuthUsable}: wrangler resolves the
@@ -309,6 +602,26 @@ function configScopes(config) {
309
602
  }
310
603
  return scopes;
311
604
  }
605
+ /** wrangler provisions only a binding with no id, so a placeholder id (`isPlaceholderId()`) fails the deploy. */
606
+ function warnPlaceholderIds(root) {
607
+ const configPath = resolve(root, "wrangler.jsonc");
608
+ const config = readWranglerConfig(configPath);
609
+ if (!config) return;
610
+ const placeholders = configScopes(config).flatMap((scope) => [...placeholderKeys(scope, "d1_databases", "database_id"), ...placeholderKeys(scope, "kv_namespaces", "id")]);
611
+ if (placeholders.length === 0) return;
612
+ const envNote = placeholders.some((key) => key.includes("(env.")) ? "\nAn env.<name> binding left with no id resolves by its database_name or the worker name, so give each environment its own name before deleting its id." : "";
613
+ console.warn(`Cloudflare build: ${configPath} has placeholder resource ids, which \`wrangler deploy\` rejects. Delete these keys, and the deploy creates each resource (or connects to one of the same name); or paste a real id in:\n ${placeholders.join("\n ")}${envNote}`);
614
+ }
615
+ function placeholderKeys(scope, key, idKey) {
616
+ return asArray(scope.config[key]).flatMap((entry, index) => {
617
+ const id = isRecord(entry) ? entry[idKey] : void 0;
618
+ return typeof id === "string" && isPlaceholderId(id) ? [`${key}[${index}].${idKey}${scope.label}`] : [];
619
+ });
620
+ }
621
+ /** D1 ids are UUIDs and KV ids 32 hex digits, so anything but hex and hyphens, or all zeros, stands in for one. */
622
+ function isPlaceholderId(id) {
623
+ return !/^[0-9a-f-]+$/i.test(id) || /^[0-]*$/.test(id);
624
+ }
312
625
  /**
313
626
  * wrangler bundles with esbuild's `keepNames: keep_names ?? true`, on deploy and in
314
627
  * dev, so `minify` alone keeps class names and only `"keep_names": false` loses them.
@@ -362,47 +675,52 @@ function indentJson(value) {
362
675
  */
363
676
  function registeredBindings(config, agents) {
364
677
  const registered = new Set(agents.map((agent) => agent.export));
678
+ return durableObjectBindings(config).filter((entry) => entry.scriptName === void 0 && registered.has(entry.className)).map((entry) => ({
679
+ name: entry.name,
680
+ class_name: entry.className
681
+ }));
682
+ }
683
+ /** The `durable_objects.bindings` of one scope; `scriptName` names another Worker that hosts the class. */
684
+ function durableObjectBindings(config) {
365
685
  const durableObjects = config.durable_objects;
366
- const hosting = [];
367
- for (const entry of asArray(isRecord(durableObjects) ? durableObjects.bindings : void 0)) {
368
- if (!isRecord(entry)) continue;
369
- const { name, class_name: className, script_name: scriptName } = entry;
370
- if (scriptName !== void 0) continue;
371
- if (typeof name !== "string" || typeof className !== "string") continue;
372
- if (!registered.has(className)) continue;
373
- hosting.push({
374
- name,
375
- class_name: className
376
- });
377
- }
378
- return hosting;
686
+ return asArray(isRecord(durableObjects) ? durableObjects.bindings : void 0).flatMap((entry) => {
687
+ if (!isRecord(entry) || typeof entry.name !== "string" || typeof entry.class_name !== "string") return [];
688
+ return [{
689
+ name: entry.name,
690
+ className: entry.class_name,
691
+ ...entry.script_name !== void 0 ? { scriptName: entry.script_name } : {}
692
+ }];
693
+ });
379
694
  }
380
695
  /**
381
- * Classes wrangler will give a SQLite storage backend, in either form. The
382
- * `migrations` list is *history*, folded in order: a class created in `v1` and
383
- * deleted in `v2` is gone, a rename carries the backend to the new name. A
384
- * declarative `exports` entry counts while it is live — `created` (the default)
385
- * or `expecting-transfer` — and `deleted`/`renamed` declare the class gone.
696
+ * Every live Durable Object class and the storage wrangler gives it, in either form. The
697
+ * `migrations` list is *history*, folded in order: a class created in `v1` and deleted in
698
+ * `v2` is gone, a rename carries the storage to the new name. A declarative `exports`
699
+ * entry counts while it is live — `created` (the default) or `expecting-transfer`.
386
700
  */
387
- function sqliteBackedClasses(config) {
388
- const classes = /* @__PURE__ */ new Set();
701
+ function durableObjectStorage(config) {
702
+ const classes = /* @__PURE__ */ new Map();
389
703
  for (const migration of asArray(config.migrations)) {
390
704
  if (!isRecord(migration)) continue;
391
- for (const name of strings(migration.new_sqlite_classes)) classes.add(name);
705
+ for (const name of strings(migration.new_sqlite_classes)) classes.set(name, "sqlite");
706
+ for (const name of strings(migration.new_classes)) classes.set(name, "legacy-kv");
392
707
  for (const rename of asArray(migration.renamed_classes)) {
393
708
  if (!isRecord(rename) || typeof rename.from !== "string" || typeof rename.to !== "string") continue;
394
- if (classes.delete(rename.from)) classes.add(rename.to);
709
+ const storage = classes.get(rename.from);
710
+ if (storage && classes.delete(rename.from)) classes.set(rename.to, storage);
395
711
  }
396
712
  for (const name of strings(migration.deleted_classes)) classes.delete(name);
397
713
  }
398
714
  const exported = config.exports;
399
715
  if (isRecord(exported)) for (const [name, entry] of Object.entries(exported)) {
400
- if (!isRecord(entry)) continue;
401
- const live = entry.state === void 0 || entry.state === "created" || entry.state === "expecting-transfer";
402
- if (entry.type === "durable-object" && entry.storage === "sqlite" && live) classes.add(name);
716
+ if (!isRecord(entry) || entry.type !== "durable-object") continue;
717
+ if ((entry.state === void 0 || entry.state === "created" || entry.state === "expecting-transfer") && (entry.storage === "sqlite" || entry.storage === "legacy-kv")) classes.set(name, entry.storage);
403
718
  }
404
719
  return classes;
405
720
  }
721
+ function sqliteBackedClasses(config) {
722
+ return new Set([...durableObjectStorage(config)].filter(([, storage]) => storage === "sqlite").map(([name]) => name));
723
+ }
406
724
  function asArray(value) {
407
725
  return Array.isArray(value) ? value : [];
408
726
  }
@@ -483,24 +801,14 @@ function devOnlyAliases(outRelative) {
483
801
  */
484
802
  function flattenD1Migrations(migrationsDir, outDir) {
485
803
  if (!existsSync(migrationsDir)) return;
486
- const entries = readdirSync(migrationsDir, { withFileTypes: true });
487
- const copies = [];
488
- for (const entry of entries) {
489
- if (entry.isFile() && entry.name.endsWith(".sql")) {
490
- copies.push({
491
- from: resolve(migrationsDir, entry.name),
492
- to: entry.name
493
- });
494
- continue;
495
- }
496
- if (entry.isDirectory() && entry.name !== "meta") {
497
- const nested = resolve(migrationsDir, entry.name, "migration.sql");
498
- if (existsSync(nested)) copies.push({
499
- from: nested,
500
- to: `${entry.name}.sql`
501
- });
502
- }
503
- }
804
+ const local = readLocalMigrations(migrationsDir);
805
+ const copies = [...local.files.map((file) => ({
806
+ from: resolve(migrationsDir, file),
807
+ to: file
808
+ })), ...local.folders.map((folder) => ({
809
+ from: resolve(migrationsDir, folder, "migration.sql"),
810
+ to: `${folder}.sql`
811
+ }))];
504
812
  const seen = /* @__PURE__ */ new Map();
505
813
  for (const copy of copies) {
506
814
  const clash = seen.get(copy.to);
@@ -593,16 +901,7 @@ function warnHeaderRuleBudget(merged, existing) {
593
901
  if (rules <= HEADER_RULE_LIMIT) return;
594
902
  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.`);
595
903
  }
596
- function readPackageJson(root) {
597
- const packageJsonPath = resolve(root, "package.json");
598
- if (!existsSync(packageJsonPath)) return {};
599
- try {
600
- return JSON.parse(readFileSync(packageJsonPath, "utf8"));
601
- } catch {
602
- return {};
603
- }
604
- }
605
- function runAppBuild(root, scripts) {
904
+ function runAppBuild(root, scripts, toStderr) {
606
905
  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.");
607
906
  if (Bun.spawnSync({
608
907
  cmd: [
@@ -611,7 +910,7 @@ function runAppBuild(root, scripts) {
611
910
  "build"
612
911
  ],
613
912
  cwd: root,
614
- stdout: "inherit",
913
+ stdout: toStderr ? 2 : "inherit",
615
914
  stderr: "inherit"
616
915
  }).exitCode !== 0) throw new Error("Cloudflare build: the app \"build\" script failed.");
617
916
  }
@@ -802,9 +1101,15 @@ function renderOAuthProvider(mcpPath, defaultEntry) {
802
1101
  resourceMetadata: { scopes_supported: ['tools:read'] },
803
1102
  })`;
804
1103
  }
1104
+ /** Substituted at bundle time, by wrangler or by the bundler `cf` delegates to. */
1105
+ const WORKER_VARS = { NODE_ENV: "production" };
1106
+ const BUNDLE_DEFINES = {
1107
+ "process.env.NODE_ENV": "\"production\"",
1108
+ "import.meta.url": "\"file:///worker.js\""
1109
+ };
805
1110
  function scaffoldWranglerConfig(root, out, packageName, mcpOAuth, agents) {
806
1111
  const configPath = resolve(root, "wrangler.jsonc");
807
- const appName = (packageName ?? "guren-app").replace(/^@[^/]+\//, "");
1112
+ const appName = workerName(packageName);
808
1113
  const outRelative = relative(root, out).split(sep).join("/");
809
1114
  const config = {
810
1115
  name: appName,
@@ -812,10 +1117,7 @@ function scaffoldWranglerConfig(root, out, packageName, mcpOAuth, agents) {
812
1117
  compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
813
1118
  compatibility_flags: ["nodejs_compat"],
814
1119
  alias: devOnlyAliases(outRelative),
815
- define: {
816
- "process.env.NODE_ENV": "\"production\"",
817
- "import.meta.url": "\"file:///worker.js\""
818
- },
1120
+ define: BUNDLE_DEFINES,
819
1121
  assets: {
820
1122
  directory: `${outRelative}/assets`,
821
1123
  html_handling: HTML_HANDLING
@@ -823,10 +1125,9 @@ function scaffoldWranglerConfig(root, out, packageName, mcpOAuth, agents) {
823
1125
  d1_databases: [{
824
1126
  binding: "DB",
825
1127
  database_name: appName,
826
- database_id: "TODO: wrangler d1 create",
827
1128
  migrations_dir: `${outRelative}/d1-migrations`
828
1129
  }],
829
- ...mcpOAuth ? { kv_namespaces: [oauthKvNamespace()] } : {},
1130
+ ...mcpOAuth ? { kv_namespaces: [OAUTH_KV_NAMESPACE] } : {},
830
1131
  ...agents.length > 0 ? {
831
1132
  durable_objects: { bindings: agents.map((agent) => ({
832
1133
  name: durableObjectBindingName(agent.export),
@@ -837,7 +1138,7 @@ function scaffoldWranglerConfig(root, out, packageName, mcpOAuth, agents) {
837
1138
  new_sqlite_classes: agents.map((agent) => agent.export)
838
1139
  }]
839
1140
  } : {},
840
- vars: { NODE_ENV: "production" }
1141
+ vars: WORKER_VARS
841
1142
  };
842
1143
  try {
843
1144
  writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { flag: "wx" });
@@ -848,9 +1149,8 @@ function scaffoldWranglerConfig(root, out, packageName, mcpOAuth, agents) {
848
1149
  }
849
1150
  throw error;
850
1151
  }
851
- const notes = ["fill in d1_databases[0].database_id"];
852
- if (mcpOAuth) notes.push(`create the ${OAUTH_KV_BINDING} namespace (wrangler kv namespace create ${OAUTH_KV_BINDING}) and fill in its id`);
853
- console.log(`Cloudflare build: scaffolded ${configPath} — ${notes.join(", and ")} before deploying.`);
1152
+ const created = mcpOAuth ? `the D1 database "${appName}" and the ${OAUTH_KV_BINDING} namespace` : `the D1 database "${appName}"`;
1153
+ console.log(`Cloudflare build: scaffolded ${configPath} with no resource ids. The first \`wrangler deploy\` (Wrangler 4.129 or later) creates ${created}, or connects to an existing one of that name on the account. The worker serves an empty database until you apply migrations right after it:\n wrangler d1 migrations apply ${appName} --remote`);
854
1154
  console.log(` Scheduled tasks need a cron trigger — add "triggers": { "crons": ["* * * * *"] } to run them. The worker runs whichever tasks are due at each firing, so a trigger coarser than your finest task means that task never runs.`);
855
1155
  }
856
1156
  /**
@@ -977,7 +1277,7 @@ function warnMissingHtmlHandling(configPath, config) {
977
1277
  * OAuth. A warning: a non-OAuth worker from the same repository is legitimate.
978
1278
  */
979
1279
  function warnOAuthDrift(configPath, config, mcpOAuth) {
980
- if (mcpOAuth || !oauthKvBinding(config)) return;
1280
+ if (mcpOAuth || !bindsOAuthKv(config)) return;
981
1281
  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.`);
982
1282
  }
983
1283
  //#endregion
@@ -1094,6 +1394,11 @@ function renderBundleReport(size, attribution, options = {}) {
1094
1394
  lines
1095
1395
  };
1096
1396
  }
1397
+ /** The size report runs wrangler's dry run on wrangler.jsonc, which an app on the cf backend does not deploy. */
1398
+ function assertSizeReportable(root, requestedBy = "Cloudflare size") {
1399
+ const app = resolve(root);
1400
+ if (detectCloudflareBackend(app) === "cf") throw new Error(`${requestedBy}: the size report measures the bundle wrangler.jsonc deploys, and ${app} deploys through cf (cloudflare.config.ts). Drop it; the cf build writes the bundle to .cloudflare/output/v0/workers/default/bundle/.`);
1401
+ }
1097
1402
  /**
1098
1403
  * Run wrangler's dry run on the assembled output and read what it would
1099
1404
  * upload. Needs no credentials. The metafile goes to a temporary directory
@@ -1102,6 +1407,7 @@ function renderBundleReport(size, attribution, options = {}) {
1102
1407
  */
1103
1408
  function reportBundleSize(options) {
1104
1409
  const root = resolve(options.root);
1410
+ assertSizeReportable(root);
1105
1411
  const outDir = mkdtempSync(join(tmpdir(), "guren-cf-size-"));
1106
1412
  const metafile = join(outDir, "meta.json");
1107
1413
  try {
@@ -1138,4 +1444,4 @@ function printBundleReport(report) {
1138
1444
  if (report.warn) console.warn(`Cloudflare size: the worker bundle is ${percent(report.share)} of the platform limit. The largest sources above are where to look; generated content belongs in Workers Static Assets, KV or R2 rather than in the bundle.`);
1139
1445
  }
1140
1446
  //#endregion
1141
- export { printBundleReport as a, buildCloudflareOutput as c, parseWranglerSize as i, flattenD1Migrations as l, WORKER_SIZE_WARN_SHARE as n, renderBundleReport as o, attributeBundle as r, reportBundleSize as s, WORKER_SIZE_LIMIT as t };
1447
+ export { readPackageJson as A, workerName as C, readLocalMigrations as D, migrationDirArgs as E, detectCloudflareBackend as O, readWranglerConfig as S, fingerprintMigrations as T, flattenD1Migrations as _, parseWranglerSize as a, readResolvedResources as b, reportBundleSize as c, assembleCloudflareOutput as d, assertAgentsPluginUsable as f, durableObjectStorage as g, durableObjectBindings as h, attributeBundle as i, isRecord as k, OAUTH_KV_BINDING as l, configScopes as m, WORKER_SIZE_WARN_SHARE as n, printBundleReport as o, buildCloudflareOutput as p, assertSizeReportable as r, renderBundleReport as s, WORKER_SIZE_LIMIT as t, asArray as u, isPlaceholderId as v, decideLayout as w, readWorkerManifest as x, readAgentRegistry as y };