@guren/plugin-cloudflare 0.10.1 → 0.12.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,7 +1,7 @@
1
1
  import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join, relative, resolve, sep } from "node:path";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
- import { AGENTS_CONFIG_FILE, DATABASE_FACTORIES, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, MCP_PLUGIN_PACKAGE, MCP_TRANSPORT_SPECIFIER, SQL_CLIENT_MODULES, appUsesMcpPlugin, assertOutputDirOutsideRoot, clientManifestJson, detectDatabaseDialects, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, stageStaticAssets, stubbableDevOnlyModules } from "@guren/core/internal/deploy-build";
4
+ 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
5
  import { reportDeployRuntimeHazards } from "@guren/core/internal/deploy-check";
6
6
  import { tmpdir } from "node:os";
7
7
  //#region src/templates.ts
@@ -55,12 +55,10 @@ async function buildCloudflareOutput(options = {}) {
55
55
  assertOutputDirOutsideRoot(out, root, "Cloudflare build");
56
56
  assertWranglerJsoncIsAuthoritative(root);
57
57
  const packageJson = readPackageJson(root);
58
- const mcpPlugin = appUsesMcpPlugin(root);
59
58
  const mcpOAuth = options.mcpOAuth === true;
60
59
  const mcpPath = options.mcpPath ?? DEFAULT_MCP_PATH;
61
- assertMcpTransportNotAliased(root, mcpPlugin);
62
60
  if (mcpOAuth) {
63
- assertMcpOAuthUsable(root, mcpPlugin);
61
+ assertMcpOAuthUsable(root);
64
62
  assertOAuthKvBound(root);
65
63
  }
66
64
  const hostsAgents = existsSync(resolve(root, AGENTS_CONFIG_FILE));
@@ -77,13 +75,13 @@ async function buildCloudflareOutput(options = {}) {
77
75
  if (!existsSync(appEntry)) throw new Error(`Cloudflare build: app entry not found at ${appEntry}. Pass "appEntry" if your Application lives elsewhere.`);
78
76
  const ssrImport = await resolveSsrImport(ssrDir, ssrEntryKey);
79
77
  const assetEnv = resolveClientAssetEnv(publicDir, clientEntryKey, "Cloudflare build");
80
- const viteManifest = clientManifestJson(publicDir);
78
+ const bundledEnv = bundledRuntimeEnv(root, publicDir, "Cloudflare build");
81
79
  resetOutputDir(out, root, "Cloudflare build");
82
80
  stageStaticAssets(publicDir, resolve(out, "assets"));
83
81
  writeAssetHeaders(resolve(out, "assets"));
84
82
  const workerEnv = renderWorkerEnvModule({
85
83
  assetEnv,
86
- viteManifest
84
+ bundledEnv
87
85
  });
88
86
  if (workerEnv) writeFileSync(resolve(out, "worker-env.js"), workerEnv);
89
87
  writeFileSync(resolve(out, "worker.js"), renderWorkerModule({
@@ -100,9 +98,8 @@ async function buildCloudflareOutput(options = {}) {
100
98
  flattenD1Migrations(resolve(root, "db/migrations"), resolve(out, "d1-migrations"));
101
99
  writeDevOnlyStubs(out);
102
100
  if (mcpOAuth) scaffoldConsentFlow(root);
103
- scaffoldWranglerConfig(root, out, packageJson.name, mcpPlugin, mcpOAuth, agents.exports);
101
+ scaffoldWranglerConfig(root, out, packageJson.name, mcpOAuth, agents.exports);
104
102
  }
105
- const MCP_UNAVAILABLE = "The MCP endpoint is unavailable on Cloudflare Workers — it generates files on disk.";
106
103
  /** `mcpPlugin()`'s own default mount path — see `BuildCloudflareOutputOptions.mcpPath`. */
107
104
  const DEFAULT_MCP_PATH = "/mcp";
108
105
  /** The OAuth provider package the generated worker imports, installed by the app. */
@@ -124,8 +121,8 @@ const OAUTH_ENDPOINTS = {
124
121
  * `@cloudflare/workers-oauth-provider`, which wrangler resolves from the *app's*
125
122
  * `node_modules` at `wrangler deploy`, from a production install — not devDeps.
126
123
  */
127
- function assertMcpOAuthUsable(root, mcpPlugin) {
128
- 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 })
124
+ function assertMcpOAuthUsable(root) {
125
+ if (!appDependsOn(root, MCP_PLUGIN_PACKAGE)) 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 })
129
126
  Or drop --mcp-oauth to build the worker without the OAuth wrapping.`);
130
127
  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.`);
131
128
  }
@@ -165,9 +162,8 @@ function oauthKvNamespace() {
165
162
  };
166
163
  }
167
164
  /**
168
- * Whether the app declares `name` under `dependencies`. Same answer-shape as
169
- * `appUsesMcpPlugin` in `@guren/core/internal/deploy-build`: an absent,
170
- * unreadable or malformed manifest answers `false`.
165
+ * Whether the app declares `name` under `dependencies` (devDependencies do not
166
+ * ship). An absent, unreadable or malformed manifest answers `false`.
171
167
  */
172
168
  function appDependsOn(root, name) {
173
169
  try {
@@ -436,7 +432,7 @@ const STUBBED_MODULES = [...DEV_ONLY_MODULES, ...SQL_CLIENT_MODULES];
436
432
  const UNAVAILABLE_ON_WORKERS = {
437
433
  sqlite: "bun:sqlite is unavailable on Cloudflare Workers — use createD1Database().",
438
434
  vite: "The Vite dev server is unavailable on Cloudflare Workers — assets are served by Workers Static Assets.",
439
- mcp: MCP_UNAVAILABLE,
435
+ mcp: "The Dev MCP endpoint and docs viewer (@guren/cli) are unavailable on Cloudflare Workers — they read and generate files on disk.",
440
436
  "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."
441
437
  };
442
438
  /**
@@ -450,8 +446,6 @@ const STUB_FILES = {
450
446
  "bun:sqlite": "stub-bun-sqlite.js",
451
447
  vite: "stub-vite.js",
452
448
  "@guren/cli": "stub-guren-cli.js",
453
- "@modelcontextprotocol/sdk/server/mcp.js": "stub-mcp-server.js",
454
- "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js": "stub-mcp-transport.js",
455
449
  postgres: "stub-postgres.js",
456
450
  mysql2: "stub-mysql2.js",
457
451
  "mysql2/promise": "stub-mysql2-promise.js",
@@ -462,30 +456,10 @@ function writeDevOnlyStubs(out) {
462
456
  }
463
457
  /**
464
458
  * A package-name alias does not cover subpaths and wrangler cannot match a
465
- * prefix, so every stubbed specifier needs its own entry (an SDK subpath added
466
- * upstream needs a new `DEV_ONLY_MODULES` entry). `mcpPlugin` drops only the App
467
- * MCP transport's alias (RFC 0016 §7; the adapter is workerd-compatible). Stub
468
- * *files* are written unconditionally, so a config still pointing at one keeps finding it.
459
+ * prefix, so every stubbed specifier needs its own entry.
469
460
  */
470
- function devOnlyAliases(outRelative, mcpPlugin) {
471
- const stubbed = [...stubbableDevOnlyModules({ mcpPlugin }), ...SQL_CLIENT_MODULES];
472
- return Object.fromEntries(stubbed.map((module) => [module.specifier, `./${outRelative}/${STUB_FILES[module.specifier]}`]));
473
- }
474
- /**
475
- * Fail rather than deploy an app declaring `@guren/plugin-mcp` while its committed
476
- * `wrangler.jsonc` aliases the App MCP transport to a stub *this build generated*:
477
- * the endpoint stays compiled shut with every gate green. The *value* decides
478
- * (another target is a deliberate override), matched on the last path segment of
479
- * either separator against `STUB_FILES`; `parseJsonc` keeps comments from matching.
480
- */
481
- function assertMcpTransportNotAliased(root, mcpPlugin) {
482
- if (!mcpPlugin) return;
483
- const configPath = resolve(root, "wrangler.jsonc");
484
- const alias = readWranglerConfig(configPath)?.alias;
485
- if (!isRecord(alias)) return;
486
- const target = alias[MCP_TRANSPORT_SPECIFIER];
487
- if (typeof target !== "string" || target.split(/[\\/]/).pop() !== STUB_FILES[MCP_TRANSPORT_SPECIFIER]) return;
488
- 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.`);
461
+ function devOnlyAliases(outRelative) {
462
+ return Object.fromEntries(STUBBED_MODULES.map((module) => [module.specifier, `./${outRelative}/${STUB_FILES[module.specifier]}`]));
489
463
  }
490
464
  /**
491
465
  * Wrangler's `migrations_dir` only discovers flat `*.sql` files, but drizzle-kit
@@ -653,7 +627,7 @@ function renderWorkerEnvModule(input) {
653
627
  const lines = [];
654
628
  if (input.assetEnv.entry) lines.push(`process.env.GUREN_INERTIA_ENTRY = ${JSON.stringify(input.assetEnv.entry)}`);
655
629
  if (input.assetEnv.styles) lines.push(`process.env.GUREN_INERTIA_STYLES = ${JSON.stringify(input.assetEnv.styles)}`);
656
- if (input.viteManifest) lines.push(`process.env.GUREN_VITE_MANIFEST = ${JSON.stringify(input.viteManifest)}`);
630
+ for (const [key, value] of Object.entries(input.bundledEnv)) lines.push(`process.env.${key} = ${JSON.stringify(value)}`);
657
631
  if (lines.length === 0) return;
658
632
  return [
659
633
  "// Generated by `guren cloudflare:build`. Do not edit — regenerate instead.",
@@ -815,7 +789,7 @@ function renderOAuthProvider(mcpPath, defaultEntry) {
815
789
  resourceMetadata: { scopes_supported: ['tools:read'] },
816
790
  })`;
817
791
  }
818
- function scaffoldWranglerConfig(root, out, packageName, mcpPlugin, mcpOAuth, agents) {
792
+ function scaffoldWranglerConfig(root, out, packageName, mcpOAuth, agents) {
819
793
  const configPath = resolve(root, "wrangler.jsonc");
820
794
  const appName = (packageName ?? "guren-app").replace(/^@[^/]+\//, "");
821
795
  const outRelative = relative(root, out).split(sep).join("/");
@@ -824,7 +798,7 @@ function scaffoldWranglerConfig(root, out, packageName, mcpPlugin, mcpOAuth, age
824
798
  main: `${outRelative}/worker.js`,
825
799
  compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
826
800
  compatibility_flags: ["nodejs_compat"],
827
- alias: devOnlyAliases(outRelative, mcpPlugin),
801
+ alias: devOnlyAliases(outRelative),
828
802
  define: {
829
803
  "process.env.NODE_ENV": "\"production\"",
830
804
  "import.meta.url": "\"file:///worker.js\""
@@ -856,7 +830,7 @@ function scaffoldWranglerConfig(root, out, packageName, mcpPlugin, mcpOAuth, age
856
830
  writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { flag: "wx" });
857
831
  } catch (error) {
858
832
  if (error.code === "EEXIST") {
859
- warnMissingBuildOwnedKeys(configPath, outRelative, mcpPlugin, mcpOAuth);
833
+ warnMissingBuildOwnedKeys(configPath, outRelative, mcpOAuth);
860
834
  return;
861
835
  }
862
836
  throw error;
@@ -954,7 +928,7 @@ function parseJsonc(text) {
954
928
  * `bun:sqlite` or never applies its migrations. Named per entry, never as a whole
955
929
  * `"alias"`/`"define"` object, which reads as one to paste over the app's own entries.
956
930
  */
957
- function warnMissingBuildOwnedKeys(configPath, outRelative, mcpPlugin, mcpOAuth) {
931
+ function warnMissingBuildOwnedKeys(configPath, outRelative, mcpOAuth) {
958
932
  const config = readWranglerConfig(configPath);
959
933
  if (!config) {
960
934
  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.`);
@@ -962,7 +936,7 @@ function warnMissingBuildOwnedKeys(configPath, outRelative, mcpPlugin, mcpOAuth)
962
936
  }
963
937
  const missing = [];
964
938
  const alias = isRecord(config.alias) ? config.alias : {};
965
- for (const [specifier, target] of Object.entries(devOnlyAliases(outRelative, mcpPlugin))) if (!(specifier in alias)) missing.push(`${JSON.stringify(specifier)}: ${JSON.stringify(target)} (inside "alias")`);
939
+ for (const [specifier, target] of Object.entries(devOnlyAliases(outRelative))) if (!(specifier in alias)) missing.push(`${JSON.stringify(specifier)}: ${JSON.stringify(target)} (inside "alias")`);
966
940
  if (!config.define?.["process.env.NODE_ENV"]) missing.push("\"process.env.NODE_ENV\": \"\\\"production\\\"\" (inside \"define\")");
967
941
  const d1 = config.d1_databases?.[0];
968
942
  if (d1 && d1.migrations_dir !== `${outRelative}/d1-migrations`) missing.push(`"migrations_dir": "${outRelative}/d1-migrations" (inside d1_databases[0])`);
package/dist/commands.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as printBundleReport, c as buildCloudflareOutput, s as reportBundleSize } from "./bundle-size-CRMs5aKL.js";
1
+ import { a as printBundleReport, c as buildCloudflareOutput, s as reportBundleSize } from "./bundle-size-i1kLeIiR.js";
2
2
  import { defineCommand } from "citty";
3
3
  //#region src/commands.ts
4
4
  const rootArg = {
package/dist/index.d.ts CHANGED
@@ -20,9 +20,14 @@ interface WorkersScheduledEvent {
20
20
  interface WorkersAppLike {
21
21
  boot(): Promise<void>;
22
22
  fetch(request: Request, env?: unknown, executionCtx?: unknown): Response | Promise<Response>;
23
- /** Only the cron entrypoint reads it, so an app-like that never receives one still satisfies boot/fetch. */
23
+ /**
24
+ * Read by the cron entrypoint. `has`/`instance` bind the entrypoint env as
25
+ * `env.source` before boot (RFC 0027 §1); optional, so an existing app-like still boots.
26
+ */
24
27
  container?: {
25
28
  makeOptional<T>(key: string): T | undefined;
29
+ has?(key: string): boolean;
30
+ instance?(key: string, value: unknown): unknown;
26
31
  };
27
32
  }
28
33
  /**
package/dist/index.js CHANGED
@@ -1,8 +1,14 @@
1
1
  import { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, resetWorkersEnv } from "./env.js";
2
- import { a as printBundleReport, c as buildCloudflareOutput, i as parseWranglerSize, l as flattenD1Migrations, n as WORKER_SIZE_WARN_SHARE, o as renderBundleReport, r as attributeBundle, s as reportBundleSize, t as WORKER_SIZE_LIMIT } from "./bundle-size-CRMs5aKL.js";
2
+ import { a as printBundleReport, c as buildCloudflareOutput, i as parseWranglerSize, l as flattenD1Migrations, n as WORKER_SIZE_WARN_SHARE, o as renderBundleReport, r as attributeBundle, s as reportBundleSize, t as WORKER_SIZE_LIMIT } from "./bundle-size-i1kLeIiR.js";
3
3
  import { definePlugin } from "@guren/core";
4
4
  //#region src/boot.ts
5
5
  const latches = /* @__PURE__ */ new WeakMap();
6
+ /** Wrangler `vars` may be missing from `process.env`; a value the app or a test bound itself is kept. */
7
+ function bindEnvSource(app, env) {
8
+ const container = app.container;
9
+ if (!container?.has || !container.instance || env === null || typeof env !== "object") return;
10
+ if (!container.has("env.source")) container.instance("env.source", env);
11
+ }
6
12
  /**
7
13
  * Boot `app` against `env`, once per isolate.
8
14
  *
@@ -16,6 +22,7 @@ async function bootWorkersApp(app, env) {
16
22
  try {
17
23
  attempt = latches.get(app);
18
24
  if (!attempt) {
25
+ bindEnvSource(app, env);
19
26
  attempt = app.boot();
20
27
  latches.set(app, attempt);
21
28
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-cloudflare",
3
- "version": "0.10.1",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -47,7 +47,7 @@
47
47
  "typecheck": "tsc --noEmit"
48
48
  },
49
49
  "dependencies": {
50
- "@guren/core": "^1.18.0",
50
+ "@guren/core": "^1.20.0",
51
51
  "citty": "^0.1.6"
52
52
  },
53
53
  "devDependencies": {