@slotform/cloudflare 0.0.0-stage → 0.1.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.
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ import { z } from "zod";
2
+ export const cloudflareOptionsSchema = z.object({}).optional();
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC"}
@@ -0,0 +1,61 @@
1
+ # Deploy to Cloudflare
2
+
3
+ `slotform deploy` ships the worker, and with `vite()` the web client, to Cloudflare Workers. Work the steps in order; each names the
4
+ page it needs and ends with its check.
5
+
6
+ ## What `slotform deploy` does
7
+
8
+ 1. Runs `slotform build`, which regenerates `.slotform/`, builds the web client to `dist/client` and
9
+ writes `dist/client/_headers`, which makes every asset unframeable (`frame-ancestors 'none'`,
10
+ `X-Frame-Options: DENY`): a Slotform app is never framed and has no option to be. A
11
+ `public/_headers` fails the build; remove it.
12
+ 2. Runs every pre-deploy check. With a D1 database: a placeholder `databaseId`, a schema change
13
+ with no committed migration, or a newest migration that drops a table or column without its
14
+ `-- slotform:allow-destructive` marker each stop the deploy here.
15
+ 3. Lists the plan (the committed migrations) and, in a terminal, asks to proceed.
16
+ 4. Applies the pending migrations to the remote database, then `src/schema/seed.ts` when it
17
+ exists: an upsert of the seeded rows, and a prune of the rows it does not list only when the
18
+ seed exports `prune = true` (`plugins/db/guide/seed.md`).
19
+ 5. Runs `wrangler deploy --config .slotform/wrangler.toml`, which uploads the worker and, with
20
+ `vite()`, `dist/client` as its static assets. The worker answers its own paths (`/rpc/*`,
21
+ `/api/auth/*`); any other path is a file from `dist/client`, else its `index.html`.
22
+
23
+ ## 1. Sign in to Cloudflare
24
+
25
+ Run `pnpm exec wrangler login`, or set `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` where
26
+ the deploy runs. Put `account_id` in the root `wrangler.toml` when the login reaches more than
27
+ one account. Page: [wrangler](./wrangler.md).
28
+
29
+ **Check:** `pnpm exec wrangler whoami` names the account.
30
+
31
+ ## 2. Point at real resources
32
+
33
+ `db({ dialect: "d1", databaseId })` holds the remote database's id, never a placeholder. A route
34
+ or a custom domain goes in the root `wrangler.toml` as `[[routes]]`. With `src/worker/queue.ts`, create
35
+ the app's queue once before the first deploy, under the name `slotform generate` writes as the `queue`
36
+ in `.slotform/wrangler.toml` (`app.name` lowercased, every other character run a `-`):
37
+ `pnpm exec wrangler queues create <that name>`. Queues and Browser
38
+ Rendering need a Workers plan that offers them. Page: [wrangler](./wrangler.md).
39
+
40
+ **Check:** `slotform generate` exits cleanly, and `.slotform/wrangler.toml` names the database id and
41
+ the routes; with a queue, `pnpm exec wrangler queues list` names it.
42
+
43
+ ## 3. Set every secret
44
+
45
+ Each declared env var's production value is a secret, set once per var. List them from `.dev.vars` (every line but `SLOTFORM_DEV`) and set each:
46
+
47
+ ```bash
48
+ pnpm exec wrangler secret put AUTH_SECRET --config .slotform/wrangler.toml
49
+ ```
50
+
51
+ `AUTH_SECRET` is 32 characters or more; `APP_URL` is the app's public `https://` URL. Page: auth's
52
+ config page (`node_modules/@slotform/auth/guide/config.md`) for auth's vars.
53
+
54
+ **Check:** `pnpm exec wrangler secret list --config .slotform/wrangler.toml` lists every var.
55
+
56
+ ## 4. Deploy
57
+
58
+ Commit the migrations, then run `pnpm run deploy` (`pnpm deploy` is pnpm's own command).
59
+
60
+ **Check:** the deploy ends with `Deployed`, and a request to the worker answers: one with a
61
+ missing secret fails its first request with `Missing env var: <NAME>`.
@@ -0,0 +1,90 @@
1
+ # Wrangler config and env
2
+
3
+ `slotform generate` writes `.slotform/wrangler.toml` from what the plugins contribute: the database, the
4
+ rate limiters, the compatibility flags, every declared env var, and with `vite()` the web
5
+ client's `[assets]`. Never edit it. Settings of your
6
+ own go in a root `wrangler.toml`, which generate merges in.
7
+
8
+ ## The root `wrangler.toml`
9
+
10
+ | Section | Merge |
11
+ | --- | --- |
12
+ | `[[d1_databases]]`, `[[kv_namespaces]]`, `[[analytics_engine_datasets]]`, `[[unsafe.bindings]]`, `compatibility_flags`, `[assets]` | Owned by the plugins: generate fails when the root file has one |
13
+ | `[[routes]]`, `[[r2_buckets]]`, `[[queues.producers]]`, `[[queues.consumers]]` | Yours merge beside the plugins'. A route pattern, a binding name or a consumed queue both sides declare fails generate. The plugins' own queue is one producer `QUEUE` and its consumer, on the queue named after `app.name` (lowercased, every other character run a `-`), present when `src/worker/queue.ts` exists; a root consumer without that file fails generate |
14
+ | `[triggers]` | Copied, and checked against `src/worker/scheduled.ts`: `crons` without the file, or the file with no cron, fails generate |
15
+ | `[browser]` | Copied as written: `binding = "BROWSER"` types `env.BROWSER` |
16
+ | `name`, `compatibility_date`, `main` | Yours win; otherwise `app.name` (lowercased, every other character run a `-`), the plugin's pinned date and the generated worker |
17
+ | `[vars]` | Yours merge with the plugins'; a key both declare fails generate |
18
+ | Anything else (`account_id`, `observability`) | Copied as written |
19
+
20
+ Every name reaching `env` (a binding, a var, a secret) is unique across all of them, or generate
21
+ fails naming both sides.
22
+
23
+ ```toml
24
+ # wrangler.toml
25
+ account_id = "…"
26
+
27
+ [[routes]]
28
+ pattern = "api.example.com/*"
29
+ zone_name = "example.com"
30
+
31
+ [[r2_buckets]]
32
+ binding = "UPLOADS"
33
+ bucket_name = "my-app-uploads"
34
+
35
+ [triggers]
36
+ crons = ["*/10 * * * *", "0 7 * * *"]
37
+
38
+ [browser]
39
+ binding = "BROWSER"
40
+ ```
41
+
42
+ wrangler reads the generated file, so a relative path in the root file resolves against `.slotform/`:
43
+ prefix it with `../`.
44
+
45
+ ## `.dev.vars`
46
+
47
+ `.dev.vars` at the root holds the dev values: `SLOTFORM_DEV=1` and every declared env var at its dev
48
+ default, auth's `AUTH_SECRET` and `APP_URL` among them. It is yours to edit, and gitignored.
49
+ Generate only appends what it lacks (`SLOTFORM_DEV`, a var declared since) and mirrors the file into
50
+ `.slotform/.dev.vars`, where wrangler reads it: after an edit, run `slotform generate` or restart
51
+ `pnpm dev`. A var your own code reads is declared with
52
+ `api({ env: [{ name, devDefault }] })`, never added to `.dev.vars` alone.
53
+
54
+ ## `Env`
55
+
56
+ `slotform generate` runs `wrangler types` into `.slotform/worker-configuration.d.ts`, which declares the
57
+ global `Env`: every binding and var, a `.dev.vars` var typed `string`. Type the worker's env with
58
+ it (`AuthCallbacks<Env>`). `Env` types the procedure context too: a handler's `context.env` is
59
+ `Env`, so `context.env.APP_URL` is a `string` and a var `Env` lacks is a type error. When `wrangler types` fails, generate warns and removes the file, so
60
+ `Env` stops resolving rather than going stale: run
61
+ `pnpm exec wrangler types .slotform/worker-configuration.d.ts -c .slotform/wrangler.toml` to see why.
62
+
63
+ ## Local state
64
+
65
+ `slotform dev` runs `wrangler dev` on `http://localhost:8787`, keeping the local D1, KV and caches
66
+ in `.wrangler/state` at the root, gitignored. The db plugin's local commands read the same
67
+ directory, so deleting it resets the local database. With `vite()` in the config, the dev server
68
+ proxies the worker's paths (`/rpc`, `/api/auth`), so the browser calls the worker on the page's
69
+ own origin, and `slotform generate` creates `dist/client` empty until the first build fills it.
70
+
71
+ A queue runs locally with no setup: a send to `env.QUEUE` reaches the `src/worker/queue.ts` handler in the
72
+ same `wrangler dev`. A cron never fires by itself locally; request the wrangler port to run one, naming
73
+ the expression from `[triggers]` (wrangler 4.156 needs no flag):
74
+
75
+ ```bash
76
+ curl "http://localhost:8787/cdn-cgi/local/scheduled?cron=0+7+*+*+*"
77
+ ```
78
+
79
+ It answers `ok` when the handler returned and a 500 when it threw. `/cdn-cgi/handler/scheduled` is
80
+ the older spelling of the same path. Local Browser Rendering downloads a headless Chrome on first use, so
81
+ the first `env.BROWSER` launch waits for it and needs network access.
82
+
83
+ ## Rules
84
+
85
+ - Set a deployed secret with `wrangler secret put`, never in a `[vars]` table or a committed file:
86
+ see [deploy](./deploy.md).
87
+ - Never set `SLOTFORM_DEV` outside `.dev.vars`: it switches the worker to dev origins and dev
88
+ checks.
89
+
90
+ **Check:** `slotform generate` exits cleanly, then `pnpm check` passes.
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@slotform/cloudflare",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "The Cloudflare Workers target for slotform: renders the wrangler config and runs wrangler for dev, types and deploy.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/fcalell/slotform.git",
9
+ "directory": "plugins/cloudflare"
10
+ },
11
+ "homepage": "https://github.com/fcalell/slotform/tree/master/plugins/cloudflare#readme",
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "engines": {
16
+ "node": ">=24.14.0"
17
+ },
18
+ "type": "module",
19
+ "sideEffects": false,
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "src",
29
+ "guide",
30
+ "README.md",
31
+ "LICENSE",
32
+ "!src/**/*.test.ts",
33
+ "!src/**/__fixtures__",
34
+ "!dist/**/*.test.*"
35
+ ],
36
+ "dependencies": {
37
+ "@slotform/cli": "^0.1.1",
38
+ "@slotform/api": "^0.1.1",
39
+ "@slotform/screens": "^0.1.1",
40
+ "@slotform/vite": "^0.1.1",
41
+ "smol-toml": "^1.9.1"
42
+ },
43
+ "devDependencies": {
44
+ "@slotform/typescript-config": "^0.1.1",
45
+ "@types/node": "^26.6.6",
46
+ "typescript": "^7.0.2",
47
+ "zod": "^4.6.7"
48
+ },
49
+ "peerDependencies": {
50
+ "zod": "^4.6.7"
51
+ },
52
+ "scripts": {
53
+ "build": "tsc -p tsconfig.build.json",
54
+ "check-types": "tsc --noEmit --pretty",
55
+ "clear": "rm -rf dist node_modules .turbo",
56
+ "test": "node --test 'src/**/*.test.ts'"
57
+ }
6
58
  }
package/src/index.ts ADDED
@@ -0,0 +1,422 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { join } from "node:path";
5
+ import { api } from "@slotform/api";
6
+ import {
7
+ type ContributionCtx,
8
+ GENERATED_DIR,
9
+ plugin,
10
+ type Slot,
11
+ slot,
12
+ } from "@slotform/cli";
13
+ import type { TsTypeRef } from "@slotform/cli/ast";
14
+ import { cliSlots, emitArtifact } from "@slotform/cli/cli-slots";
15
+ import { screens } from "@slotform/screens";
16
+ import { startServer } from "@slotform/screens/node";
17
+ import { vite } from "@slotform/vite";
18
+ import {
19
+ aggregateDevVars,
20
+ aggregateWrangler,
21
+ escapeDevVarValue,
22
+ sanitizeWranglerName,
23
+ } from "./node/codegen.ts";
24
+ import { assertEnvName, declaresDevVar } from "./node/dev-vars.ts";
25
+ import {
26
+ cloudflareOptionsSchema,
27
+ type ServeConfig,
28
+ type WranglerBindingSpec,
29
+ } from "./types.ts";
30
+
31
+ const SOURCE = "cloudflare";
32
+
33
+ // The pinned default compatibility date: docs/architecture/plugins/cloudflare.md, "Compatibility date".
34
+ const DEFAULT_COMPATIBILITY_DATE = "2025-01-01";
35
+
36
+ // `wrangler dev`'s listen port, passed explicitly so the dev process and the
37
+ // worker's dev origin agree.
38
+ const WRANGLER_DEV_PORT = 8787;
39
+ const DEV_ORIGIN = `http://localhost:${WRANGLER_DEV_PORT}`;
40
+
41
+ const WRANGLER_CONFIG = `${GENERATED_DIR}/wrangler.toml`;
42
+ const WORKER_TYPES = `${GENERATED_DIR}/worker-configuration.d.ts`;
43
+
44
+ // Miniflare's state dir, shared with the `db` plugin: docs/architecture/plugins/cloudflare.md, "Local state".
45
+ export const LOCAL_PERSIST = ".wrangler/state";
46
+
47
+ // ── Slot declarations ──────────────────────────────────────────────
48
+ //
49
+ // Bindings compose into wranglerToml: docs/architecture/plugins/cloudflare.md, "Slots and contributions".
50
+
51
+ const bindings = slot.list<WranglerBindingSpec>({
52
+ source: SOURCE,
53
+ name: "bindings",
54
+ });
55
+
56
+ const compatibilityFlags = slot.list<string>({
57
+ source: SOURCE,
58
+ name: "compatibilityFlags",
59
+ });
60
+
61
+ // Seeded from the pinned constant, never the wall clock: docs/architecture/plugins/cloudflare.md, "Compatibility date".
62
+ const compatibilityDate = slot.value<string>({
63
+ source: SOURCE,
64
+ name: "compatibilityDate",
65
+ seed: () => DEFAULT_COMPATIBILITY_DATE,
66
+ });
67
+
68
+ // The final wrangler.toml source, a pure derivation: docs/architecture/plugins/cloudflare.md, "Slots and contributions".
69
+ const wranglerInputs = {
70
+ bindings,
71
+ env: api.slots.env,
72
+ compatibilityDate,
73
+ compatibilityFlags,
74
+ clientDir: vite.slots.outDir,
75
+ routePrefixes: api.slots.routePrefixes,
76
+ queueHandler: api.slots.queueHandler,
77
+ scheduledHandler: api.slots.scheduledHandler,
78
+ };
79
+
80
+ type WranglerInputs = {
81
+ [K in keyof typeof wranglerInputs]: (typeof wranglerInputs)[K] extends Slot<
82
+ infer T
83
+ >
84
+ ? T
85
+ : never;
86
+ };
87
+
88
+ // The consumer's root `wrangler.toml`, or null without one.
89
+ async function consumerWrangler(ctx: ContributionCtx): Promise<string | null> {
90
+ return (await ctx.fileExists("wrangler.toml"))
91
+ ? ctx.readFile("wrangler.toml")
92
+ : null;
93
+ }
94
+
95
+ function renderWrangler(
96
+ inp: WranglerInputs,
97
+ ctx: ContributionCtx,
98
+ consumer: string | null,
99
+ serve: ServeConfig | undefined,
100
+ ): string {
101
+ return aggregateWrangler({
102
+ consumerWrangler: consumer,
103
+ payload: {
104
+ bindings: inp.bindings,
105
+ secrets: inp.env,
106
+ compatibilityDate: inp.compatibilityDate,
107
+ compatibilityFlags: inp.compatibilityFlags,
108
+ clientDir: inp.clientDir,
109
+ routePrefixes: inp.routePrefixes,
110
+ queueHandler: inp.queueHandler !== null,
111
+ scheduledHandler: inp.scheduledHandler !== null,
112
+ serve,
113
+ },
114
+ name: ctx.app.name,
115
+ log: ctx.log,
116
+ });
117
+ }
118
+
119
+ const wranglerToml = slot.derived({
120
+ source: SOURCE,
121
+ name: "wranglerToml",
122
+ inputs: wranglerInputs,
123
+ compute: async (inp, ctx) =>
124
+ renderWrangler(inp, ctx, await consumerWrangler(ctx), undefined),
125
+ });
126
+
127
+ // The config of a `slotform screens serve` run: the same toml with the run's own
128
+ // entry and client build, as a function of them.
129
+ const serveWranglerToml = slot.derived({
130
+ source: SOURCE,
131
+ name: "serveWranglerToml",
132
+ inputs: wranglerInputs,
133
+ compute: async (inp, ctx) => {
134
+ const consumer = await consumerWrangler(ctx);
135
+ return (serve: ServeConfig) => renderWrangler(inp, ctx, consumer, serve);
136
+ },
137
+ });
138
+
139
+ // The --config and --tsconfig every bundling command reads: docs/architecture/plugins/cloudflare.md, "Wrangler invocation".
140
+ async function wranglerConfigArgs(ctx: ContributionCtx): Promise<string[]> {
141
+ const tsconfig = await ctx.resolve(cliSlots.workerTsconfig);
142
+ return ["--config", WRANGLER_CONFIG, "--tsconfig", join(ctx.cwd, tsconfig)];
143
+ }
144
+
145
+ const SLOTFORM_DEV_LINE =
146
+ "# SLOTFORM_DEV marks local dev; never set in production.\nSLOTFORM_DEV=1\n";
147
+
148
+ // The dev values, and whether the root `.dev.vars` is written: docs/architecture/plugins/cloudflare.md, ".dev.vars".
149
+ async function devVars(
150
+ ctx: ContributionCtx,
151
+ ): Promise<{ content: string; write: boolean }> {
152
+ const env = await ctx.resolve(api.slots.env);
153
+ for (const e of env) assertEnvName(e.name);
154
+ if (!(await ctx.fileExists(".dev.vars"))) {
155
+ return {
156
+ content: `${SLOTFORM_DEV_LINE}${aggregateDevVars(env) ?? ""}`,
157
+ write: true,
158
+ };
159
+ }
160
+ const existing = await ctx.readFile(".dev.vars");
161
+ const declared = (name: string) => declaresDevVar(existing, name);
162
+ const missing = `${declared("SLOTFORM_DEV") ? "" : SLOTFORM_DEV_LINE}${
163
+ aggregateDevVars(env.filter((e) => !declared(e.name))) ?? ""
164
+ }`;
165
+ if (!missing) return { content: existing, write: false };
166
+ const separator = existing === "" || existing.endsWith("\n") ? "" : "\n";
167
+ return { content: `${existing}${separator}${missing}`, write: true };
168
+ }
169
+
170
+ export const cloudflare = plugin("cloudflare", {
171
+ label: "Cloudflare",
172
+
173
+ schema: cloudflareOptionsSchema,
174
+
175
+ devDependencies: {
176
+ wrangler: "^4.162.0",
177
+ },
178
+ gitignore: [".wrangler", ".dev.vars"],
179
+
180
+ guide: [
181
+ {
182
+ page: "wrangler",
183
+ trigger:
184
+ "Editing the root `wrangler.toml` or `.dev.vars`, adding a binding or route, or typing `Env`",
185
+ },
186
+ { page: "deploy", trigger: "Deploying the app to Cloudflare" },
187
+ ],
188
+
189
+ slots: {
190
+ bindings,
191
+ compatibilityDate,
192
+ compatibilityFlags,
193
+ wranglerToml,
194
+ serveWranglerToml,
195
+ },
196
+
197
+ contributes: (self) => [
198
+ emitArtifact(WRANGLER_CONFIG, self.slots.wranglerToml),
199
+
200
+ // The blanket per-IP volume limiter: docs/architecture/plugins/api.md, "Rate limiting".
201
+ self.slots.bindings.contribute(async (ctx) => {
202
+ if ((await ctx.resolve(api.slots.routePrefixes)).length === 0) {
203
+ return undefined;
204
+ }
205
+ return {
206
+ kind: "rate_limiter" as const,
207
+ binding: "RATE_LIMITER_RPC",
208
+ simple: { limit: 1000, period: 60 },
209
+ };
210
+ }),
211
+
212
+ // The app's one queue: docs/architecture/plugins/cloudflare.md, "wrangler.toml merge contract".
213
+ self.slots.bindings.contribute(async (ctx) => {
214
+ if ((await ctx.resolve(api.slots.queueHandler)) === null) {
215
+ return undefined;
216
+ }
217
+ return {
218
+ kind: "queue" as const,
219
+ binding: "QUEUE",
220
+ queue: sanitizeWranglerName(ctx.app.name),
221
+ consumer: { maxBatchSize: 10, maxBatchTimeout: 5, maxRetries: 3 },
222
+ };
223
+ }),
224
+
225
+ // Emit .dev.vars and mirror it into .slotform/: docs/architecture/plugins/cloudflare.md, ".dev.vars".
226
+ cliSlots.artifactFiles.contribute(async (ctx) => {
227
+ const { content, write } = await devVars(ctx);
228
+ return [
229
+ ...(write ? [{ path: ".dev.vars", content }] : []),
230
+ {
231
+ path: `${GENERATED_DIR}/.dev.vars`,
232
+ content: `# Generated mirror of ../.dev.vars — edit that file, then re-run slotform generate.\n${content}`,
233
+ },
234
+ ];
235
+ }),
236
+
237
+ // The global `Env` `wrangler types` declares types the worker's `env`:
238
+ // `.slotform/worker.ts` and `.slotform/procedure.ts` render `createWorker<Env>(…)`.
239
+ api.slots.envType.contribute(
240
+ (): TsTypeRef => ({ kind: "reference", name: "Env" }),
241
+ ),
242
+
243
+ // The worker's own dev origin: docs/architecture/plugins/api.md, "Local and dev origins".
244
+ api.slots.devTargetOrigins.contribute((ctx) =>
245
+ ctx.app.origins !== undefined ? undefined : DEV_ORIGIN,
246
+ ),
247
+
248
+ // Same-origin dev proxy, inert without vite: docs/architecture/plugins/vite.md, "Dev server proxy, file access and watching".
249
+ vite.slots.serverProxy.contribute(async (ctx) => {
250
+ const prefixes = await ctx.resolve(api.slots.routePrefixes);
251
+ return prefixes.map((path) => ({ path, target: DEV_ORIGIN }));
252
+ }),
253
+
254
+ // Ignore .slotform/.wrangler so Vite never reloads on it: docs/architecture/plugins/cloudflare.md, "Dev and Vite root".
255
+ vite.slots.watchIgnored.contribute(() => "**/.wrangler/**"),
256
+
257
+ // The shared --config and --persist-to, outside .slotform/: docs/architecture/plugins/cloudflare.md, "Local state".
258
+ cliSlots.devProcesses.contribute(async (ctx) => ({
259
+ name: "wrangler",
260
+ command: "npx",
261
+ args: [
262
+ "wrangler",
263
+ "dev",
264
+ ...(await wranglerConfigArgs(ctx)),
265
+ "--port",
266
+ String(WRANGLER_DEV_PORT),
267
+ "--persist-to",
268
+ LOCAL_PERSIST,
269
+ ],
270
+ defaultPort: WRANGLER_DEV_PORT,
271
+ readyPattern: /Ready on/,
272
+ })),
273
+
274
+ // The screens serve target: docs/architecture/plugins/cloudflare.md, "Screens serve".
275
+ screens.slots.serveTargets.contribute(async (ctx) => {
276
+ if ((await ctx.resolve(api.slots.workerSource)) === null) {
277
+ return undefined;
278
+ }
279
+ const render = await ctx.resolve(self.slots.serveWranglerToml);
280
+ // The run's entry sits outside the app, so it names the controls by path.
281
+ const require = createRequire(join(ctx.cwd, "package.json"));
282
+ const controls = require.resolve("@slotform/screens/serve");
283
+ const named = await ctx.resolve(screens.slots.serveControls);
284
+ const extra = named.map((spec) => require.resolve(spec));
285
+ const { content: devValues } = await devVars(ctx);
286
+ const tsconfig = join(
287
+ ctx.cwd,
288
+ await ctx.resolve(cliSlots.workerTsconfig),
289
+ );
290
+ return {
291
+ name: "cloudflare",
292
+ async start(serve) {
293
+ const main = join(serve.dir, "worker.ts");
294
+ writeFileSync(
295
+ main,
296
+ [
297
+ `import { fixtureControls } from ${JSON.stringify(controls)};`,
298
+ ...extra.map(
299
+ (path, i) => `import c${i} from ${JSON.stringify(path)};`,
300
+ ),
301
+ `import worker from ${JSON.stringify(join(ctx.cwd, GENERATED_DIR, "worker.ts"))};`,
302
+ `export default fixtureControls(worker${extra.map((_, i) => `, c${i}`).join("")});`,
303
+ "",
304
+ ].join("\n"),
305
+ );
306
+ const config = join(serve.dir, "wrangler.toml");
307
+ writeFileSync(config, render({ main, clientDir: serve.client }));
308
+ const overrides = Object.entries(serve.env)
309
+ .map(([name, value]) => `${name}=${escapeDevVarValue(value)}`)
310
+ .join("\n");
311
+ writeFileSync(
312
+ join(serve.dir, ".dev.vars"),
313
+ `${devValues}\n${overrides}\n`,
314
+ );
315
+ return startServer(
316
+ serve,
317
+ "wrangler",
318
+ "npx",
319
+ [
320
+ "wrangler",
321
+ "dev",
322
+ "--config",
323
+ config,
324
+ "--tsconfig",
325
+ tsconfig,
326
+ "--ip",
327
+ "127.0.0.1",
328
+ "--port",
329
+ String(serve.port),
330
+ "--persist-to",
331
+ serve.state,
332
+ ],
333
+ ctx.env,
334
+ );
335
+ },
336
+ };
337
+ }),
338
+
339
+ cliSlots.deploySteps.contribute(async (ctx) => ({
340
+ name: "Worker",
341
+ phase: "main",
342
+ exec: {
343
+ command: "npx",
344
+ args: ["wrangler", "deploy", ...(await wranglerConfigArgs(ctx))],
345
+ },
346
+ })),
347
+
348
+ // The _headers step: docs/architecture/plugins/cloudflare.md, "Client headers".
349
+ cliSlots.buildSteps.contribute(async (ctx) => {
350
+ const clientDir = await ctx.resolve(vite.slots.outDir);
351
+ const headers = await ctx.resolve(vite.slots.clientHeaders);
352
+ const names = Object.keys(headers).sort();
353
+ if (clientDir === null || names.length === 0) return undefined;
354
+ return {
355
+ name: "client-headers",
356
+ phase: "post" as const,
357
+ run: async () => {
358
+ const file = join(ctx.cwd, clientDir, "_headers");
359
+ if (existsSync(file)) {
360
+ throw new Error(
361
+ "public/_headers is refused: Slotform writes the web client's _headers from vite.slots.clientHeaders, and Cloudflare joins a header two rules set. Remove public/_headers.",
362
+ );
363
+ }
364
+ const rules = names.map((n) => ` ${n}: ${headers[n]}`).join("\n");
365
+ writeFileSync(file, `/*\n${rules}\n`);
366
+ },
367
+ };
368
+ }),
369
+
370
+ // wrangler refuses to start when `assets.directory` is missing, which it
371
+ // is until the first `slotform build`; an empty one serves nothing and
372
+ // lets `wrangler dev` run on a fresh clone.
373
+ cliSlots.postWrite.contribute((ctx) => async () => {
374
+ const clientDir = await ctx.resolve(vite.slots.outDir);
375
+ if (clientDir !== null) {
376
+ mkdirSync(join(ctx.cwd, clientDir), { recursive: true });
377
+ }
378
+ }),
379
+
380
+ // wrangler types after the toml is written, non-fatal: docs/architecture/plugins/cloudflare.md, "Wrangler invocation".
381
+ cliSlots.postWrite.contribute((ctx) => async () => {
382
+ // A failed removal (a locked file) is a warning of its own, so it
383
+ // never masks the wrangler error being reported.
384
+ const removeStaleDts = () => {
385
+ try {
386
+ rmSync(join(ctx.cwd, WORKER_TYPES), { force: true });
387
+ } catch (err) {
388
+ const detail = err instanceof Error ? err.message : String(err);
389
+ ctx.log.warn(`${WORKER_TYPES} could not be removed: ${detail}`);
390
+ }
391
+ };
392
+
393
+ const result = spawnSync(
394
+ "npx",
395
+ ["wrangler", "types", WORKER_TYPES, "-c", WRANGLER_CONFIG],
396
+ { cwd: ctx.cwd, stdio: "pipe", env: ctx.env },
397
+ );
398
+ if (result.error) {
399
+ removeStaleDts();
400
+ const err = result.error;
401
+ const hint =
402
+ "code" in err && err.code === "ENOENT"
403
+ ? "npx not found on PATH; install Node.js or wrangler and re-run `slotform generate`."
404
+ : err.message;
405
+ ctx.log.warn(
406
+ `wrangler types could not run (Env typings removed to surface the failure): ${hint}`,
407
+ );
408
+ return;
409
+ }
410
+ if (result.status !== 0) {
411
+ removeStaleDts();
412
+ const stderr = result.stderr?.toString().trim() ?? "";
413
+ ctx.log.warn(
414
+ `wrangler types failed (Env typings removed to surface the failure)${stderr ? `: ${stderr}` : ""}. ` +
415
+ `Run \`pnpm exec wrangler types ${WORKER_TYPES} -c ${WRANGLER_CONFIG}\` manually to see the full error.`,
416
+ );
417
+ }
418
+ }),
419
+ ],
420
+ });
421
+
422
+ export type { WranglerBindingSpec } from "./types.ts";