@guren/plugin-vercel 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +24 -18
  2. package/dist/index.js +194 -169
  3. package/package.json +5 -5
package/dist/index.d.ts CHANGED
@@ -1,28 +1,34 @@
1
- import { ServiceProviderConstructor } from '@guren/core';
2
- import { PathLike } from '@guren/core/internal/deploy-build';
3
-
1
+ import { ServiceProviderConstructor } from "@guren/core";
2
+ import { DatabaseDialect, PathLike } from "@guren/core/internal/deploy-build";
3
+ //#region src/index.d.ts
4
4
  interface VercelAppLike {
5
- boot(): Promise<void>;
6
- fetch(request: Request): Response | Promise<Response>;
5
+ boot(): Promise<void>;
6
+ fetch(request: Request): Response | Promise<Response>;
7
7
  }
8
8
  interface VercelHandler {
9
- fetch(request: Request): Response | Promise<Response>;
9
+ fetch(request: Request): Response | Promise<Response>;
10
10
  }
11
11
  interface BuildVercelOutputOptions {
12
- rootDir?: PathLike;
13
- entrypoint?: PathLike;
14
- outputDir?: PathLike;
15
- publicDir?: PathLike;
16
- docsDir?: PathLike;
17
- ssrDir?: PathLike;
18
- migrationsDir?: PathLike;
12
+ rootDir?: PathLike;
13
+ entrypoint?: PathLike;
14
+ outputDir?: PathLike;
15
+ publicDir?: PathLike;
16
+ docsDir?: PathLike;
17
+ ssrDir?: PathLike;
18
+ migrationsDir?: PathLike;
19
+ /**
20
+ * Databases this app connects to, overriding what is read from
21
+ * `config/database.ts`. Every other dialect's client is stubbed out of the
22
+ * bundle. Pass this when the config reaches a factory without naming it and
23
+ * the build reports that it could not tell.
24
+ */
25
+ databaseDialects?: readonly DatabaseDialect[];
19
26
  }
20
27
  /**
21
28
  * Configuration for the Vercel plugin. Currently empty — reserved so future
22
29
  * fields never force another registration-shape change.
23
30
  */
24
- interface VercelPluginConfig {
25
- }
31
+ interface VercelPluginConfig {}
26
32
  /**
27
33
  * Register the Vercel plugin.
28
34
  *
@@ -33,6 +39,6 @@ interface VercelPluginConfig {
33
39
  */
34
40
  declare function vercelPlugin(config?: VercelPluginConfig): ServiceProviderConstructor;
35
41
  declare function createVercelHandler(app: VercelAppLike): Promise<VercelHandler>;
36
- declare function buildVercelOutput(options?: BuildVercelOutputOptions): void;
37
-
38
- export { type BuildVercelOutputOptions, type VercelAppLike, type VercelHandler, type VercelPluginConfig, buildVercelOutput, createVercelHandler, vercelPlugin };
42
+ declare function buildVercelOutput(options?: BuildVercelOutputOptions): Promise<void>;
43
+ //#endregion
44
+ export { BuildVercelOutputOptions, VercelAppLike, VercelHandler, VercelPluginConfig, buildVercelOutput, createVercelHandler, vercelPlugin };
package/dist/index.js CHANGED
@@ -1,180 +1,205 @@
1
- // src/index.ts
2
- import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
3
- import { basename, extname, resolve } from "path";
1
+ import { cpSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { basename, extname, resolve } from "node:path";
4
3
  import { definePlugin } from "@guren/core";
5
- import {
6
- assertOutputDirOutsideRoot,
7
- resetOutputDir,
8
- resolveClientAssetEnv,
9
- resolvePathLike,
10
- resolveSsrEntryFile,
11
- ssrRuntimePaths
12
- } from "@guren/core/internal/deploy-build";
13
- var LABEL = "Vercel build";
14
- var factory = definePlugin({
15
- name: "vercel",
16
- register() {
17
- }
4
+ import { DEV_ONLY_MODULES, MCP_SDK_SUBPATH_PREFIX, assertOutputDirOutsideRoot, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, unusedSqlClients } from "@guren/core/internal/deploy-build";
5
+ //#region src/index.ts
6
+ /** Prefixes every diagnostic this build emits. */
7
+ const LABEL = "Vercel build";
8
+ const factory = definePlugin({
9
+ name: "vercel",
10
+ register() {}
18
11
  });
12
+ /**
13
+ * Register the Vercel plugin.
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * createApp({ providers: [vercelPlugin()] })
18
+ * ```
19
+ */
19
20
  function vercelPlugin(config = {}) {
20
- return factory(config);
21
+ return factory(config);
21
22
  }
22
23
  async function createVercelHandler(app) {
23
- await app.boot();
24
- return {
25
- fetch(request) {
26
- return app.fetch(request);
27
- }
28
- };
24
+ await app.boot();
25
+ return { fetch(request) {
26
+ return app.fetch(request);
27
+ } };
29
28
  }
30
- function buildVercelOutput(options = {}) {
31
- const root = resolvePathLike(options.rootDir ?? new URL("..", import.meta.url));
32
- const out = resolvePathLike(options.outputDir ?? resolve(root, ".vercel/output"));
33
- const funcDir = resolve(out, "functions/index.func");
34
- const entrypoint = resolvePathLike(options.entrypoint ?? resolve(root, "src/vercel.ts"));
35
- const handler = `${basename(entrypoint, extname(entrypoint))}.js`;
36
- const publicDir = resolvePathLike(options.publicDir ?? resolve(root, "public"));
37
- const docsDir = resolvePathLike(options.docsDir ?? resolveNearestDocsDir(root) ?? resolve(root, "docs"));
38
- const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
39
- const migrationsDir = resolvePathLike(options.migrationsDir ?? resolve(root, "db/migrations"));
40
- assertOutputDirOutsideRoot(out, root, LABEL);
41
- if (!existsSync(entrypoint)) {
42
- throw new Error(
43
- `${LABEL}: entrypoint not found at ${entrypoint}. Run \`bunx guren plugin @guren/plugin-vercel\` to scaffold src/vercel.ts, or pass "entrypoint".`
44
- );
45
- }
46
- const env = buildVercelEnvironment(publicDir, ssrDir);
47
- resetOutputDir(out, root, LABEL);
48
- mkdirSync(funcDir, { recursive: true });
49
- mkdirSync(resolve(out, "static"), { recursive: true });
50
- writeFileSync(
51
- resolve(out, "config.json"),
52
- JSON.stringify(
53
- {
54
- version: 3,
55
- routes: [
56
- // Built assets self-reference the Vite plugin's derived base,
57
- // `/public/assets/`, while the files themselves are copied to the
58
- // output root. Without this the entry script still loads — its path
59
- // is injected directly — but every chunk it imports falls through
60
- // to the function and comes back as HTML.
61
- //
62
- // A `rewrites` entry in vercel.json only covers builds Vercel runs
63
- // itself; a `--prebuilt` upload is routed by this file alone, which
64
- // is the flow the deployment guide documents.
65
- { src: "/public/(.*)", dest: "/$1" },
66
- { handle: "filesystem" },
67
- { src: "/(.*)", dest: "/index" }
68
- ]
69
- },
70
- null,
71
- 2
72
- )
73
- );
74
- writeFileSync(
75
- resolve(funcDir, ".vc-config.json"),
76
- JSON.stringify(
77
- {
78
- handler,
79
- runtime: "bun1.x",
80
- launcherType: "Nodejs",
81
- shouldAddHelpers: true,
82
- environment: env
83
- },
84
- null,
85
- 2
86
- )
87
- );
88
- const result = Bun.spawnSync({
89
- // `bun build` inlines `process.env.NODE_ENV` at bundle time (defaulting to
90
- // "development"), so pin it to "production" for the deployed function.
91
- //
92
- // Whitespace and syntax only — never plain `--minify`, which also mangles
93
- // identifiers. Guren keys durable records on class names: the queue
94
- // registry stores each job's wire name (its class name unless it declares a
95
- // jobName) in every queued message, and notifications persist
96
- // `constructor.name` as their `type`. Mangled, a job dispatched by one
97
- // deploy resolves to nothing after the next.
98
- //
99
- // Not `--keep-names`: as of Bun 1.3.14 it is accepted and silently leaves
100
- // class names mangled, so it cannot replace this.
101
- cmd: [
102
- "bun",
103
- "build",
104
- entrypoint,
105
- "--outdir",
106
- funcDir,
107
- "--target",
108
- "bun",
109
- "--minify-whitespace",
110
- "--minify-syntax",
111
- "--define",
112
- 'process.env.NODE_ENV="production"'
113
- ],
114
- cwd: root,
115
- stdout: "inherit",
116
- stderr: "inherit"
117
- });
118
- if (result.exitCode !== 0) {
119
- throw new Error("bun build failed");
120
- }
121
- if (existsSync(ssrDir)) {
122
- cpSync(ssrDir, resolve(funcDir, ".guren/ssr"), { recursive: true });
123
- }
124
- if (existsSync(migrationsDir)) {
125
- cpSync(migrationsDir, resolve(funcDir, "db/migrations"), { recursive: true });
126
- }
127
- if (existsSync(docsDir)) {
128
- cpSync(docsDir, resolve(funcDir, "docs"), { recursive: true });
129
- }
130
- if (existsSync(publicDir)) {
131
- cpSync(publicDir, resolve(out, "static"), { recursive: true });
132
- }
29
+ async function buildVercelOutput(options = {}) {
30
+ const root = resolvePathLike(options.rootDir ?? new URL("..", import.meta.url));
31
+ const out = resolvePathLike(options.outputDir ?? resolve(root, ".vercel/output"));
32
+ const funcDir = resolve(out, "functions/index.func");
33
+ const entrypoint = resolvePathLike(options.entrypoint ?? resolve(root, "src/vercel.ts"));
34
+ const handler = `${basename(entrypoint, extname(entrypoint))}.js`;
35
+ const publicDir = resolvePathLike(options.publicDir ?? resolve(root, "public"));
36
+ const docsDir = resolvePathLike(options.docsDir ?? resolveNearestDocsDir(root) ?? resolve(root, "docs"));
37
+ const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
38
+ const migrationsDir = resolvePathLike(options.migrationsDir ?? resolve(root, "db/migrations"));
39
+ assertOutputDirOutsideRoot(out, root, LABEL);
40
+ if (!existsSync(entrypoint)) throw new Error(`${LABEL}: entrypoint not found at ${entrypoint}. Run \`bunx guren plugin @guren/plugin-vercel\` to scaffold src/vercel.ts, or pass "entrypoint".`);
41
+ const env = buildVercelEnvironment(publicDir, ssrDir);
42
+ resetOutputDir(out, root, LABEL);
43
+ mkdirSync(funcDir, { recursive: true });
44
+ mkdirSync(resolve(out, "static"), { recursive: true });
45
+ writeFileSync(resolve(out, "config.json"), JSON.stringify({
46
+ version: 3,
47
+ routes: [
48
+ {
49
+ src: "/public/(.*)",
50
+ dest: "/$1"
51
+ },
52
+ { handle: "filesystem" },
53
+ {
54
+ src: "/(.*)",
55
+ dest: "/index"
56
+ }
57
+ ]
58
+ }, null, 2));
59
+ writeFileSync(resolve(funcDir, ".vc-config.json"), JSON.stringify({
60
+ handler,
61
+ runtime: "bun1.x",
62
+ launcherType: "Nodejs",
63
+ shouldAddHelpers: true,
64
+ environment: env
65
+ }, null, 2));
66
+ await bundleFunction({
67
+ entrypoint,
68
+ funcDir,
69
+ root,
70
+ dialects: options.databaseDialects
71
+ });
72
+ if (existsSync(ssrDir)) cpSync(ssrDir, resolve(funcDir, ".guren/ssr"), { recursive: true });
73
+ if (existsSync(migrationsDir)) cpSync(migrationsDir, resolve(funcDir, "db/migrations"), { recursive: true });
74
+ if (existsSync(docsDir)) cpSync(docsDir, resolve(funcDir, "docs"), { recursive: true });
75
+ if (existsSync(publicDir)) cpSync(publicDir, resolve(out, "static"), { recursive: true });
76
+ }
77
+ const MCP_UNAVAILABLE = "The MCP endpoint is unavailable on Vercel — it generates files on disk, and the function filesystem is read-only.";
78
+ /**
79
+ * Why each dev-only module cannot run here, or `null` for one that can and is
80
+ * therefore left alone.
81
+ *
82
+ * `sqlite` is the `null`, and it is written as an entry rather than filtered
83
+ * out somewhere else so the decision sits where the reason does: the function
84
+ * runs on Vercel's Bun runtime, so `bun:sqlite` is a working database here —
85
+ * unlike on Workers and Lambda, whose tables name a replacement for it.
86
+ * Stubbing it would break an app that ships a read-only sqlite file beside
87
+ * its function.
88
+ *
89
+ * Keyed on every kind `DEV_ONLY_MODULES` contains, so a kind added there is a
90
+ * compile error here rather than a module that silently stubs to `undefined`.
91
+ */
92
+ const UNAVAILABLE_ON_VERCEL = {
93
+ sqlite: null,
94
+ vite: "The Vite dev server is unavailable on Vercel — assets are served from the static output directory.",
95
+ mcp: MCP_UNAVAILABLE
96
+ };
97
+ /**
98
+ * Modules replaced with throwing stubs, in the order they are matched.
99
+ *
100
+ * Two separate reasons, both of them the same defect shape — a *literal*
101
+ * dynamic import of a package the app never installed, which a bundler
102
+ * follows whether or not the branch can be taken:
103
+ *
104
+ * - The dev-only ones. A scaffolded app could not be bundled for Vercel at
105
+ * all: the disabled MCP endpoint's `import("@guren/cli")` resolves, and the
106
+ * CLI's own `import("@guren/openapi")` behind it does not. Lambda never saw
107
+ * this because it has stubbed these since it shipped.
108
+ * - The database clients for dialects the app does not use, decided per app
109
+ * rather than per platform — the ones it *does* use are load-bearing here,
110
+ * unlike on Workers where D1 is the only database.
111
+ */
112
+ function stubbedModules(root, dialects) {
113
+ const devOnly = DEV_ONLY_MODULES.flatMap((module) => {
114
+ const message = UNAVAILABLE_ON_VERCEL[module.kind];
115
+ return message === null ? [] : [[module.specifier, renderDevOnlyStub(module, message)]];
116
+ });
117
+ const unused = unusedSqlClients({
118
+ root,
119
+ label: LABEL,
120
+ dialects
121
+ }).map(({ module, message }) => [module.specifier, renderDevOnlyStub(module, message)]);
122
+ return Object.fromEntries([...devOnly, ...unused]);
123
+ }
124
+ /**
125
+ * Fallback for an MCP SDK subpath `DEV_ONLY_MODULES` does not name. It cannot
126
+ * know which names the importer destructures, so it throws on evaluation
127
+ * rather than resolving to an empty module: a subpath reached from app code
128
+ * (not Guren's disabled MCP endpoint) must fail loudly at build or cold start,
129
+ * never silently hand back missing exports.
130
+ */
131
+ const unlistedMcpStub = `throw new Error(${JSON.stringify(MCP_UNAVAILABLE)})\n`;
132
+ /**
133
+ * Bundle the function with Bun's JS API rather than by spawning `bun build`.
134
+ *
135
+ * The CLI has no way to replace a module — no alias flag, no plugin flag — and
136
+ * this build needs one, which is why this platform had no stub mechanism at
137
+ * all while the other two did. The API takes plugins.
138
+ */
139
+ async function bundleFunction(input) {
140
+ const stubs = stubbedModules(input.root, input.dialects);
141
+ const filter = new RegExp(`^(?:${[...Object.keys(stubs).map(escapeRegExp), `${escapeRegExp(MCP_SDK_SUBPATH_PREFIX)}.+`].join("|")})$`);
142
+ const result = await Bun.build({
143
+ entrypoints: [input.entrypoint],
144
+ throw: false,
145
+ outdir: input.funcDir,
146
+ target: "bun",
147
+ minify: {
148
+ whitespace: true,
149
+ syntax: true,
150
+ identifiers: false
151
+ },
152
+ define: { "process.env.NODE_ENV": "\"production\"" },
153
+ plugins: [{
154
+ name: "guren-vercel-stubs",
155
+ setup(build) {
156
+ build.onResolve({ filter }, (args) => ({
157
+ path: args.path,
158
+ namespace: "guren-vercel-stub"
159
+ }));
160
+ build.onLoad({
161
+ filter: /.*/,
162
+ namespace: "guren-vercel-stub"
163
+ }, (args) => ({
164
+ contents: stubs[args.path] ?? unlistedMcpStub,
165
+ loader: "js"
166
+ }));
167
+ }
168
+ }]
169
+ });
170
+ if (!result.success) throw new Error(`${LABEL}: bun build failed.\n${result.logs.map((log) => String(log)).join("\n")}`);
171
+ }
172
+ function escapeRegExp(value) {
173
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
133
174
  }
134
175
  function buildVercelEnvironment(publicDir, ssrDir) {
135
- const env = {
136
- NODE_ENV: "production",
137
- BUN_RUNTIME_TRANSPILER_CACHE_PATH: "/tmp/.bun-cache",
138
- BUN_INSTALL_CACHE_DIR: "/tmp/.bun-install-cache",
139
- TMPDIR: "/tmp"
140
- };
141
- const assetEnv = resolveClientAssetEnv(publicDir, "resources/js/app.tsx", LABEL);
142
- if (assetEnv.entry) {
143
- env.GUREN_INERTIA_ENTRY = assetEnv.entry;
144
- }
145
- if (assetEnv.styles) {
146
- env.GUREN_INERTIA_STYLES = assetEnv.styles;
147
- }
148
- const ssrFile = resolveSsrEntryFile(ssrDir, "resources/js/ssr.tsx", LABEL);
149
- if (ssrFile) {
150
- const ssrPaths = ssrRuntimePaths(ssrDir, ssrFile, "./.guren/ssr");
151
- env.GUREN_INERTIA_SSR_ENTRY = ssrPaths.entry;
152
- if (ssrPaths.manifest) {
153
- env.GUREN_INERTIA_SSR_MANIFEST = ssrPaths.manifest;
154
- }
155
- }
156
- env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify({
157
- "@guren/inertia-client": "/vendor/inertia-client.tsx"
158
- });
159
- return env;
176
+ const env = {
177
+ NODE_ENV: "production",
178
+ BUN_RUNTIME_TRANSPILER_CACHE_PATH: "/tmp/.bun-cache",
179
+ BUN_INSTALL_CACHE_DIR: "/tmp/.bun-install-cache",
180
+ TMPDIR: "/tmp"
181
+ };
182
+ const assetEnv = resolveClientAssetEnv(publicDir, "resources/js/app.tsx", LABEL);
183
+ if (assetEnv.entry) env.GUREN_INERTIA_ENTRY = assetEnv.entry;
184
+ if (assetEnv.styles) env.GUREN_INERTIA_STYLES = assetEnv.styles;
185
+ const ssrFile = resolveSsrEntryFile(ssrDir, "resources/js/ssr.tsx", LABEL);
186
+ if (ssrFile) {
187
+ const ssrPaths = ssrRuntimePaths(ssrDir, ssrFile, "./.guren/ssr");
188
+ env.GUREN_INERTIA_SSR_ENTRY = ssrPaths.entry;
189
+ if (ssrPaths.manifest) env.GUREN_INERTIA_SSR_MANIFEST = ssrPaths.manifest;
190
+ }
191
+ env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify({ "@guren/inertia-client": "/vendor/inertia-client.tsx" });
192
+ return env;
160
193
  }
161
194
  function resolveNearestDocsDir(startDir, maxDepth = 6) {
162
- let currentDir = startDir;
163
- for (let depth = 0; depth < maxDepth; depth += 1) {
164
- const candidate = resolve(currentDir, "docs");
165
- if (existsSync(candidate)) {
166
- return candidate;
167
- }
168
- const parent = resolve(currentDir, "..");
169
- if (parent === currentDir) {
170
- break;
171
- }
172
- currentDir = parent;
173
- }
174
- return void 0;
195
+ let currentDir = startDir;
196
+ for (let depth = 0; depth < maxDepth; depth += 1) {
197
+ const candidate = resolve(currentDir, "docs");
198
+ if (existsSync(candidate)) return candidate;
199
+ const parent = resolve(currentDir, "..");
200
+ if (parent === currentDir) break;
201
+ currentDir = parent;
202
+ }
175
203
  }
176
- export {
177
- buildVercelOutput,
178
- createVercelHandler,
179
- vercelPlugin
180
- };
204
+ //#endregion
205
+ export { buildVercelOutput, createVercelHandler, vercelPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-vercel",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -30,16 +30,16 @@
30
30
  }
31
31
  },
32
32
  "scripts": {
33
- "build": "tsup",
33
+ "build": "bun --bun tsdown",
34
34
  "test": "bun test",
35
35
  "typecheck": "tsc --noEmit"
36
36
  },
37
37
  "dependencies": {
38
- "@guren/core": "^1.4.0"
38
+ "@guren/core": "^1.8.1"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/node": "^20.14.10",
42
- "tsup": "^8.5.0",
43
- "typescript": "^5.4.0"
42
+ "tsdown": "^0.22.14",
43
+ "typescript": "^7.0.2"
44
44
  }
45
45
  }