@moku-labs/worker 0.9.2 → 0.11.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,4175 +0,0 @@
1
- import { envPlugin, logPlugin } from "@moku-labs/common";
2
- import { createCoreConfig, createCorePlugin } from "@moku-labs/core";
3
- import { brandedSink, createBrandConsole, createBrandPrompts } from "@moku-labs/common/cli";
4
- import { access, readdir, stat, writeFile } from "node:fs/promises";
5
- import path from "node:path";
6
- import { spawn } from "node:child_process";
7
- import { existsSync, readFileSync, watch } from "node:fs";
8
- /**
9
- * stage core plugin — deployment-stage / dev-mode detection, flat-injected on
10
- * every regular plugin's context as `ctx.stage` (spec/02 §6). No state, no
11
- * events, no depends, no lifecycle hooks.
12
- *
13
- * @see README.md
14
- * @example
15
- * ```typescript
16
- * // Inside any regular plugin's api factory:
17
- * api: (ctx) => ({
18
- * errorBody: (e: Error) =>
19
- * ctx.stage.isDev() ? e.stack ?? e.message : "Internal Error",
20
- * })
21
- * ```
22
- */
23
- const stagePlugin = createCorePlugin("stage", {
24
- config: { stage: "production" },
25
- /**
26
- * Builds the stage accessor surface from the resolved stage.
27
- *
28
- * @param ctx - Core plugin context (spec/02 §6 — `{ config, state }` only;
29
- * no `global`, `emit`, or `require`). `state` is unused by this plugin.
30
- * @param ctx.config - The resolved plugin config containing the deployment stage.
31
- * @returns The `ctx.stage` API: `isDev`, `isProduction`, `current`.
32
- * @example
33
- * ```typescript
34
- * const api = stagePlugin.spec.api({ config: { stage: "development" }, state: {} });
35
- * api.isDev(); // true
36
- * ```
37
- */
38
- api: ({ config }) => ({
39
- /**
40
- * Whether this Worker runs in the development stage.
41
- *
42
- * @returns True iff `stage === "development"`.
43
- * @example
44
- * ```typescript
45
- * if (ctx.stage.isDev()) return Response.json({ stack: err.stack });
46
- * ```
47
- */
48
- isDev: () => config.stage === "development",
49
- /**
50
- * Whether this Worker runs in the production stage. Note: false in "test".
51
- *
52
- * @returns True iff `stage === "production"`.
53
- * @example
54
- * ```typescript
55
- * const cc = ctx.stage.isProduction() ? "public, max-age=31536000" : "no-store";
56
- * ```
57
- */
58
- isProduction: () => config.stage === "production",
59
- /**
60
- * The raw deployment stage, as the literal union (not `string`).
61
- *
62
- * @returns The resolved stage.
63
- * @example
64
- * ```typescript
65
- * ctx.log.info("startup", { stage: ctx.stage.current() });
66
- * ```
67
- */
68
- current: () => config.stage
69
- })
70
- });
71
- const coreConfig = createCoreConfig("moku-worker", {
72
- config: {
73
- stage: "production",
74
- name: "moku-worker",
75
- compatibilityDate: ""
76
- },
77
- plugins: [
78
- logPlugin,
79
- envPlugin,
80
- stagePlugin
81
- ]
82
- });
83
- const { createPlugin, createCore } = coreConfig;
84
- //#endregion
85
- //#region src/plugins/bindings/api.ts
86
- /**
87
- * Checks whether a value read from an env object is nullish (null or undefined).
88
- * Cloudflare supplies either form when a binding is absent, so both must be caught.
89
- *
90
- * @param value - The value read from the env object.
91
- * @returns True when the value is null or undefined.
92
- * @example
93
- * ```typescript
94
- * isNullish(undefined); // true
95
- * isNullish(0); // false — falsy but bound
96
- * ```
97
- */
98
- const isNullish = (value) => value === void 0 || value === null;
99
- /**
100
- * Resolves binding `name` off a request-supplied env object, narrowed to T.
101
- * Throws a `[moku-worker]`-prefixed error when the binding is nullish.
102
- * The env argument is read but never retained.
103
- *
104
- * @param env - The Cloudflare request env object passed to fetch/scheduled/queue.
105
- * @param name - The binding name to resolve.
106
- * @returns The binding value narrowed to T.
107
- * @throws {Error} With a `[moku-worker]` prefix when the binding is null or undefined.
108
- * @example
109
- * ```typescript
110
- * const kv = requireBinding<KVNamespace>(env, "MY_KV");
111
- * ```
112
- */
113
- const requireBinding = (env, name) => {
114
- const value = env[name];
115
- if (isNullish(value)) throw new Error(`[moku-worker] binding "${name}" is not bound.\n Declare it in wrangler config and pass it in via the request env.`);
116
- return value;
117
- };
118
- /**
119
- * Returns true when `name` resolves to a non-nullish value on the request env.
120
- * Never throws. Use for optional-binding branching without forcing an error.
121
- *
122
- * @param env - The Cloudflare request env object passed to fetch/scheduled/queue.
123
- * @param name - The binding name to check.
124
- * @returns Whether the binding is present and non-nullish.
125
- * @example
126
- * ```typescript
127
- * const ok = hasBinding(env, "DB"); // false if DB is not bound
128
- * ```
129
- */
130
- const hasBinding = (env, name) => !isNullish(env[name]);
131
- /**
132
- * Builds the app.bindings API surface. The factory receives a context but does
133
- * not use it — bindings holds no state (F4) and all resolution is argument-local.
134
- *
135
- * @param _ctx - Plugin context (unused; bindings is stateless — F4).
136
- * @returns BindingsApi with `require` and `has` methods.
137
- * @example
138
- * ```typescript
139
- * const api = createBindingsApi(ctx);
140
- * const kv = api.require<KVNamespace>(env, "MY_KV");
141
- * ```
142
- */
143
- const createBindingsApi = (_ctx) => ({
144
- require: requireBinding,
145
- has: hasBinding
146
- });
147
- /**
148
- * Standard-tier stateless resolver — the binding-family dependency root.
149
- *
150
- * Exposes `require<T>(env, name)` and `has(env, name)` off a per-request env
151
- * object. Regular plugin so downstream binding plugins can declare
152
- * `depends: [bindingsPlugin]` and reach it via `ctx.require(bindingsPlugin)`.
153
- *
154
- * @see README.md
155
- */
156
- const bindingsPlugin = createPlugin("bindings", {
157
- config: { required: [] },
158
- api: createBindingsApi
159
- });
160
- //#endregion
161
- //#region src/instances.ts
162
- /**
163
- * Resolve the default instance key from a keyed-map config: the sole entry, or the one flagged
164
- * `default: true`. Throws a branded error when there are no instances, or several without (or with
165
- * more than one) `default: true`.
166
- *
167
- * @param instances - The keyed-map config (`Record<key, instance>`).
168
- * @param kind - The resource kind, for the error message (e.g. "kv", "d1").
169
- * @returns The default instance's key.
170
- * @throws {Error} With a `[moku-worker]` prefix when no single default can be resolved.
171
- * @example
172
- * ```ts
173
- * defaultInstanceKey({ main: { name: "db", binding: "DB" } }, "d1"); // "main"
174
- * ```
175
- */
176
- const defaultInstanceKey = (instances, kind) => {
177
- const keys = Object.keys(instances);
178
- if (keys.length === 0) throw new Error(`[moku-worker] No ${kind} instance is configured.`);
179
- if (keys.length === 1) return keys[0];
180
- const flagged = keys.filter((key) => instances[key]?.default === true);
181
- if (flagged.length === 1) return flagged[0];
182
- throw new Error(`[moku-worker] ${kind} has ${String(keys.length)} instances — mark exactly one with \`default: true\`.`);
183
- };
184
- /**
185
- * Look up a resource instance by key, with a branded error listing the configured keys when absent.
186
- *
187
- * @param instances - The keyed-map config (`Record<key, instance>`).
188
- * @param key - The instance key to resolve (the `use(key)` selector).
189
- * @param kind - The resource kind, for the error message.
190
- * @returns The instance at `key`.
191
- * @throws {Error} With a `[moku-worker]` prefix when `key` is not configured.
192
- * @example
193
- * ```ts
194
- * pickInstance(cfg, "analytics", "d1");
195
- * ```
196
- */
197
- const pickInstance = (instances, key, kind) => {
198
- const instance = instances[key];
199
- if (instance === void 0) {
200
- const configured = Object.keys(instances).join(", ") || "(none)";
201
- throw new Error(`[moku-worker] No ${kind} instance "${key}". Configured: ${configured}.`);
202
- }
203
- return instance;
204
- };
205
- //#endregion
206
- //#region src/plugins/d1/api.ts
207
- /**
208
- * Create the d1 api over a keyed map of database instances. The default-database methods and
209
- * `use(key)` both resolve the `D1Database` off the REQUEST-SUPPLIED env on every call — env is
210
- * threaded, never stored (SB4), so concurrent requests stay isolated — and the instance key is
211
- * resolved lazily by binding-getter so an unconfigured-but-present plugin only errors when actually
212
- * called.
213
- *
214
- * The return is intentionally NOT annotated `: Api`. Annotating it would
215
- * collapse the per-method call-site generic `<T>` on `query`/`first` to
216
- * `unknown`; instead the implementation forwards `<T>` to `all<T>()` /
217
- * `first<T>()` and `types.ts#Api` remains the public-surface source of truth.
218
- *
219
- * @param {D1Ctx} ctx - Plugin context (keyed-map config + require).
220
- * @returns {object} The d1 public api (query, first, run, batch, prepare, use, deployManifest).
221
- * @example
222
- * ```typescript
223
- * const api = createD1Api(ctx);
224
- * const { results } = await api.query<Product>(env, "SELECT * FROM products");
225
- * await api.use("analytics").run(env, "INSERT INTO events (name) VALUES (?)", "click");
226
- * ```
227
- */
228
- const createD1Api = (ctx) => {
229
- const bindings = ctx.require(bindingsPlugin);
230
- const surface = (binding) => {
231
- const db = (env) => bindings.require(env, binding());
232
- return {
233
- /**
234
- * Run a statement against this database and return all rows.
235
- *
236
- * @param env - The per-request Cloudflare env.
237
- * @param sql - SQL with `?` placeholders.
238
- * @param params - Bind parameters for the placeholders.
239
- * @returns All rows in a D1 result.
240
- * @example
241
- * ```typescript
242
- * const { results } = await api.query<Product>(env, "SELECT * FROM products");
243
- * ```
244
- */
245
- query: (env, sql, ...params) => db(env).prepare(sql).bind(...params).all(),
246
- /**
247
- * Run a statement against this database and return the first row, or null when none.
248
- *
249
- * @param env - The per-request Cloudflare env.
250
- * @param sql - SQL with `?` placeholders.
251
- * @param params - Bind parameters for the placeholders.
252
- * @returns The first row, or null if none.
253
- * @example
254
- * ```typescript
255
- * const product = await api.first<Product>(env, "SELECT * FROM products WHERE id = ?", 1);
256
- * ```
257
- */
258
- first: (env, sql, ...params) => db(env).prepare(sql).bind(...params).first(),
259
- /**
260
- * Run a write/DDL statement against this database and return its result meta.
261
- *
262
- * @param env - The per-request Cloudflare env.
263
- * @param sql - SQL with `?` placeholders.
264
- * @param params - Bind parameters for the placeholders.
265
- * @returns Result carrying `.meta`.
266
- * @example
267
- * ```typescript
268
- * await api.run(env, "INSERT INTO events (name) VALUES (?)", "click");
269
- * ```
270
- */
271
- run: (env, sql, ...params) => db(env).prepare(sql).bind(...params).run(),
272
- /**
273
- * Execute caller-built prepared statements atomically in one round-trip.
274
- *
275
- * @param env - The per-request Cloudflare env.
276
- * @param stmts - Caller-built prepared statements.
277
- * @returns One result per statement, order preserved.
278
- * @example
279
- * ```typescript
280
- * await api.batch(env, [api.prepare(env).prepare("INSERT INTO t (id) VALUES (1)")]);
281
- * ```
282
- */
283
- batch: (env, stmts) => db(env).batch(stmts),
284
- /**
285
- * Resolve the request `D1Database` so callers can build statements for `batch()`.
286
- *
287
- * @param env - The per-request Cloudflare env.
288
- * @returns The request-resolved database handle.
289
- * @example
290
- * ```typescript
291
- * const stmt = api.prepare(env).prepare("SELECT * FROM products");
292
- * ```
293
- */
294
- prepare: (env) => db(env)
295
- };
296
- };
297
- const defaultBinding = () => pickInstance(ctx.config, defaultInstanceKey(ctx.config, "d1"), "d1").binding;
298
- return {
299
- ...surface(defaultBinding),
300
- /**
301
- * Select a specific D1 database instance by its config key.
302
- *
303
- * @param key - The instance key (as configured under `pluginConfigs.d1`).
304
- * @returns The SQL surface bound to that database.
305
- * @example
306
- * ```typescript
307
- * await api.use("analytics").run(env, "INSERT INTO events (name) VALUES (?)", "click");
308
- * ```
309
- */
310
- use: (key) => surface(() => pickInstance(ctx.config, key, "d1").binding),
311
- /**
312
- * Return this plugin's deploy metadata — one descriptor per configured database.
313
- *
314
- * @returns One d1 deploy descriptor per instance.
315
- * @example
316
- * ```typescript
317
- * const manifest = api.deployManifest(); // [{ kind: "d1", name: "tracker-db", binding: "DB" }]
318
- * ```
319
- */
320
- deployManifest: () => Object.values(ctx.config).map((instance) => {
321
- const entry = {
322
- kind: "d1",
323
- name: instance.name,
324
- binding: instance.binding
325
- };
326
- if (instance.migrations !== void 0) entry.migrations = instance.migrations;
327
- return entry;
328
- })
329
- };
330
- };
331
- /**
332
- * Standard tier — Cloudflare D1 SQL access (thin typed wrappers, not an ORM).
333
- *
334
- * Exposes `query`, `first`, `run`, `batch`, `prepare`, and `deployManifest`.
335
- * Resolves the D1 binding off the per-request `env` via the bindings plugin.
336
- * No state, no events, no lifecycle hooks (request-scoped, spec/06 §3).
337
- *
338
- * @see README.md
339
- */
340
- const d1Plugin = createPlugin("d1", {
341
- depends: [bindingsPlugin],
342
- config: {},
343
- api: (ctx) => createD1Api(ctx)
344
- });
345
- //#endregion
346
- //#region src/plugins/durable-objects/api.ts
347
- /**
348
- * Builds the `app.durableObjects` API surface — `get` and `deployManifest`.
349
- *
350
- * All namespace resolution uses the per-call `env` argument: `env` is threaded, never
351
- * stored (SB4 / design §1a). The keyed-map config is frozen and read-only. No state
352
- * is held on the plugin between calls (stateless — `Record<string, never>`).
353
- *
354
- * @param ctx - Plugin context with the keyed-map `config`, `require(bindingsPlugin)`, and core APIs.
355
- * @returns The durableObjects API: `{ get, deployManifest }`.
356
- * @example
357
- * ```typescript
358
- * const api = createDoApi(ctx);
359
- * const stub = api.get(env, "board", "room-42");
360
- * const manifest = api.deployManifest(); // [{ kind: "do", binding: "BOARD", className: "BoardChannel" }]
361
- * ```
362
- */
363
- const createDoApi = (ctx) => ({
364
- /**
365
- * Resolves a `DurableObjectStub` off the per-request env.
366
- *
367
- * Selects the configured instance by `logicalName` (the config key) via `pickInstance`, resolves
368
- * its `binding` off `env`, derives a deterministic id via `namespace.idFromName(idName)`, and
369
- * returns the addressed stub. Synchronous — returns a stub, not a Promise. Throws (branded) when
370
- * `logicalName` is not configured, or (via the bindings resolver) when the binding is not present
371
- * on `env`.
372
- *
373
- * @param env - Per-request Cloudflare bindings object (Worker fetch/queue/scheduled env).
374
- * @param logicalName - Logical DO key (selects the configured instance, e.g. `"board"`).
375
- * @param idName - Stable id name passed to `idFromName` (e.g. `"room-42"`).
376
- * @returns The addressed `DurableObjectStub`.
377
- * @throws {Error} With `[moku-worker]` prefix when `logicalName` is not configured, or when the
378
- * binding is not bound on `env`.
379
- * @example
380
- * ```typescript
381
- * const stub = app.durableObjects.get(env, "board", "room-42");
382
- * const res = await stub.fetch("https://do/increment");
383
- * ```
384
- */
385
- get: (env, logicalName, idName) => {
386
- const binding = pickInstance(ctx.config, logicalName, "durableObjects").binding;
387
- const ns = ctx.require(bindingsPlugin).require(env, binding);
388
- return ns.get(ns.idFromName(idName));
389
- },
390
- /**
391
- * Returns this plugin's deploy metadata — one entry per configured instance, read by the `deploy`
392
- * plugin via `ctx.require(durableObjectsPlugin)`. Never reads sibling `pluginConfigs` (F6;
393
- * spec/08 §5, §7). Pure synchronous read of `ctx.config`.
394
- *
395
- * @returns One `{ kind: "do", binding, className }` per configured instance.
396
- * @example
397
- * ```typescript
398
- * const manifest = app.durableObjects.deployManifest();
399
- * // → [{ kind: "do", binding: "BOARD", className: "BoardChannel" }]
400
- * ```
401
- */
402
- deployManifest: () => Object.values(ctx.config).map((instance) => ({
403
- kind: "do",
404
- binding: instance.binding,
405
- className: instance.className
406
- }))
407
- });
408
- //#endregion
409
- //#region src/plugins/durable-objects/helpers.ts
410
- /**
411
- * Returns a base class the consumer extends and exports from `worker.ts`.
412
- *
413
- * PURE (spec/03 §1): takes no `ctx`, has no side effects, and may be called before
414
- * `createApp`. The static `doName` property captures `name` for diagnostics and
415
- * binding correlation. The constructor stores `(state, env)` as `this.ctx` / `this.env`,
416
- * satisfying the Cloudflare Durable Object constructor contract. The plugin NEVER
417
- * generates the final exported class — the consumer owns that class.
418
- *
419
- * @param name - Logical DO name; captured as `static doName` for diagnostics.
420
- * @returns A base class (constructor) the consumer extends.
421
- * @example
422
- * ```typescript
423
- * // src/counter.ts
424
- * import { defineDurableObject } from "@moku-labs/worker";
425
- *
426
- * export class Counter extends defineDurableObject("Counter") {
427
- * async fetch(): Promise<Response> {
428
- * const n = ((await this.ctx.storage.get<number>("n")) ?? 0) + 1;
429
- * await this.ctx.storage.put("n", n);
430
- * return Response.json({ n });
431
- * }
432
- * }
433
- * ```
434
- */
435
- const defineDurableObject = (name) => {
436
- /**
437
- * Base implementation of the Cloudflare Durable Object constructor contract.
438
- * Stores `(ctx, env)` as readonly properties for consumer subclasses to use.
439
- */
440
- class DurableObjectBaseImpl {
441
- /**
442
- * Cloudflare per-object storage/alarm context (DurableObjectState).
443
- * Use `this.ctx.storage` to read/write durable storage and `this.ctx.id` to inspect the DO id.
444
- */
445
- ctx;
446
- /**
447
- * Per-object Cloudflare bindings (per-request WorkerEnv).
448
- * Mirrors the env passed at construction time; never cached across requests.
449
- */
450
- env;
451
- /**
452
- * Logical DO name captured from `defineDurableObject(name)`.
453
- * Used for diagnostics and binding correlation.
454
- */
455
- static doName = name;
456
- /**
457
- * Constructs the base Durable Object with Cloudflare's required signature.
458
- *
459
- * @param ctx - Cloudflare DurableObjectState (storage, id, blockConcurrencyWhile, …).
460
- * @param env - Per-request Cloudflare bindings object (WorkerEnv).
461
- * @example
462
- * ```typescript
463
- * class Counter extends Base {
464
- * constructor(ctx: DurableObjectState, env: WorkerEnv) { super(ctx, env); }
465
- * }
466
- * ```
467
- */
468
- constructor(ctx, env) {
469
- this.ctx = ctx;
470
- this.env = env;
471
- }
472
- }
473
- return DurableObjectBaseImpl;
474
- };
475
- /**
476
- * Cloudflare Durable Objects plugin — Standard tier.
477
- *
478
- * Exposes `get(env, logicalName, idName)` (synchronous stub accessor, threaded env) and
479
- * `deployManifest()` (build-time metadata, one entry per configured instance). Depends on
480
- * `bindingsPlugin` for namespace resolution. The `defineDurableObject` helper is mounted under
481
- * `helpers` and re-exported at the top level for consumer use.
482
- *
483
- * @example
484
- * ```typescript
485
- * // Consumer endpoint handler:
486
- * const stub = app.durableObjects.get(env, "board", params.room!);
487
- * const res = await stub.fetch("https://do/increment");
488
- * // Consumer DO class (the EXPORTED className referenced by the "board" instance):
489
- * export class BoardChannel extends defineDurableObject("BoardChannel") {
490
- * async fetch(): Promise<Response> { return new Response("ok"); }
491
- * }
492
- * ```
493
- * @see README.md
494
- */
495
- const durableObjectsPlugin = createPlugin("durableObjects", {
496
- depends: [bindingsPlugin],
497
- config: {},
498
- api: createDoApi,
499
- helpers: { defineDurableObject }
500
- });
501
- //#endregion
502
- //#region src/plugins/kv/api.ts
503
- /**
504
- * Builds the app.kv.* api over a keyed map of namespace instances. The default-namespace methods and
505
- * `use(key)` both resolve the namespace off the REQUEST-SUPPLIED env on every call — env is threaded,
506
- * never stored (design §1a / SB4) — and the instance key is resolved lazily so an unconfigured-but-
507
- * present plugin only errors when actually called.
508
- *
509
- * @param ctx - The kv plugin context (keyed-map config + merged events).
510
- * @returns The app.kv api: get / put / delete / list / use / deployManifest.
511
- * @example
512
- * ```typescript
513
- * const api = createKvApi(ctx);
514
- * const value = await api.get(env, "key");
515
- * await api.use("sessions").put(env, "s:1", "data");
516
- * ```
517
- */
518
- const createKvApi = (ctx) => {
519
- const bindings = ctx.require(bindingsPlugin);
520
- const surface = (binding) => {
521
- const ns = (env) => bindings.require(env, binding());
522
- return {
523
- /**
524
- * Read a value by key from this namespace. Returns null when absent.
525
- *
526
- * @param env - The per-request Cloudflare env.
527
- * @param key - The key to read.
528
- * @returns The stored value, or null when absent.
529
- * @example
530
- * ```typescript
531
- * const value = await api.get(env, "feature-flags");
532
- * ```
533
- */
534
- get: async (env, key) => ns(env).get(key),
535
- /**
536
- * Write a string value under a key, optionally with KV put options.
537
- *
538
- * @param env - The per-request Cloudflare env.
539
- * @param key - The key to write.
540
- * @param value - The string value to store.
541
- * @param opts - Optional expiration / metadata.
542
- * @returns Resolves once the write is acknowledged.
543
- * @example
544
- * ```typescript
545
- * await api.put(env, "session:1", "data", { expirationTtl: 3600 });
546
- * ```
547
- */
548
- put: async (env, key, value, opts) => ns(env).put(key, value, opts),
549
- /**
550
- * Remove a key from this namespace (no-op if absent).
551
- *
552
- * @param env - The per-request Cloudflare env.
553
- * @param key - The key to delete.
554
- * @returns Resolves once the delete is acknowledged.
555
- * @example
556
- * ```typescript
557
- * await api.delete(env, "session:expired");
558
- * ```
559
- */
560
- delete: async (env, key) => ns(env).delete(key),
561
- /**
562
- * List keys in this namespace, optionally filtered/paginated.
563
- *
564
- * @param env - The per-request Cloudflare env.
565
- * @param opts - Optional prefix / cursor / limit.
566
- * @returns The list result.
567
- * @example
568
- * ```typescript
569
- * const { keys } = await api.list(env, { prefix: "session:" });
570
- * ```
571
- */
572
- list: async (env, opts) => ns(env).list(opts)
573
- };
574
- };
575
- const defaultBinding = () => pickInstance(ctx.config, defaultInstanceKey(ctx.config, "kv"), "kv").binding;
576
- return {
577
- ...surface(defaultBinding),
578
- /**
579
- * Select a specific KV namespace instance by its config key.
580
- *
581
- * @param key - The instance key (as configured under `pluginConfigs.kv`).
582
- * @returns The key/value surface bound to that namespace.
583
- * @example
584
- * ```typescript
585
- * await api.use("sessions").get(env, "s:1");
586
- * ```
587
- */
588
- use: (key) => surface(() => pickInstance(ctx.config, key, "kv").binding),
589
- /**
590
- * Return this plugin's deploy metadata — one descriptor per configured namespace.
591
- *
592
- * @returns One kv deploy descriptor per instance.
593
- * @example
594
- * ```typescript
595
- * const manifest = api.deployManifest(); // [{ kind: "kv", name: "tracker-cache", binding: "CACHE" }]
596
- * ```
597
- */
598
- deployManifest: () => Object.values(ctx.config).map((instance) => ({
599
- kind: "kv",
600
- name: instance.name,
601
- binding: instance.binding
602
- }))
603
- };
604
- };
605
- /**
606
- * Micro tier — thin env-first wrapper over a Cloudflare KV namespace.
607
- *
608
- * Resolves the KV namespace per request via `ctx.require(bindingsPlugin)`;
609
- * never stores env in state (design §1a / SB4). No lifecycle hooks —
610
- * request-scoped; nothing to open or close.
611
- *
612
- * @see README.md
613
- */
614
- const kvPlugin = createPlugin("kv", {
615
- depends: [bindingsPlugin],
616
- config: {},
617
- api: createKvApi
618
- });
619
- //#endregion
620
- //#region src/plugins/queues/api.ts
621
- /**
622
- * Resolve the instance a consumed batch belongs to. With a single instance, that instance always
623
- * matches. With several, match the instance whose `name` equals `batch.queue` OR whose stage-suffixed
624
- * form (`${name}-`) prefixes it (tolerant of the deploy stage suffix, e.g. `tracker-activity-dev`);
625
- * fall back to the default instance when nothing matches.
626
- *
627
- * @param config - The keyed-map queues config.
628
- * @param queueName - The CF queue name from `batch.queue`.
629
- * @returns The matched `QueueInstance` (its `onMessage` is what `consume` awaits).
630
- * @example
631
- * ```ts
632
- * routeInstance(cfg, "tracker-activity-dev"); // → the `activity` instance
633
- * ```
634
- */
635
- const routeInstance = (config, queueName) => {
636
- const keys = Object.keys(config);
637
- if (keys.length === 1) return pickInstance(config, keys[0], "queues");
638
- return Object.values(config).find((instance) => instance.name === queueName || queueName.startsWith(`${instance.name}-`)) ?? pickInstance(config, defaultInstanceKey(config, "queues"), "queues");
639
- };
640
- /**
641
- * Builds app.queues.* over a keyed map of Queue instances — read by worker.ts queue() delegation
642
- * (design §1d; spec/02 §7). The default-instance producer methods and `use(key)` both resolve the
643
- * Queue off the REQUEST-SUPPLIED env on every call (env is threaded, never stored — SB4); the
644
- * instance key is resolved lazily. Emits `queue:message` for observability after each consumed
645
- * message (F8).
646
- *
647
- * @param ctx - Plugin context (keyed-map config + require + emit).
648
- * @returns The queues API surface: send, sendBatch, use, consume, deployManifest.
649
- * @example
650
- * ```ts
651
- * const api = createQueuesApi(ctx);
652
- * await api.send(env, { orderId: "1" }); // default instance
653
- * await api.use("activity").send(env, { id: 2 }); // a named instance
654
- * // Worker entry (design §1d): queue: (b, e, c) => app.queues.consume(b, e, c)
655
- * ```
656
- */
657
- const createQueuesApi = (ctx) => {
658
- const bindings = ctx.require(bindingsPlugin);
659
- const surface = (binding) => {
660
- const queue = (env) => bindings.require(env, binding());
661
- return {
662
- /**
663
- * Enqueue a single message onto this instance's queue.
664
- *
665
- * @param env - The per-request Cloudflare env.
666
- * @param body - The message body to enqueue.
667
- * @returns Resolves once the message is enqueued.
668
- * @example
669
- * ```typescript
670
- * await api.send(env, { userId: "u1" });
671
- * ```
672
- */
673
- send: async (env, body) => {
674
- await queue(env).send(body);
675
- },
676
- /**
677
- * Enqueue many messages onto this instance's queue; each element becomes one message.
678
- *
679
- * @param env - The per-request Cloudflare env.
680
- * @param bodies - Array of message bodies; each becomes one message.
681
- * @returns Resolves once all messages are enqueued.
682
- * @example
683
- * ```typescript
684
- * await api.sendBatch(env, [{ id: 1 }, { id: 2 }]);
685
- * ```
686
- */
687
- sendBatch: async (env, bodies) => {
688
- await queue(env).sendBatch(bodies.map((body) => ({ body })));
689
- }
690
- };
691
- };
692
- const defaultBinding = () => pickInstance(ctx.config, defaultInstanceKey(ctx.config, "queues"), "queues").binding;
693
- return {
694
- ...surface(defaultBinding),
695
- /**
696
- * Select a specific Queue instance by its config key.
697
- *
698
- * @param key - The instance key (as configured under `pluginConfigs.queues`).
699
- * @returns The producer surface bound to that instance.
700
- * @example
701
- * ```typescript
702
- * await api.use("activity").send(env, { id: 2 });
703
- * ```
704
- */
705
- use: (key) => surface(() => pickInstance(ctx.config, key, "queues").binding),
706
- /**
707
- * Consumer dispatch — the Worker's `queue()` export delegates here. Routes the batch to the
708
- * matching instance's `onMessage` and emits `queue:message` per message.
709
- *
710
- * @param batch - The incoming message batch.
711
- * @param env - The per-request Cloudflare env.
712
- * @param _ctx - The execution context (waitUntil / passThroughOnException); unused.
713
- * @returns Resolves after all messages settle.
714
- * @example
715
- * ```typescript
716
- * // Worker entry (design §1d): queue: (b, e, c) => app.queues.consume(b, e, c)
717
- * ```
718
- */
719
- consume: async (batch, env, _ctx) => {
720
- const instance = routeInstance(ctx.config, batch.queue);
721
- for (const m of batch.messages) {
722
- if (instance.onMessage) await instance.onMessage(m, env);
723
- ctx.emit("queue:message", {
724
- queue: batch.queue,
725
- messageId: m.id
726
- });
727
- }
728
- },
729
- /**
730
- * Return this plugin's deploy metadata — one descriptor per configured instance.
731
- *
732
- * @returns One queue deploy descriptor per instance.
733
- * @example
734
- * ```typescript
735
- * const manifest = api.deployManifest(); // [{ kind: "queue", name: "tracker-activity", binding: "ACTIVITY" }]
736
- * ```
737
- */
738
- deployManifest: () => Object.values(ctx.config).map((instance) => ({
739
- kind: "queue",
740
- name: instance.name,
741
- binding: instance.binding,
742
- ...instance.onMessage ? { consumer: true } : {},
743
- ...instance.maxBatchTimeout === void 0 ? {} : { maxBatchTimeout: instance.maxBatchTimeout }
744
- }))
745
- };
746
- };
747
- /**
748
- * Standard tier — Cloudflare Queues producer + per-instance consumer dispatch over a keyed map of
749
- * instances.
750
- *
751
- * `events` is declared first and via `register.map<QueueEvents>` so the plugin's own events infer
752
- * into the factory context; the api wiring is therefore arrow-wrapped (contextually typed).
753
- *
754
- * Emits the plugin-local `queue:message` event after each consumed message.
755
- *
756
- * @see README.md
757
- */
758
- const queuesPlugin = createPlugin("queues", {
759
- events: (register) => register.map({ "queue:message": "A queue message was processed" }),
760
- depends: [bindingsPlugin],
761
- config: {},
762
- api: (ctx) => createQueuesApi(ctx)
763
- });
764
- //#endregion
765
- //#region src/plugins/storage/providers/r2.ts
766
- /**
767
- * Build a StorageProvider backed by the real R2Bucket resolved off the
768
- * per-request env via the bindings plugin. The bucket is resolved fresh on
769
- * EVERY method call — never cached, so concurrent requests stay isolated
770
- * (worker-api-design SB4; spec/08 §6).
771
- *
772
- * Each method is `async` so that synchronous throws from `bindings.require`
773
- * (e.g. missing binding) are automatically wrapped in rejected Promises —
774
- * callers can always use `await` / `.catch` instead of `try/catch`.
775
- *
776
- * @param bindings - The bindings plugin API (provides `require<T>`).
777
- * @param env - The per-request Cloudflare bindings object.
778
- * @param bucket - The R2 bucket binding name (e.g. "ASSETS").
779
- * @returns {StorageProvider} A provider that delegates to the resolved R2Bucket.
780
- * @example
781
- * ```typescript
782
- * const provider = resolveR2Provider(ctx.require(bindingsPlugin), env, ctx.config.bucket);
783
- * const body = await provider.get("my-object");
784
- * ```
785
- */
786
- const resolveR2Provider = (bindings, env, bucket) => {
787
- /**
788
- * Resolve the R2Bucket for this request's env. Throws on missing binding.
789
- *
790
- * @returns {R2Bucket} The resolved R2Bucket binding.
791
- * @example
792
- * ```typescript
793
- * const bucket = b();
794
- * ```
795
- */
796
- const b = () => bindings.require(env, bucket);
797
- return {
798
- /**
799
- * Read an object from the bucket.
800
- *
801
- * @param key - The object key.
802
- * @returns {Promise<R2ObjectBody | null>} The R2ObjectBody, or null if the key is absent.
803
- * @example
804
- * ```typescript
805
- * const body = await provider.get("assets/logo.png");
806
- * ```
807
- */
808
- async get(key) {
809
- return b().get(key);
810
- },
811
- /**
812
- * Write an object to the bucket.
813
- *
814
- * @param key - The object key.
815
- * @param value - The object contents (any R2-accepted type).
816
- * @returns {Promise<R2Object>} The R2Object metadata for the written object.
817
- * @example
818
- * ```typescript
819
- * const obj = await provider.put("assets/logo.png", buffer);
820
- * ```
821
- */
822
- async put(key, value) {
823
- return b().put(key, value);
824
- },
825
- /**
826
- * Remove one or more objects from the bucket. No-op when a key is absent.
827
- *
828
- * @param key - A single key or array of keys to remove.
829
- * @returns {Promise<void>} Resolves once removed.
830
- * @example
831
- * ```typescript
832
- * await provider.delete("assets/old.png");
833
- * ```
834
- */
835
- async delete(key) {
836
- return b().delete(key);
837
- },
838
- /**
839
- * List objects, optionally filtered by R2ListOptions.
840
- *
841
- * @param opts - Optional list options (prefix, limit, cursor, delimiter).
842
- * @returns {Promise<R2Objects>} The R2Objects list result.
843
- * @example
844
- * ```typescript
845
- * const { objects } = await provider.list({ prefix: "images/" });
846
- * ```
847
- */
848
- async list(opts) {
849
- return b().list(opts);
850
- }
851
- };
852
- };
853
- //#endregion
854
- //#region src/plugins/storage/api.ts
855
- /**
856
- * Build the app.storage.* api over a keyed map of R2 bucket instances. The default-bucket methods and
857
- * `use(key)` both resolve the bucket off the REQUEST-SUPPLIED env on every call — env is threaded,
858
- * never stored (worker-api-design SB4; spec/08 §6,§7) — and the instance key is resolved lazily so an
859
- * unconfigured-but-present plugin only errors when actually called.
860
- *
861
- * The `deployManifest()` method is build-time only: it reads from `ctx.config`
862
- * and never touches `env` or R2.
863
- *
864
- * @param ctx - Plugin context (keyed-map config + require for bindings resolution).
865
- * @returns {StorageApi} The app.storage api: get / put / delete / list / use / deployManifest.
866
- * @example
867
- * ```typescript
868
- * const api = createStorageApi(ctx);
869
- * const body = await api.get(env, "my-object");
870
- * await api.use("uploads").put(env, "avatar.png", buffer);
871
- * ```
872
- */
873
- const createStorageApi = (ctx) => {
874
- const bindings = ctx.require(bindingsPlugin);
875
- const surface = (binding) => {
876
- const provider = (env) => resolveR2Provider(bindings, env, binding());
877
- return {
878
- /**
879
- * Read an object from this bucket; resolves null when the key is absent.
880
- *
881
- * @param env - The per-request Cloudflare env.
882
- * @param key - The object key to read.
883
- * @returns The object body, or null.
884
- * @example
885
- * ```typescript
886
- * const body = await api.get(env, "assets/logo.png");
887
- * ```
888
- */
889
- get: (env, key) => provider(env).get(key),
890
- /**
891
- * Write an object to this bucket.
892
- *
893
- * @param env - The per-request Cloudflare env.
894
- * @param key - The object key to write.
895
- * @param value - The object contents.
896
- * @returns The written object metadata.
897
- * @example
898
- * ```typescript
899
- * await api.put(env, "avatar.png", buffer);
900
- * ```
901
- */
902
- put: (env, key, value) => provider(env).put(key, value),
903
- /**
904
- * Remove an object (or keys) from this bucket. No-op when absent.
905
- *
906
- * @param env - The per-request Cloudflare env.
907
- * @param key - The object key or keys to delete.
908
- * @returns Resolves once removed.
909
- * @example
910
- * ```typescript
911
- * await api.delete(env, "assets/old-logo.png");
912
- * ```
913
- */
914
- delete: (env, key) => provider(env).delete(key),
915
- /**
916
- * List objects in this bucket, optionally filtered by R2ListOptions.
917
- *
918
- * @param env - The per-request Cloudflare env.
919
- * @param opts - Optional prefix / limit / cursor / delimiter.
920
- * @returns The list result.
921
- * @example
922
- * ```typescript
923
- * const { objects } = await api.list(env, { prefix: "assets/" });
924
- * ```
925
- */
926
- list: (env, opts) => provider(env).list(opts)
927
- };
928
- };
929
- const defaultBinding = () => pickInstance(ctx.config, defaultInstanceKey(ctx.config, "r2"), "r2").binding;
930
- return {
931
- ...surface(defaultBinding),
932
- /**
933
- * Select a specific R2 bucket instance by its config key.
934
- *
935
- * @param key - The instance key (as configured under `pluginConfigs.storage`).
936
- * @returns The object surface bound to that bucket.
937
- * @example
938
- * ```typescript
939
- * await api.use("uploads").put(env, "avatar.png", buffer);
940
- * ```
941
- */
942
- use: (key) => surface(() => pickInstance(ctx.config, key, "r2").binding),
943
- /**
944
- * Return this plugin's deploy metadata — one descriptor per configured bucket.
945
- *
946
- * @returns One r2 deploy descriptor per instance.
947
- * @example
948
- * ```typescript
949
- * const manifest = api.deployManifest(); // [{ kind: "r2", name: "tracker-files", binding: "FILES" }]
950
- * ```
951
- */
952
- deployManifest: () => Object.values(ctx.config).map((instance) => ({
953
- kind: "r2",
954
- name: instance.name,
955
- binding: instance.binding,
956
- ...instance.upload === void 0 ? {} : { upload: instance.upload }
957
- }))
958
- };
959
- };
960
- /**
961
- * Complex tier — Cloudflare R2 object storage behind a provider adapter seam.
962
- *
963
- * Exposes `get`, `put`, `delete`, `list` (all env-first) and `deployManifest()`
964
- * (build-time). Depends on `bindingsPlugin` to resolve the `R2Bucket` binding
965
- * per request. No state, no events, no lifecycle hooks.
966
- *
967
- * @see README.md
968
- */
969
- const storagePlugin = createPlugin("storage", {
970
- depends: [bindingsPlugin],
971
- config: {},
972
- api: createStorageApi
973
- });
974
- //#endregion
975
- //#region src/plugins/deploy/auth/env-file.ts
976
- /**
977
- * @file deploy plugin — `.env.local` scaffolder (node:fs).
978
- *
979
- * Writes a ready-to-fill `.env.local` so the guided deploy can hand the user a real file to paste
980
- * their Cloudflare token into — NEVER clobbering an existing one (it may already hold real secrets).
981
- * Node-only; never imported by the runtime Worker bundle.
982
- */
983
- /**
984
- * Create `<dir>/.env.local` with the given contents, unless it already exists. Existing files are
985
- * left untouched (they may hold real secrets) — the caller tells the user to fill that one in.
986
- *
987
- * @param dir - Directory to create the file in (usually `process.cwd()`).
988
- * @param content - The file contents to write when absent (e.g. `envLocalScaffold(manifest)`).
989
- * @returns Whether the file was created (false when it already existed) and its path.
990
- * @example
991
- * ```ts
992
- * const { created, path } = await ensureEnvLocal(process.cwd(), envLocalScaffold(manifest));
993
- * ```
994
- */
995
- const ensureEnvLocal = async (dir, content) => {
996
- const filePath = path.join(dir, ".env.local");
997
- try {
998
- await access(filePath);
999
- return {
1000
- created: false,
1001
- path: filePath
1002
- };
1003
- } catch {
1004
- await writeFile(filePath, content, "utf8");
1005
- return {
1006
- created: true,
1007
- path: filePath
1008
- };
1009
- }
1010
- };
1011
- //#endregion
1012
- //#region src/plugins/deploy/auth/permissions.ts
1013
- /** Permission groups every deploy needs, regardless of resources. */
1014
- const ALWAYS = [{
1015
- group: "Account · Workers Scripts",
1016
- scope: "Edit",
1017
- reason: "deploy",
1018
- inBaseTemplate: true
1019
- }, {
1020
- group: "Account · Account Settings",
1021
- scope: "Read",
1022
- reason: "account",
1023
- inBaseTemplate: true
1024
- }];
1025
- /**
1026
- * Per-resource-kind permission group. `do` needs nothing extra (Durable Objects ship with the
1027
- * Worker script, covered by Workers Scripts · Edit). `d1`/`queue` are NOT in the stock template.
1028
- */
1029
- const BY_KIND = {
1030
- kv: {
1031
- group: "Account · Workers KV Storage",
1032
- scope: "Edit",
1033
- reason: "kv",
1034
- inBaseTemplate: true
1035
- },
1036
- r2: {
1037
- group: "Account · Workers R2 Storage",
1038
- scope: "Edit",
1039
- reason: "r2",
1040
- inBaseTemplate: true
1041
- },
1042
- d1: {
1043
- group: "Account · D1",
1044
- scope: "Edit",
1045
- reason: "d1",
1046
- inBaseTemplate: false
1047
- },
1048
- queue: {
1049
- group: "Account · Queues",
1050
- scope: "Edit",
1051
- reason: "queue",
1052
- inBaseTemplate: false
1053
- },
1054
- do: void 0
1055
- };
1056
- /**
1057
- * Derive the Cloudflare API token requirement from an app manifest: the full permission set plus
1058
- * the subset that must be ADDED to the stock "Edit Cloudflare Workers" template.
1059
- *
1060
- * @param manifest - The assembled deploy manifest.
1061
- * @returns The token requirement (base template, full required set, and groups to add).
1062
- * @example
1063
- * ```ts
1064
- * const { toAdd } = requiredToken({ name: "w", compatibilityDate: "…", resources: [{ kind: "d1", binding: "DB" }] });
1065
- * // toAdd → [{ group: "Account · D1", scope: "Edit", … }]
1066
- * ```
1067
- */
1068
- const requiredToken = (manifest) => {
1069
- const required = [...ALWAYS];
1070
- const seen = new Set(required.map((permission) => permission.group));
1071
- for (const resource of manifest.resources) {
1072
- const permission = BY_KIND[resource.kind];
1073
- if (permission !== void 0 && !seen.has(permission.group)) {
1074
- required.push(permission);
1075
- seen.add(permission.group);
1076
- }
1077
- }
1078
- return {
1079
- base: "Edit Cloudflare Workers",
1080
- required,
1081
- toAdd: required.filter((permission) => !permission.inBaseTemplate)
1082
- };
1083
- };
1084
- /** Permission every CI/automation redeploy needs: ship the Worker script. */
1085
- const CI_ALWAYS = [{
1086
- group: "Account · Workers Scripts",
1087
- scope: "Edit",
1088
- reason: "deploy",
1089
- inBaseTemplate: true
1090
- }];
1091
- /**
1092
- * Per-resource-kind permission for the CI/automation token. After a first LOCAL deploy has
1093
- * provisioned everything, CI only needs to LIST existing infra (the idempotent preflight) and
1094
- * ship — so data resources drop to `Read`; R2 stays `Edit` because asset upload writes objects.
1095
- */
1096
- const CI_BY_KIND = {
1097
- kv: {
1098
- group: "Account · Workers KV Storage",
1099
- scope: "Read",
1100
- reason: "kv (preflight)",
1101
- inBaseTemplate: true
1102
- },
1103
- r2: {
1104
- group: "Account · Workers R2 Storage",
1105
- scope: "Edit",
1106
- reason: "r2 (asset upload)",
1107
- inBaseTemplate: true
1108
- },
1109
- d1: {
1110
- group: "Account · D1",
1111
- scope: "Read",
1112
- reason: "d1 (preflight)",
1113
- inBaseTemplate: false
1114
- },
1115
- queue: {
1116
- group: "Account · Queues",
1117
- scope: "Read",
1118
- reason: "queue (preflight)",
1119
- inBaseTemplate: false
1120
- },
1121
- do: void 0
1122
- };
1123
- /**
1124
- * Derive the REDUCED Cloudflare API token for CI/automation redeploys, from the same manifest.
1125
- * Assumes a prior LOCAL deploy already provisioned the infra, so CI never creates: data resources
1126
- * need only `Read` (the idempotent preflight lists them), R2 keeps `Edit` for asset upload, and no
1127
- * `Account Settings · Read` is needed because CI pins `CLOUDFLARE_ACCOUNT_ID`. Pure: no network.
1128
- *
1129
- * @param manifest - The assembled deploy manifest.
1130
- * @returns The minimum permission groups for a CI redeploy token (deduped, manifest-scoped).
1131
- * @example
1132
- * ```ts
1133
- * const groups = ciToken({ name: "w", compatibilityDate: "…", resources: [{ kind: "d1", binding: "DB" }] });
1134
- * // → [Workers Scripts·Edit, D1·Read]
1135
- * ```
1136
- */
1137
- const ciToken = (manifest) => {
1138
- const groups = [...CI_ALWAYS];
1139
- const seen = new Set(groups.map((permission) => permission.group));
1140
- for (const resource of manifest.resources) {
1141
- const permission = CI_BY_KIND[resource.kind];
1142
- if (permission !== void 0 && !seen.has(permission.group)) {
1143
- groups.push(permission);
1144
- seen.add(permission.group);
1145
- }
1146
- }
1147
- return groups;
1148
- };
1149
- //#endregion
1150
- //#region src/plugins/deploy/auth/render.ts
1151
- /** Cloudflare's dashboard path for creating API tokens. */
1152
- const TOKENS_URL$1 = "https://dash.cloudflare.com/profile/api-tokens";
1153
- /**
1154
- * Render one permission as a framed row. With the template flag on (the LOCAL panel) a green `✓`
1155
- * marks a permission the stock template already includes and a pink `+ ← add to template` marks one
1156
- * the user must add; with it off (the CI panel) every row is a neutral bullet. Scope bold, reason dim.
1157
- *
1158
- * @param ui - The branded console (for its palette).
1159
- * @param permission - The permission group to render.
1160
- * @param showTemplateFlag - Whether to mark template-vs-add (LOCAL) or use a neutral bullet (CI).
1161
- * @returns The rendered (colorized) row, ready to drop into a box.
1162
- * @example
1163
- * ```ts
1164
- * permissionRow(ui, { group: "Account · D1", scope: "Edit", reason: "d1", inBaseTemplate: false }, true);
1165
- * ```
1166
- */
1167
- const permissionRow = (ui, permission, showTemplateFlag) => {
1168
- const { palette } = ui;
1169
- const templateMark = permission.inBaseTemplate ? palette.green("✓") : palette.pink("+");
1170
- const mark = showTemplateFlag ? templateMark : palette.dim("•");
1171
- const flag = showTemplateFlag && !permission.inBaseTemplate ? palette.pink(" ← add to template") : "";
1172
- const reason = palette.dim(`(${permission.reason})`);
1173
- return `${mark} ${permission.group} : ${palette.bold(permission.scope)} ${reason}${flag}`;
1174
- };
1175
- /**
1176
- * Render the LOCAL (first deploy) token panel: the full permission set with template/add markers,
1177
- * then the numbered create-token steps (URL cyan, template + `.env.local` bold).
1178
- *
1179
- * @param ui - The branded console to render through.
1180
- * @param requirement - The LOCAL token requirement (from requiredToken()).
1181
- * @example
1182
- * ```ts
1183
- * localPanel(ui, requiredToken(manifest));
1184
- * ```
1185
- */
1186
- const localPanel = (ui, requirement) => {
1187
- const { palette } = ui;
1188
- const adds = requirement.toAdd.map((permission) => `${permission.group.replace("Account · ", "")} → ${permission.scope}`).join(", ");
1189
- const coversAll = palette.dim(`The "${requirement.base}" template covers everything.`);
1190
- const addStep = requirement.toAdd.length > 0 ? ` 3. ADD ${palette.pink(adds)}` : ` 3. ${coversAll}`;
1191
- const template = palette.bold(`"${requirement.base}"`);
1192
- ui.box([
1193
- palette.bold("LOCAL — first deploy (creates your infra)"),
1194
- "",
1195
- ...requirement.required.map((permission) => permissionRow(ui, permission, true)),
1196
- "",
1197
- ` 1. ${palette.cyan(TOKENS_URL$1)}`,
1198
- ` 2. Create Token → start from the ${template} template.`,
1199
- addStep,
1200
- " 4. Account Resources → Include → your account.",
1201
- ` 5. Create it, copy it, then paste into ${palette.bold(".env.local")} (below).`
1202
- ]);
1203
- };
1204
- /**
1205
- * Render the compact CI (automation redeploy) token panel: the reduced, read-mostly permission set
1206
- * for a later Custom Token. No template markers — CI builds a token from scratch, not the template.
1207
- *
1208
- * @param ui - The branded console to render through.
1209
- * @param groups - The CI token permission groups (from ciToken()).
1210
- * @example
1211
- * ```ts
1212
- * ciPanel(ui, ciToken(manifest));
1213
- * ```
1214
- */
1215
- const ciPanel = (ui, groups) => {
1216
- const { palette } = ui;
1217
- ui.box([
1218
- palette.bold("CI — automation redeploy (optional, later)"),
1219
- "",
1220
- ...groups.map((permission) => permissionRow(ui, permission, false)),
1221
- "",
1222
- palette.dim("Create a Custom Token with exactly these (Read, not Edit, on data)."),
1223
- palette.dim("Store as the CLOUDFLARE_API_TOKEN secret; pin CLOUDFLARE_ACCOUNT_ID.")
1224
- ]);
1225
- };
1226
- /**
1227
- * Render the full branded `auth setup` guidance: a heading, the LOCAL token panel (what to create
1228
- * now), and — when `opts.ci` is supplied — the compact CI panel; otherwise a one-line pointer to
1229
- * `auth setup` for the CI token (so the guided deploy stays focused on the immediate next step).
1230
- *
1231
- * @param ui - The branded console to render through.
1232
- * @param requirement - The LOCAL token requirement (from requiredToken()).
1233
- * @param opts - Optional rendering options.
1234
- * @param opts.ci - The CI token permission groups (from ciToken()); omit to show a pointer instead.
1235
- * @example
1236
- * ```ts
1237
- * renderAuthSetup(ui, requiredToken(manifest)); // guided deploy (LOCAL only)
1238
- * renderAuthSetup(ui, requiredToken(manifest), { ci: ciToken(m) }); // `auth setup` (LOCAL + CI)
1239
- * ```
1240
- */
1241
- const renderAuthSetup = (ui, requirement, opts) => {
1242
- ui.heading("Cloudflare API token");
1243
- localPanel(ui, requirement);
1244
- if (opts?.ci) ciPanel(ui, opts.ci);
1245
- else ui.line(ui.palette.dim(" Need a CI token later? Run `auth setup` for the reduced set."));
1246
- };
1247
- //#endregion
1248
- //#region src/plugins/deploy/auth/setup.ts
1249
- /** Cloudflare's dashboard path for creating API tokens. */
1250
- const TOKENS_URL = "https://dash.cloudflare.com/profile/api-tokens";
1251
- /**
1252
- * Render the FULL local-first token section (the deploy that provisions everything): the permission
1253
- * table flagging template-missing rows, the template + "add these" steps, and the `.env.local` lines.
1254
- *
1255
- * @param requirement - The full token requirement (from requiredToken()).
1256
- * @returns The local-first section lines.
1257
- * @example
1258
- * ```ts
1259
- * const lines = localSection(requiredToken(manifest));
1260
- * ```
1261
- */
1262
- const localSection = (requirement) => {
1263
- const permissionRows = requirement.required.map((permission) => {
1264
- const flag = permission.inBaseTemplate ? "" : " <- add to template";
1265
- return ` - ${permission.group} : ${permission.scope} (${permission.reason})${flag}`;
1266
- });
1267
- const step3 = requirement.toAdd.length > 0 ? [` 3. Under Permissions, ADD: ${requirement.toAdd.map((permission) => `${permission.group.replace("Account · ", "")} -> ${permission.scope}`).join(", ")}`, " (the template omits these; everything else is already included)"] : [` 3. The "${requirement.base}" template covers everything — no changes needed.`];
1268
- return [
1269
- "LOCAL — first deploy (provisions infra). A Cloudflare API token with these permissions:",
1270
- "",
1271
- ...permissionRows,
1272
- "",
1273
- "Fastest path:",
1274
- ` 1. ${TOKENS_URL} -> Create Token`,
1275
- ` 2. Start from the "${requirement.base}" template.`,
1276
- ...step3,
1277
- " 4. Account Resources -> Include -> your account.",
1278
- " 5. Create the token, copy it, then add it to .env.local:",
1279
- " CLOUDFLARE_API_TOKEN=<paste your token>",
1280
- " CLOUDFLARE_ACCOUNT_ID=<your account id>",
1281
- " 6. Verify it with `auth` (app.deploy.verifyAuth())."
1282
- ];
1283
- };
1284
- /**
1285
- * Render the REDUCED CI/automation token section (redeploy-only): the scoped permission table plus
1286
- * the CI-secret + account-pin steps.
1287
- *
1288
- * @param groups - The CI permission groups (from ciToken()).
1289
- * @returns The CI section lines.
1290
- * @example
1291
- * ```ts
1292
- * const lines = ciSection(ciToken(manifest));
1293
- * ```
1294
- */
1295
- const ciSection = (groups) => {
1296
- return [
1297
- "CI — automation redeploy (infra already provisioned by a local deploy). A SCOPED token with:",
1298
- "",
1299
- ...groups.map((permission) => ` - ${permission.group} : ${permission.scope} (${permission.reason})`),
1300
- "",
1301
- ` 1. ${TOKENS_URL} -> Create Token -> Create Custom Token.`,
1302
- " 2. Add exactly the permissions above (Read, not Edit, on data resources — CI never creates).",
1303
- " 3. Account Resources -> Include -> your account.",
1304
- " 4. Store it as the CLOUDFLARE_API_TOKEN secret in CI, and PIN the account so no account",
1305
- " lookup (and no Account Settings -> Read) is needed:",
1306
- " CLOUDFLARE_ACCOUNT_ID=<your account id>",
1307
- " CI reuses the same idempotent pipeline — it lists existing infra and ships. To let CI also",
1308
- " CREATE missing infra (self-heal), give it the LOCAL token above instead."
1309
- ];
1310
- };
1311
- /**
1312
- * Render the `auth setup` instructions from the app manifest: the FULL local-first token (provisions
1313
- * everything) followed by the REDUCED CI/automation token (redeploy-only).
1314
- *
1315
- * @param manifest - The assembled deploy manifest.
1316
- * @returns A multi-line instruction string covering both tokens.
1317
- * @example
1318
- * ```ts
1319
- * const text = tokenInstructions(manifest);
1320
- * ```
1321
- */
1322
- const tokenInstructions = (manifest) => [
1323
- ...localSection(requiredToken(manifest)),
1324
- "",
1325
- ...ciSection(ciToken(manifest))
1326
- ].join("\n");
1327
- /**
1328
- * Render a ready-to-fill `.env.local` for the guided deploy: the two Cloudflare credential keys
1329
- * (left blank to paste into) preceded by a comment block derived from the manifest — where to
1330
- * create the token, which template to start from, exactly which permissions to add, and how to find
1331
- * the account id. The same guidance {@link tokenInstructions} prints, but PERSISTED in the file the
1332
- * user edits (so it survives the terminal scrolling away). Pure: no fs, no network.
1333
- *
1334
- * @param manifest - The assembled deploy manifest.
1335
- * @returns The `.env.local` file contents (trailing newline included).
1336
- * @example
1337
- * ```ts
1338
- * await writeFile(".env.local", envLocalScaffold(manifest));
1339
- * ```
1340
- */
1341
- const envLocalScaffold = (manifest) => {
1342
- const requirement = requiredToken(manifest);
1343
- const addStep = requirement.toAdd.length > 0 ? `# 3. Under Permissions, ADD: ${requirement.toAdd.map((permission) => `${permission.group.replace("Account · ", "")} -> ${permission.scope}`).join(", ")}` : `# 3. The "${requirement.base}" template covers everything — no changes needed.`;
1344
- return `${[
1345
- "# Cloudflare credentials for the moku deploy — fill in the two values below, then re-run deploy.",
1346
- "# Local-only: keep this file out of git (.env.local is gitignored by convention).",
1347
- "#",
1348
- "# Create the API token:",
1349
- `# 1. ${TOKENS_URL} -> Create Token`,
1350
- `# 2. Start from the "${requirement.base}" template.`,
1351
- addStep,
1352
- "# 4. Account Resources -> Include -> your account.",
1353
- "# 5. Create the token, copy it, and paste it after CLOUDFLARE_API_TOKEN= below.",
1354
- "#",
1355
- "# Account id: open https://dash.cloudflare.com — it is the id in the URL",
1356
- "# (dash.cloudflare.com/<account-id>) or in the right sidebar of any domain's overview.",
1357
- "",
1358
- "CLOUDFLARE_API_TOKEN=",
1359
- "CLOUDFLARE_ACCOUNT_ID="
1360
- ].join("\n")}\n`;
1361
- };
1362
- //#endregion
1363
- //#region src/plugins/deploy/infra/cloudflare.ts
1364
- /**
1365
- * @file deploy plugin — Cloudflare REST discovery client (infra preflight).
1366
- *
1367
- * Lists what already exists in a Cloudflare account so the deploy pipeline can create only the
1368
- * missing resources (idempotent provisioning) and recover real ids for existing kv/d1 bindings.
1369
- * Authenticated with the `.env` API token (CLOUDFLARE_API_TOKEN) — never an interactive login.
1370
- * Uses the global `fetch`; node-only, never imported by the runtime Worker bundle.
1371
- */
1372
- const API_BASE = "https://api.cloudflare.com/client/v4";
1373
- /**
1374
- * GET a Cloudflare API path with the bearer token and unwrap the `result`.
1375
- *
1376
- * @param token - The Cloudflare API token (CLOUDFLARE_API_TOKEN).
1377
- * @param path - API path beneath the v4 base (e.g. "/accounts").
1378
- * @returns The unwrapped `result` payload, typed by the caller.
1379
- * @throws {Error} When the HTTP request fails or the API reports `success: false`.
1380
- * @example
1381
- * ```ts
1382
- * const accounts = await cfGet<Array<{ id: string }>>(token, "/accounts");
1383
- * ```
1384
- */
1385
- const cfGet = async (token, path) => {
1386
- const response = await fetch(`${API_BASE}${path}`, { headers: {
1387
- Authorization: `Bearer ${token}`,
1388
- "Content-Type": "application/json"
1389
- } });
1390
- const body = await response.json();
1391
- if (!response.ok || !body.success) {
1392
- const detail = body.errors?.map((error) => error.message).join("; ") || `HTTP ${response.status}`;
1393
- throw new Error(`[moku-worker] Cloudflare API request failed (${path}): ${detail}`);
1394
- }
1395
- return body.result;
1396
- };
1397
- /**
1398
- * Resolve the Cloudflare account (id + display name) accessible to the token. Used when the
1399
- * consumer did not pin CLOUDFLARE_ACCOUNT_ID; the first accessible account is chosen.
1400
- *
1401
- * @param token - The Cloudflare API token.
1402
- * @returns The resolved account id and name.
1403
- * @throws {Error} When the token can access no account.
1404
- * @example
1405
- * ```ts
1406
- * const { id, name } = await resolveAccount(token);
1407
- * ```
1408
- */
1409
- const resolveAccount = async (token) => {
1410
- const first = (await cfGet(token, "/accounts"))[0];
1411
- if (!first) throw new Error("[moku-worker] No Cloudflare account is accessible with this API token.");
1412
- return {
1413
- id: first.id,
1414
- name: first.name
1415
- };
1416
- };
1417
- /**
1418
- * Verify a Cloudflare API token via `GET /user/tokens/verify`. Returns its status (`"active"` for
1419
- * a usable token); throws (via cfGet) when the token is rejected outright (401/invalid).
1420
- *
1421
- * @param token - The Cloudflare API token to verify.
1422
- * @returns The token status string reported by Cloudflare.
1423
- * @throws {Error} When the verify request fails (invalid/expired token).
1424
- * @example
1425
- * ```ts
1426
- * const { status } = await verifyToken(token); // status === "active"
1427
- * ```
1428
- */
1429
- const verifyToken = async (token) => {
1430
- return { status: (await cfGet(token, "/user/tokens/verify")).status };
1431
- };
1432
- /**
1433
- * List the resources that already exist in the account, querying ONLY the kinds the app declares
1434
- * (one request per declared kind, in parallel), indexed for the preflight diff. Scoping to the
1435
- * declared kinds keeps the API token minimal — an app with only KV never lists (and so never needs
1436
- * read permission on) D1, R2, or Queues.
1437
- *
1438
- * @param token - The Cloudflare API token.
1439
- * @param accountId - The Cloudflare account id to scope the listings to.
1440
- * @param kinds - The resource kinds present in the manifest (the only kinds queried).
1441
- * @returns The existing resources, indexed by kind (un-queried kinds resolve empty).
1442
- * @throws {Error} When any listing request fails.
1443
- * @example
1444
- * ```ts
1445
- * const existing = await listExisting(token, accountId, new Set(["kv", "d1"]));
1446
- * if (existing.kv.has("SESSIONS")) { ... }
1447
- * ```
1448
- */
1449
- const listExisting = async (token, accountId, kinds) => {
1450
- const base = `/accounts/${accountId}`;
1451
- const [kv, d1, r2, queues] = await Promise.all([
1452
- kinds.has("kv") ? cfGet(token, `${base}/storage/kv/namespaces`) : Promise.resolve([]),
1453
- kinds.has("d1") ? cfGet(token, `${base}/d1/database`) : Promise.resolve([]),
1454
- kinds.has("r2") ? cfGet(token, `${base}/r2/buckets`) : Promise.resolve({}),
1455
- kinds.has("queue") ? cfGet(token, `${base}/queues`) : Promise.resolve([])
1456
- ]);
1457
- return {
1458
- kv: new Map(kv.map((namespace) => [namespace.title, namespace.id])),
1459
- d1: new Map(d1.map((database) => [database.name, database.uuid])),
1460
- r2: new Set((r2.buckets ?? []).map((bucket) => bucket.name)),
1461
- queue: new Set(queues.map((queue) => queue.queue_name))
1462
- };
1463
- };
1464
- //#endregion
1465
- //#region src/plugins/deploy/auth/verify.ts
1466
- /**
1467
- * @file deploy plugin — `.env` token verification + account resolution.
1468
- *
1469
- * Reads CLOUDFLARE_API_TOKEN via ctx.env, verifies it is active against the Cloudflare API, and
1470
- * resolves the account. Emits auth:verified. Throws a branded, actionable error (pointing at
1471
- * `auth setup`) when the token is absent, invalid, or inactive — never an interactive login.
1472
- * Node-only; never imported by the runtime Worker bundle.
1473
- */
1474
- /** Branded hint appended to every auth failure so the user knows the next step. */
1475
- const SETUP_HINT = "Run `auth setup` for the exact token to create.";
1476
- /**
1477
- * Verify the `.env` Cloudflare API token and resolve its account.
1478
- *
1479
- * @param ctx - The deploy plugin context (env + emit).
1480
- * @returns The verified auth status (account + id).
1481
- * @throws {Error} When the token is absent, invalid/expired, or not active.
1482
- * @example
1483
- * ```ts
1484
- * const { account, accountId } = await verifyAuth(ctx);
1485
- * ```
1486
- */
1487
- const verifyAuth = async (ctx) => {
1488
- const token = ctx.env.get("CLOUDFLARE_API_TOKEN");
1489
- if (token === void 0 || token === "") throw new Error(`[moku-worker] CLOUDFLARE_API_TOKEN is not set. ${SETUP_HINT}`);
1490
- let status;
1491
- try {
1492
- ({status} = await verifyToken(token));
1493
- } catch (error) {
1494
- throw new Error(`[moku-worker] Cloudflare API token is invalid or expired. ${SETUP_HINT}`, { cause: error });
1495
- }
1496
- if (status !== "active") throw new Error(`[moku-worker] Cloudflare API token is "${status}", not active. ${SETUP_HINT}`);
1497
- const pinnedAccountId = ctx.env.get("CLOUDFLARE_ACCOUNT_ID");
1498
- const account = pinnedAccountId === void 0 || pinnedAccountId === "" ? await resolveAccount(token) : {
1499
- id: pinnedAccountId,
1500
- name: pinnedAccountId
1501
- };
1502
- ctx.emit("auth:verified", {
1503
- account: account.name,
1504
- accountId: account.id,
1505
- scopes: []
1506
- });
1507
- return {
1508
- ok: true,
1509
- account: account.name,
1510
- accountId: account.id,
1511
- scopes: []
1512
- };
1513
- };
1514
- //#endregion
1515
- //#region src/plugins/deploy/runner.ts
1516
- /**
1517
- * @file deploy plugin — wrangler subprocess wrapper (node:child_process).
1518
- *
1519
- * Spawns `wrangler` with the given args and resolves the deployed URL
1520
- * (extracted from stdout for `wrangler deploy`), or the full stdout for other verbs.
1521
- * This module is node-only; never imported by the runtime Worker bundle.
1522
- */
1523
- /**
1524
- * Extract the deployed URL from `wrangler deploy` stdout.
1525
- * Wrangler prints a line like: "Published my-worker (1.23 sec) https://..."
1526
- * or "Deployed my-worker (1.23 sec) https://...".
1527
- *
1528
- * @param output - The combined stdout from wrangler deploy.
1529
- * @returns The deployed URL, or empty string when not found.
1530
- * @example
1531
- * ```ts
1532
- * extractDeployedUrl("Deployed my-worker (0.5 sec) https://my-worker.workers.dev");
1533
- * // "https://my-worker.workers.dev"
1534
- * ```
1535
- */
1536
- const extractDeployedUrl = (output) => {
1537
- return /https:\/\/[^\s]+\.workers\.dev[^\s]*/u.exec(output)?.[0] ?? "";
1538
- };
1539
- /**
1540
- * Spawn `wrangler` with the given args and resolve the output string.
1541
- * For `wrangler deploy`, the resolved value is the deployed URL parsed from stdout.
1542
- * For all other verbs (dev, kv namespace create, etc.), the resolved value is stdout.
1543
- *
1544
- * @param args - Wrangler CLI arguments (e.g. ["deploy", "--config", "wrangler.jsonc"]).
1545
- * @returns Resolves with the deployed URL (deploy verb) or full stdout (other verbs).
1546
- * @throws {Error} When wrangler exits with a non-zero code.
1547
- * @example
1548
- * ```ts
1549
- * const url = await runWrangler(["deploy", "--config", "wrangler.jsonc"]);
1550
- * await runWrangler(["kv", "namespace", "create", "CACHE"]);
1551
- * ```
1552
- */
1553
- const runWrangler = (args) => new Promise((resolve, reject) => {
1554
- const chunks = [];
1555
- const errChunks = [];
1556
- const child = spawn("wrangler", args, {
1557
- env: { ...process.env },
1558
- stdio: [
1559
- "ignore",
1560
- "pipe",
1561
- "pipe"
1562
- ]
1563
- });
1564
- child.stdout.on("data", (chunk) => {
1565
- chunks.push(chunk);
1566
- });
1567
- child.stderr.on("data", (chunk) => {
1568
- errChunks.push(chunk);
1569
- });
1570
- child.on("error", (err) => {
1571
- reject(/* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${err.message}`));
1572
- });
1573
- child.on("close", (code) => {
1574
- const stdout = Buffer.concat(chunks).toString("utf8");
1575
- const stderr = Buffer.concat(errChunks).toString("utf8");
1576
- if (code !== 0) {
1577
- reject(/* @__PURE__ */ new Error(`[moku-worker] wrangler exited with code ${String(code)}.\n ${stderr || stdout}`));
1578
- return;
1579
- }
1580
- resolve(args[0] === "deploy" ? extractDeployedUrl(stdout) : stdout);
1581
- });
1582
- });
1583
- /**
1584
- * Spawn `wrangler` with the given args, inheriting stdio so its output streams live to the user's
1585
- * terminal (used by the generic passthrough and long-lived commands like `tail`).
1586
- *
1587
- * @param args - Wrangler CLI arguments (e.g. ["kv", "namespace", "list"]).
1588
- * @returns Resolves once wrangler exits successfully.
1589
- * @throws {Error} When wrangler cannot be spawned or exits non-zero.
1590
- * @example
1591
- * ```ts
1592
- * await runWranglerInherit(["kv", "namespace", "list"]);
1593
- * ```
1594
- */
1595
- const runWranglerInherit = (args) => {
1596
- return new Promise((resolve, reject) => {
1597
- const child = spawn("wrangler", args, { stdio: "inherit" });
1598
- child.on("error", (error) => {
1599
- reject(/* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${error.message}`));
1600
- });
1601
- child.on("close", (code) => {
1602
- if (code === 0) {
1603
- resolve();
1604
- return;
1605
- }
1606
- reject(/* @__PURE__ */ new Error(`[moku-worker] wrangler exited with code ${String(code)}.`));
1607
- });
1608
- });
1609
- };
1610
- //#endregion
1611
- //#region src/plugins/deploy/seed.ts
1612
- /**
1613
- * @file deploy plugin — shared D1 seed helpers (resolve the target db, run a configured seed).
1614
- *
1615
- * Pure orchestration over an INJECTED wrangler runner, so the post-deploy REMOTE seed (api.ts) and
1616
- * the dev-session LOCAL seed (dev/runner.ts) stay in lockstep — same file, same KV-reset semantics,
1617
- * differing only in the `--remote` / `--local` scope. Migrations are NOT applied here: each caller
1618
- * applies the schema first (the deploy's migration step / dev's local-migrate step), then seeds.
1619
- * Node-only; never imported by the runtime Worker bundle.
1620
- */
1621
- /**
1622
- * Resolve the single configured d1 database (or the one bound to `binding` when several exist) from
1623
- * the d1 plugin's manifest. The shared resolver behind `seed()`, the post-deploy seed, and the dev
1624
- * seed; throws a branded error when the choice is ambiguous (none/several, no binding) or unknown.
1625
- *
1626
- * @param ctx - The deploy plugin context.
1627
- * @param binding - The d1 binding to target when more than one is configured; the sole one otherwise.
1628
- * @returns The resolved d1 resource descriptor (its binding + optional migrations dir).
1629
- * @throws {Error} When no single database resolves (none/several without a binding, or unknown binding).
1630
- * @example
1631
- * ```ts
1632
- * const db = resolveD1(ctx, "DB");
1633
- * ```
1634
- */
1635
- const resolveD1 = (ctx, binding) => {
1636
- const databases = ctx.require(d1Plugin).deployManifest();
1637
- const matched = binding === void 0 ? databases : databases.filter((db) => db.binding === binding);
1638
- const target = matched.length === 1 ? matched[0] : void 0;
1639
- if (target === void 0) throw new Error(binding === void 0 ? `[moku-worker] seed: ${String(databases.length)} d1 databases configured — pass { binding } to choose one.` : `[moku-worker] seed: no d1 database is bound to "${binding}".`);
1640
- return target;
1641
- };
1642
- /**
1643
- * Run a configured seed against one scope: execute the seed SQL against the d1 database, then delete
1644
- * each configured cached KV key so the next read rebuilds it from the freshly-seeded rows. The
1645
- * schema is assumed to exist (the caller applies migrations first), so this never migrates. The
1646
- * wrangler runner is injected so the same orchestration serves the streamed deploy path and the
1647
- * injectable dev path.
1648
- *
1649
- * @param ctx - The deploy plugin context.
1650
- * @param run - The wrangler runner to execute each command through.
1651
- * @param seed - The resolved seed config (SQL file, optional binding, KV keys to reset).
1652
- * @param scope - The wrangler scope: `--remote` (deploy) or `--local` (dev).
1653
- * @returns Resolves once the seed file has executed and every cached KV key is cleared.
1654
- * @throws {Error} When no d1 database is configured, or the seed's binding cannot be resolved.
1655
- * @example
1656
- * ```ts
1657
- * await runConfiguredSeed(ctx, runWranglerInherit, ctx.config.seed, "--remote");
1658
- * ```
1659
- */
1660
- const runConfiguredSeed = async (ctx, run, seed, scope) => {
1661
- if (!ctx.has("d1")) throw new Error("[moku-worker] seed: no d1 database is configured.");
1662
- await run([
1663
- "d1",
1664
- "execute",
1665
- resolveD1(ctx, seed.binding).binding,
1666
- scope,
1667
- "--file",
1668
- seed.file
1669
- ]);
1670
- for (const entry of seed.resetKv ?? []) await run([
1671
- "kv",
1672
- "key",
1673
- "delete",
1674
- entry.key,
1675
- "--binding",
1676
- entry.binding,
1677
- scope
1678
- ]);
1679
- };
1680
- //#endregion
1681
- //#region src/plugins/deploy/dev/build.ts
1682
- /**
1683
- * @file deploy plugin — dev site-rebuild resolution.
1684
- *
1685
- * Resolves HOW to rebuild the Moku web site on change: the in-process `webBuild` hook (preferred,
1686
- * fast, typed — passed call-time from the consumer's script or set as a config default) → a
1687
- * `buildCommand` shell string → an auto-detected `scripts/build.ts`. When nothing is configured,
1688
- * dev serves the worker only and says so. Subprocesses inherit the parent env by default.
1689
- * Node-only; never imported by the runtime Worker bundle.
1690
- */
1691
- /** Convention build script auto-detected when no webBuild/buildCommand is configured. */
1692
- const AUTO_DETECT = "scripts/build.ts";
1693
- /**
1694
- * Opportunistically read a numeric `files` count off an arbitrary web build result. A real web
1695
- * build returns its own summary shape (the worker framework cannot know it), so anything without a
1696
- * numeric `files` field reports 0.
1697
- *
1698
- * @param result - The resolved value of a {@link WebBuild} hook (any shape).
1699
- * @returns The `files` count when present and numeric, else 0.
1700
- * @example
1701
- * ```ts
1702
- * fileCountOf({ files: 12 }); // 12
1703
- * fileCountOf({ outDir: "dist", pageCount: 4 }); // 0
1704
- * ```
1705
- */
1706
- const fileCountOf = (result) => {
1707
- if (typeof result === "object" && result !== null && "files" in result) {
1708
- const { files } = result;
1709
- return typeof files === "number" ? files : 0;
1710
- }
1711
- return 0;
1712
- };
1713
- /**
1714
- * Run a shell build command, resolving on a zero exit and rejecting otherwise.
1715
- *
1716
- * @param command - The shell command to run (the consumer's own configured build).
1717
- * @returns Resolves once the command exits successfully.
1718
- * @throws {Error} When the command fails to start or exits non-zero.
1719
- * @example
1720
- * ```ts
1721
- * await runShellBuild("bun run scripts/build.ts");
1722
- * ```
1723
- */
1724
- const runShellBuild = (command) => {
1725
- return new Promise((resolve, reject) => {
1726
- const child = spawn(command, {
1727
- shell: true,
1728
- stdio: "inherit"
1729
- });
1730
- child.on("error", (error) => {
1731
- reject(/* @__PURE__ */ new Error(`[moku-worker] site build failed to start.\n ${error.message}`));
1732
- });
1733
- child.on("close", (code) => {
1734
- if (code === 0) {
1735
- resolve();
1736
- return;
1737
- }
1738
- reject(/* @__PURE__ */ new Error(`[moku-worker] site build exited with code ${String(code)}.`));
1739
- });
1740
- });
1741
- };
1742
- /**
1743
- * Rebuild the Moku web site using the resolved strategy: the call-time `webBuild` hook (the
1744
- * script-driven path), else the `webBuild` config default, else the `buildCommand` shell string,
1745
- * else an auto-detected `scripts/build.ts`. A hook's result is normalized to a `{ files }` count
1746
- * (0 when the hook reports none, and for the shell path where it is unknown).
1747
- *
1748
- * @param ctx - The deploy plugin context (config + emit).
1749
- * @param webBuild - Optional call-time web build hook (takes precedence over `ctx.config.webBuild`).
1750
- * @returns The rebuilt file count (0 for the shell path / a countless hook).
1751
- * @throws {Error} When the resolved shell build fails.
1752
- * @example
1753
- * ```ts
1754
- * const { files } = await buildSite(ctx, () => web.cli.build());
1755
- * ```
1756
- */
1757
- const buildSite = async (ctx, webBuild) => {
1758
- const hook = webBuild ?? ctx.config.webBuild;
1759
- if (hook !== void 0) return { files: fileCountOf(await hook()) };
1760
- const command = ctx.config.buildCommand || (existsSync(AUTO_DETECT) ? `bun run ${AUTO_DETECT}` : "");
1761
- if (command === "") {
1762
- ctx.emit("dev:error", { message: "No site build configured (pass webBuild or set buildCommand); serving worker only." });
1763
- return { files: 0 };
1764
- }
1765
- await runShellBuild(command);
1766
- return { files: 0 };
1767
- };
1768
- //#endregion
1769
- //#region src/plugins/deploy/dev/watch.ts
1770
- /**
1771
- * @file deploy plugin — debounced filesystem watcher for dev.
1772
- *
1773
- * Watches the top-level directories implied by the config globs (recursive) and fires a debounced
1774
- * change callback with the SET of paths changed in the window (so a burst of edits coalesces into
1775
- * one rebuild that knows every changed file). Uses node:fs.watch — no extra dependency.
1776
- * Node-only; never imported by the runtime Worker bundle.
1777
- */
1778
- /**
1779
- * Derive the set of top-level directories to watch from glob patterns.
1780
- *
1781
- * @param globs - Watch globs (e.g. ["src/**\/*.ts", "public/**\/*"]).
1782
- * @returns The distinct top-level directories (e.g. ["src", "public"]).
1783
- * @example
1784
- * ```ts
1785
- * watchDirectories(["src/**\/*.ts", "public/**\/*"]); // ["src", "public"]
1786
- * ```
1787
- */
1788
- const watchDirectories = (globs) => {
1789
- const directories = /* @__PURE__ */ new Set();
1790
- for (const glob of globs) {
1791
- const globStart = glob.search(/[*?[{]/u);
1792
- const top = (globStart === -1 ? path.dirname(glob) : glob.slice(0, globStart)).split(/[/\\]/u).find((segment) => segment !== "") ?? ".";
1793
- directories.add(top);
1794
- }
1795
- return [...directories];
1796
- };
1797
- /**
1798
- * Watch the directories implied by `globs` and fire `onChange` (debounced by `debounceMs`) with the
1799
- * distinct set of paths changed within the window. Missing directories are skipped silently.
1800
- *
1801
- * @param globs - Watch globs.
1802
- * @param debounceMs - Coalesce rapid changes into one callback within this window.
1803
- * @param onChange - Called with the changed paths (snapshot of the window) after the debounce settles.
1804
- * @returns A handle whose close() stops all watchers and cancels any pending callback.
1805
- * @example
1806
- * ```ts
1807
- * const handle = watchPaths(["src/**\/*.ts"], 120, paths => rebuild(paths));
1808
- * handle.close();
1809
- * ```
1810
- */
1811
- const watchPaths = (globs, debounceMs, onChange) => {
1812
- let timer;
1813
- const changed = /* @__PURE__ */ new Set();
1814
- const fire = (changedPath) => {
1815
- changed.add(changedPath);
1816
- if (timer !== void 0) clearTimeout(timer);
1817
- timer = setTimeout(() => {
1818
- const batch = [...changed];
1819
- changed.clear();
1820
- onChange(batch);
1821
- }, debounceMs);
1822
- };
1823
- const watchers = [];
1824
- for (const directory of watchDirectories(globs)) {
1825
- if (!existsSync(directory)) continue;
1826
- watchers.push(watch(directory, { recursive: true }, (_event, filename) => {
1827
- if (filename !== null) fire(path.join(directory, filename.toString()));
1828
- }));
1829
- }
1830
- return { close: () => {
1831
- if (timer !== void 0) clearTimeout(timer);
1832
- for (const watcher of watchers) watcher.close();
1833
- } };
1834
- };
1835
- //#endregion
1836
- //#region src/plugins/deploy/dev/runner.ts
1837
- /**
1838
- * @file deploy plugin — dev watch/recompile orchestrator.
1839
- *
1840
- * One long-lived session: cold-build the Moku site, optionally apply local D1 migrations, spawn
1841
- * `wrangler dev --live-reload` ONCE, then watch the site sources and rebuild on change (wrangler's
1842
- * asset server live-reloads the browser). Build failures keep the session serving the last good
1843
- * build. Tears down cleanly on SIGINT. Side-effecting work is injected via DevDeps so the
1844
- * orchestration is unit-testable without real processes, watchers, or signals.
1845
- * Node-only; never imported by the runtime Worker bundle.
1846
- */
1847
- /** Grace period (ms) before escalating a hung `wrangler dev` shutdown from SIGINT to SIGKILL. */
1848
- const STOP_GRACE_MS = 4e3;
1849
- /**
1850
- * Spawn the long-lived `wrangler dev` child (inherits the parent env; non-blocking).
1851
- *
1852
- * `whenExited` settles when the child exits OR fails to spawn — the `error` listener is essential:
1853
- * a missing/unexecutable wrangler emits `error` (not `exit`), which is otherwise unhandled (crashes
1854
- * the process) and would leave `whenExited` pending forever, hanging `stop()`. `stop()` shuts
1855
- * wrangler down the way its own Ctrl+C does — a graceful SIGINT, then a SIGKILL escalation if it has
1856
- * not exited within {@link STOP_GRACE_MS} — resolving only once it is gone; a spawn failure is
1857
- * surfaced as a thrown branded error so the caller can render it. Without the wait, the
1858
- * inherited-stdio child can keep the parent alive after the watcher closes ("stuck on stopping").
1859
- *
1860
- * @param args - The `wrangler dev …` arguments.
1861
- * @returns A handle: `whenExited` (settles on exit/spawn-failure) and `stop()` (resolves once gone).
1862
- * @example
1863
- * ```ts
1864
- * const child = spawnWranglerDev(["dev", "--port", "8787"]);
1865
- * await Promise.race([untilSignal(), child.whenExited]);
1866
- * await child.stop();
1867
- * ```
1868
- */
1869
- const spawnWranglerDev = (args) => {
1870
- const child = spawn("wrangler", args, { stdio: "inherit" });
1871
- let spawnError;
1872
- const whenExited = new Promise((resolve) => {
1873
- child.once("exit", () => {
1874
- resolve();
1875
- });
1876
- child.once("error", (error) => {
1877
- spawnError = /* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${error.message}`);
1878
- resolve();
1879
- });
1880
- });
1881
- const stop = async () => {
1882
- if (spawnError !== void 0) throw spawnError;
1883
- if (child.exitCode !== null || child.signalCode !== null || child.pid === void 0) return;
1884
- child.kill("SIGINT");
1885
- const forceKill = setTimeout(() => child.kill("SIGKILL"), STOP_GRACE_MS);
1886
- await whenExited;
1887
- clearTimeout(forceKill);
1888
- };
1889
- return {
1890
- stop,
1891
- whenExited
1892
- };
1893
- };
1894
- /**
1895
- * Resolve when the user first interrupts the dev session (SIGINT).
1896
- *
1897
- * @returns A promise that settles on the first SIGINT.
1898
- * @example
1899
- * ```ts
1900
- * await waitForSigint();
1901
- * ```
1902
- */
1903
- const waitForSigint = () => {
1904
- return new Promise((resolve) => {
1905
- process.once("SIGINT", () => {
1906
- resolve();
1907
- });
1908
- });
1909
- };
1910
- /**
1911
- * Wall-clock timestamp in ms (extracted so realDevDeps holds only named references).
1912
- *
1913
- * @returns The current time in milliseconds.
1914
- * @example
1915
- * ```ts
1916
- * const t = nowMs();
1917
- * ```
1918
- */
1919
- const nowMs = () => Date.now();
1920
- /**
1921
- * Build the real (side-effecting) dev deps used by api.dev(). Subprocesses inherit the parent env.
1922
- *
1923
- * @returns The production DevDeps (real spawn / fs.watch / SIGINT / Date.now).
1924
- * @example
1925
- * ```ts
1926
- * await runDev(ctx, opts, realDevDeps());
1927
- * ```
1928
- */
1929
- const realDevDeps = () => ({
1930
- build: buildSite,
1931
- runWrangler,
1932
- spawnDev: spawnWranglerDev,
1933
- watch: watchPaths,
1934
- untilSignal: waitForSigint,
1935
- now: nowMs
1936
- });
1937
- /**
1938
- * The d1 bindings to migrate locally — one per configured d1 instance that declares a migrations
1939
- * directory (empty when no d1 plugin is present, or none declares migrations).
1940
- *
1941
- * @param ctx - The deploy plugin context.
1942
- * @returns The d1 binding names with migrations (e.g. `["DB"]`).
1943
- * @example
1944
- * ```ts
1945
- * const bindings = d1MigrationBindings(ctx); // ["DB"]
1946
- * ```
1947
- */
1948
- const d1MigrationBindings = (ctx) => ctx.has("d1") ? ctx.require(d1Plugin).deployManifest().filter((manifest) => manifest.migrations !== void 0).map((manifest) => manifest.binding) : [];
1949
- /**
1950
- * One-line description of a changed-path batch for the `dev:phase rebuild` detail: the single path,
1951
- * or the first path plus a `(+N more)` tail. Empty batches (defensive) read as "site".
1952
- *
1953
- * @param paths - The changed paths the watcher coalesced for this rebuild.
1954
- * @returns The detail string for the rebuild phase event.
1955
- * @example
1956
- * ```ts
1957
- * describeChanges(["src/a.ts", "src/b.css"]); // "src/a.ts (+1 more)"
1958
- * ```
1959
- */
1960
- const describeChanges = (paths) => {
1961
- const [first, ...rest] = paths;
1962
- if (first === void 0) return "site";
1963
- return rest.length === 0 ? first : `${first} (+${String(rest.length)} more)`;
1964
- };
1965
- /**
1966
- * Rebuild the site once for a changed-path batch and announce the result. The FAST path is the
1967
- * incremental `onChange(changedPaths)` hook (e.g. `web.cli.update`) when wired; otherwise it falls
1968
- * back to a full `webBuild()` rebuild (via deps.build) — the prior behavior. A failed rebuild keeps
1969
- * the session alive (it just emits dev:error and serves the last good build). Both paths share one
1970
- * `dev:phase rebuild` → `dev:rebuilt`/`dev:error` envelope so the branded dev TUI is identical.
1971
- *
1972
- * @param ctx - The deploy plugin context.
1973
- * @param deps - The injected dev deps.
1974
- * @param changedPaths - The paths that triggered the rebuild (the watcher's debounced set).
1975
- * @param hooks - The consumer rebuild hooks.
1976
- * @param hooks.webBuild - Full rebuild (used when `onChange` is absent — the prior behavior).
1977
- * @param hooks.onChange - Incremental rebuild for the changed set (the fast path when wired).
1978
- * @returns Resolves once the rebuild attempt completes.
1979
- * @example
1980
- * ```ts
1981
- * await rebuild(ctx, deps, ["src/app.tsx"], { onChange: c => web.cli.update(c) });
1982
- * ```
1983
- */
1984
- const rebuild = async (ctx, deps, changedPaths, hooks) => {
1985
- ctx.emit("dev:phase", {
1986
- phase: "rebuild",
1987
- detail: describeChanges(changedPaths)
1988
- });
1989
- const started = deps.now();
1990
- try {
1991
- let files;
1992
- if (hooks.onChange) files = fileCountOf(await hooks.onChange(changedPaths));
1993
- else files = (await deps.build(ctx, hooks.webBuild)).files;
1994
- ctx.emit("dev:rebuilt", {
1995
- files,
1996
- ms: deps.now() - started
1997
- });
1998
- } catch (error) {
1999
- ctx.emit("dev:error", { message: error instanceof Error ? error.message : String(error) });
2000
- }
2001
- };
2002
- /**
2003
- * Load the configured seed into the LOCAL D1 for a `dev --seed` session: execute the SQL file, then
2004
- * clear the configured cached KV keys so the app rebuilds them from the freshly-seeded rows. The
2005
- * schema already exists (the migrate step above runs first), so this never migrates — the local
2006
- * analogue of the deploy's remote seed, over the same `pluginConfigs.deploy.seed` config.
2007
- *
2008
- * @param ctx - The deploy plugin context.
2009
- * @param deps - The injected dev deps (for the wrangler runner).
2010
- * @returns Resolves once the seed file has executed and every cached KV key is cleared.
2011
- * @throws {Error} When `--seed` is set but no seed is configured under `pluginConfigs.deploy.seed`.
2012
- * @example
2013
- * ```ts
2014
- * await seedLocal(ctx, realDevDeps());
2015
- * ```
2016
- */
2017
- const seedLocal = async (ctx, deps) => {
2018
- const config = ctx.config.seed;
2019
- if (config === void 0) throw new Error("[moku-worker] dev({ seed: true }) but no seed is configured — set pluginConfigs.deploy.seed.");
2020
- ctx.emit("dev:phase", {
2021
- phase: "seed",
2022
- detail: config.file
2023
- });
2024
- await runConfiguredSeed(ctx, deps.runWrangler, config, "--local");
2025
- };
2026
- /**
2027
- * Run a long-lived dev session: cold build → (local d1 migrate) → (local seed) → spawn `wrangler
2028
- * dev` → watch + rebuild on change → teardown on signal.
2029
- *
2030
- * @param ctx - The deploy plugin context (config + emit + require/has).
2031
- * @param opts - Optional options.
2032
- * @param opts.port - Local dev port (default 8787).
2033
- * @param opts.webBuild - Cold-build hook (also the per-change rebuild when `onChange` is omitted).
2034
- * @param opts.onChange - Incremental per-change rebuild hook (e.g. `c => web.cli.update(c)`); when
2035
- * set, each debounced change rebuilds only the changed paths instead of a full `webBuild()`.
2036
- * @param opts.seed - Load the configured seed into the LOCAL D1 (+ reset its KV keys) before serving.
2037
- * @param deps - Injected side effects (real ones from realDevDeps in production).
2038
- * @returns Resolves when the session ends (SIGINT).
2039
- * @example
2040
- * ```ts
2041
- * await runDev(ctx, { port: 8787, seed: true, webBuild: () => web.cli.build() }, realDevDeps());
2042
- * ```
2043
- */
2044
- const runDev = async (ctx, opts, deps) => {
2045
- const port = opts?.port ?? 8787;
2046
- const webBuild = opts?.webBuild;
2047
- const onChange = opts?.onChange;
2048
- const seed = opts?.seed === true;
2049
- ctx.emit("dev:phase", {
2050
- phase: "build",
2051
- detail: "site"
2052
- });
2053
- await deps.build(ctx, webBuild);
2054
- const migrationBindings = ctx.config.migrateLocal || seed ? d1MigrationBindings(ctx) : [];
2055
- if (migrationBindings.length > 0) {
2056
- ctx.emit("dev:phase", {
2057
- phase: "migrate",
2058
- detail: "d1 (local)"
2059
- });
2060
- for (const binding of migrationBindings) await deps.runWrangler([
2061
- "d1",
2062
- "migrations",
2063
- "apply",
2064
- binding,
2065
- "--local"
2066
- ]);
2067
- }
2068
- if (seed) await seedLocal(ctx, deps);
2069
- ctx.emit("dev:phase", {
2070
- phase: "serve",
2071
- detail: `http://localhost:${String(port)}`
2072
- });
2073
- const child = deps.spawnDev([
2074
- "dev",
2075
- "--port",
2076
- String(port),
2077
- "--config",
2078
- ctx.config.configFile,
2079
- "--live-reload"
2080
- ]);
2081
- const watcher = deps.watch(ctx.config.watch, ctx.config.debounceMs, (changedPaths) => rebuild(ctx, deps, changedPaths, {
2082
- webBuild,
2083
- onChange
2084
- }));
2085
- await Promise.race([deps.untilSignal(), child.whenExited]);
2086
- ctx.emit("dev:phase", { phase: "stopping" });
2087
- watcher.close();
2088
- await child.stop();
2089
- };
2090
- //#endregion
2091
- //#region src/plugins/deploy/infra/plan.ts
2092
- /**
2093
- * Decide whether a single API-provisioned resource already exists in the account, recovering its id
2094
- * (kv/d1) when it does. Durable Objects are NOT handled here — they ship with the Worker (`wrangler
2095
- * deploy` + the auto-derived DO migration create the namespace), are never provisioned via the API,
2096
- * and are partitioned into the plan's `ships` bucket by {@link planInfra} before this is ever called.
2097
- *
2098
- * @param resource - The declared (provisionable) resource descriptor.
2099
- * @param existing - The indexed set of resources already in the account.
2100
- * @returns Whether it exists, plus the captured id for kv/d1.
2101
- * @example
2102
- * ```ts
2103
- * checkExisting({ kind: "kv", binding: "SESSIONS" }, existing); // { exists: true, id: "ns123" }
2104
- * ```
2105
- */
2106
- const checkExisting = (resource, existing) => {
2107
- switch (resource.kind) {
2108
- case "kv": {
2109
- const id = existing.kv.get(resource.name);
2110
- return id === void 0 ? { exists: false } : {
2111
- exists: true,
2112
- id
2113
- };
2114
- }
2115
- case "d1": {
2116
- const id = existing.d1.get(resource.name);
2117
- return id === void 0 ? { exists: false } : {
2118
- exists: true,
2119
- id
2120
- };
2121
- }
2122
- case "r2": return { exists: existing.r2.has(resource.name) };
2123
- case "queue": return { exists: existing.queue.has(resource.name) };
2124
- }
2125
- };
2126
- /**
2127
- * Run the read-only infra preflight: resolve the account, list existing resources, diff against
2128
- * the manifest, emit `provision:plan`, and return the plan. Writes nothing.
2129
- *
2130
- * @param ctx - The deploy plugin context (env + emit).
2131
- * @param manifest - The assembled (or caller-supplied) deploy manifest.
2132
- * @returns The infra plan: existing (with ids) vs missing vs ships-with-Worker (Durable Objects).
2133
- * @throws {Error} When the token is absent/invalid or a Cloudflare listing fails.
2134
- * @example
2135
- * ```ts
2136
- * const plan = await planInfra(ctx, manifest);
2137
- * ```
2138
- */
2139
- const planInfra = async (ctx, manifest) => {
2140
- const token = ctx.env.require("CLOUDFLARE_API_TOKEN");
2141
- const pinnedAccountId = ctx.env.get("CLOUDFLARE_ACCOUNT_ID");
2142
- const account = pinnedAccountId ? {
2143
- id: pinnedAccountId,
2144
- name: pinnedAccountId
2145
- } : await resolveAccount(token);
2146
- const kinds = /* @__PURE__ */ new Set();
2147
- for (const resource of manifest.resources) if (resource.kind !== "do") kinds.add(resource.kind);
2148
- const existing = await listExisting(token, account.id, kinds);
2149
- const exists = [];
2150
- const missing = [];
2151
- const ships = [];
2152
- for (const resource of manifest.resources) {
2153
- if (resource.kind === "do") {
2154
- ships.push(resource);
2155
- continue;
2156
- }
2157
- const check = checkExisting(resource, existing);
2158
- if (check.exists) exists.push(check.id === void 0 ? { resource } : {
2159
- resource,
2160
- id: check.id
2161
- });
2162
- else missing.push(resource);
2163
- }
2164
- ctx.emit("provision:plan", {
2165
- exists: exists.length,
2166
- missing: missing.length,
2167
- ships: ships.length,
2168
- account: account.name
2169
- });
2170
- return {
2171
- account: account.name,
2172
- accountId: account.id,
2173
- exists,
2174
- missing,
2175
- ships
2176
- };
2177
- };
2178
- //#endregion
2179
- //#region src/plugins/deploy/infra/render.ts
2180
- /**
2181
- * Derive a human-readable name from a resource descriptor: the Cloudflare resource `name` for the
2182
- * provisioned kinds (kv/r2/d1/queue), or the exported `className` for a Durable Object (which has no
2183
- * provisioned name). Used in both the provision events and the branded panels so the two agree.
2184
- *
2185
- * @param resource - The resource descriptor.
2186
- * @returns A short name identifying the resource.
2187
- * @example
2188
- * ```ts
2189
- * resourceName({ kind: "kv", name: "tracker-cache", binding: "CACHE" }); // "tracker-cache"
2190
- * ```
2191
- */
2192
- const resourceName = (resource) => resource.kind === "do" ? resource.className : resource.name;
2193
- /**
2194
- * Format a `kind name` cell, padding the kind so the names line up in a column.
2195
- *
2196
- * @param kind - The resource kind (kv / r2 / d1 / queue / do).
2197
- * @param name - The resource name.
2198
- * @returns The aligned `kind name` cell.
2199
- * @example
2200
- * ```ts
2201
- * cell("kv", "CACHE"); // "kv CACHE"
2202
- * ```
2203
- */
2204
- const cell = (kind, name) => `${kind.padEnd(6)}${name}`;
2205
- /**
2206
- * Row tag for a Durable Object — it ships with the Worker (`wrangler deploy` creates the namespace),
2207
- * so it is NEVER labelled `(exists)` (the planner never queried the account for it). Shared by the
2208
- * plan and provision-result panels so the two always read the same.
2209
- */
2210
- const SHIPS_WITH_WORKER = "(ships with worker)";
2211
- /**
2212
- * ANSI SGR matcher — built from `String.fromCharCode(27)` (the ESC byte) so no control character
2213
- * appears in a regex literal (which both linters reject).
2214
- */
2215
- const ANSI_SGR = new RegExp(String.raw`${String.fromCodePoint(27)}\[[0-9;]*m`, "gu");
2216
- /**
2217
- * Strip ANSI SGR escape sequences so a captured (colorized) error renders as plain, readable text.
2218
- *
2219
- * @param text - The (possibly colorized) text.
2220
- * @returns The text with ANSI color codes removed.
2221
- * @example
2222
- * ```ts
2223
- * stripAnsi(`${String.fromCharCode(27)}[31mX${String.fromCharCode(27)}[0m`); // "X"
2224
- * ```
2225
- */
2226
- const stripAnsi = (text) => text.replaceAll(ANSI_SGR, "");
2227
- /**
2228
- * Clean a captured (colorized, multi-line, wrapper-wrapped) provision error down to its meaningful
2229
- * text: strip ANSI, drop the wrapper lines (the branded prefix, wrangler's log-file pointer), strip
2230
- * each `✘ [ERROR]` marker, and join what's left. Returns the FULL message (the caller word-wraps it)
2231
- * so the user reads the actual reason — never a truncated `…`.
2232
- *
2233
- * @param message - The captured error message.
2234
- * @returns The full, plain failure reason.
2235
- * @example
2236
- * ```ts
2237
- * cleanError("[moku-worker] wrangler exited…\n ✘ [ERROR] The bucket name is invalid.");
2238
- * // "The bucket name is invalid."
2239
- * ```
2240
- */
2241
- const cleanError = (message) => {
2242
- const cleaned = stripAnsi(message).split("\n").map((line) => line.trim()).filter((line) => line.length > 0).filter((line) => !/^\[moku-worker\]/u.test(line)).filter((line) => !/logs were written to/iu.test(line)).map((line) => line.replace(/^✘\s*/u, "").replace(/^\[error\]\s*/iu, "")).join(" ");
2243
- return cleaned.length > 0 ? cleaned : stripAnsi(message).trim();
2244
- };
2245
- /**
2246
- * Word-wrap text to `width` columns (never splitting inside a word), so a long failure reason reads
2247
- * as a tidy indented block instead of forcing the box wide or scrolling off the edge.
2248
- *
2249
- * @param text - The text to wrap.
2250
- * @param width - The maximum column width per line.
2251
- * @returns The wrapped lines.
2252
- * @example
2253
- * ```ts
2254
- * wrapText("a long sentence to wrap", 10); // ["a long", "sentence", "to wrap"]
2255
- * ```
2256
- */
2257
- const wrapText = (text, width) => {
2258
- const lines = [];
2259
- let line = "";
2260
- for (const word of text.split(/\s+/u).filter(Boolean)) if (line.length === 0) line = word;
2261
- else if (line.length + 1 + word.length <= width) line += ` ${word}`;
2262
- else {
2263
- lines.push(line);
2264
- line = word;
2265
- }
2266
- if (line.length > 0) lines.push(line);
2267
- return lines;
2268
- };
2269
- /**
2270
- * Render the infra preflight plan as a branded panel: a dim summary line (counts + account) then one
2271
- * row per declared resource — a pink `+` for those to create, a dim `~ (exists)` for those already
2272
- * present, and a dim `~ (ships with worker)` for Durable Objects (created by `wrangler deploy`, never
2273
- * pre-provisioned). When nothing needs creating it still renders, so the user sees the full picture.
2274
- *
2275
- * @param ui - The branded console to render through.
2276
- * @param plan - The infra plan (existing vs missing vs ships-with-Worker) from checkInfra()/planInfra().
2277
- * @example
2278
- * ```ts
2279
- * renderPlan(ui, await planInfra(ctx, manifest));
2280
- * ```
2281
- */
2282
- const renderPlan = (ui, plan) => {
2283
- const { palette } = ui;
2284
- const counts = [`${String(plan.missing.length)} to create`, `${String(plan.exists.length)} exist`];
2285
- if (plan.ships.length > 0) counts.push(`${String(plan.ships.length)} with worker`);
2286
- const summary = palette.dim(`${counts.join(" · ")} · ${plan.account}`);
2287
- const createRows = plan.missing.map((resource) => `${palette.pink("+")} ${cell(resource.kind, resourceName(resource))}`);
2288
- const existsRows = plan.exists.map((ref) => `${palette.dim("~")} ${cell(ref.resource.kind, resourceName(ref.resource))} ${palette.dim("(exists)")}`);
2289
- const shipsRows = plan.ships.map((resource) => `${palette.dim("~")} ${cell(resource.kind, resourceName(resource))} ${palette.dim(SHIPS_WITH_WORKER)}`);
2290
- ui.heading("Infra plan");
2291
- ui.box([
2292
- summary,
2293
- "",
2294
- ...createRows,
2295
- ...existsRows,
2296
- ...shipsRows
2297
- ]);
2298
- };
2299
- /**
2300
- * Render the provision result as a branded panel — a green `✓` per created resource, a dim `~` per
2301
- * skipped, a dim `~ (ships with worker)` per Durable Object, a red `✗` per failure, then a summary
2302
- * line (failed count red when non-zero) — followed, when anything failed, by a detail block printing
2303
- * each failure's FULL reason (ANSI-stripped and word-wrapped) so it is actually readable instead of
2304
- * truncated inside the box.
2305
- *
2306
- * @param ui - The branded console to render through.
2307
- * @param result - The provision result from provisionInfra()/the deploy pipeline.
2308
- * @example
2309
- * ```ts
2310
- * renderProvisionResult(ui, await provisionInfra(plan));
2311
- * ```
2312
- */
2313
- const renderProvisionResult = (ui, result) => {
2314
- const { palette } = ui;
2315
- const createdRows = result.created.map((ref) => `${palette.green("✓")} ${cell(ref.resource.kind, resourceName(ref.resource))}`);
2316
- const skippedRows = result.skipped.map((ref) => `${palette.dim("~")} ${cell(ref.resource.kind, resourceName(ref.resource))} ${palette.dim("(exists)")}`);
2317
- const bundledRows = result.bundled.map((resource) => `${palette.dim("~")} ${cell(resource.kind, resourceName(resource))} ${palette.dim(SHIPS_WITH_WORKER)}`);
2318
- const failedRows = result.failed.map((failure) => `${palette.red("✗")} ${cell(failure.resource.kind, resourceName(failure.resource))}`);
2319
- const failedCount = result.failed.length > 0 ? palette.red(`${String(result.failed.length)} failed`) : "0 failed";
2320
- const counts = [`${String(result.created.length)} created`, `${String(result.skipped.length)} exist`];
2321
- if (result.bundled.length > 0) counts.push(`${String(result.bundled.length)} with worker`);
2322
- const summary = `${counts.join(" · ")} · ${failedCount}`;
2323
- ui.heading("Provisioned");
2324
- ui.box([
2325
- ...createdRows,
2326
- ...skippedRows,
2327
- ...bundledRows,
2328
- ...failedRows,
2329
- "",
2330
- summary
2331
- ]);
2332
- if (result.failed.length > 0) {
2333
- ui.line();
2334
- for (const failure of result.failed) {
2335
- ui.line(` ${palette.red("✗")} ${cell(failure.resource.kind, resourceName(failure.resource))}`);
2336
- for (const wrapped of wrapText(cleanError(failure.error), ui.width - 4)) ui.line(palette.dim(` ${wrapped}`));
2337
- }
2338
- }
2339
- };
2340
- /**
2341
- * Format an elapsed duration compactly: sub-second as `820ms`, otherwise one-decimal seconds (`4.2s`),
2342
- * and minutes once it crosses 60s (`1m04s`) so a long deploy stays readable.
2343
- *
2344
- * @param ms - The elapsed milliseconds.
2345
- * @returns The compact duration string.
2346
- * @example
2347
- * ```ts
2348
- * formatDuration(4234); // "4.2s"
2349
- * ```
2350
- */
2351
- const formatDuration = (ms) => {
2352
- if (ms < 1e3) return `${String(ms)}ms`;
2353
- const seconds = ms / 1e3;
2354
- if (seconds < 60) return `${seconds.toFixed(1)}s`;
2355
- const whole = Math.floor(seconds);
2356
- return `${String(Math.floor(whole / 60))}m${String(whole % 60).padStart(2, "0")}s`;
2357
- };
2358
- /**
2359
- * Render the terminal deploy summary as a branded panel — the headline the user actually wants. The
2360
- * live URL leads on its own line (pink, so it is the first thing the eye lands on), then a dim
2361
- * key/value block: the target stage, the resource tally (with a red `failed` count when non-zero),
2362
- * and the wall-clock time the whole deploy took. Replaces the prior single `deployed → url` line.
2363
- *
2364
- * @param ui - The branded console to render through.
2365
- * @param summary - The deploy summary fields.
2366
- * @param summary.url - The live deployed URL (the panel headline).
2367
- * @param summary.stage - The target stage the worker deployed to.
2368
- * @param summary.created - How many resources were created this run.
2369
- * @param summary.exists - How many resources already existed (skipped).
2370
- * @param summary.bundled - How many Durable Objects shipped with the Worker.
2371
- * @param summary.failed - How many resources failed to provision.
2372
- * @param summary.elapsedMs - The wall-clock deploy duration in milliseconds.
2373
- * @example
2374
- * ```ts
2375
- * renderDeploySummary(ui, { url, stage: "production", created: 0, exists: 5, bundled: 1, failed: 0, elapsedMs: 4234 });
2376
- * ```
2377
- */
2378
- const renderDeploySummary = (ui, summary) => {
2379
- const { palette } = ui;
2380
- const parts = [`${String(summary.exists)} exist`, `${String(summary.created)} created`];
2381
- if (summary.bundled > 0) parts.push(`${String(summary.bundled)} with worker`);
2382
- const tally = parts.join(" · ");
2383
- const failedLabel = palette.red(`${String(summary.failed)} failed`);
2384
- const resources = summary.failed > 0 ? `${tally} · ${failedLabel}` : tally;
2385
- ui.heading("Deployed");
2386
- ui.box([
2387
- palette.pink(summary.url),
2388
- "",
2389
- `${palette.dim("stage".padEnd(10))}${summary.stage}`,
2390
- `${palette.dim("resources".padEnd(10))}${resources}`,
2391
- `${palette.dim("took".padEnd(10))}${formatDuration(summary.elapsedMs)}`
2392
- ]);
2393
- };
2394
- //#endregion
2395
- //#region src/plugins/deploy/naming.ts
2396
- /**
2397
- * @file deploy plugin — stage-aware resource naming.
2398
- *
2399
- * One source of truth for turning a base Cloudflare resource name into its stage variant, so the
2400
- * worker name, the provisioners, the infra existence diff, and the generated wrangler config all
2401
- * agree. Production keeps the base name; every other stage gets a `-${stage}` suffix. Node-only;
2402
- * never imported by the runtime Worker bundle.
2403
- */
2404
- /**
2405
- * Apply the deploy stage to a base Cloudflare resource name: the base name in `production`, else
2406
- * `${base}-${stage}` (e.g. dev → `tracker-db-dev`). Env bindings + DO class names never get the
2407
- * suffix — only provisioned resource names (and the worker name) are stage-qualified.
2408
- *
2409
- * @param base - The base resource name (e.g. "tracker-db").
2410
- * @param stage - The deploy stage (e.g. "production", "development", "dev").
2411
- * @returns The stage-qualified name.
2412
- * @example
2413
- * ```ts
2414
- * stageName("tracker-db", "production"); // "tracker-db"
2415
- * stageName("tracker-db", "dev"); // "tracker-db-dev"
2416
- * ```
2417
- */
2418
- const stageName = (base, stage) => stage === "production" ? base : `${base}-${stage}`;
2419
- //#endregion
2420
- //#region src/plugins/deploy/providers/d1.ts
2421
- /**
2422
- * @file deploy plugin — D1 provisioning adapter.
2423
- *
2424
- * Creates a Cloudflare D1 database via `wrangler d1 create <binding>`, captures the created
2425
- * database id from wrangler's output (so writeWranglerConfig can write a real `database_id`
2426
- * instead of an empty placeholder), and applies migrations when declared.
2427
- * Node-only; never imported by the runtime Worker bundle.
2428
- */
2429
- /**
2430
- * Parse the created D1 database id from `wrangler d1 create` output.
2431
- * Wrangler prints the new binding as JSON (`"database_id": "..."`) or TOML
2432
- * (`database_id = "..."`); the leading boundary keeps the match anchored to the field name.
2433
- *
2434
- * @param output - Raw stdout from the wrangler create command.
2435
- * @returns The database id, or undefined when none is found.
2436
- * @example
2437
- * ```ts
2438
- * parseD1DatabaseId('{ "database_id": "uuid-1234" }'); // "uuid-1234"
2439
- * ```
2440
- */
2441
- const parseD1DatabaseId = (output) => {
2442
- return /(?:^|[\s,{])"?database_id"?\s*[:=]\s*"([^"]+)"/m.exec(output)?.[1];
2443
- };
2444
- /**
2445
- * Provision a D1 database via `wrangler d1 create`, capture its id, and apply migrations.
2446
- *
2447
- * @param manifest - The D1 resource descriptor.
2448
- * @param _ci - Whether running non-interactively.
2449
- * @returns The captured database id when wrangler reported one, else an empty outcome.
2450
- * @example
2451
- * ```ts
2452
- * const { id } = await provisionD1({ kind: "d1", binding: "DB", migrations: "./migrations" }, false);
2453
- * ```
2454
- */
2455
- const provisionD1 = async (manifest, _ci) => {
2456
- const id = parseD1DatabaseId(await runWrangler([
2457
- "d1",
2458
- "create",
2459
- manifest.name
2460
- ]));
2461
- if (manifest.migrations) await runWrangler([
2462
- "d1",
2463
- "migrations",
2464
- "apply",
2465
- manifest.name,
2466
- "--local"
2467
- ]);
2468
- return id ? { id } : {};
2469
- };
2470
- //#endregion
2471
- //#region src/plugins/deploy/providers/do.ts
2472
- /**
2473
- * Provision Durable Object bindings. DOs are config-driven (no `wrangler do create` command
2474
- * exists) — the actual binding entries are written by writeWranglerConfig. This function is
2475
- * a resolved no-op for the dispatch step.
2476
- *
2477
- * @param _manifest - The Durable Objects resource descriptor.
2478
- * @param _ci - Whether running non-interactively.
2479
- * @returns Resolves immediately (DOs are config-only provisioning).
2480
- * @example
2481
- * ```ts
2482
- * await provisionDurableObject({ kind: "do", bindings: { counter: "COUNTER" } }, false);
2483
- * ```
2484
- */
2485
- const provisionDurableObject = async (_manifest, _ci) => {};
2486
- //#endregion
2487
- //#region src/plugins/deploy/providers/kv.ts
2488
- /**
2489
- * @file deploy plugin — KV provisioning adapter.
2490
- *
2491
- * Creates a Cloudflare KV namespace via `wrangler kv namespace create <binding>` and captures
2492
- * the created namespace id from wrangler's output, so writeWranglerConfig can write a real `id`
2493
- * (not an empty placeholder) into the generated wrangler config — otherwise the binding resolves
2494
- * to nothing at runtime. Node-only; never imported by the runtime Worker bundle.
2495
- */
2496
- /**
2497
- * Parse the created KV namespace id from `wrangler kv namespace create` output.
2498
- * Wrangler prints the new binding as JSON (`"id": "..."`) or TOML (`id = "..."`); the leading
2499
- * boundary (start / whitespace / `{` / `,`) keeps the match off a longer identifier such as
2500
- * `kv_namespace_id`.
2501
- *
2502
- * @param output - Raw stdout from the wrangler create command.
2503
- * @returns The namespace id, or undefined when none is found.
2504
- * @example
2505
- * ```ts
2506
- * parseKvNamespaceId('{ "id": "abc123" }'); // "abc123"
2507
- * ```
2508
- */
2509
- const parseKvNamespaceId = (output) => {
2510
- return /(?:^|[\s,{])"?id"?\s*[:=]\s*"([^"]+)"/m.exec(output)?.[1];
2511
- };
2512
- /**
2513
- * Provision a KV namespace via `wrangler kv namespace create` and capture its id.
2514
- *
2515
- * @param manifest - The KV resource descriptor.
2516
- * @param _ci - Whether running non-interactively (passed through; wrangler respects env vars).
2517
- * @returns The captured namespace id when wrangler reported one, else an empty outcome.
2518
- * @example
2519
- * ```ts
2520
- * const { id } = await provisionKv({ kind: "kv", binding: "CACHE" }, false);
2521
- * ```
2522
- */
2523
- const provisionKv = async (manifest, _ci) => {
2524
- const id = parseKvNamespaceId(await runWrangler([
2525
- "kv",
2526
- "namespace",
2527
- "create",
2528
- manifest.name
2529
- ]));
2530
- return id ? { id } : {};
2531
- };
2532
- //#endregion
2533
- //#region src/plugins/deploy/providers/queues.ts
2534
- /**
2535
- * @file deploy plugin — Queues provisioning adapter.
2536
- *
2537
- * Creates one Cloudflare Queue via `wrangler queues create <name>` per queue instance.
2538
- * Node-only; never imported by the runtime Worker bundle.
2539
- */
2540
- /**
2541
- * Provision the queue via `wrangler queues create <name>`.
2542
- *
2543
- * @param manifest - The queue resource descriptor.
2544
- * @param _ci - Whether running non-interactively.
2545
- * @returns Resolves once the queue is created.
2546
- * @example
2547
- * ```ts
2548
- * await provisionQueue({ kind: "queue", name: "tracker-activity", binding: "ACTIVITY" }, false);
2549
- * ```
2550
- */
2551
- const provisionQueue = async (manifest, _ci) => {
2552
- await runWrangler([
2553
- "queues",
2554
- "create",
2555
- manifest.name
2556
- ]);
2557
- };
2558
- //#endregion
2559
- //#region src/plugins/deploy/providers/r2.ts
2560
- /**
2561
- * @file deploy plugin — R2 provisioning + asset upload adapter.
2562
- *
2563
- * Provides two exports:
2564
- * - `provisionR2`: creates an R2 bucket via `wrangler r2 bucket create`.
2565
- * - `uploadDirToR2`: walks a directory recursively and uploads each file via
2566
- * `wrangler r2 object put`, returning the uploaded file count.
2567
- *
2568
- * Node-only; never imported by the runtime Worker bundle.
2569
- */
2570
- /**
2571
- * Provision an R2 bucket via `wrangler r2 bucket create`.
2572
- *
2573
- * @param manifest - The R2 resource descriptor.
2574
- * @param _ci - Whether running non-interactively.
2575
- * @returns Resolves once the bucket is created.
2576
- * @example
2577
- * ```ts
2578
- * await provisionR2({ kind: "r2", name: "tracker-files", binding: "FILES" }, false);
2579
- * ```
2580
- */
2581
- const provisionR2 = async (manifest, _ci) => {
2582
- await runWrangler([
2583
- "r2",
2584
- "bucket",
2585
- "create",
2586
- manifest.name
2587
- ]);
2588
- };
2589
- /**
2590
- * Walk a directory recursively and return all file paths (absolute).
2591
- *
2592
- * @param directory - Directory path to walk.
2593
- * @returns All file paths found under the directory.
2594
- * @example
2595
- * ```ts
2596
- * const files = await walkDir("./public");
2597
- * ```
2598
- */
2599
- const walkDir = async (directory) => {
2600
- const entries = await readdir(directory);
2601
- const results = [];
2602
- for (const entry of entries) {
2603
- const fullPath = path.join(directory, entry);
2604
- if ((await stat(fullPath)).isDirectory()) {
2605
- const nested = await walkDir(fullPath);
2606
- results.push(...nested);
2607
- } else results.push(fullPath);
2608
- }
2609
- return results;
2610
- };
2611
- /**
2612
- * Upload a directory to an R2 bucket and return the uploaded file count.
2613
- * Each file is uploaded via `wrangler r2 object put <bucket>/<key> --file <path>`.
2614
- *
2615
- * @param bucket - The R2 bucket binding name.
2616
- * @param directory - The directory to upload.
2617
- * @returns The number of files uploaded.
2618
- * @example
2619
- * ```ts
2620
- * const count = await uploadDirToR2("ASSETS", "./public");
2621
- * ```
2622
- */
2623
- const uploadDirToR2 = async (bucket, directory) => {
2624
- const files = await walkDir(directory);
2625
- for (const filePath of files) await runWrangler([
2626
- "r2",
2627
- "object",
2628
- "put",
2629
- `${bucket}/${path.relative(directory, filePath)}`,
2630
- "--file",
2631
- filePath
2632
- ]);
2633
- return files.length;
2634
- };
2635
- //#endregion
2636
- //#region src/plugins/deploy/providers/index.ts
2637
- /**
2638
- * Dispatch a resource descriptor to the matching provider's provisioning routine.
2639
- *
2640
- * @param resource - The resource descriptor to provision.
2641
- * @param ci - Whether running non-interactively.
2642
- * @returns The provisioning outcome — `{ id }` for kv/d1, `{}` for r2/queue/do.
2643
- * @example
2644
- * ```ts
2645
- * const { id } = await provisionResource({ kind: "kv", binding: "CACHE" }, false);
2646
- * await provisionResource({ kind: "r2", bucket: "ASSETS" }, false); // {}
2647
- * ```
2648
- */
2649
- const provisionResource = async (resource, ci) => {
2650
- switch (resource.kind) {
2651
- case "kv": return provisionKv(resource, ci);
2652
- case "d1": return provisionD1(resource, ci);
2653
- case "r2":
2654
- await provisionR2(resource, ci);
2655
- return {};
2656
- case "queue":
2657
- await provisionQueue(resource, ci);
2658
- return {};
2659
- case "do":
2660
- await provisionDurableObject(resource, ci);
2661
- return {};
2662
- }
2663
- };
2664
- //#endregion
2665
- //#region src/plugins/deploy/tty.ts
2666
- /**
2667
- * @file deploy plugin — TTY detection (isolated so the guided flow is testable).
2668
- *
2669
- * The guided deploy only prompts on an interactive terminal; in a pipe or CI it must never block
2670
- * on stdin. Kept in its own module so tests can mock it without stubbing `process.stdout`.
2671
- * Node-only; never imported by the runtime Worker bundle.
2672
- */
2673
- /**
2674
- * Whether stdout is an interactive TTY (so prompts are safe to show).
2675
- *
2676
- * @returns True when stdout is a terminal.
2677
- * @example
2678
- * ```ts
2679
- * if (stdoutIsTty()) await prompts.confirm("Deploy?");
2680
- * ```
2681
- */
2682
- const stdoutIsTty = () => process.stdout.isTTY === true;
2683
- //#endregion
2684
- //#region src/plugins/deploy/wrangler-config.ts
2685
- /**
2686
- * @file deploy plugin — wrangler config generation + scaffold.
2687
- *
2688
- * Provides two exports:
2689
- * - `writeWranglerConfig`: generates/updates a wrangler.jsonc file from an ExternalManifest.
2690
- * Non-destructive: preserves existing top-level keys not managed by deploy.
2691
- * - `scaffoldWranglerAndCi`: creates a minimal starter wrangler config when the file does not
2692
- * exist yet; idempotent (leaves existing files untouched).
2693
- *
2694
- * Node-only; never imported by the runtime Worker bundle.
2695
- */
2696
- /**
2697
- * Strip JSONC line- and block-comments, then JSON.parse the result.
2698
- *
2699
- * @param source - Raw JSONC file contents.
2700
- * @returns The parsed object.
2701
- * @example
2702
- * ```ts
2703
- * const cfg = parseJsonc('{ "name": "w" } // trailing comment');
2704
- * ```
2705
- */
2706
- const parseJsonc = (source) => {
2707
- const stripped = source.replaceAll(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/gu, "");
2708
- return JSON.parse(stripped);
2709
- };
2710
- /**
2711
- * Build the wrangler `kv_namespaces` array from the manifest's kv resources.
2712
- *
2713
- * @param resources - All resource descriptors from the manifest.
2714
- * @param ids - Captured Cloudflare ids keyed by binding; the entry's `id` is filled from here.
2715
- * @returns One wrangler KV namespace entry per kv resource — real `id` when known, omitted otherwise
2716
- * (wrangler rejects an empty `id`, but a local-dev / freshly-generated config validates without one).
2717
- * @example
2718
- * ```ts
2719
- * const kv = buildKvNamespaces([{ kind: "kv", binding: "CACHE" }], { CACHE: "ns123" });
2720
- * ```
2721
- */
2722
- const buildKvNamespaces = (resources, ids) => resources.filter((resource) => resource.kind === "kv").map((resource) => {
2723
- const id = ids[resource.binding];
2724
- return id ? {
2725
- binding: resource.binding,
2726
- id
2727
- } : { binding: resource.binding };
2728
- });
2729
- /**
2730
- * Build the wrangler `r2_buckets` array from the manifest's r2 resources.
2731
- *
2732
- * @param resources - All resource descriptors from the manifest.
2733
- * @returns One wrangler R2 bucket entry per r2 resource.
2734
- * @example
2735
- * ```ts
2736
- * const r2 = buildR2Buckets([{ kind: "r2", name: "tracker-files", binding: "FILES" }]);
2737
- * ```
2738
- */
2739
- const buildR2Buckets = (resources) => resources.filter((resource) => resource.kind === "r2").map((resource) => ({
2740
- binding: resource.binding,
2741
- bucket_name: resource.name
2742
- }));
2743
- /**
2744
- * Build the wrangler `d1_databases` array from the manifest's d1 resources.
2745
- *
2746
- * @param resources - All resource descriptors from the manifest.
2747
- * @param ids - Captured Cloudflare ids keyed by binding; the entry's `database_id` is filled from here.
2748
- * @returns One wrangler D1 database entry per d1 resource (migrations_dir set when present).
2749
- * @example
2750
- * ```ts
2751
- * const d1 = buildD1Databases([{ kind: "d1", name: "tracker-db", binding: "DB" }], { DB: "uuid-1234" });
2752
- * ```
2753
- */
2754
- const buildD1Databases = (resources, ids) => resources.filter((resource) => resource.kind === "d1").map((resource) => {
2755
- const databaseId = ids[resource.binding];
2756
- const entry = {
2757
- binding: resource.binding,
2758
- database_name: resource.name
2759
- };
2760
- if (databaseId) entry.database_id = databaseId;
2761
- if (resource.migrations) entry.migrations_dir = resource.migrations;
2762
- return entry;
2763
- });
2764
- /**
2765
- * Build the wrangler `queues` section (producers + consumers) from the manifest's queue resources.
2766
- * Every queue is a `producer`; a queue flagged `consumer: true` (it declares an `onMessage` handler)
2767
- * is ALSO registered as a `consumer` so wrangler delivers its messages to this Worker's queue()
2768
- * handler — both locally under `wrangler dev` and in production. Without the consumer entry the
2769
- * handler never runs (the bug that silently drops a queue-driven activity feed). A consumer that
2770
- * sets `maxBatchTimeout` carries it through as wrangler's `max_batch_timeout` (lower delivery latency).
2771
- *
2772
- * @param resources - All resource descriptors from the manifest.
2773
- * @returns The queues section (producers, plus consumers when any), or undefined when there are none.
2774
- * @example
2775
- * ```ts
2776
- * const q = buildQueues([{ kind: "queue", name: "tracker-activity", binding: "ACTIVITY", consumer: true, maxBatchTimeout: 1 }]);
2777
- * ```
2778
- */
2779
- const buildQueues = (resources) => {
2780
- const queueResources = resources.filter((resource) => resource.kind === "queue");
2781
- if (queueResources.length === 0) return void 0;
2782
- const producers = queueResources.map((resource) => ({
2783
- queue: resource.name,
2784
- binding: resource.binding
2785
- }));
2786
- const consumers = queueResources.filter((resource) => resource.consumer === true).map((resource) => {
2787
- const entry = { queue: resource.name };
2788
- if (resource.maxBatchTimeout !== void 0) entry.max_batch_timeout = resource.maxBatchTimeout;
2789
- return entry;
2790
- });
2791
- return consumers.length > 0 ? {
2792
- producers,
2793
- consumers
2794
- } : { producers };
2795
- };
2796
- /**
2797
- * Build the wrangler `durable_objects` bindings section from the manifest's do resources.
2798
- *
2799
- * @param resources - All resource descriptors from the manifest.
2800
- * @returns The durable_objects section, or undefined when there are no do resources.
2801
- * @example
2802
- * ```ts
2803
- * const dobj = buildDurableObjects([{ kind: "do", binding: "COUNTER", className: "Counter" }]);
2804
- * ```
2805
- */
2806
- const buildDurableObjects = (resources) => {
2807
- const doResources = resources.filter((resource) => resource.kind === "do");
2808
- if (doResources.length === 0) return void 0;
2809
- return { bindings: doResources.map((resource) => ({
2810
- name: resource.binding,
2811
- class_name: resource.className
2812
- })) };
2813
- };
2814
- /**
2815
- * Build the auto Durable Object `migrations` from the manifest's do classes. wrangler REQUIRES a
2816
- * migration for every DO class, so this derives a single `v1` migration registering each class as
2817
- * SQLite-backed (the modern default) — the exact section wrangler prompts for when it is missing.
2818
- *
2819
- * @param resources - All resource descriptors from the manifest.
2820
- * @returns A single-entry migrations array, or undefined when there are no do resources.
2821
- * @example
2822
- * ```ts
2823
- * buildMigrations([{ kind: "do", binding: "BOARD", className: "BoardChannel" }]);
2824
- * // [{ tag: "v1", new_sqlite_classes: ["BoardChannel"] }]
2825
- * ```
2826
- */
2827
- const buildMigrations = (resources) => {
2828
- const classes = resources.filter((resource) => resource.kind === "do").map((resource) => resource.className);
2829
- return classes.length > 0 ? [{
2830
- tag: "v1",
2831
- new_sqlite_classes: classes
2832
- }] : void 0;
2833
- };
2834
- /**
2835
- * Extract the already-captured Cloudflare ids (kv namespace `id`, d1 `database_id`) from an existing
2836
- * parsed wrangler config, keyed by binding — so a regeneration (e.g. on `dev`) can preserve ids it
2837
- * isn't handed. Tolerant of a malformed/hand-edited file (skips non-object / non-string entries).
2838
- *
2839
- * @param existing - The parsed existing wrangler config (or `{}`).
2840
- * @returns A binding → id map (empty when the file has none).
2841
- * @example
2842
- * ```ts
2843
- * extractExistingIds({ kv_namespaces: [{ binding: "CACHE", id: "ns1" }] }); // { CACHE: "ns1" }
2844
- * ```
2845
- */
2846
- const extractExistingIds = (existing) => {
2847
- const ids = {};
2848
- const collect = (list, idKey) => {
2849
- if (!Array.isArray(list)) return;
2850
- for (const raw of list) {
2851
- if (raw === null || typeof raw !== "object") continue;
2852
- const entry = raw;
2853
- const binding = entry.binding;
2854
- const id = entry[idKey];
2855
- if (typeof binding === "string" && typeof id === "string" && id.length > 0) ids[binding] = id;
2856
- }
2857
- };
2858
- collect(existing.kv_namespaces, "id");
2859
- collect(existing.d1_databases, "database_id");
2860
- return ids;
2861
- };
2862
- /**
2863
- * Build the extra top-level wrangler keys from the typed deploy config: `entry` → `main`,
2864
- * `nodeCompat` → `compatibility_flags: ["nodejs_compat"]`, `assets` → the wrangler `assets` block
2865
- * (SPA fallback when `spa`), then the raw `wrangler` passthrough last (the escape hatch wins / adds
2866
- * anything else). Pass the result as the `extra` argument to {@link writeWranglerConfig}.
2867
- *
2868
- * @param config - The deploy plugin config.
2869
- * @returns The merged extra wrangler keys.
2870
- * @example
2871
- * ```ts
2872
- * await writeWranglerConfig(file, manifest, ids, wranglerExtra(ctx.config));
2873
- * ```
2874
- */
2875
- const wranglerExtra = (config) => {
2876
- const extra = {};
2877
- if (config.entry !== void 0) extra.main = config.entry;
2878
- if (config.nodeCompat === true) extra.compatibility_flags = ["nodejs_compat"];
2879
- if (config.assets !== void 0) extra.assets = {
2880
- directory: config.assets.directory,
2881
- binding: config.assets.binding,
2882
- ...config.assets.spa === true ? { not_found_handling: "single-page-application" } : {}
2883
- };
2884
- return {
2885
- ...extra,
2886
- ...config.wrangler
2887
- };
2888
- };
2889
- /**
2890
- * Generate/update the wrangler config file from a manifest (non-destructive merge).
2891
- *
2892
- * Layering (last wins): existing file keys → the `extra` passthrough (the app's `wrangler` config:
2893
- * `main`, `compatibility_flags`, `assets`, `vars`, …) → the deploy-managed keys (name,
2894
- * compatibility_date, kv_namespaces, r2_buckets, d1_databases, queues, durable_objects). So the
2895
- * framework always owns the resource sections, the app supplies what the manifest can't derive, and
2896
- * any other hand-written keys survive. Durable Object `migrations` are auto-derived for every DO
2897
- * class (the section wrangler requires) UNLESS the file/passthrough already defines `migrations`.
2898
- *
2899
- * @param configFile - Path to the wrangler config file.
2900
- * @param manifest - The assembled deploy manifest.
2901
- * @param ids - Captured Cloudflare ids keyed by binding (kv namespace id, d1 database id). Defaults
2902
- * to an empty map, in which case `id`/`database_id` are OMITTED (not "") so the generated config
2903
- * still validates for local `dev` (wrangler rejects an empty id); a deploy fills the real ids.
2904
- * @param extra - Extra top-level wrangler keys to merge in (the app's `deploy.wrangler` config).
2905
- * @returns Resolves once the file is written.
2906
- * @example
2907
- * ```ts
2908
- * await writeWranglerConfig("wrangler.jsonc", manifest, { CACHE: "ns123" }, {
2909
- * main: "src/cloudflare/worker.ts",
2910
- * compatibility_flags: ["nodejs_compat"],
2911
- * assets: { directory: "dist/client", binding: "ASSETS" }
2912
- * });
2913
- * ```
2914
- */
2915
- const writeWranglerConfig = async (configFile, manifest, ids = {}, extra = {}) => {
2916
- let existing = {};
2917
- if (existsSync(configFile)) try {
2918
- existing = parseJsonc(readFileSync(configFile, "utf8"));
2919
- } catch {
2920
- existing = {};
2921
- }
2922
- const effectiveIds = {
2923
- ...extractExistingIds(existing),
2924
- ...ids
2925
- };
2926
- const kvNamespaces = buildKvNamespaces(manifest.resources, effectiveIds);
2927
- const r2Buckets = buildR2Buckets(manifest.resources);
2928
- const d1Databases = buildD1Databases(manifest.resources, effectiveIds);
2929
- const queues = buildQueues(manifest.resources);
2930
- const durableObjects = buildDurableObjects(manifest.resources);
2931
- const updated = {
2932
- ...existing,
2933
- ...extra,
2934
- name: manifest.name,
2935
- compatibility_date: manifest.compatibilityDate
2936
- };
2937
- if (kvNamespaces.length > 0) updated.kv_namespaces = kvNamespaces;
2938
- if (r2Buckets.length > 0) updated.r2_buckets = r2Buckets;
2939
- if (d1Databases.length > 0) updated.d1_databases = d1Databases;
2940
- if (queues !== void 0) updated.queues = queues;
2941
- if (durableObjects !== void 0) updated.durable_objects = durableObjects;
2942
- const migrations = buildMigrations(manifest.resources);
2943
- if (migrations !== void 0 && updated.migrations === void 0) updated.migrations = migrations;
2944
- await writeFile(configFile, JSON.stringify(updated, void 0, 2));
2945
- };
2946
- /**
2947
- * Scaffold a starting wrangler config and, when ci is set, CI workflow files.
2948
- * Idempotent: an existing config file is left completely untouched.
2949
- *
2950
- * @param configFile - Path to the wrangler config file.
2951
- * @param _ci - Whether to also scaffold CI workflow files.
2952
- * @returns Resolves once scaffolding is written.
2953
- * @example
2954
- * ```ts
2955
- * await scaffoldWranglerAndCi("wrangler.jsonc", true);
2956
- * ```
2957
- */
2958
- const scaffoldWranglerAndCi = async (configFile, _ci) => {
2959
- if (existsSync(configFile)) return;
2960
- const starter = {
2961
- name: "my-worker",
2962
- main: "src/worker.ts",
2963
- compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)
2964
- };
2965
- await writeFile(configFile, JSON.stringify(starter, void 0, 2));
2966
- };
2967
- //#endregion
2968
- //#region src/plugins/deploy/api.ts
2969
- /**
2970
- * @file deploy plugin — API factory (run, dev, init, checkInfra, provisionInfra).
2971
- *
2972
- * Pure ctx-taking factory. Assembles the deploy manifest from each resource plugin's own
2973
- * deployManifest() api (never sibling pluginConfigs — design F6), runs an infra preflight
2974
- * (check-before-create + capture real ids), generates/updates the wrangler config, uploads the
2975
- * R2 upload dir, and runs wrangler deploy. Emits only global events: deploy:phase,
2976
- * deploy:complete, provision:resource, provision:plan, provision:skip.
2977
- *
2978
- * Node-only: uses node:child_process (via runner.ts), node:fs (via wrangler-config.ts), and the
2979
- * Cloudflare REST API (via infra/). Never called in the deployed Worker runtime.
2980
- */
2981
- /**
2982
- * Assemble the deploy manifest from each present resource plugin's OWN deployManifest() api (each
2983
- * returns one entry PER configured instance), gated by ctx.has(name) so absent plugins are skipped —
2984
- * never sibling pluginConfigs (F6). The single place the deploy stage is baked into names: the worker
2985
- * name and every provisioned resource `name` are run through {@link stageName} (bindings/DO class
2986
- * names are never suffixed), so provisioning, the existence diff, and the generated config all agree.
2987
- *
2988
- * @param ctx - The deploy plugin context.
2989
- * @param stage - The deploy stage (e.g. "production", "dev") applied to every resource name.
2990
- * @returns The assembled manifest (stage-qualified name, compatibilityDate, per-instance resources).
2991
- * @example
2992
- * ```ts
2993
- * const manifest = assembleManifest(ctx, "production");
2994
- * ```
2995
- */
2996
- const assembleManifest = (ctx, stage) => {
2997
- const resources = [
2998
- ctx.has("storage") ? ctx.require(storagePlugin).deployManifest() : [],
2999
- ctx.has("kv") ? ctx.require(kvPlugin).deployManifest() : [],
3000
- ctx.has("d1") ? ctx.require(d1Plugin).deployManifest() : [],
3001
- ctx.has("queues") ? ctx.require(queuesPlugin).deployManifest() : [],
3002
- ctx.has("durableObjects") ? ctx.require(durableObjectsPlugin).deployManifest() : []
3003
- ].flat();
3004
- return {
3005
- name: stageName(ctx.global.name, stage),
3006
- compatibilityDate: ctx.global.compatibilityDate,
3007
- resources: resources.map((resource) => "name" in resource ? {
3008
- ...resource,
3009
- name: stageName(resource.name, stage)
3010
- } : resource)
3011
- };
3012
- };
3013
- /**
3014
- * Create the still-missing resources one at a time: provision each, fold its captured id (kv/d1) into
3015
- * the shared `ids` map, and announce it via provision:resource. Resilient — a single failure is
3016
- * CAPTURED (not thrown), so one bad resource never aborts the rest. Extracted from {@link applyPlan}
3017
- * so that orchestrator stays flat (skip existing, skip DOs, create missing).
3018
- *
3019
- * @param ctx - The deploy plugin context.
3020
- * @param missing - The resources the plan flagged as not-yet-existing.
3021
- * @param ci - Whether provisioning runs non-interactively (forwarded to each provider).
3022
- * @param ids - The binding → Cloudflare id map, mutated in place with each created kv/d1 id.
3023
- * @returns The created refs and any captured per-resource failures.
3024
- * @example
3025
- * ```ts
3026
- * const { created, failed } = await provisionMissing(ctx, plan.missing, false, ids);
3027
- * ```
3028
- */
3029
- const provisionMissing = async (ctx, missing, ci, ids) => {
3030
- const created = [];
3031
- const failed = [];
3032
- for (const resource of missing) try {
3033
- const { id } = await provisionResource(resource, ci);
3034
- if (id !== void 0 && (resource.kind === "kv" || resource.kind === "d1")) ids[resource.binding] = id;
3035
- created.push(id === void 0 ? { resource } : {
3036
- resource,
3037
- id
3038
- });
3039
- ctx.emit("provision:resource", {
3040
- kind: resource.kind,
3041
- name: resourceName(resource)
3042
- });
3043
- } catch (error) {
3044
- failed.push({
3045
- resource,
3046
- error: error instanceof Error ? error.message : String(error)
3047
- });
3048
- }
3049
- return {
3050
- created,
3051
- failed
3052
- };
3053
- };
3054
- /**
3055
- * Act on an infra plan: skip the resources that already exist (reusing their ids), skip the Durable
3056
- * Objects that ship with the Worker, create the missing ones (capturing each new id), and announce
3057
- * each via provision:skip / :resource. Resilient — a single resource that fails to create is CAPTURED
3058
- * in `failed` (not thrown), so one bad resource (e.g. an invalid bucket name) never aborts the whole
3059
- * run and the caller can report a clear result.
3060
- *
3061
- * @param ctx - The deploy plugin context.
3062
- * @param plan - The infra plan from planInfra (existing vs missing vs ships-with-Worker).
3063
- * @param ci - Whether provisioning runs non-interactively (forwarded to each provider).
3064
- * @returns The provisioning result: created, skipped, bundled, failed, and the merged binding → id map.
3065
- * @example
3066
- * ```ts
3067
- * const { created, failed } = await applyPlan(ctx, plan, false);
3068
- * ```
3069
- */
3070
- const applyPlan = async (ctx, plan, ci) => {
3071
- const ids = {};
3072
- for (const ref of plan.exists) {
3073
- if (ref.id !== void 0 && (ref.resource.kind === "kv" || ref.resource.kind === "d1")) ids[ref.resource.binding] = ref.id;
3074
- ctx.emit("provision:skip", {
3075
- kind: ref.resource.kind,
3076
- name: resourceName(ref.resource)
3077
- });
3078
- }
3079
- for (const resource of plan.ships) ctx.emit("provision:skip", {
3080
- kind: resource.kind,
3081
- name: resourceName(resource)
3082
- });
3083
- const { created, failed } = await provisionMissing(ctx, plan.missing, ci, ids);
3084
- return {
3085
- created,
3086
- skipped: plan.exists,
3087
- bundled: plan.ships,
3088
- failed,
3089
- ids
3090
- };
3091
- };
3092
- /**
3093
- * Sentinel a guided helper resolves to when the user declined recovery — a clean abort the caller
3094
- * turns into a `deploy:phase aborted` + early return, never a thrown (and re-rendered) error.
3095
- */
3096
- const ABORTED = Symbol("deploy:aborted");
3097
- /** Retry guidance shown beneath each step's failure, before the "Retry?" prompt. */
3098
- const HINTS = {
3099
- build: "Web build failed — fix the error above, then retry.",
3100
- provision: "Verify your token's account scopes and Cloudflare's status, then retry.",
3101
- upload: "R2 upload failed — check the bucket and your token's R2 scope, then retry.",
3102
- deploy: "wrangler deploy failed — review the output above, then retry."
3103
- };
3104
- /**
3105
- * Emit the terminal `aborted` phase AND build the matching {@link DeployReport} — the single exit
3106
- * every guided gate/retry funnels through when the user stops the deploy (or auth was never set up).
3107
- * Centralizing it keeps every abort path emitting one consistent line and returning the same shaped
3108
- * report: `status: "aborted"`, both post-steps `"skipped"`, no errors — so a calling script sees a
3109
- * clean stop, never a half-filled success, and the remote-DB migration/seed are guaranteed unrun.
3110
- *
3111
- * @param ctx - The deploy plugin context.
3112
- * @param stage - The resolved deploy stage (echoed into the report).
3113
- * @param startedAt - The run's start timestamp, for the elapsed field.
3114
- * @returns The aborted deploy report.
3115
- * @example
3116
- * ```ts
3117
- * if (declined) return aborted(ctx, stage, startedAt);
3118
- * ```
3119
- */
3120
- const aborted = (ctx, stage, startedAt) => {
3121
- ctx.emit("deploy:phase", { phase: "aborted" });
3122
- return {
3123
- ok: false,
3124
- status: "aborted",
3125
- stage,
3126
- migration: "skipped",
3127
- seed: "skipped",
3128
- elapsedMs: Date.now() - startedAt,
3129
- errors: []
3130
- };
3131
- };
3132
- /**
3133
- * The full guided token setup shown after an auth failure on a TTY. Offers to walk the user through
3134
- * it, and when accepted: prints WHERE to create the Cloudflare token (dashboard URL, which template,
3135
- * the exact permissions to add) AND scaffolds a ready-to-fill `.env.local` — the same guidance baked
3136
- * in as comments — for the user to paste the token + account id into (never clobbering an existing
3137
- * file). Always ends pointing at the re-run.
3138
- *
3139
- * @param ctx - The deploy plugin context.
3140
- * @param ui - The branded console to render the guidance through.
3141
- * @param confirm - The yes/no prompt.
3142
- * @returns Resolves once the guidance (and optional `.env.local` scaffold) has been rendered.
3143
- * @example
3144
- * ```ts
3145
- * await guidedTokenSetup(ctx, createBrandConsole(), confirm);
3146
- * ```
3147
- */
3148
- const guidedTokenSetup = async (ctx, ui, confirm) => {
3149
- if (!await confirm("Set up Cloudflare credentials now? (guided)")) {
3150
- ui.info("Set CLOUDFLARE_API_TOKEN in .env.local, then run `deploy` again.");
3151
- return;
3152
- }
3153
- const manifest = assembleManifest(ctx, ctx.global.stage);
3154
- renderAuthSetup(ui, requiredToken(manifest));
3155
- const { created, path } = await ensureEnvLocal(process.cwd(), envLocalScaffold(manifest));
3156
- ui.info(created ? `Created ${path} — paste your token + account id there, then run \`deploy\` again.` : `${path} already exists — fill in CLOUDFLARE_API_TOKEN there, then run \`deploy\` again.`);
3157
- };
3158
- /**
3159
- * Verify the `.env` token, turning a missing/invalid token into a guided recovery on a TTY: surface
3160
- * WHY auth failed, then walk the user through {@link guidedTokenSetup} (where to create the token +
3161
- * scaffold a `.env.local`). The env is snapshotted at app start, so a freshly-pasted token only
3162
- * takes effect on a NEW run. In CI/pipes the branded error re-throws (fail-fast).
3163
- *
3164
- * @param ctx - The deploy plugin context.
3165
- * @param deps - Interactivity + the confirm prompt.
3166
- * @returns True when the token verified; false when the user must set it up and re-run.
3167
- * @throws {Error} Re-throws the branded auth error in CI / non-interactive runs.
3168
- * @example
3169
- * ```ts
3170
- * if (!(await guidedAuth(ctx, { interactive, confirm }))) return;
3171
- * ```
3172
- */
3173
- const guidedAuth = async (ctx, deps) => {
3174
- try {
3175
- await verifyAuth(ctx);
3176
- return true;
3177
- } catch (error) {
3178
- if (!deps.interactive) throw error;
3179
- const ui = createBrandConsole();
3180
- ui.error(error instanceof Error ? error.message : String(error));
3181
- await guidedTokenSetup(ctx, ui, deps.confirm);
3182
- return false;
3183
- }
3184
- };
3185
- /**
3186
- * Run one external pipeline step with interactive recovery: on failure, render the branded error +
3187
- * an actionable hint, then offer to retry — looping until the step succeeds or the user declines.
3188
- * A decline resolves to {@link ABORTED} (a clean abort the caller surfaces), so the error is shown
3189
- * once, not re-rendered downstream. In CI/pipes the first failure re-throws (fail-fast). The step
3190
- * MUST be safe to re-run (idempotent).
3191
- *
3192
- * @param step - The async step to run (e.g. the web build, the R2 upload, `wrangler deploy`).
3193
- * @param hint - One-line guidance shown beneath the error before the retry prompt.
3194
- * @param deps - Interactivity + the confirm prompt.
3195
- * @returns The step's resolved value once it succeeds, or {@link ABORTED} when a retry is declined.
3196
- * @throws {Error} Re-throws the step's error in CI / non-interactive runs.
3197
- * @example
3198
- * ```ts
3199
- * const url = await guidedStep(() => runWrangler(args), "wrangler deploy failed …", deps);
3200
- * if (url === ABORTED) return;
3201
- * ```
3202
- */
3203
- const guidedStep = async (step, hint, deps) => {
3204
- for (;;) try {
3205
- return await step();
3206
- } catch (error) {
3207
- if (!deps.interactive) throw error;
3208
- const ui = createBrandConsole();
3209
- ui.error(error instanceof Error ? error.message : String(error));
3210
- ui.info(hint);
3211
- if (!await deps.confirm("Retry?")) return ABORTED;
3212
- }
3213
- };
3214
- /**
3215
- * Run the read-only infra preflight with interactive recovery: a network/scope failure fails fast in
3216
- * CI, or (on a TTY) renders the error + hint and offers a retry. Resolves the plan, or {@link ABORTED}
3217
- * when the user declines the retry.
3218
- *
3219
- * @param ctx - The deploy plugin context.
3220
- * @param manifest - The assembled (or caller-supplied) deploy manifest.
3221
- * @param deps - Interactivity + the confirm prompt.
3222
- * @returns The infra plan, or {@link ABORTED} when a preflight retry is declined.
3223
- * @throws {Error} Re-throws the preflight error in CI / non-interactive runs.
3224
- * @example
3225
- * ```ts
3226
- * const plan = await guidedPlan(ctx, manifest, deps);
3227
- * if (plan === ABORTED) return;
3228
- * ```
3229
- */
3230
- const guidedPlan = async (ctx, manifest, deps) => {
3231
- for (;;) try {
3232
- return await planInfra(ctx, manifest);
3233
- } catch (error) {
3234
- if (!deps.interactive) throw error;
3235
- const ui = createBrandConsole();
3236
- ui.error(error instanceof Error ? error.message : String(error));
3237
- ui.info(HINTS.provision);
3238
- if (!await deps.confirm("Retry?")) return ABORTED;
3239
- }
3240
- };
3241
- /**
3242
- * Plan + provision the infra with branded panels and interactive recovery. Each attempt RE-PLANS
3243
- * (a resource created by a prior attempt is seen as existing and skipped — retries stay idempotent),
3244
- * renders the plan panel (what will be created vs already exists), confirms the create gate, creates
3245
- * the resources, then renders the result panel (created / skipped / failed). When some resources
3246
- * FAIL it offers to retry just those (interactive) or fails fast (CI). Resolves to {@link ABORTED}
3247
- * when the user declines the gate or a retry.
3248
- *
3249
- * @param ctx - The deploy plugin context.
3250
- * @param manifest - The assembled (or caller-supplied) deploy manifest.
3251
- * @param ci - Whether provisioning runs non-interactively (forwarded to each provider).
3252
- * @param deps - Interactivity + the confirm prompt.
3253
- * @returns The provisioning result (all created/skipped), or {@link ABORTED} when the user declined.
3254
- * @throws {Error} Re-throws a plan error, or throws on a provision failure, in CI / non-interactive runs.
3255
- * @example
3256
- * ```ts
3257
- * const provisioned = await guidedProvision(ctx, manifest, ci, deps);
3258
- * if (provisioned === ABORTED) return;
3259
- * ```
3260
- */
3261
- const guidedProvision = async (ctx, manifest, ci, deps) => {
3262
- for (;;) {
3263
- const plan = await guidedPlan(ctx, manifest, deps);
3264
- if (plan === ABORTED) return ABORTED;
3265
- const ui = createBrandConsole();
3266
- renderPlan(ui, plan);
3267
- if (plan.missing.length > 0 && !await deps.confirm(`Create ${String(plan.missing.length)} missing resource(s) in "${plan.account}"?`)) return ABORTED;
3268
- const result = await applyPlan(ctx, plan, ci);
3269
- renderProvisionResult(ui, result);
3270
- if (result.failed.length === 0) return result;
3271
- if (!deps.interactive) throw new Error(`[moku-worker] ${String(result.failed.length)} resource(s) failed to provision.`);
3272
- if (!await deps.confirm("Retry the failed resource(s)?")) return ABORTED;
3273
- }
3274
- };
3275
- /**
3276
- * Build the web site first (when a hook is wired in), so its assets exist before the R2 upload and
3277
- * `wrangler deploy`. Emits the `build · web` phase, then runs the build with interactive retry.
3278
- *
3279
- * @param ctx - The deploy plugin context.
3280
- * @param webBuild - The web build hook, or undefined when none is wired (then this is a no-op).
3281
- * @param deps - Interactivity + the confirm prompt.
3282
- * @returns True to continue the pipeline; false when the user declined a build retry (abort).
3283
- * @example
3284
- * ```ts
3285
- * if (!(await guidedWebBuild(ctx, webBuild, deps))) return emitAborted(ctx);
3286
- * ```
3287
- */
3288
- const guidedWebBuild = async (ctx, webBuild, deps) => {
3289
- if (webBuild === void 0) return true;
3290
- ctx.emit("deploy:phase", {
3291
- phase: "build",
3292
- detail: "web"
3293
- });
3294
- return await guidedStep(() => webBuild(), HINTS.build, deps) !== ABORTED;
3295
- };
3296
- /**
3297
- * Upload the R2 directory when a bucket declares an upload source, with interactive retry. Emits the
3298
- * `upload · N files` phase on success; a no-op (and emits nothing) when no bucket declares an upload.
3299
- *
3300
- * @param ctx - The deploy plugin context.
3301
- * @param manifest - The assembled (or caller-supplied) deploy manifest.
3302
- * @param deps - Interactivity + the confirm prompt.
3303
- * @returns True to continue the pipeline; false when the user declined an upload retry (abort).
3304
- * @example
3305
- * ```ts
3306
- * if (!(await guidedUpload(ctx, manifest, deps))) return emitAborted(ctx);
3307
- * ```
3308
- */
3309
- const guidedUpload = async (ctx, manifest, deps) => {
3310
- const r2 = manifest.resources.find((resource) => resource.kind === "r2");
3311
- if (!r2?.upload) return true;
3312
- const bucket = r2.name;
3313
- const uploadDir = r2.upload;
3314
- const count = await guidedStep(() => uploadDirToR2(bucket, uploadDir), HINTS.upload, deps);
3315
- if (count === ABORTED) return false;
3316
- ctx.emit("deploy:phase", {
3317
- phase: "upload",
3318
- detail: `${String(count)} files`
3319
- });
3320
- return true;
3321
- };
3322
- /**
3323
- * The final deploy step: confirm the target (guided only), run `wrangler deploy` with interactive
3324
- * retry, then emit deploy:complete. Returns the deployed URL, or undefined when the target gate or a
3325
- * deploy retry is declined (so the caller renders the summary panel only on a real success).
3326
- *
3327
- * @param ctx - The deploy plugin context.
3328
- * @param manifest - The assembled (or caller-supplied) deploy manifest.
3329
- * @param stage - The resolved deploy stage (for the confirm prompt).
3330
- * @param deps - Interactivity + the confirm prompt.
3331
- * @returns The deployed URL once live; undefined when the user declined the gate or a retry (abort).
3332
- * @example
3333
- * ```ts
3334
- * const url = await guidedDeployStep(ctx, manifest, stage, deps);
3335
- * if (url === undefined) return emitAborted(ctx);
3336
- * ```
3337
- */
3338
- const guidedDeployStep = async (ctx, manifest, stage, deps) => {
3339
- if (!await deps.confirm(`Deploy "${manifest.name}" to ${stage}?`)) return void 0;
3340
- ctx.emit("deploy:phase", { phase: "deploy" });
3341
- const url = await guidedStep(() => runWrangler([
3342
- "deploy",
3343
- "--config",
3344
- ctx.config.configFile
3345
- ]), HINTS.deploy, deps);
3346
- if (url === ABORTED) return void 0;
3347
- ctx.emit("deploy:complete", { url });
3348
- return url;
3349
- };
3350
- /**
3351
- * Apply pending D1 migrations to the REMOTE database for every configured d1 instance that ships a
3352
- * migrations dir — the generic, deploy-owned analogue of `wrangler d1 migrations apply <binding>
3353
- * --remote`. The wrangler config was written earlier in the pipeline, so each binding resolves. The
3354
- * caller runs this only AFTER a successful deploy, so a deploy that never happened never migrates a
3355
- * remote DB. Streams wrangler's output; throws on the first non-zero exit (the caller folds it into
3356
- * the report).
3357
- *
3358
- * @param ctx - The deploy plugin context.
3359
- * @returns Resolves once every configured database's remote migrations have been applied.
3360
- * @example
3361
- * ```ts
3362
- * await applyRemoteMigrations(ctx);
3363
- * ```
3364
- */
3365
- const applyRemoteMigrations = async (ctx) => {
3366
- if (!ctx.has("d1")) return;
3367
- for (const database of ctx.require(d1Plugin).deployManifest()) if (database.migrations !== void 0) await runWranglerInherit([
3368
- "d1",
3369
- "migrations",
3370
- "apply",
3371
- database.binding,
3372
- "--remote"
3373
- ]);
3374
- };
3375
- /**
3376
- * Render a post-deploy step's failure as a branded line and capture its message into `errors` —
3377
- * folding the failure into the report instead of throwing, so a deploy that already went live still
3378
- * yields a complete, honest report when a later remote step (migration/seed) fails.
3379
- *
3380
- * @param ui - The branded console to render the error through.
3381
- * @param errors - The accumulator the captured message is pushed into.
3382
- * @param error - The thrown error (or value) to brand and capture.
3383
- * @returns The captured (branded) message.
3384
- * @example
3385
- * ```ts
3386
- * captureFailure(ui, errors, new Error("[moku-worker] seed failed"));
3387
- * ```
3388
- */
3389
- const captureFailure = (ui, errors, error) => {
3390
- const message = error instanceof Error ? error.message : String(error);
3391
- ui.error(message);
3392
- errors.push(message);
3393
- return message;
3394
- };
3395
- /**
3396
- * Run the post-deploy remote steps — REACHED ONLY ON A SUCCESSFUL DEPLOY (every gate in `run` returns
3397
- * early before here), so a deploy that never happened never touches a remote DB. Applies remote D1
3398
- * migrations (when requested), then loads the configured seed (when requested) — but skips the seed
3399
- * if the migration it depends on failed. Each step's failure is RENDERED inline and CAPTURED in
3400
- * `errors` (never thrown), so one failed step still yields a complete, honest report.
3401
- *
3402
- * @param ctx - The deploy plugin context.
3403
- * @param want - Which post-steps the caller requested.
3404
- * @param want.migration - Whether to apply pending remote D1 migrations.
3405
- * @param want.seed - Whether to load the configured remote seed (and reset its KV keys).
3406
- * @returns The migration + seed outcomes and any captured branded errors.
3407
- * @example
3408
- * ```ts
3409
- * const post = await runPostDeploy(ctx, { migration: true, seed: true });
3410
- * ```
3411
- */
3412
- const runPostDeploy = async (ctx, want) => {
3413
- const ui = createBrandConsole();
3414
- const errors = [];
3415
- let migration = "skipped";
3416
- if (want.migration) try {
3417
- await applyRemoteMigrations(ctx);
3418
- migration = "applied";
3419
- ui.check(true, "migrated", "remote D1");
3420
- } catch (error) {
3421
- migration = "failed";
3422
- captureFailure(ui, errors, error);
3423
- }
3424
- let seed = "skipped";
3425
- if (want.seed && migration === "failed") {
3426
- seed = "failed";
3427
- captureFailure(ui, errors, /* @__PURE__ */ new Error("[moku-worker] seed skipped — the remote migration it depends on failed."));
3428
- } else if (want.seed) {
3429
- const config = ctx.config.seed;
3430
- if (config === void 0) {
3431
- seed = "failed";
3432
- captureFailure(ui, errors, /* @__PURE__ */ new Error("[moku-worker] deploy({ seed: true }) but no seed is configured — set pluginConfigs.deploy.seed."));
3433
- } else try {
3434
- await runConfiguredSeed(ctx, runWranglerInherit, config, "--remote");
3435
- seed = "applied";
3436
- ui.check(true, "seeded", config.file);
3437
- } catch (error) {
3438
- seed = "failed";
3439
- captureFailure(ui, errors, error);
3440
- }
3441
- }
3442
- return {
3443
- migration,
3444
- seed,
3445
- errors
3446
- };
3447
- };
3448
- /**
3449
- * Create the deploy api. Assembles the manifest from each resource plugin's own deployManifest(),
3450
- * runs an infra preflight (check-before-create + id capture), generates config, uploads, and runs
3451
- * `wrangler deploy`, emitting global deploy events along the way.
3452
- *
3453
- * @param ctx - Plugin context (own config + require + has + emit + global + env).
3454
- * @returns The app.deploy api: run / dev / init / checkInfra / provisionInfra.
3455
- * @example
3456
- * ```ts
3457
- * const api = createDeployApi(ctx);
3458
- * await api.run();
3459
- * ```
3460
- */
3461
- const createDeployApi = (ctx) => ({
3462
- /**
3463
- * Run the full deploy pipeline: detect → preflight (check-before-create) → provision (only the
3464
- * missing) → wrangler-config (with real ids) → upload → deploy, then — ONLY on a successful
3465
- * deploy — the requested post-deploy remote steps (migration, seed). When opts.manifest is
3466
- * supplied it is used verbatim (universal path).
3467
- *
3468
- * On a TTY the run is GUIDED end to end: each gate is confirmed, and every failure is recovered
3469
- * interactively rather than thrown — a missing/invalid token offers a `.env.local` scaffold, and
3470
- * the build, infra, upload, and `wrangler deploy` steps offer a retry. In CI/pipes it fails fast
3471
- * (no prompt, the first error propagates to the branded CLI handler).
3472
- *
3473
- * Resolves to a {@link DeployReport}. Every abort path (a declined gate, or auth never set up)
3474
- * returns `status: "aborted"` BEFORE the post-deploy steps, so `migration`/`seed` run only when
3475
- * the worker actually went live — a first `deploy --seed` with no token aborts cleanly instead of
3476
- * falling through to a raw `wrangler … --remote` auth error.
3477
- *
3478
- * @param opts - Optional run options.
3479
- * @param opts.ci - CI/automated mode: never prompts, auto-confirms every gate, fails fast. When
3480
- * false (the default) and stdout is a TTY, the deploy is guided — each gate is confirmed and
3481
- * failures are recovered interactively. Falls back to ctx.config.ci when omitted.
3482
- * @param opts.stage - Target stage; suffixes resource names (`production` = bare). Falls back to the app stage.
3483
- * @param opts.webBuild - Build the web site first (e.g. `() => webApp.cli.build()`), before deploy.
3484
- * @param opts.manifest - Caller-supplied manifest (bypasses deployManifest() assembly).
3485
- * @param opts.migration - After a successful deploy, apply pending remote D1 migrations for every
3486
- * configured d1 instance that ships migrations. Skipped (not attempted) on an aborted deploy.
3487
- * @param opts.seed - After a successful deploy (+ migration), load the seed configured under
3488
- * `pluginConfigs.deploy.seed` into the remote D1 and reset its cached KV keys. Skipped on abort.
3489
- * @returns The deploy report (status, url, resource tally, migration/seed outcome, errors).
3490
- * @example
3491
- * ```ts
3492
- * const report = await api.run({ webBuild: () => web.cli.build(), migration: true, seed: true });
3493
- * if (!report.ok) process.exitCode = 1; // aborted or a post-step failed
3494
- * ```
3495
- */
3496
- async run(opts) {
3497
- const ci = opts?.ci ?? ctx.config.ci;
3498
- const stage = opts?.stage ?? ctx.global.stage;
3499
- const interactive = !ci && stdoutIsTty();
3500
- const deps = {
3501
- interactive,
3502
- confirm: interactive ? createBrandPrompts().confirm : async (_question) => true
3503
- };
3504
- const startedAt = Date.now();
3505
- ctx.emit("deploy:phase", { phase: "auth" });
3506
- if (!await guidedAuth(ctx, deps)) return aborted(ctx, stage, startedAt);
3507
- if (!await guidedWebBuild(ctx, opts?.webBuild ?? ctx.config.webBuild, deps)) return aborted(ctx, stage, startedAt);
3508
- ctx.emit("deploy:phase", { phase: "detect" });
3509
- const manifest = opts?.manifest ?? assembleManifest(ctx, stage);
3510
- ctx.emit("deploy:phase", { phase: "provision" });
3511
- const provisioned = await guidedProvision(ctx, manifest, ci, deps);
3512
- if (provisioned === ABORTED) return aborted(ctx, stage, startedAt);
3513
- ctx.emit("deploy:phase", { phase: "wrangler-config" });
3514
- await writeWranglerConfig(ctx.config.configFile, manifest, provisioned.ids, wranglerExtra(ctx.config));
3515
- if (!await guidedUpload(ctx, manifest, deps)) return aborted(ctx, stage, startedAt);
3516
- const url = await guidedDeployStep(ctx, manifest, stage, deps);
3517
- if (url === void 0) return aborted(ctx, stage, startedAt);
3518
- const resources = {
3519
- created: provisioned.created.length,
3520
- exists: provisioned.skipped.length,
3521
- bundled: provisioned.bundled.length,
3522
- failed: provisioned.failed.length
3523
- };
3524
- renderDeploySummary(createBrandConsole(), {
3525
- url,
3526
- stage,
3527
- ...resources,
3528
- elapsedMs: Date.now() - startedAt
3529
- });
3530
- const post = await runPostDeploy(ctx, {
3531
- migration: opts?.migration === true,
3532
- seed: opts?.seed === true
3533
- });
3534
- return {
3535
- ok: post.errors.length === 0,
3536
- status: post.errors.length === 0 ? "deployed" : "failed",
3537
- stage,
3538
- url,
3539
- resources,
3540
- migration: post.migration,
3541
- seed: post.seed,
3542
- elapsedMs: Date.now() - startedAt,
3543
- errors: post.errors
3544
- };
3545
- },
3546
- /**
3547
- * Start a long-lived local dev session: cold-build the Moku site, spawn `wrangler dev
3548
- * --live-reload`, and watch the site sources — rebuilding on change (wrangler live-reloads the
3549
- * browser). Resolves on SIGINT.
3550
- *
3551
- * @param opts - Optional options.
3552
- * @param opts.port - Local dev port (default 8787).
3553
- * @param opts.stage - Stage for the generated config's resource names (defaults to the app stage).
3554
- * @param opts.webBuild - Cold-build the web site (e.g. `() => webApp.cli.build()`); also the
3555
- * per-change rebuild when `onChange` is omitted.
3556
- * @param opts.onChange - Incremental per-change rebuild (e.g. `changes => webApp.cli.update(changes)`).
3557
- * @param opts.seed - Load the configured seed (`pluginConfigs.deploy.seed`) into the LOCAL D1 and
3558
- * reset its cached KV keys before serving — the local analogue of `deploy({ seed: true })`.
3559
- * @returns Resolves when the dev session ends.
3560
- * @example
3561
- * ```ts
3562
- * await api.dev({ port: 8787, seed: true, webBuild: () => web.cli.build(), onChange: c => web.cli.update(c) });
3563
- * ```
3564
- */
3565
- async dev(opts) {
3566
- const manifest = assembleManifest(ctx, opts?.stage ?? ctx.global.stage);
3567
- await writeWranglerConfig(ctx.config.configFile, manifest, {}, wranglerExtra(ctx.config));
3568
- await runDev(ctx, opts, realDevDeps());
3569
- },
3570
- /**
3571
- * Execute a SQL file against a configured D1 database via `wrangler d1 execute` — for seeding dev
3572
- * data. Local by default (applies that database's migrations first so the file's tables exist);
3573
- * `opts.remote` seeds Cloudflare (schema is applied by `deploy`). Generates the wrangler config up
3574
- * front so the binding resolves even on a first run. Streams wrangler's output.
3575
- *
3576
- * @param sqlFile - Path to the SQL file to execute (e.g. "db/seed.sql").
3577
- * @param opts - Optional options.
3578
- * @param opts.stage - Stage for the generated config's resource names (defaults to the app stage).
3579
- * @param opts.binding - The d1 binding to target when more than one is configured (e.g. "DB").
3580
- * @param opts.remote - Seed the remote (Cloudflare) D1 instead of the local one.
3581
- * @returns Resolves once wrangler finishes executing the file.
3582
- * @example
3583
- * ```ts
3584
- * await api.seed("db/seed.sql"); // local default d1 (migrate, then execute)
3585
- * await api.seed("db/seed.sql", { remote: true }); // remote d1
3586
- * ```
3587
- */
3588
- async seed(sqlFile, opts) {
3589
- if (!ctx.has("d1")) throw new Error("[moku-worker] seed: no d1 database is configured.");
3590
- const stage = opts?.stage ?? ctx.global.stage;
3591
- await writeWranglerConfig(ctx.config.configFile, assembleManifest(ctx, stage), {}, wranglerExtra(ctx.config));
3592
- const target = resolveD1(ctx, opts?.binding);
3593
- const scope = opts?.remote === true ? "--remote" : "--local";
3594
- if (scope === "--local" && target.migrations !== void 0) await runWranglerInherit([
3595
- "d1",
3596
- "migrations",
3597
- "apply",
3598
- target.binding,
3599
- "--local"
3600
- ]);
3601
- await runWranglerInherit([
3602
- "d1",
3603
- "execute",
3604
- target.binding,
3605
- scope,
3606
- "--file",
3607
- sqlFile
3608
- ]);
3609
- },
3610
- /**
3611
- * Scaffold a starting wrangler config (and CI files when ci is set).
3612
- * Idempotent: an existing config file is left untouched.
3613
- *
3614
- * @param opts - Optional options.
3615
- * @param opts.ci - Also scaffold CI workflow files.
3616
- * @returns Resolves once scaffolding is written.
3617
- * @example
3618
- * ```ts
3619
- * await api.init({ ci: true });
3620
- * ```
3621
- */
3622
- init: async (opts) => {
3623
- await scaffoldWranglerAndCi(ctx.config.configFile, opts?.ci ?? ctx.config.ci);
3624
- },
3625
- /**
3626
- * Read-only infra preflight: assemble the manifest, resolve the account, list what exists in
3627
- * Cloudflare, diff, emit provision:plan, and return the plan. Writes nothing.
3628
- *
3629
- * @returns The infra plan (existing vs missing resources, with captured ids).
3630
- * @example
3631
- * ```ts
3632
- * const plan = await api.checkInfra();
3633
- * ```
3634
- */
3635
- checkInfra: () => planInfra(ctx, assembleManifest(ctx, ctx.global.stage)),
3636
- /**
3637
- * Create only the resources missing from the plan (skipping existing), capturing each id.
3638
- *
3639
- * @param plan - A plan produced by checkInfra().
3640
- * @returns The provisioning result: created, skipped, and the merged id map.
3641
- * @example
3642
- * ```ts
3643
- * const { created } = await api.provisionInfra(await api.checkInfra());
3644
- * ```
3645
- */
3646
- provisionInfra: (plan) => applyPlan(ctx, plan, ctx.config.ci),
3647
- /**
3648
- * Verify the `.env` Cloudflare API token (must be active) and resolve its account; emits
3649
- * auth:verified. Throws a branded error pointing at `auth setup` when absent/invalid/inactive.
3650
- *
3651
- * @returns The verified auth status (account + id).
3652
- * @example
3653
- * ```ts
3654
- * const { account } = await api.verifyAuth();
3655
- * ```
3656
- */
3657
- verifyAuth: () => verifyAuth(ctx),
3658
- /**
3659
- * Derive the minimum Cloudflare API token this app needs from its manifest (pure, no network).
3660
- *
3661
- * @returns The token requirement (full set + groups to add to the stock template).
3662
- * @example
3663
- * ```ts
3664
- * const { toAdd } = api.requiredToken();
3665
- * ```
3666
- */
3667
- requiredToken: () => requiredToken(assembleManifest(ctx, ctx.global.stage)),
3668
- /**
3669
- * Derive the REDUCED CI/automation redeploy token permission groups from the manifest (pure, no
3670
- * network). Used by the branded `auth setup` renderer to show the scoped CI token alongside the
3671
- * full LOCAL one.
3672
- *
3673
- * @returns The CI token permission groups (read-mostly, manifest-scoped).
3674
- * @example
3675
- * ```ts
3676
- * const groups = api.ciToken();
3677
- * ```
3678
- */
3679
- ciToken: () => ciToken(assembleManifest(ctx, ctx.global.stage)),
3680
- /**
3681
- * Render the `auth setup` guidance from the derived token requirement (pure, no network).
3682
- *
3683
- * @returns The rendered instruction text.
3684
- * @example
3685
- * ```ts
3686
- * const text = api.tokenInstructions();
3687
- * ```
3688
- */
3689
- tokenInstructions: () => tokenInstructions(assembleManifest(ctx, ctx.global.stage)),
3690
- /**
3691
- * Run an arbitrary wrangler command, streaming its output (the branded CLI escape hatch).
3692
- *
3693
- * @param args - The wrangler arguments.
3694
- * @returns Resolves once wrangler exits.
3695
- * @example
3696
- * ```ts
3697
- * await api.wrangler(["kv", "namespace", "list"]);
3698
- * ```
3699
- */
3700
- wrangler: (args) => runWranglerInherit(args)
3701
- });
3702
- /**
3703
- * Complex tier (node-only) — build-time deploy orchestrator over the five resource plugins.
3704
- *
3705
- * Assembles each resource plugin's deployManifest() via ctx.require, provisions resources,
3706
- * generates/updates wrangler config, uploads the R2 upload dir, and runs wrangler deploy.
3707
- * Also supports a universal path: run({ manifest }) uses a caller-supplied manifest verbatim.
3708
- *
3709
- * Emits only the global events `deploy:phase`, `deploy:complete`, and `provision:resource`
3710
- * (declared in WorkerEvents — no per-plugin events block).
3711
- *
3712
- * @see README.md
3713
- */
3714
- const deployPlugin = createPlugin("deploy", {
3715
- config: {
3716
- configFile: "wrangler.jsonc",
3717
- ci: false,
3718
- watch: ["src/**/*.{ts,tsx,css}", "public/**/*"],
3719
- buildCommand: "",
3720
- migrateLocal: true,
3721
- debounceMs: 120
3722
- },
3723
- depends: [
3724
- storagePlugin,
3725
- kvPlugin,
3726
- d1Plugin,
3727
- queuesPlugin,
3728
- durableObjectsPlugin
3729
- ],
3730
- api: (ctx) => createDeployApi(ctx)
3731
- });
3732
- //#endregion
3733
- //#region src/plugins/cli/args.ts
3734
- /**
3735
- * @file cli plugin — argv parsing helpers (isolated so they unit-test without a real process).
3736
- *
3737
- * `deploy`/`dev` resolve the target stage from the command line (`--stage dev`) so a consumer never
3738
- * hardcodes it. The dev PORT is not parsed here — it comes only from the `dev()` argument (no hidden
3739
- * argv/config resolution). Pure: takes an argv array, reads no globals. Node-only tooling.
3740
- */
3741
- /**
3742
- * Extract a `--stage` value from a single token (and the token after it, for the spaced form).
3743
- *
3744
- * @param token - The current argv token.
3745
- * @param next - The following argv token (the value, for the `--stage dev` spaced form).
3746
- * @returns The raw string value when this token is a stage flag, else undefined.
3747
- * @example
3748
- * ```ts
3749
- * stageValueFrom("--stage=dev", undefined); // "dev"
3750
- * stageValueFrom("--stage", "dev"); // "dev"
3751
- * stageValueFrom("--other", "x"); // undefined
3752
- * ```
3753
- */
3754
- const stageValueFrom = (token, next) => {
3755
- const inline = /^--stage=(.+)$/u.exec(token);
3756
- if (inline) return inline[1];
3757
- if (token === "--stage") return next;
3758
- };
3759
- /**
3760
- * Parse a `--stage <name>` / `--stage=<name>` flag out of an argv array — the deploy/dev stage that
3761
- * drives the resource-name suffix (e.g. `tracker-db-dev`). Returns the first non-empty value, or
3762
- * undefined so the caller can fall back to the app's configured stage.
3763
- *
3764
- * @param argv - The argv array to scan (the caller passes the process argv).
3765
- * @returns The parsed stage string, or undefined when no `--stage` flag is present.
3766
- * @example
3767
- * ```ts
3768
- * parseStageArg(["bun", "scripts/deploy.ts", "--stage", "dev"]); // "dev"
3769
- * parseStageArg(["bun", "scripts/deploy.ts"]); // undefined
3770
- * ```
3771
- */
3772
- const parseStageArg = (argv) => {
3773
- for (let index = 0; index < argv.length; index++) {
3774
- const token = argv[index];
3775
- if (token === void 0) continue;
3776
- const raw = stageValueFrom(token, argv[index + 1]);
3777
- if (raw !== void 0 && raw.length > 0) return raw;
3778
- }
3779
- };
3780
- //#endregion
3781
- //#region src/plugins/cli/api.ts
3782
- /**
3783
- * @file cli plugin — API factory (dev, deploy, auth, doctor).
3784
- */
3785
- /**
3786
- * Builds app.cli.* over the deploy plugin (via ctx.require(deployPlugin)). `dev`/`deploy` resolve
3787
- * their args (port from `--port`; guided unless `ci`) then delegate, catching any failure into a
3788
- * branded `✗` line + non-zero exit; the read-only verbs (auth/doctor/whoami) render in Moku style.
3789
- *
3790
- * @param ctx - CLI plugin context (own config + typed require to deployPlugin).
3791
- * @returns The cli API object (dev, deploy, auth, doctor, whoami, wrangler).
3792
- * @example
3793
- * ```ts
3794
- * const api = createCliApi(ctx);
3795
- * await api.dev({ webBuild: () => web.cli.build() }); // → deploy.dev({ port })
3796
- * await api.deploy({ ci: true }); // → deploy.run({ ci: true })
3797
- * ```
3798
- */
3799
- const createCliApi = (ctx) => ({
3800
- /**
3801
- * Run the Worker locally. The dev port comes ONLY from `opts.port` — the consumer passes it (e.g.
3802
- * parsed from its own CLI flags in scripts/dev.ts); when omitted it defaults to wrangler's 8787.
3803
- * There is no hidden argv/config port resolution. Prints a branded dev-session banner, then
3804
- * delegates to deploy.dev; a `webBuild` hook (e.g. `() => webApp.cli.build()`) wires the web build
3805
- * into the dev loop so the site recompiles on change. A failure renders a branded `✗` line +
3806
- * non-zero exit, not a stack.
3807
- *
3808
- * @param opts - Optional local dev options.
3809
- * @param opts.port - Local dev port to bind. Defaults to 8787 when omitted.
3810
- * @param opts.stage - Stage for the generated wrangler config; falls back to `--stage` then the app stage.
3811
- * @param opts.webBuild - Cold-build the web site (e.g. `() => webApp.cli.build()`); also the
3812
- * per-change rebuild when `onChange` is omitted.
3813
- * @param opts.onChange - Incremental per-change rebuild (e.g. `changes => webApp.cli.update(changes)`),
3814
- * so each change rebuilds only the changed paths instead of a full `webBuild()`.
3815
- * @param opts.seed - Load the configured seed (`pluginConfigs.deploy.seed`) into the LOCAL D1 and
3816
- * reset its cached KV keys before serving — the local analogue of `deploy({ seed: true })`.
3817
- * @returns Resolves when the dev session ends.
3818
- * @example
3819
- * ```ts
3820
- * await api.dev({ port: 7878, seed: true, webBuild: () => web.cli.build(), onChange: c => web.cli.update(c) });
3821
- * ```
3822
- */
3823
- async dev(opts) {
3824
- const ui = createBrandConsole();
3825
- ui.lockup({
3826
- wordmark: "moku worker",
3827
- label: "dev session"
3828
- });
3829
- const stage = opts?.stage ?? parseStageArg(process.argv);
3830
- try {
3831
- await ctx.require(deployPlugin).dev({
3832
- ...opts?.port === void 0 ? {} : { port: opts.port },
3833
- ...stage === void 0 ? {} : { stage },
3834
- ...opts?.webBuild ? { webBuild: opts.webBuild } : {},
3835
- ...opts?.onChange ? { onChange: opts.onChange } : {},
3836
- ...opts?.seed ? { seed: opts.seed } : {}
3837
- });
3838
- ui.check(true, "dev session stopped cleanly");
3839
- } catch (error) {
3840
- ui.error(error instanceof Error ? error.message : String(error));
3841
- process.exitCode = 1;
3842
- }
3843
- },
3844
- /**
3845
- * One-command Cloudflare deploy; forwards opts verbatim to deploy.run, then — only on a successful
3846
- * deploy — the requested post-deploy migration/seed. Guided/interactive by default; `{ ci: true }`
3847
- * runs the automated path (CI). A `webBuild` hook builds the web site first (before `wrangler
3848
- * deploy`). RETURNS the structured {@link DeployReport}; on a failure it also renders a branded `✗`
3849
- * line + sets a non-zero exit code (matching cli.auth/doctor), never a raw stack trace.
3850
- *
3851
- * @param opts - Optional deploy options.
3852
- * @param opts.ci - Automated mode: never prompts, auto-confirms. Omit/false → guided on a TTY.
3853
- * @param opts.stage - Target stage (resource-name suffix); falls back to `--stage` then the app stage.
3854
- * @param opts.webBuild - Build the web site first (e.g. `() => webApp.cli.build()`), before deploy.
3855
- * @param opts.migration - Apply pending remote D1 migrations after a successful deploy (skipped on abort).
3856
- * @param opts.seed - Load the configured remote seed (`pluginConfigs.deploy.seed`) after a
3857
- * successful deploy (+ migration); skipped on an aborted deploy.
3858
- * @returns The deploy report (status, url, resource tally, migration/seed outcome, errors).
3859
- * @example
3860
- * ```ts
3861
- * const report = await api.deploy({ webBuild: () => web.cli.build(), migration: true, seed: true });
3862
- * if (report.status === "aborted") return; // creds not set up yet — nothing shipped
3863
- * ```
3864
- */
3865
- async deploy(opts) {
3866
- const stage = opts?.stage ?? parseStageArg(process.argv);
3867
- try {
3868
- const report = await ctx.require(deployPlugin).run({
3869
- ...opts,
3870
- ...stage === void 0 ? {} : { stage }
3871
- });
3872
- if (report.status === "failed") process.exitCode = 1;
3873
- return report;
3874
- } catch (error) {
3875
- const message = error instanceof Error ? error.message : String(error);
3876
- createBrandConsole().error(message);
3877
- process.exitCode = 1;
3878
- return {
3879
- ok: false,
3880
- status: "failed",
3881
- stage: stage ?? "production",
3882
- migration: "skipped",
3883
- seed: "skipped",
3884
- elapsedMs: 0,
3885
- errors: [message]
3886
- };
3887
- }
3888
- },
3889
- /**
3890
- * Seed a configured D1 database from a SQL file (delegates to deploy.seed). Local by default;
3891
- * `opts.remote` seeds Cloudflare. The stage is resolved from a `--stage <name>` CLI flag (so
3892
- * `bun run dev --seed --stage dev` seeds the dev database). A failure renders a branded `✗` line
3893
- * and sets a non-zero exit code rather than throwing.
3894
- *
3895
- * @param sqlFile - Path to the SQL file to execute (e.g. "db/seed.sql").
3896
- * @param opts - Optional options.
3897
- * @param opts.binding - The d1 binding to target when more than one is configured (e.g. "DB").
3898
- * @param opts.remote - Seed the remote (Cloudflare) D1 instead of the local one.
3899
- * @returns Resolves once the seed completes (or after a failure is rendered).
3900
- * @example
3901
- * ```ts
3902
- * await app.cli.seed("db/seed.sql"); // before app.cli.dev(...)
3903
- * ```
3904
- */
3905
- async seed(sqlFile, opts) {
3906
- const ui = createBrandConsole();
3907
- ui.lockup({
3908
- wordmark: "moku worker",
3909
- label: "seed"
3910
- });
3911
- const stage = parseStageArg(process.argv);
3912
- try {
3913
- await ctx.require(deployPlugin).seed(sqlFile, {
3914
- ...opts,
3915
- ...stage === void 0 ? {} : { stage }
3916
- });
3917
- ui.check(true, "seeded", sqlFile);
3918
- } catch (error) {
3919
- ui.error(error instanceof Error ? error.message : String(error));
3920
- process.exitCode = 1;
3921
- }
3922
- },
3923
- /**
3924
- * Verify the `.env` token (no sub) or print the config-derived token guidance (`"setup"`),
3925
- * rendered in Moku style. `setup` works without a token; verify reports the resolved account.
3926
- *
3927
- * @param sub - Pass "setup" to print guidance; omit to verify the current token.
3928
- * @returns Resolves once the check or guidance render completes.
3929
- * @example
3930
- * ```ts
3931
- * await api.auth("setup"); // print what token to create
3932
- * await api.auth(); // verify the current token
3933
- * ```
3934
- */
3935
- async auth(sub) {
3936
- const deploy = ctx.require(deployPlugin);
3937
- const ui = createBrandConsole();
3938
- if (sub === "setup") {
3939
- renderAuthSetup(ui, deploy.requiredToken(), { ci: deploy.ciToken() });
3940
- return;
3941
- }
3942
- try {
3943
- const status = await deploy.verifyAuth();
3944
- ui.check(true, "token valid", `account "${status.account}" (${status.accountId})`);
3945
- } catch (error) {
3946
- ui.error(error instanceof Error ? error.message : String(error));
3947
- }
3948
- },
3949
- /**
3950
- * One-shot preflight report: token + account (verifyAuth) then infra drift (checkInfra),
3951
- * each as a branded check line. Stops after the token check when auth fails.
3952
- *
3953
- * @returns Resolves once the report is printed.
3954
- * @example
3955
- * ```ts
3956
- * await api.doctor();
3957
- * ```
3958
- */
3959
- async doctor() {
3960
- const deploy = ctx.require(deployPlugin);
3961
- const ui = createBrandConsole();
3962
- ui.heading("doctor");
3963
- let tokenOk = false;
3964
- try {
3965
- const status = await deploy.verifyAuth();
3966
- tokenOk = true;
3967
- ui.check(true, "token", `valid · account "${status.account}" (${status.accountId})`);
3968
- } catch (error) {
3969
- ui.check(false, "token", error instanceof Error ? error.message : String(error));
3970
- }
3971
- if (!tokenOk) {
3972
- ui.line("Run `auth setup` for the exact token to create.");
3973
- return;
3974
- }
3975
- try {
3976
- const plan = await deploy.checkInfra();
3977
- ui.check(true, "infra", `${plan.exists.length} exist, ${plan.missing.length} to create in "${plan.account}"`);
3978
- } catch (error) {
3979
- ui.check(false, "infra", error instanceof Error ? error.message : String(error));
3980
- }
3981
- },
3982
- /**
3983
- * Print the resolved Cloudflare account for the current `.env` token.
3984
- *
3985
- * @returns Resolves once the account summary is printed.
3986
- * @example
3987
- * ```ts
3988
- * await api.whoami();
3989
- * ```
3990
- */
3991
- async whoami() {
3992
- const ui = createBrandConsole();
3993
- try {
3994
- const status = await ctx.require(deployPlugin).verifyAuth();
3995
- ui.check(true, "account", `${status.account} (${status.accountId})`);
3996
- } catch (error) {
3997
- ui.error(error instanceof Error ? error.message : String(error));
3998
- }
3999
- },
4000
- /**
4001
- * Run an arbitrary wrangler command through the branded CLI (escape hatch). Streams its output.
4002
- *
4003
- * @param args - The wrangler arguments.
4004
- * @returns Resolves once wrangler exits.
4005
- * @example
4006
- * ```ts
4007
- * await api.wrangler(["kv", "namespace", "list"]);
4008
- * ```
4009
- */
4010
- async wrangler(args) {
4011
- createBrandConsole().heading(`wrangler ${args.join(" ")}`);
4012
- await ctx.require(deployPlugin).wrangler(args);
4013
- }
4014
- });
4015
- //#endregion
4016
- //#region src/plugins/cli/handlers.ts
4017
- /** Divider drawn before the native `wrangler dev` TUI so the moku preamble reads as one section. */
4018
- const WRANGLER_DIVIDER = ` ── wrangler ${"─".repeat(48)}`;
4019
- /** Deploy phases that are a slow, opaque wait (captured output) — worth a live spinner on a TTY. */
4020
- const SPINNER_PHASES = new Set(["upload", "deploy"]);
4021
- /** Braille spinner glyphs; advance one per tick. */
4022
- const SPINNER_FRAMES = [
4023
- "⠋",
4024
- "⠙",
4025
- "⠹",
4026
- "⠸",
4027
- "⠼",
4028
- "⠴",
4029
- "⠦",
4030
- "⠧",
4031
- "⠇",
4032
- "⠏"
4033
- ];
4034
- /** Spinner tick interval (ms). */
4035
- const SPINNER_TICK_MS = 80;
4036
- /** Carriage-return + blanks + carriage-return that wipes the transient spinner line before settling. */
4037
- const SPINNER_CLEAR = `\r${" ".repeat(72)}\r`;
4038
- /**
4039
- * Builds the hook handlers that turn global deploy events into a live progress TUI.
4040
- * Each logs a clean, prefix-free message via `ctx.log`; the branded log sink (installed
4041
- * by the cli plugin's onInit from `@moku-labs/common/cli`) adds the `›` marker, brand
4042
- * color, and stderr routing. Pure observers — print and return; never mutate state,
4043
- * never block the deploy pipeline (fire-and-forget, spec/07 §3,§4).
4044
- *
4045
- * @param ctx - CLI plugin context with injected log core API.
4046
- * @returns Hook map for the deploy/dev phase + completion events (provision detail is panel-rendered).
4047
- * @example
4048
- * ```ts
4049
- * const hooks = createCliHooks(ctx);
4050
- * hooks["deploy:phase"]({ phase: "detect" }); // logs "detect" → renders " › detect"
4051
- * hooks["dev:phase"]({ phase: "serve", detail: "http://localhost:8787" }); // "serve · …"
4052
- * hooks["deploy:complete"](); // settles the deploy spinner; the "Deployed" panel renders separately
4053
- * ```
4054
- */
4055
- const createCliHooks = (ctx) => {
4056
- const ui = createBrandConsole();
4057
- const { palette } = ui;
4058
- let spinnerTimer;
4059
- let spinnerLabel;
4060
- const stopSpinner = () => {
4061
- if (spinnerTimer !== void 0) {
4062
- clearInterval(spinnerTimer);
4063
- spinnerTimer = void 0;
4064
- }
4065
- if (spinnerLabel !== void 0) {
4066
- process.stdout.write(SPINNER_CLEAR);
4067
- ctx.log.info(spinnerLabel);
4068
- spinnerLabel = void 0;
4069
- }
4070
- };
4071
- const startSpinner = (label) => {
4072
- spinnerLabel = label;
4073
- let frame = 0;
4074
- const text = `${label} …`;
4075
- spinnerTimer = setInterval(() => {
4076
- const glyph = SPINNER_FRAMES[frame % SPINNER_FRAMES.length] ?? SPINNER_FRAMES[0];
4077
- frame += 1;
4078
- process.stdout.write(`\r ${palette.pink(glyph)} ${palette.dim(text)}`);
4079
- }, SPINNER_TICK_MS);
4080
- };
4081
- return {
4082
- /**
4083
- * Render one pipeline phase. Quick phases print a clean line ("phase" / "phase · detail"); the
4084
- * slow opaque waits (upload / deploy) animate a branded spinner on a TTY, settling to a line when
4085
- * the next phase or completion arrives. Off a TTY every phase is a plain line (unchanged).
4086
- *
4087
- * @param p - The deploy:phase event payload.
4088
- * @example
4089
- * ```ts
4090
- * handler({ phase: "detect" }); // "detect"
4091
- * handler({ phase: "deploy" }); // spins on a TTY, else "deploy"
4092
- * ```
4093
- */
4094
- "deploy:phase"(p) {
4095
- stopSpinner();
4096
- const label = p.detail ? `${p.phase} · ${p.detail}` : p.phase;
4097
- if (process.stdout.isTTY === true && SPINNER_PHASES.has(p.phase)) startSpinner(label);
4098
- else ctx.log.info(label);
4099
- },
4100
- /**
4101
- * Log one dev-session phase: "phase" or "phase · detail".
4102
- *
4103
- * @param p - The dev:phase event payload.
4104
- * @example
4105
- * ```ts
4106
- * handler({ phase: "serve", detail: "http://localhost:8787" }); // "serve · http://localhost:8787"
4107
- * ```
4108
- */
4109
- "dev:phase"(p) {
4110
- ctx.log.info(p.detail ? `${p.phase} · ${p.detail}` : p.phase);
4111
- if (p.phase === "serve") ui.line(WRANGLER_DIVIDER);
4112
- },
4113
- /**
4114
- * Log the site rebuild result: "site <n> files · <ms>ms" (omits the count when unknown).
4115
- *
4116
- * @param p - The dev:rebuilt event payload.
4117
- * @example
4118
- * ```ts
4119
- * handler({ files: 12, ms: 240 }); // "site 12 files · 240ms"
4120
- * handler({ files: 0, ms: 240 }); // "site · 240ms"
4121
- * ```
4122
- */
4123
- "dev:rebuilt"(p) {
4124
- ctx.log.info(p.files > 0 ? `site ${String(p.files)} files · ${String(p.ms)}ms` : `site · ${String(p.ms)}ms`);
4125
- },
4126
- /**
4127
- * Log a non-fatal dev build failure via warn (the session keeps serving the last good build).
4128
- *
4129
- * @param p - The dev:error event payload.
4130
- * @example
4131
- * ```ts
4132
- * handler({ message: "build failed" }); // warn "build failed"
4133
- * ```
4134
- */
4135
- "dev:error"(p) {
4136
- ctx.log.warn(p.message);
4137
- },
4138
- /**
4139
- * Settle the final deploy spinner. The deployed URL + summary now render as a branded panel (the
4140
- * deploy plugin's renderDeploySummary), so the cli no longer logs a duplicate `deployed → url`.
4141
- *
4142
- * @example
4143
- * ```ts
4144
- * handler(); // clears the `deploy` spinner; the "Deployed" panel follows from the deploy plugin
4145
- * ```
4146
- */
4147
- "deploy:complete"() {
4148
- stopSpinner();
4149
- }
4150
- };
4151
- };
4152
- /**
4153
- * Standard tier (node-only) — developer-facing CLI surface.
4154
- *
4155
- * Mounts `app.cli.dev()` and `app.cli.deploy()` as thin passthroughs to deployPlugin.
4156
- * Hooks subscribe to the global deploy:phase / provision:resource / deploy:complete events
4157
- * and print a live progress TUI via the injected ctx.log core API.
4158
- *
4159
- * Inline lambdas on `api`/`hooks` preserve event-name inference so the hook map keys
4160
- * are constrained to `WorkerEvents` keys (spec/15 §5).
4161
- *
4162
- * @see README.md
4163
- */
4164
- const cliPlugin = createPlugin("cli", {
4165
- depends: [deployPlugin],
4166
- config: {},
4167
- onInit: (ctx) => {
4168
- ctx.log.clearSinks();
4169
- ctx.log.addSink(brandedSink("info"));
4170
- },
4171
- api: (ctx) => createCliApi(ctx),
4172
- hooks: (ctx) => createCliHooks(ctx)
4173
- });
4174
- //#endregion
4175
- export { kvPlugin as a, d1Plugin as c, createCore as d, createPlugin as f, queuesPlugin as i, bindingsPlugin as l, deployPlugin as n, durableObjectsPlugin as o, stagePlugin as p, storagePlugin as r, defineDurableObject as s, cliPlugin as t, coreConfig as u };