@moku-labs/worker 0.10.0 → 0.11.0

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