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