@moku-labs/worker 0.5.1 → 0.6.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.
package/dist/cli.mjs CHANGED
@@ -1,1896 +1,2 @@
1
- import { i as durableObjectsPlugin, n as queuesPlugin, o as d1Plugin, r as kvPlugin, t as storagePlugin, u as createPlugin } from "./storage-COo-F38H.mjs";
2
- import { brandedSink, createBrandConsole, createBrandPrompts } from "@moku-labs/common/cli";
3
- import { spawn } from "node:child_process";
4
- import { existsSync, readFileSync, watch } from "node:fs";
5
- import path from "node:path";
6
- import { readdir, stat, writeFile } from "node:fs/promises";
7
- //#region src/plugins/deploy/auth/permissions.ts
8
- /** Permission groups every deploy needs, regardless of resources. */
9
- const ALWAYS = [{
10
- group: "Account · Workers Scripts",
11
- scope: "Edit",
12
- reason: "deploy",
13
- inBaseTemplate: true
14
- }, {
15
- group: "Account · Account Settings",
16
- scope: "Read",
17
- reason: "account",
18
- inBaseTemplate: true
19
- }];
20
- /**
21
- * Per-resource-kind permission group. `do` needs nothing extra (Durable Objects ship with the
22
- * Worker script, covered by Workers Scripts · Edit). `d1`/`queue` are NOT in the stock template.
23
- */
24
- const BY_KIND = {
25
- kv: {
26
- group: "Account · Workers KV Storage",
27
- scope: "Edit",
28
- reason: "kv",
29
- inBaseTemplate: true
30
- },
31
- r2: {
32
- group: "Account · Workers R2 Storage",
33
- scope: "Edit",
34
- reason: "r2",
35
- inBaseTemplate: true
36
- },
37
- d1: {
38
- group: "Account · D1",
39
- scope: "Edit",
40
- reason: "d1",
41
- inBaseTemplate: false
42
- },
43
- queue: {
44
- group: "Account · Queues",
45
- scope: "Edit",
46
- reason: "queue",
47
- inBaseTemplate: false
48
- },
49
- do: void 0
50
- };
51
- /**
52
- * Derive the Cloudflare API token requirement from an app manifest: the full permission set plus
53
- * the subset that must be ADDED to the stock "Edit Cloudflare Workers" template.
54
- *
55
- * @param manifest - The assembled deploy manifest.
56
- * @returns The token requirement (base template, full required set, and groups to add).
57
- * @example
58
- * ```ts
59
- * const { toAdd } = requiredToken({ name: "w", compatibilityDate: "…", resources: [{ kind: "d1", binding: "DB" }] });
60
- * // toAdd → [{ group: "Account · D1", scope: "Edit", … }]
61
- * ```
62
- */
63
- const requiredToken = (manifest) => {
64
- const required = [...ALWAYS];
65
- const seen = new Set(required.map((permission) => permission.group));
66
- for (const resource of manifest.resources) {
67
- const permission = BY_KIND[resource.kind];
68
- if (permission !== void 0 && !seen.has(permission.group)) {
69
- required.push(permission);
70
- seen.add(permission.group);
71
- }
72
- }
73
- return {
74
- base: "Edit Cloudflare Workers",
75
- required,
76
- toAdd: required.filter((permission) => !permission.inBaseTemplate)
77
- };
78
- };
79
- /** Permission every CI/automation redeploy needs: ship the Worker script. */
80
- const CI_ALWAYS = [{
81
- group: "Account · Workers Scripts",
82
- scope: "Edit",
83
- reason: "deploy",
84
- inBaseTemplate: true
85
- }];
86
- /**
87
- * Per-resource-kind permission for the CI/automation token. After a first LOCAL deploy has
88
- * provisioned everything, CI only needs to LIST existing infra (the idempotent preflight) and
89
- * ship — so data resources drop to `Read`; R2 stays `Edit` because asset upload writes objects.
90
- */
91
- const CI_BY_KIND = {
92
- kv: {
93
- group: "Account · Workers KV Storage",
94
- scope: "Read",
95
- reason: "kv (preflight)",
96
- inBaseTemplate: true
97
- },
98
- r2: {
99
- group: "Account · Workers R2 Storage",
100
- scope: "Edit",
101
- reason: "r2 (asset upload)",
102
- inBaseTemplate: true
103
- },
104
- d1: {
105
- group: "Account · D1",
106
- scope: "Read",
107
- reason: "d1 (preflight)",
108
- inBaseTemplate: false
109
- },
110
- queue: {
111
- group: "Account · Queues",
112
- scope: "Read",
113
- reason: "queue (preflight)",
114
- inBaseTemplate: false
115
- },
116
- do: void 0
117
- };
118
- /**
119
- * Derive the REDUCED Cloudflare API token for CI/automation redeploys, from the same manifest.
120
- * Assumes a prior LOCAL deploy already provisioned the infra, so CI never creates: data resources
121
- * need only `Read` (the idempotent preflight lists them), R2 keeps `Edit` for asset upload, and no
122
- * `Account Settings · Read` is needed because CI pins `CLOUDFLARE_ACCOUNT_ID`. Pure: no network.
123
- *
124
- * @param manifest - The assembled deploy manifest.
125
- * @returns The minimum permission groups for a CI redeploy token (deduped, manifest-scoped).
126
- * @example
127
- * ```ts
128
- * const groups = ciToken({ name: "w", compatibilityDate: "…", resources: [{ kind: "d1", binding: "DB" }] });
129
- * // → [Workers Scripts·Edit, D1·Read]
130
- * ```
131
- */
132
- const ciToken = (manifest) => {
133
- const groups = [...CI_ALWAYS];
134
- const seen = new Set(groups.map((permission) => permission.group));
135
- for (const resource of manifest.resources) {
136
- const permission = CI_BY_KIND[resource.kind];
137
- if (permission !== void 0 && !seen.has(permission.group)) {
138
- groups.push(permission);
139
- seen.add(permission.group);
140
- }
141
- }
142
- return groups;
143
- };
144
- //#endregion
145
- //#region src/plugins/deploy/auth/setup.ts
146
- /** Cloudflare's dashboard path for creating API tokens. */
147
- const TOKENS_URL = "https://dash.cloudflare.com/profile/api-tokens";
148
- /**
149
- * Render the FULL local-first token section (the deploy that provisions everything): the permission
150
- * table flagging template-missing rows, the template + "add these" steps, and the `.env.local` lines.
151
- *
152
- * @param requirement - The full token requirement (from requiredToken()).
153
- * @returns The local-first section lines.
154
- * @example
155
- * ```ts
156
- * const lines = localSection(requiredToken(manifest));
157
- * ```
158
- */
159
- const localSection = (requirement) => {
160
- const permissionRows = requirement.required.map((permission) => {
161
- const flag = permission.inBaseTemplate ? "" : " <- add to template";
162
- return ` - ${permission.group} : ${permission.scope} (${permission.reason})${flag}`;
163
- });
164
- 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.`];
165
- return [
166
- "LOCAL — first deploy (provisions infra). A Cloudflare API token with these permissions:",
167
- "",
168
- ...permissionRows,
169
- "",
170
- "Fastest path:",
171
- ` 1. ${TOKENS_URL} -> Create Token`,
172
- ` 2. Start from the "${requirement.base}" template.`,
173
- ...step3,
174
- " 4. Account Resources -> Include -> your account.",
175
- " 5. Create the token, copy it, then add it to .env.local:",
176
- " CLOUDFLARE_API_TOKEN=<paste your token>",
177
- " CLOUDFLARE_ACCOUNT_ID=<your account id>",
178
- " 6. Verify it with `auth` (app.deploy.verifyAuth())."
179
- ];
180
- };
181
- /**
182
- * Render the REDUCED CI/automation token section (redeploy-only): the scoped permission table plus
183
- * the CI-secret + account-pin steps.
184
- *
185
- * @param groups - The CI permission groups (from ciToken()).
186
- * @returns The CI section lines.
187
- * @example
188
- * ```ts
189
- * const lines = ciSection(ciToken(manifest));
190
- * ```
191
- */
192
- const ciSection = (groups) => {
193
- return [
194
- "CI — automation redeploy (infra already provisioned by a local deploy). A SCOPED token with:",
195
- "",
196
- ...groups.map((permission) => ` - ${permission.group} : ${permission.scope} (${permission.reason})`),
197
- "",
198
- ` 1. ${TOKENS_URL} -> Create Token -> Create Custom Token.`,
199
- " 2. Add exactly the permissions above (Read, not Edit, on data resources — CI never creates).",
200
- " 3. Account Resources -> Include -> your account.",
201
- " 4. Store it as the CLOUDFLARE_API_TOKEN secret in CI, and PIN the account so no account",
202
- " lookup (and no Account Settings -> Read) is needed:",
203
- " CLOUDFLARE_ACCOUNT_ID=<your account id>",
204
- " CI reuses the same idempotent pipeline — it lists existing infra and ships. To let CI also",
205
- " CREATE missing infra (self-heal), give it the LOCAL token above instead."
206
- ];
207
- };
208
- /**
209
- * Render the `auth setup` instructions from the app manifest: the FULL local-first token (provisions
210
- * everything) followed by the REDUCED CI/automation token (redeploy-only).
211
- *
212
- * @param manifest - The assembled deploy manifest.
213
- * @returns A multi-line instruction string covering both tokens.
214
- * @example
215
- * ```ts
216
- * const text = tokenInstructions(manifest);
217
- * ```
218
- */
219
- const tokenInstructions = (manifest) => [
220
- ...localSection(requiredToken(manifest)),
221
- "",
222
- ...ciSection(ciToken(manifest))
223
- ].join("\n");
224
- //#endregion
225
- //#region src/plugins/deploy/infra/cloudflare.ts
226
- /**
227
- * @file deploy plugin — Cloudflare REST discovery client (infra preflight).
228
- *
229
- * Lists what already exists in a Cloudflare account so the deploy pipeline can create only the
230
- * missing resources (idempotent provisioning) and recover real ids for existing kv/d1 bindings.
231
- * Authenticated with the `.env` API token (CLOUDFLARE_API_TOKEN) — never an interactive login.
232
- * Uses the global `fetch`; node-only, never imported by the runtime Worker bundle.
233
- */
234
- const API_BASE = "https://api.cloudflare.com/client/v4";
235
- /**
236
- * GET a Cloudflare API path with the bearer token and unwrap the `result`.
237
- *
238
- * @param token - The Cloudflare API token (CLOUDFLARE_API_TOKEN).
239
- * @param path - API path beneath the v4 base (e.g. "/accounts").
240
- * @returns The unwrapped `result` payload, typed by the caller.
241
- * @throws {Error} When the HTTP request fails or the API reports `success: false`.
242
- * @example
243
- * ```ts
244
- * const accounts = await cfGet<Array<{ id: string }>>(token, "/accounts");
245
- * ```
246
- */
247
- const cfGet = async (token, path) => {
248
- const response = await fetch(`${API_BASE}${path}`, { headers: {
249
- Authorization: `Bearer ${token}`,
250
- "Content-Type": "application/json"
251
- } });
252
- const body = await response.json();
253
- if (!response.ok || !body.success) {
254
- const detail = body.errors?.map((error) => error.message).join("; ") || `HTTP ${response.status}`;
255
- throw new Error(`[moku-worker] Cloudflare API request failed (${path}): ${detail}`);
256
- }
257
- return body.result;
258
- };
259
- /**
260
- * Resolve the Cloudflare account (id + display name) accessible to the token. Used when the
261
- * consumer did not pin CLOUDFLARE_ACCOUNT_ID; the first accessible account is chosen.
262
- *
263
- * @param token - The Cloudflare API token.
264
- * @returns The resolved account id and name.
265
- * @throws {Error} When the token can access no account.
266
- * @example
267
- * ```ts
268
- * const { id, name } = await resolveAccount(token);
269
- * ```
270
- */
271
- const resolveAccount = async (token) => {
272
- const first = (await cfGet(token, "/accounts"))[0];
273
- if (!first) throw new Error("[moku-worker] No Cloudflare account is accessible with this API token.");
274
- return {
275
- id: first.id,
276
- name: first.name
277
- };
278
- };
279
- /**
280
- * Verify a Cloudflare API token via `GET /user/tokens/verify`. Returns its status (`"active"` for
281
- * a usable token); throws (via cfGet) when the token is rejected outright (401/invalid).
282
- *
283
- * @param token - The Cloudflare API token to verify.
284
- * @returns The token status string reported by Cloudflare.
285
- * @throws {Error} When the verify request fails (invalid/expired token).
286
- * @example
287
- * ```ts
288
- * const { status } = await verifyToken(token); // status === "active"
289
- * ```
290
- */
291
- const verifyToken = async (token) => {
292
- return { status: (await cfGet(token, "/user/tokens/verify")).status };
293
- };
294
- /**
295
- * List the resources that already exist in the account, querying ONLY the kinds the app declares
296
- * (one request per declared kind, in parallel), indexed for the preflight diff. Scoping to the
297
- * declared kinds keeps the API token minimal — an app with only KV never lists (and so never needs
298
- * read permission on) D1, R2, or Queues.
299
- *
300
- * @param token - The Cloudflare API token.
301
- * @param accountId - The Cloudflare account id to scope the listings to.
302
- * @param kinds - The resource kinds present in the manifest (the only kinds queried).
303
- * @returns The existing resources, indexed by kind (un-queried kinds resolve empty).
304
- * @throws {Error} When any listing request fails.
305
- * @example
306
- * ```ts
307
- * const existing = await listExisting(token, accountId, new Set(["kv", "d1"]));
308
- * if (existing.kv.has("SESSIONS")) { ... }
309
- * ```
310
- */
311
- const listExisting = async (token, accountId, kinds) => {
312
- const base = `/accounts/${accountId}`;
313
- const [kv, d1, r2, queues] = await Promise.all([
314
- kinds.has("kv") ? cfGet(token, `${base}/storage/kv/namespaces`) : Promise.resolve([]),
315
- kinds.has("d1") ? cfGet(token, `${base}/d1/database`) : Promise.resolve([]),
316
- kinds.has("r2") ? cfGet(token, `${base}/r2/buckets`) : Promise.resolve({}),
317
- kinds.has("queue") ? cfGet(token, `${base}/queues`) : Promise.resolve([])
318
- ]);
319
- return {
320
- kv: new Map(kv.map((namespace) => [namespace.title, namespace.id])),
321
- d1: new Map(d1.map((database) => [database.name, database.uuid])),
322
- r2: new Set((r2.buckets ?? []).map((bucket) => bucket.name)),
323
- queue: new Set(queues.map((queue) => queue.queue_name))
324
- };
325
- };
326
- //#endregion
327
- //#region src/plugins/deploy/auth/verify.ts
328
- /**
329
- * @file deploy plugin — `.env` token verification + account resolution.
330
- *
331
- * Reads CLOUDFLARE_API_TOKEN via ctx.env, verifies it is active against the Cloudflare API, and
332
- * resolves the account. Emits auth:verified. Throws a branded, actionable error (pointing at
333
- * `auth setup`) when the token is absent, invalid, or inactive — never an interactive login.
334
- * Node-only; never imported by the runtime Worker bundle.
335
- */
336
- /** Branded hint appended to every auth failure so the user knows the next step. */
337
- const SETUP_HINT = "Run `auth setup` for the exact token to create.";
338
- /**
339
- * Verify the `.env` Cloudflare API token and resolve its account.
340
- *
341
- * @param ctx - The deploy plugin context (env + emit).
342
- * @returns The verified auth status (account + id).
343
- * @throws {Error} When the token is absent, invalid/expired, or not active.
344
- * @example
345
- * ```ts
346
- * const { account, accountId } = await verifyAuth(ctx);
347
- * ```
348
- */
349
- const verifyAuth = async (ctx) => {
350
- const token = ctx.env.get("CLOUDFLARE_API_TOKEN");
351
- if (token === void 0 || token === "") throw new Error(`[moku-worker] CLOUDFLARE_API_TOKEN is not set. ${SETUP_HINT}`);
352
- let status;
353
- try {
354
- ({status} = await verifyToken(token));
355
- } catch (error) {
356
- throw new Error(`[moku-worker] Cloudflare API token is invalid or expired. ${SETUP_HINT}`, { cause: error });
357
- }
358
- if (status !== "active") throw new Error(`[moku-worker] Cloudflare API token is "${status}", not active. ${SETUP_HINT}`);
359
- const pinnedAccountId = ctx.env.get("CLOUDFLARE_ACCOUNT_ID");
360
- const account = pinnedAccountId === void 0 || pinnedAccountId === "" ? await resolveAccount(token) : {
361
- id: pinnedAccountId,
362
- name: pinnedAccountId
363
- };
364
- ctx.emit("auth:verified", {
365
- account: account.name,
366
- accountId: account.id,
367
- scopes: []
368
- });
369
- return {
370
- ok: true,
371
- account: account.name,
372
- accountId: account.id,
373
- scopes: []
374
- };
375
- };
376
- //#endregion
377
- //#region src/plugins/deploy/runner.ts
378
- /**
379
- * @file deploy plugin — wrangler subprocess wrapper (node:child_process).
380
- *
381
- * Spawns `wrangler` with the given args and resolves the deployed URL
382
- * (extracted from stdout for `wrangler deploy`), or the full stdout for other verbs.
383
- * This module is node-only; never imported by the runtime Worker bundle.
384
- */
385
- /**
386
- * Extract the deployed URL from `wrangler deploy` stdout.
387
- * Wrangler prints a line like: "Published my-worker (1.23 sec) https://..."
388
- * or "Deployed my-worker (1.23 sec) https://...".
389
- *
390
- * @param output - The combined stdout from wrangler deploy.
391
- * @returns The deployed URL, or empty string when not found.
392
- * @example
393
- * ```ts
394
- * extractDeployedUrl("Deployed my-worker (0.5 sec) https://my-worker.workers.dev");
395
- * // "https://my-worker.workers.dev"
396
- * ```
397
- */
398
- const extractDeployedUrl = (output) => {
399
- return /https:\/\/[^\s]+\.workers\.dev[^\s]*/u.exec(output)?.[0] ?? "";
400
- };
401
- /**
402
- * Spawn `wrangler` with the given args and resolve the output string.
403
- * For `wrangler deploy`, the resolved value is the deployed URL parsed from stdout.
404
- * For all other verbs (dev, kv namespace create, etc.), the resolved value is stdout.
405
- *
406
- * @param args - Wrangler CLI arguments (e.g. ["deploy", "--config", "wrangler.jsonc"]).
407
- * @returns Resolves with the deployed URL (deploy verb) or full stdout (other verbs).
408
- * @throws {Error} When wrangler exits with a non-zero code.
409
- * @example
410
- * ```ts
411
- * const url = await runWrangler(["deploy", "--config", "wrangler.jsonc"]);
412
- * await runWrangler(["kv", "namespace", "create", "CACHE"]);
413
- * ```
414
- */
415
- const runWrangler = (args) => new Promise((resolve, reject) => {
416
- const chunks = [];
417
- const errChunks = [];
418
- const child = spawn("wrangler", args, {
419
- env: { ...process.env },
420
- stdio: [
421
- "ignore",
422
- "pipe",
423
- "pipe"
424
- ]
425
- });
426
- child.stdout.on("data", (chunk) => {
427
- chunks.push(chunk);
428
- });
429
- child.stderr.on("data", (chunk) => {
430
- errChunks.push(chunk);
431
- });
432
- child.on("error", (err) => {
433
- reject(/* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${err.message}`));
434
- });
435
- child.on("close", (code) => {
436
- const stdout = Buffer.concat(chunks).toString("utf8");
437
- const stderr = Buffer.concat(errChunks).toString("utf8");
438
- if (code !== 0) {
439
- reject(/* @__PURE__ */ new Error(`[moku-worker] wrangler exited with code ${String(code)}.\n ${stderr || stdout}`));
440
- return;
441
- }
442
- resolve(args[0] === "deploy" ? extractDeployedUrl(stdout) : stdout);
443
- });
444
- });
445
- /**
446
- * Spawn `wrangler` with the given args, inheriting stdio so its output streams live to the user's
447
- * terminal (used by the generic passthrough and long-lived commands like `tail`).
448
- *
449
- * @param args - Wrangler CLI arguments (e.g. ["kv", "namespace", "list"]).
450
- * @returns Resolves once wrangler exits successfully.
451
- * @throws {Error} When wrangler cannot be spawned or exits non-zero.
452
- * @example
453
- * ```ts
454
- * await runWranglerInherit(["kv", "namespace", "list"]);
455
- * ```
456
- */
457
- const runWranglerInherit = (args) => {
458
- return new Promise((resolve, reject) => {
459
- const child = spawn("wrangler", args, { stdio: "inherit" });
460
- child.on("error", (error) => {
461
- reject(/* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${error.message}`));
462
- });
463
- child.on("close", (code) => {
464
- if (code === 0) {
465
- resolve();
466
- return;
467
- }
468
- reject(/* @__PURE__ */ new Error(`[moku-worker] wrangler exited with code ${String(code)}.`));
469
- });
470
- });
471
- };
472
- //#endregion
473
- //#region src/plugins/deploy/dev/build.ts
474
- /**
475
- * @file deploy plugin — dev site-rebuild resolution.
476
- *
477
- * Resolves HOW to rebuild the Moku web site on change: the in-process `webBuild` hook (preferred,
478
- * fast, typed — passed call-time from the consumer's script or set as a config default) → a
479
- * `buildCommand` shell string → an auto-detected `scripts/build.ts`. When nothing is configured,
480
- * dev serves the worker only and says so. Subprocesses inherit the parent env by default.
481
- * Node-only; never imported by the runtime Worker bundle.
482
- */
483
- /** Convention build script auto-detected when no webBuild/buildCommand is configured. */
484
- const AUTO_DETECT = "scripts/build.ts";
485
- /**
486
- * Opportunistically read a numeric `files` count off an arbitrary web build result. A real web
487
- * build returns its own summary shape (the worker framework cannot know it), so anything without a
488
- * numeric `files` field reports 0.
489
- *
490
- * @param result - The resolved value of a {@link WebBuild} hook (any shape).
491
- * @returns The `files` count when present and numeric, else 0.
492
- * @example
493
- * ```ts
494
- * fileCountOf({ files: 12 }); // 12
495
- * fileCountOf({ outDir: "dist", pageCount: 4 }); // 0
496
- * ```
497
- */
498
- const fileCountOf = (result) => {
499
- if (typeof result === "object" && result !== null && "files" in result) {
500
- const { files } = result;
501
- return typeof files === "number" ? files : 0;
502
- }
503
- return 0;
504
- };
505
- /**
506
- * Run a shell build command, resolving on a zero exit and rejecting otherwise.
507
- *
508
- * @param command - The shell command to run (the consumer's own configured build).
509
- * @returns Resolves once the command exits successfully.
510
- * @throws {Error} When the command fails to start or exits non-zero.
511
- * @example
512
- * ```ts
513
- * await runShellBuild("bun run scripts/build.ts");
514
- * ```
515
- */
516
- const runShellBuild = (command) => {
517
- return new Promise((resolve, reject) => {
518
- const child = spawn(command, {
519
- shell: true,
520
- stdio: "inherit"
521
- });
522
- child.on("error", (error) => {
523
- reject(/* @__PURE__ */ new Error(`[moku-worker] site build failed to start.\n ${error.message}`));
524
- });
525
- child.on("close", (code) => {
526
- if (code === 0) {
527
- resolve();
528
- return;
529
- }
530
- reject(/* @__PURE__ */ new Error(`[moku-worker] site build exited with code ${String(code)}.`));
531
- });
532
- });
533
- };
534
- /**
535
- * Rebuild the Moku web site using the resolved strategy: the call-time `webBuild` hook (the
536
- * script-driven path), else the `webBuild` config default, else the `buildCommand` shell string,
537
- * else an auto-detected `scripts/build.ts`. A hook's result is normalized to a `{ files }` count
538
- * (0 when the hook reports none, and for the shell path where it is unknown).
539
- *
540
- * @param ctx - The deploy plugin context (config + emit).
541
- * @param webBuild - Optional call-time web build hook (takes precedence over `ctx.config.webBuild`).
542
- * @returns The rebuilt file count (0 for the shell path / a countless hook).
543
- * @throws {Error} When the resolved shell build fails.
544
- * @example
545
- * ```ts
546
- * const { files } = await buildSite(ctx, () => web.cli.build());
547
- * ```
548
- */
549
- const buildSite = async (ctx, webBuild) => {
550
- const hook = webBuild ?? ctx.config.webBuild;
551
- if (hook !== void 0) return { files: fileCountOf(await hook()) };
552
- const command = ctx.config.buildCommand || (existsSync(AUTO_DETECT) ? `bun run ${AUTO_DETECT}` : "");
553
- if (command === "") {
554
- ctx.emit("dev:error", { message: "No site build configured (pass webBuild or set buildCommand); serving worker only." });
555
- return { files: 0 };
556
- }
557
- await runShellBuild(command);
558
- return { files: 0 };
559
- };
560
- //#endregion
561
- //#region src/plugins/deploy/dev/watch.ts
562
- /**
563
- * @file deploy plugin — debounced filesystem watcher for dev.
564
- *
565
- * Watches the top-level directories implied by the config globs (recursive) and fires a debounced
566
- * change callback with the last changed path. Uses node:fs.watch — no extra dependency.
567
- * Node-only; never imported by the runtime Worker bundle.
568
- */
569
- /**
570
- * Derive the set of top-level directories to watch from glob patterns.
571
- *
572
- * @param globs - Watch globs (e.g. ["src/**\/*.ts", "public/**\/*"]).
573
- * @returns The distinct top-level directories (e.g. ["src", "public"]).
574
- * @example
575
- * ```ts
576
- * watchDirectories(["src/**\/*.ts", "public/**\/*"]); // ["src", "public"]
577
- * ```
578
- */
579
- const watchDirectories = (globs) => {
580
- const directories = /* @__PURE__ */ new Set();
581
- for (const glob of globs) {
582
- const globStart = glob.search(/[*?[{]/u);
583
- const top = (globStart === -1 ? path.dirname(glob) : glob.slice(0, globStart)).split(/[/\\]/u).find((segment) => segment !== "") ?? ".";
584
- directories.add(top);
585
- }
586
- return [...directories];
587
- };
588
- /**
589
- * Watch the directories implied by `globs` and fire `onChange` (debounced by `debounceMs`) with
590
- * the last changed path. Missing directories are skipped silently.
591
- *
592
- * @param globs - Watch globs.
593
- * @param debounceMs - Coalesce rapid changes into one callback within this window.
594
- * @param onChange - Called with the last changed path after the debounce settles.
595
- * @returns A handle whose close() stops all watchers and cancels any pending callback.
596
- * @example
597
- * ```ts
598
- * const handle = watchPaths(["src/**\/*.ts"], 120, p => rebuild(p));
599
- * handle.close();
600
- * ```
601
- */
602
- const watchPaths = (globs, debounceMs, onChange) => {
603
- let timer;
604
- let lastPath = "";
605
- const fire = (changedPath) => {
606
- lastPath = changedPath;
607
- if (timer !== void 0) clearTimeout(timer);
608
- timer = setTimeout(() => {
609
- onChange(lastPath);
610
- }, debounceMs);
611
- };
612
- const watchers = [];
613
- for (const directory of watchDirectories(globs)) {
614
- if (!existsSync(directory)) continue;
615
- watchers.push(watch(directory, { recursive: true }, (_event, filename) => {
616
- if (filename !== null) fire(path.join(directory, filename.toString()));
617
- }));
618
- }
619
- return { close: () => {
620
- if (timer !== void 0) clearTimeout(timer);
621
- for (const watcher of watchers) watcher.close();
622
- } };
623
- };
624
- //#endregion
625
- //#region src/plugins/deploy/dev/runner.ts
626
- /**
627
- * @file deploy plugin — dev watch/recompile orchestrator.
628
- *
629
- * One long-lived session: cold-build the Moku site, optionally apply local D1 migrations, spawn
630
- * `wrangler dev --live-reload` ONCE, then watch the site sources and rebuild on change (wrangler's
631
- * asset server live-reloads the browser). Build failures keep the session serving the last good
632
- * build. Tears down cleanly on SIGINT. Side-effecting work is injected via DevDeps so the
633
- * orchestration is unit-testable without real processes, watchers, or signals.
634
- * Node-only; never imported by the runtime Worker bundle.
635
- */
636
- /**
637
- * Spawn the long-lived `wrangler dev` child (inherits the parent env; non-blocking).
638
- *
639
- * @param args - The `wrangler dev …` arguments.
640
- * @returns A handle exposing kill().
641
- * @example
642
- * ```ts
643
- * const child = spawnWranglerDev(["dev", "--port", "8787"]);
644
- * ```
645
- */
646
- const spawnWranglerDev = (args) => {
647
- const child = spawn("wrangler", args, { stdio: "inherit" });
648
- return { kill: () => child.kill() };
649
- };
650
- /**
651
- * Resolve when the user first interrupts the dev session (SIGINT).
652
- *
653
- * @returns A promise that settles on the first SIGINT.
654
- * @example
655
- * ```ts
656
- * await waitForSigint();
657
- * ```
658
- */
659
- const waitForSigint = () => {
660
- return new Promise((resolve) => {
661
- process.once("SIGINT", () => {
662
- resolve();
663
- });
664
- });
665
- };
666
- /**
667
- * Wall-clock timestamp in ms (extracted so realDevDeps holds only named references).
668
- *
669
- * @returns The current time in milliseconds.
670
- * @example
671
- * ```ts
672
- * const t = nowMs();
673
- * ```
674
- */
675
- const nowMs = () => Date.now();
676
- /**
677
- * Build the real (side-effecting) dev deps used by api.dev(). Subprocesses inherit the parent env.
678
- *
679
- * @returns The production DevDeps (real spawn / fs.watch / SIGINT / Date.now).
680
- * @example
681
- * ```ts
682
- * await runDev(ctx, opts, realDevDeps());
683
- * ```
684
- */
685
- const realDevDeps = () => ({
686
- build: buildSite,
687
- runWrangler,
688
- spawnDev: spawnWranglerDev,
689
- watch: watchPaths,
690
- untilSignal: waitForSigint,
691
- now: nowMs
692
- });
693
- /**
694
- * The d1 binding to migrate locally, when a d1 plugin is present in the app.
695
- *
696
- * @param ctx - The deploy plugin context.
697
- * @returns The d1 binding name, or undefined when no d1 plugin is present.
698
- * @example
699
- * ```ts
700
- * const binding = d1Binding(ctx); // "DB" | undefined
701
- * ```
702
- */
703
- const d1Binding = (ctx) => ctx.has("d1") ? ctx.require(d1Plugin).deployManifest().binding : void 0;
704
- /**
705
- * Rebuild the site once and announce the result. A failed build keeps the session alive (it just
706
- * emits dev:error and serves the last good build).
707
- *
708
- * @param ctx - The deploy plugin context.
709
- * @param deps - The injected dev deps.
710
- * @param changedPath - The path that triggered the rebuild.
711
- * @param webBuild - Optional call-time web build hook threaded into the rebuild.
712
- * @returns Resolves once the rebuild attempt completes.
713
- * @example
714
- * ```ts
715
- * await rebuild(ctx, deps, "src/app.tsx", () => web.cli.build());
716
- * ```
717
- */
718
- const rebuild = async (ctx, deps, changedPath, webBuild) => {
719
- ctx.emit("dev:phase", {
720
- phase: "rebuild",
721
- detail: changedPath
722
- });
723
- const started = deps.now();
724
- try {
725
- const { files } = await deps.build(ctx, webBuild);
726
- ctx.emit("dev:rebuilt", {
727
- files,
728
- ms: deps.now() - started
729
- });
730
- } catch (error) {
731
- ctx.emit("dev:error", { message: error instanceof Error ? error.message : String(error) });
732
- }
733
- };
734
- /**
735
- * Run a long-lived dev session: cold build → (local d1 migrate) → spawn `wrangler dev` →
736
- * watch + rebuild on change → teardown on signal.
737
- *
738
- * @param ctx - The deploy plugin context (config + emit + require/has).
739
- * @param opts - Optional options.
740
- * @param opts.port - Local dev port (default 8787).
741
- * @param opts.webBuild - Web build hook (re)run on cold build + each change (e.g. `() => web.cli.build()`).
742
- * @param deps - Injected side effects (real ones from realDevDeps in production).
743
- * @returns Resolves when the session ends (SIGINT).
744
- * @example
745
- * ```ts
746
- * await runDev(ctx, { port: 8787, webBuild: () => web.cli.build() }, realDevDeps());
747
- * ```
748
- */
749
- const runDev = async (ctx, opts, deps) => {
750
- const port = opts?.port ?? 8787;
751
- const webBuild = opts?.webBuild;
752
- ctx.emit("dev:phase", {
753
- phase: "build",
754
- detail: "site"
755
- });
756
- await deps.build(ctx, webBuild);
757
- const binding = d1Binding(ctx);
758
- if (ctx.config.migrateLocal && binding !== void 0) {
759
- ctx.emit("dev:phase", {
760
- phase: "migrate",
761
- detail: "d1 (local)"
762
- });
763
- await deps.runWrangler([
764
- "d1",
765
- "migrations",
766
- "apply",
767
- binding,
768
- "--local"
769
- ]);
770
- }
771
- ctx.emit("dev:phase", {
772
- phase: "serve",
773
- detail: `http://localhost:${String(port)}`
774
- });
775
- const child = deps.spawnDev([
776
- "dev",
777
- "--port",
778
- String(port),
779
- "--config",
780
- ctx.config.configFile,
781
- "--live-reload"
782
- ]);
783
- const watcher = deps.watch(ctx.config.watch, ctx.config.debounceMs, (changedPath) => rebuild(ctx, deps, changedPath, webBuild));
784
- await deps.untilSignal();
785
- watcher.close();
786
- child.kill();
787
- ctx.emit("dev:phase", { phase: "stopped" });
788
- };
789
- //#endregion
790
- //#region src/plugins/deploy/infra/plan.ts
791
- /**
792
- * Decide whether a single declared resource already exists in the account, recovering its id
793
- * (kv/d1) when it does. Durable Objects are config-only (they ship with the script), so they are
794
- * always treated as "missing" — provisioning them is a no-op that just records the binding.
795
- *
796
- * @param resource - The declared resource descriptor.
797
- * @param existing - The indexed set of resources already in the account.
798
- * @returns Whether it exists, plus the captured id for kv/d1.
799
- * @example
800
- * ```ts
801
- * checkExisting({ kind: "kv", binding: "SESSIONS" }, existing); // { exists: true, id: "ns123" }
802
- * ```
803
- */
804
- const checkExisting = (resource, existing) => {
805
- switch (resource.kind) {
806
- case "kv": {
807
- const id = existing.kv.get(resource.binding);
808
- return id === void 0 ? { exists: false } : {
809
- exists: true,
810
- id
811
- };
812
- }
813
- case "d1": {
814
- const id = existing.d1.get(resource.binding);
815
- return id === void 0 ? { exists: false } : {
816
- exists: true,
817
- id
818
- };
819
- }
820
- case "r2": return { exists: existing.r2.has(resource.bucket) };
821
- case "queue": return { exists: resource.producers.every((producer) => existing.queue.has(producer)) };
822
- case "do": return { exists: false };
823
- }
824
- };
825
- /**
826
- * Run the read-only infra preflight: resolve the account, list existing resources, diff against
827
- * the manifest, emit `provision:plan`, and return the plan. Writes nothing.
828
- *
829
- * @param ctx - The deploy plugin context (env + emit).
830
- * @param manifest - The assembled (or caller-supplied) deploy manifest.
831
- * @returns The infra plan: existing (with ids) vs missing resources.
832
- * @throws {Error} When the token is absent/invalid or a Cloudflare listing fails.
833
- * @example
834
- * ```ts
835
- * const plan = await planInfra(ctx, manifest);
836
- * ```
837
- */
838
- const planInfra = async (ctx, manifest) => {
839
- const token = ctx.env.require("CLOUDFLARE_API_TOKEN");
840
- const pinnedAccountId = ctx.env.get("CLOUDFLARE_ACCOUNT_ID");
841
- const account = pinnedAccountId ? {
842
- id: pinnedAccountId,
843
- name: pinnedAccountId
844
- } : await resolveAccount(token);
845
- const kinds = /* @__PURE__ */ new Set();
846
- for (const resource of manifest.resources) if (resource.kind !== "do") kinds.add(resource.kind);
847
- const existing = await listExisting(token, account.id, kinds);
848
- const exists = [];
849
- const missing = [];
850
- for (const resource of manifest.resources) {
851
- const check = checkExisting(resource, existing);
852
- if (check.exists) exists.push(check.id === void 0 ? { resource } : {
853
- resource,
854
- id: check.id
855
- });
856
- else missing.push(resource);
857
- }
858
- ctx.emit("provision:plan", {
859
- exists: exists.length,
860
- missing: missing.length,
861
- account: account.name
862
- });
863
- return {
864
- account: account.name,
865
- accountId: account.id,
866
- exists,
867
- missing
868
- };
869
- };
870
- //#endregion
871
- //#region src/plugins/deploy/providers/d1.ts
872
- /**
873
- * @file deploy plugin — D1 provisioning adapter.
874
- *
875
- * Creates a Cloudflare D1 database via `wrangler d1 create <binding>`, captures the created
876
- * database id from wrangler's output (so writeWranglerConfig can write a real `database_id`
877
- * instead of an empty placeholder), and applies migrations when declared.
878
- * Node-only; never imported by the runtime Worker bundle.
879
- */
880
- /**
881
- * Parse the created D1 database id from `wrangler d1 create` output.
882
- * Wrangler prints the new binding as JSON (`"database_id": "..."`) or TOML
883
- * (`database_id = "..."`); the leading boundary keeps the match anchored to the field name.
884
- *
885
- * @param output - Raw stdout from the wrangler create command.
886
- * @returns The database id, or undefined when none is found.
887
- * @example
888
- * ```ts
889
- * parseD1DatabaseId('{ "database_id": "uuid-1234" }'); // "uuid-1234"
890
- * ```
891
- */
892
- const parseD1DatabaseId = (output) => {
893
- return /(?:^|[\s,{])"?database_id"?\s*[:=]\s*"([^"]+)"/m.exec(output)?.[1];
894
- };
895
- /**
896
- * Provision a D1 database via `wrangler d1 create`, capture its id, and apply migrations.
897
- *
898
- * @param manifest - The D1 resource descriptor.
899
- * @param _ci - Whether running non-interactively.
900
- * @returns The captured database id when wrangler reported one, else an empty outcome.
901
- * @example
902
- * ```ts
903
- * const { id } = await provisionD1({ kind: "d1", binding: "DB", migrations: "./migrations" }, false);
904
- * ```
905
- */
906
- const provisionD1 = async (manifest, _ci) => {
907
- const id = parseD1DatabaseId(await runWrangler([
908
- "d1",
909
- "create",
910
- manifest.binding
911
- ]));
912
- if (manifest.migrations) await runWrangler([
913
- "d1",
914
- "migrations",
915
- "apply",
916
- manifest.binding,
917
- "--local"
918
- ]);
919
- return id ? { id } : {};
920
- };
921
- //#endregion
922
- //#region src/plugins/deploy/providers/do.ts
923
- /**
924
- * Provision Durable Object bindings. DOs are config-driven (no `wrangler do create` command
925
- * exists) — the actual binding entries are written by writeWranglerConfig. This function is
926
- * a resolved no-op for the dispatch step.
927
- *
928
- * @param _manifest - The Durable Objects resource descriptor.
929
- * @param _ci - Whether running non-interactively.
930
- * @returns Resolves immediately (DOs are config-only provisioning).
931
- * @example
932
- * ```ts
933
- * await provisionDurableObject({ kind: "do", bindings: { counter: "COUNTER" } }, false);
934
- * ```
935
- */
936
- const provisionDurableObject = async (_manifest, _ci) => {};
937
- //#endregion
938
- //#region src/plugins/deploy/providers/kv.ts
939
- /**
940
- * @file deploy plugin — KV provisioning adapter.
941
- *
942
- * Creates a Cloudflare KV namespace via `wrangler kv namespace create <binding>` and captures
943
- * the created namespace id from wrangler's output, so writeWranglerConfig can write a real `id`
944
- * (not an empty placeholder) into the generated wrangler config — otherwise the binding resolves
945
- * to nothing at runtime. Node-only; never imported by the runtime Worker bundle.
946
- */
947
- /**
948
- * Parse the created KV namespace id from `wrangler kv namespace create` output.
949
- * Wrangler prints the new binding as JSON (`"id": "..."`) or TOML (`id = "..."`); the leading
950
- * boundary (start / whitespace / `{` / `,`) keeps the match off a longer identifier such as
951
- * `kv_namespace_id`.
952
- *
953
- * @param output - Raw stdout from the wrangler create command.
954
- * @returns The namespace id, or undefined when none is found.
955
- * @example
956
- * ```ts
957
- * parseKvNamespaceId('{ "id": "abc123" }'); // "abc123"
958
- * ```
959
- */
960
- const parseKvNamespaceId = (output) => {
961
- return /(?:^|[\s,{])"?id"?\s*[:=]\s*"([^"]+)"/m.exec(output)?.[1];
962
- };
963
- /**
964
- * Provision a KV namespace via `wrangler kv namespace create` and capture its id.
965
- *
966
- * @param manifest - The KV resource descriptor.
967
- * @param _ci - Whether running non-interactively (passed through; wrangler respects env vars).
968
- * @returns The captured namespace id when wrangler reported one, else an empty outcome.
969
- * @example
970
- * ```ts
971
- * const { id } = await provisionKv({ kind: "kv", binding: "CACHE" }, false);
972
- * ```
973
- */
974
- const provisionKv = async (manifest, _ci) => {
975
- const id = parseKvNamespaceId(await runWrangler([
976
- "kv",
977
- "namespace",
978
- "create",
979
- manifest.binding
980
- ]));
981
- return id ? { id } : {};
982
- };
983
- //#endregion
984
- //#region src/plugins/deploy/providers/queues.ts
985
- /**
986
- * @file deploy plugin — Queues provisioning adapter.
987
- *
988
- * Creates Cloudflare Queues via `wrangler queues create <name>` for each producer.
989
- * Node-only; never imported by the runtime Worker bundle.
990
- */
991
- /**
992
- * Provision queues via `wrangler queues create` for each declared producer.
993
- *
994
- * @param manifest - The queue resource descriptor.
995
- * @param _ci - Whether running non-interactively.
996
- * @returns Resolves once all queues are created.
997
- * @example
998
- * ```ts
999
- * await provisionQueue({ kind: "queue", producers: ["orders"] }, false);
1000
- * ```
1001
- */
1002
- const provisionQueue = async (manifest, _ci) => {
1003
- for (const producer of manifest.producers) await runWrangler([
1004
- "queues",
1005
- "create",
1006
- producer
1007
- ]);
1008
- };
1009
- //#endregion
1010
- //#region src/plugins/deploy/providers/r2.ts
1011
- /**
1012
- * @file deploy plugin — R2 provisioning + asset upload adapter.
1013
- *
1014
- * Provides two exports:
1015
- * - `provisionR2`: creates an R2 bucket via `wrangler r2 bucket create`.
1016
- * - `uploadDirToR2`: walks a directory recursively and uploads each file via
1017
- * `wrangler r2 object put`, returning the uploaded file count.
1018
- *
1019
- * Node-only; never imported by the runtime Worker bundle.
1020
- */
1021
- /**
1022
- * Provision an R2 bucket via `wrangler r2 bucket create`.
1023
- *
1024
- * @param manifest - The R2 resource descriptor.
1025
- * @param _ci - Whether running non-interactively.
1026
- * @returns Resolves once the bucket is created.
1027
- * @example
1028
- * ```ts
1029
- * await provisionR2({ kind: "r2", bucket: "ASSETS" }, false);
1030
- * ```
1031
- */
1032
- const provisionR2 = async (manifest, _ci) => {
1033
- await runWrangler([
1034
- "r2",
1035
- "bucket",
1036
- "create",
1037
- manifest.bucket
1038
- ]);
1039
- };
1040
- /**
1041
- * Walk a directory recursively and return all file paths (absolute).
1042
- *
1043
- * @param directory - Directory path to walk.
1044
- * @returns All file paths found under the directory.
1045
- * @example
1046
- * ```ts
1047
- * const files = await walkDir("./public");
1048
- * ```
1049
- */
1050
- const walkDir = async (directory) => {
1051
- const entries = await readdir(directory);
1052
- const results = [];
1053
- for (const entry of entries) {
1054
- const fullPath = path.join(directory, entry);
1055
- if ((await stat(fullPath)).isDirectory()) {
1056
- const nested = await walkDir(fullPath);
1057
- results.push(...nested);
1058
- } else results.push(fullPath);
1059
- }
1060
- return results;
1061
- };
1062
- /**
1063
- * Upload a directory to an R2 bucket and return the uploaded file count.
1064
- * Each file is uploaded via `wrangler r2 object put <bucket>/<key> --file <path>`.
1065
- *
1066
- * @param bucket - The R2 bucket binding name.
1067
- * @param directory - The directory to upload.
1068
- * @returns The number of files uploaded.
1069
- * @example
1070
- * ```ts
1071
- * const count = await uploadDirToR2("ASSETS", "./public");
1072
- * ```
1073
- */
1074
- const uploadDirToR2 = async (bucket, directory) => {
1075
- const files = await walkDir(directory);
1076
- for (const filePath of files) await runWrangler([
1077
- "r2",
1078
- "object",
1079
- "put",
1080
- `${bucket}/${path.relative(directory, filePath)}`,
1081
- "--file",
1082
- filePath
1083
- ]);
1084
- return files.length;
1085
- };
1086
- //#endregion
1087
- //#region src/plugins/deploy/providers/index.ts
1088
- /**
1089
- * Dispatch a resource descriptor to the matching provider's provisioning routine.
1090
- *
1091
- * @param resource - The resource descriptor to provision.
1092
- * @param ci - Whether running non-interactively.
1093
- * @returns The provisioning outcome — `{ id }` for kv/d1, `{}` for r2/queue/do.
1094
- * @example
1095
- * ```ts
1096
- * const { id } = await provisionResource({ kind: "kv", binding: "CACHE" }, false);
1097
- * await provisionResource({ kind: "r2", bucket: "ASSETS" }, false); // {}
1098
- * ```
1099
- */
1100
- const provisionResource = async (resource, ci) => {
1101
- switch (resource.kind) {
1102
- case "kv": return provisionKv(resource, ci);
1103
- case "d1": return provisionD1(resource, ci);
1104
- case "r2":
1105
- await provisionR2(resource, ci);
1106
- return {};
1107
- case "queue":
1108
- await provisionQueue(resource, ci);
1109
- return {};
1110
- case "do":
1111
- await provisionDurableObject(resource, ci);
1112
- return {};
1113
- }
1114
- };
1115
- //#endregion
1116
- //#region src/plugins/deploy/tty.ts
1117
- /**
1118
- * @file deploy plugin — TTY detection (isolated so the guided flow is testable).
1119
- *
1120
- * The guided deploy only prompts on an interactive terminal; in a pipe or CI it must never block
1121
- * on stdin. Kept in its own module so tests can mock it without stubbing `process.stdout`.
1122
- * Node-only; never imported by the runtime Worker bundle.
1123
- */
1124
- /**
1125
- * Whether stdout is an interactive TTY (so prompts are safe to show).
1126
- *
1127
- * @returns True when stdout is a terminal.
1128
- * @example
1129
- * ```ts
1130
- * if (stdoutIsTty()) await prompts.confirm("Deploy?");
1131
- * ```
1132
- */
1133
- const stdoutIsTty = () => process.stdout.isTTY === true;
1134
- //#endregion
1135
- //#region src/plugins/deploy/wrangler-config.ts
1136
- /**
1137
- * @file deploy plugin — wrangler config generation + scaffold.
1138
- *
1139
- * Provides two exports:
1140
- * - `writeWranglerConfig`: generates/updates a wrangler.jsonc file from an ExternalManifest.
1141
- * Non-destructive: preserves existing top-level keys not managed by deploy.
1142
- * - `scaffoldWranglerAndCi`: creates a minimal starter wrangler config when the file does not
1143
- * exist yet; idempotent (leaves existing files untouched).
1144
- *
1145
- * Node-only; never imported by the runtime Worker bundle.
1146
- */
1147
- /**
1148
- * Strip JSONC line- and block-comments, then JSON.parse the result.
1149
- *
1150
- * @param source - Raw JSONC file contents.
1151
- * @returns The parsed object.
1152
- * @example
1153
- * ```ts
1154
- * const cfg = parseJsonc('{ "name": "w" } // trailing comment');
1155
- * ```
1156
- */
1157
- const parseJsonc = (source) => {
1158
- const stripped = source.replaceAll(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/gu, "");
1159
- return JSON.parse(stripped);
1160
- };
1161
- /**
1162
- * Build the wrangler `kv_namespaces` array from the manifest's kv resources.
1163
- *
1164
- * @param resources - All resource descriptors from the manifest.
1165
- * @param ids - Captured Cloudflare ids keyed by binding; the entry's `id` is filled from here.
1166
- * @returns One wrangler KV namespace entry per kv resource (real `id` when known, else "").
1167
- * @example
1168
- * ```ts
1169
- * const kv = buildKvNamespaces([{ kind: "kv", binding: "CACHE" }], { CACHE: "ns123" });
1170
- * ```
1171
- */
1172
- const buildKvNamespaces = (resources, ids) => resources.filter((resource) => resource.kind === "kv").map((resource) => ({
1173
- binding: resource.binding,
1174
- id: ids[resource.binding] ?? ""
1175
- }));
1176
- /**
1177
- * Build the wrangler `r2_buckets` array from the manifest's r2 resources.
1178
- *
1179
- * @param resources - All resource descriptors from the manifest.
1180
- * @returns One wrangler R2 bucket entry per r2 resource.
1181
- * @example
1182
- * ```ts
1183
- * const r2 = buildR2Buckets([{ kind: "r2", bucket: "ASSETS" }]);
1184
- * ```
1185
- */
1186
- const buildR2Buckets = (resources) => resources.filter((resource) => resource.kind === "r2").map((resource) => ({
1187
- binding: resource.bucket,
1188
- bucket_name: resource.bucket.toLowerCase()
1189
- }));
1190
- /**
1191
- * Build the wrangler `d1_databases` array from the manifest's d1 resources.
1192
- *
1193
- * @param resources - All resource descriptors from the manifest.
1194
- * @param ids - Captured Cloudflare ids keyed by binding; the entry's `database_id` is filled from here.
1195
- * @returns One wrangler D1 database entry per d1 resource (migrations_dir set when present).
1196
- * @example
1197
- * ```ts
1198
- * const d1 = buildD1Databases([{ kind: "d1", binding: "DB" }], { DB: "uuid-1234" });
1199
- * ```
1200
- */
1201
- const buildD1Databases = (resources, ids) => resources.filter((resource) => resource.kind === "d1").map((resource) => {
1202
- const entry = {
1203
- binding: resource.binding,
1204
- database_name: resource.binding.toLowerCase(),
1205
- database_id: ids[resource.binding] ?? ""
1206
- };
1207
- if (resource.migrations) entry.migrations_dir = resource.migrations;
1208
- return entry;
1209
- });
1210
- /**
1211
- * Build the wrangler `queues` producers section from the manifest's queue resources.
1212
- *
1213
- * @param resources - All resource descriptors from the manifest.
1214
- * @returns The queues section, or undefined when there are no queue resources.
1215
- * @example
1216
- * ```ts
1217
- * const q = buildQueues([{ kind: "queue", producers: ["jobs"] }]);
1218
- * ```
1219
- */
1220
- const buildQueues = (resources) => {
1221
- const queueResources = resources.filter((resource) => resource.kind === "queue");
1222
- if (queueResources.length === 0) return void 0;
1223
- return { producers: queueResources.flatMap((resource) => resource.producers.map((producer) => ({
1224
- queue: producer,
1225
- binding: producer.toUpperCase()
1226
- }))) };
1227
- };
1228
- /**
1229
- * Build the wrangler `durable_objects` bindings section from the manifest's do resources.
1230
- *
1231
- * @param resources - All resource descriptors from the manifest.
1232
- * @returns The durable_objects section, or undefined when there are no do resources.
1233
- * @example
1234
- * ```ts
1235
- * const dobj = buildDurableObjects([{ kind: "do", bindings: { Counter: "COUNTER" } }]);
1236
- * ```
1237
- */
1238
- const buildDurableObjects = (resources) => {
1239
- const doResources = resources.filter((resource) => resource.kind === "do");
1240
- if (doResources.length === 0) return void 0;
1241
- return { bindings: doResources.flatMap((resource) => Object.entries(resource.bindings).map(([className, bindingName]) => ({
1242
- name: bindingName,
1243
- class_name: className
1244
- }))) };
1245
- };
1246
- /**
1247
- * Generate/update the wrangler config file from a manifest (non-destructive merge).
1248
- * If the file exists, its top-level keys are preserved and only deploy-managed keys
1249
- * (name, compatibility_date, kv_namespaces, r2_buckets, d1_databases, queues,
1250
- * durable_objects) are updated.
1251
- *
1252
- * @param configFile - Path to the wrangler config file.
1253
- * @param manifest - The assembled deploy manifest.
1254
- * @param ids - Captured Cloudflare ids keyed by binding (kv namespace id, d1 database id). Defaults
1255
- * to an empty map, in which case `id`/`database_id` are written as "" (e.g. the universal path).
1256
- * @returns Resolves once the file is written.
1257
- * @example
1258
- * ```ts
1259
- * await writeWranglerConfig("wrangler.jsonc", manifest, { CACHE: "ns123", DB: "uuid-1234" });
1260
- * ```
1261
- */
1262
- const writeWranglerConfig = async (configFile, manifest, ids = {}) => {
1263
- let existing = {};
1264
- if (existsSync(configFile)) try {
1265
- existing = parseJsonc(readFileSync(configFile, "utf8"));
1266
- } catch {
1267
- existing = {};
1268
- }
1269
- const kvNamespaces = buildKvNamespaces(manifest.resources, ids);
1270
- const r2Buckets = buildR2Buckets(manifest.resources);
1271
- const d1Databases = buildD1Databases(manifest.resources, ids);
1272
- const queues = buildQueues(manifest.resources);
1273
- const durableObjects = buildDurableObjects(manifest.resources);
1274
- const updated = {
1275
- ...existing,
1276
- name: manifest.name,
1277
- compatibility_date: manifest.compatibilityDate
1278
- };
1279
- if (kvNamespaces.length > 0) updated.kv_namespaces = kvNamespaces;
1280
- if (r2Buckets.length > 0) updated.r2_buckets = r2Buckets;
1281
- if (d1Databases.length > 0) updated.d1_databases = d1Databases;
1282
- if (queues !== void 0) updated.queues = queues;
1283
- if (durableObjects !== void 0) updated.durable_objects = durableObjects;
1284
- await writeFile(configFile, JSON.stringify(updated, void 0, 2));
1285
- };
1286
- /**
1287
- * Scaffold a starting wrangler config and, when ci is set, CI workflow files.
1288
- * Idempotent: an existing config file is left completely untouched.
1289
- *
1290
- * @param configFile - Path to the wrangler config file.
1291
- * @param _ci - Whether to also scaffold CI workflow files.
1292
- * @returns Resolves once scaffolding is written.
1293
- * @example
1294
- * ```ts
1295
- * await scaffoldWranglerAndCi("wrangler.jsonc", true);
1296
- * ```
1297
- */
1298
- const scaffoldWranglerAndCi = async (configFile, _ci) => {
1299
- if (existsSync(configFile)) return;
1300
- const starter = {
1301
- name: "my-worker",
1302
- main: "src/worker.ts",
1303
- compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)
1304
- };
1305
- await writeFile(configFile, JSON.stringify(starter, void 0, 2));
1306
- };
1307
- //#endregion
1308
- //#region src/plugins/deploy/api.ts
1309
- /**
1310
- * @file deploy plugin — API factory (run, dev, init, checkInfra, provisionInfra).
1311
- *
1312
- * Pure ctx-taking factory. Assembles the deploy manifest from each resource plugin's own
1313
- * deployManifest() api (never sibling pluginConfigs — design F6), runs an infra preflight
1314
- * (check-before-create + capture real ids), generates/updates the wrangler config, uploads the
1315
- * R2 upload dir, and runs wrangler deploy. Emits only global events: deploy:phase,
1316
- * deploy:complete, provision:resource, provision:plan, provision:skip.
1317
- *
1318
- * Node-only: uses node:child_process (via runner.ts), node:fs (via wrangler-config.ts), and the
1319
- * Cloudflare REST API (via infra/). Never called in the deployed Worker runtime.
1320
- */
1321
- /**
1322
- * Derive a human-readable name string from a resource descriptor (used in provision events).
1323
- *
1324
- * @param resource - The resource descriptor.
1325
- * @returns A name suitable for the provision:resource / provision:skip event payload.
1326
- * @example
1327
- * ```ts
1328
- * resourceName({ kind: "kv", binding: "CACHE" }); // "CACHE"
1329
- * ```
1330
- */
1331
- const resourceName = (resource) => {
1332
- switch (resource.kind) {
1333
- case "r2": return resource.bucket;
1334
- case "do": return Object.values(resource.bindings).join(",");
1335
- case "queue": return resource.producers.join(",");
1336
- default: return resource.binding;
1337
- }
1338
- };
1339
- /**
1340
- * Assemble the deploy manifest from each present resource plugin's OWN deployManifest() api,
1341
- * gated by ctx.has(name) so absent plugins are skipped — never sibling pluginConfigs (F6).
1342
- *
1343
- * @param ctx - The deploy plugin context.
1344
- * @returns The assembled manifest (name, compatibilityDate, resources).
1345
- * @example
1346
- * ```ts
1347
- * const manifest = assembleManifest(ctx);
1348
- * ```
1349
- */
1350
- const assembleManifest = (ctx) => ({
1351
- name: ctx.global.name,
1352
- compatibilityDate: ctx.global.compatibilityDate,
1353
- resources: [
1354
- ctx.has("storage") ? ctx.require(storagePlugin).deployManifest() : void 0,
1355
- ctx.has("kv") ? ctx.require(kvPlugin).deployManifest() : void 0,
1356
- ctx.has("d1") ? ctx.require(d1Plugin).deployManifest() : void 0,
1357
- ctx.has("queues") ? ctx.require(queuesPlugin).deployManifest() : void 0,
1358
- ctx.has("durableObjects") ? ctx.require(durableObjectsPlugin).deployManifest() : void 0
1359
- ].filter((resource) => resource !== void 0)
1360
- });
1361
- /**
1362
- * Act on an infra plan: skip the resources that already exist (reusing their ids), create only
1363
- * the missing ones (capturing each new id), and announce each via provision:skip / :resource.
1364
- *
1365
- * @param ctx - The deploy plugin context.
1366
- * @param plan - The infra plan from planInfra (existing vs missing).
1367
- * @returns The provisioning result: created, skipped, and the merged binding → id map.
1368
- * @example
1369
- * ```ts
1370
- * const { ids } = await applyPlan(ctx, plan);
1371
- * ```
1372
- */
1373
- const applyPlan = async (ctx, plan) => {
1374
- const ids = {};
1375
- for (const ref of plan.exists) {
1376
- if (ref.id !== void 0 && (ref.resource.kind === "kv" || ref.resource.kind === "d1")) ids[ref.resource.binding] = ref.id;
1377
- ctx.emit("provision:skip", {
1378
- kind: ref.resource.kind,
1379
- name: resourceName(ref.resource)
1380
- });
1381
- }
1382
- const created = [];
1383
- for (const resource of plan.missing) {
1384
- const { id } = await provisionResource(resource, ctx.config.ci);
1385
- if (id !== void 0 && (resource.kind === "kv" || resource.kind === "d1")) ids[resource.binding] = id;
1386
- created.push(id === void 0 ? { resource } : {
1387
- resource,
1388
- id
1389
- });
1390
- ctx.emit("provision:resource", {
1391
- kind: resource.kind,
1392
- name: resourceName(resource)
1393
- });
1394
- }
1395
- return {
1396
- created,
1397
- skipped: plan.exists,
1398
- ids
1399
- };
1400
- };
1401
- /**
1402
- * Create the deploy api. Assembles the manifest from each resource plugin's own deployManifest(),
1403
- * runs an infra preflight (check-before-create + id capture), generates config, uploads, and runs
1404
- * `wrangler deploy`, emitting global deploy events along the way.
1405
- *
1406
- * @param ctx - Plugin context (own config + require + has + emit + global + env).
1407
- * @returns The app.deploy api: run / dev / init / checkInfra / provisionInfra.
1408
- * @example
1409
- * ```ts
1410
- * const api = createDeployApi(ctx);
1411
- * await api.run();
1412
- * ```
1413
- */
1414
- const createDeployApi = (ctx) => ({
1415
- /**
1416
- * Run the full deploy pipeline: detect → preflight (check-before-create) → provision (only the
1417
- * missing) → wrangler-config (with real ids) → upload → deploy. When opts.manifest is supplied
1418
- * it is used verbatim (universal path).
1419
- *
1420
- * @param opts - Optional run options.
1421
- * @param opts.guided - Enable interactive confirmation steps (only on a TTY, non-CI).
1422
- * @param opts.yes - Auto-confirm all prompts (non-interactive / CI).
1423
- * @param opts.webBuild - Build the web site first (e.g. `() => webApp.cli.build()`), before deploy.
1424
- * @param opts.manifest - Caller-supplied manifest (bypasses deployManifest() assembly).
1425
- * @returns Resolves once the deploy completes.
1426
- * @example
1427
- * ```ts
1428
- * await api.run({ guided: true, webBuild: () => web.cli.build() });
1429
- * await api.run({ manifest: { name: "w", compatibilityDate: "2026-06-17", resources: [] } });
1430
- * ```
1431
- */
1432
- async run(opts) {
1433
- const confirm = (opts?.guided ?? false) && !ctx.config.ci && !(opts?.yes ?? false) && stdoutIsTty() ? createBrandPrompts().confirm : async (_question) => true;
1434
- ctx.emit("deploy:phase", { phase: "auth" });
1435
- await verifyAuth(ctx);
1436
- const webBuild = opts?.webBuild ?? ctx.config.webBuild;
1437
- if (webBuild !== void 0) {
1438
- ctx.emit("deploy:phase", {
1439
- phase: "build",
1440
- detail: "web"
1441
- });
1442
- await webBuild();
1443
- }
1444
- ctx.emit("deploy:phase", { phase: "detect" });
1445
- const manifest = opts?.manifest ?? assembleManifest(ctx);
1446
- ctx.emit("deploy:phase", { phase: "provision" });
1447
- const plan = await planInfra(ctx, manifest);
1448
- if (plan.missing.length > 0 && !await confirm(`Create ${plan.missing.length} missing resource(s) in "${plan.account}"?`)) {
1449
- ctx.emit("deploy:phase", { phase: "aborted" });
1450
- return;
1451
- }
1452
- const { ids } = await applyPlan(ctx, plan);
1453
- ctx.emit("deploy:phase", { phase: "wrangler-config" });
1454
- await writeWranglerConfig(ctx.config.configFile, manifest, ids);
1455
- const r2Resource = manifest.resources.find((resource) => resource.kind === "r2");
1456
- if (r2Resource?.upload) {
1457
- const count = await uploadDirToR2(r2Resource.bucket, r2Resource.upload);
1458
- ctx.emit("deploy:phase", {
1459
- phase: "upload",
1460
- detail: `${String(count)} files`
1461
- });
1462
- }
1463
- if (!await confirm(`Deploy "${manifest.name}" to ${ctx.global.stage}?`)) {
1464
- ctx.emit("deploy:phase", { phase: "aborted" });
1465
- return;
1466
- }
1467
- ctx.emit("deploy:phase", { phase: "deploy" });
1468
- const url = await runWrangler([
1469
- "deploy",
1470
- "--config",
1471
- ctx.config.configFile
1472
- ]);
1473
- ctx.emit("deploy:complete", { url });
1474
- },
1475
- /**
1476
- * Start a long-lived local dev session: cold-build the Moku site, spawn `wrangler dev
1477
- * --live-reload`, and watch the site sources — rebuilding on change (wrangler live-reloads the
1478
- * browser). Resolves on SIGINT.
1479
- *
1480
- * @param opts - Optional options.
1481
- * @param opts.port - Local dev port (default 8787).
1482
- * @param opts.webBuild - Rebuild the web site on change (e.g. `() => webApp.cli.build()`).
1483
- * @returns Resolves when the dev session ends.
1484
- * @example
1485
- * ```ts
1486
- * await api.dev({ port: 8787, webBuild: () => web.cli.build() });
1487
- * ```
1488
- */
1489
- dev: (opts) => runDev(ctx, opts, realDevDeps()),
1490
- /**
1491
- * Scaffold a starting wrangler config (and CI files when ci is set).
1492
- * Idempotent: an existing config file is left untouched.
1493
- *
1494
- * @param opts - Optional options.
1495
- * @param opts.ci - Also scaffold CI workflow files.
1496
- * @returns Resolves once scaffolding is written.
1497
- * @example
1498
- * ```ts
1499
- * await api.init({ ci: true });
1500
- * ```
1501
- */
1502
- init: async (opts) => {
1503
- await scaffoldWranglerAndCi(ctx.config.configFile, opts?.ci ?? ctx.config.ci);
1504
- },
1505
- /**
1506
- * Read-only infra preflight: assemble the manifest, resolve the account, list what exists in
1507
- * Cloudflare, diff, emit provision:plan, and return the plan. Writes nothing.
1508
- *
1509
- * @returns The infra plan (existing vs missing resources, with captured ids).
1510
- * @example
1511
- * ```ts
1512
- * const plan = await api.checkInfra();
1513
- * ```
1514
- */
1515
- checkInfra: () => planInfra(ctx, assembleManifest(ctx)),
1516
- /**
1517
- * Create only the resources missing from the plan (skipping existing), capturing each id.
1518
- *
1519
- * @param plan - A plan produced by checkInfra().
1520
- * @returns The provisioning result: created, skipped, and the merged id map.
1521
- * @example
1522
- * ```ts
1523
- * const { created } = await api.provisionInfra(await api.checkInfra());
1524
- * ```
1525
- */
1526
- provisionInfra: (plan) => applyPlan(ctx, plan),
1527
- /**
1528
- * Verify the `.env` Cloudflare API token (must be active) and resolve its account; emits
1529
- * auth:verified. Throws a branded error pointing at `auth setup` when absent/invalid/inactive.
1530
- *
1531
- * @returns The verified auth status (account + id).
1532
- * @example
1533
- * ```ts
1534
- * const { account } = await api.verifyAuth();
1535
- * ```
1536
- */
1537
- verifyAuth: () => verifyAuth(ctx),
1538
- /**
1539
- * Derive the minimum Cloudflare API token this app needs from its manifest (pure, no network).
1540
- *
1541
- * @returns The token requirement (full set + groups to add to the stock template).
1542
- * @example
1543
- * ```ts
1544
- * const { toAdd } = api.requiredToken();
1545
- * ```
1546
- */
1547
- requiredToken: () => requiredToken(assembleManifest(ctx)),
1548
- /**
1549
- * Render the `auth setup` guidance from the derived token requirement (pure, no network).
1550
- *
1551
- * @returns The rendered instruction text.
1552
- * @example
1553
- * ```ts
1554
- * const text = api.tokenInstructions();
1555
- * ```
1556
- */
1557
- tokenInstructions: () => tokenInstructions(assembleManifest(ctx)),
1558
- /**
1559
- * Run an arbitrary wrangler command, streaming its output (the branded CLI escape hatch).
1560
- *
1561
- * @param args - The wrangler arguments.
1562
- * @returns Resolves once wrangler exits.
1563
- * @example
1564
- * ```ts
1565
- * await api.wrangler(["kv", "namespace", "list"]);
1566
- * ```
1567
- */
1568
- wrangler: (args) => runWranglerInherit(args)
1569
- });
1570
- /**
1571
- * Complex tier (node-only) — build-time deploy orchestrator over the five resource plugins.
1572
- *
1573
- * Assembles each resource plugin's deployManifest() via ctx.require, provisions resources,
1574
- * generates/updates wrangler config, uploads the R2 upload dir, and runs wrangler deploy.
1575
- * Also supports a universal path: run({ manifest }) uses a caller-supplied manifest verbatim.
1576
- *
1577
- * Emits only the global events `deploy:phase`, `deploy:complete`, and `provision:resource`
1578
- * (declared in WorkerEvents — no per-plugin events block).
1579
- *
1580
- * @see README.md
1581
- */
1582
- const deployPlugin = createPlugin("deploy", {
1583
- config: {
1584
- configFile: "wrangler.jsonc",
1585
- ci: false,
1586
- watch: ["src/**/*.{ts,tsx,css}", "public/**/*"],
1587
- buildCommand: "",
1588
- migrateLocal: true,
1589
- debounceMs: 120
1590
- },
1591
- depends: [
1592
- storagePlugin,
1593
- kvPlugin,
1594
- d1Plugin,
1595
- queuesPlugin,
1596
- durableObjectsPlugin
1597
- ],
1598
- api: (ctx) => createDeployApi(ctx)
1599
- });
1600
- //#endregion
1601
- //#region src/plugins/cli/api.ts
1602
- /**
1603
- * @file cli plugin — API factory (dev, deploy, auth, doctor).
1604
- */
1605
- /**
1606
- * Builds app.cli.* — thin passthroughs to the deploy plugin via ctx.require(deployPlugin).
1607
- * Both verbs forward their opts verbatim; `dev` defaults port to ctx.config.port when no
1608
- * opts are supplied.
1609
- *
1610
- * @param ctx - CLI plugin context (own config + typed require to deployPlugin).
1611
- * @returns The cli API object with `dev` and `deploy` methods.
1612
- * @example
1613
- * ```ts
1614
- * const api = createCliApi(ctx);
1615
- * await api.dev(); // → deploy.dev({ port: 8787 })
1616
- * await api.deploy({ yes: true }); // → deploy.run({ yes: true })
1617
- * ```
1618
- */
1619
- const createCliApi = (ctx) => ({
1620
- /**
1621
- * Run the Worker locally; defaults port to ctx.config.port (8787) when no opts supplied. A
1622
- * `webBuild` hook (e.g. `() => webApp.cli.build()`) wires the web build into the dev loop so the
1623
- * site recompiles on change — this is how an app-side script composes web + worker.
1624
- *
1625
- * @param opts - Optional local dev options.
1626
- * @param opts.port - Local dev port to bind. Defaults to ctx.config.port (8787).
1627
- * @param opts.webBuild - Rebuild the web site on change (e.g. `() => webApp.cli.build()`).
1628
- * @returns Resolves when the dev session ends.
1629
- * @example
1630
- * ```ts
1631
- * await api.dev(); // port 8787, worker only
1632
- * await api.dev({ webBuild: () => web.cli.build() }); // wire the web build in
1633
- * ```
1634
- */
1635
- dev(opts) {
1636
- const port = opts?.port ?? ctx.config.port;
1637
- return ctx.require(deployPlugin).dev(opts?.webBuild ? {
1638
- port,
1639
- webBuild: opts.webBuild
1640
- } : { port });
1641
- },
1642
- /**
1643
- * One-command guided Cloudflare deploy; forwards flags verbatim to deploy.run.
1644
- * Passes `undefined` when called with no opts (not a default empty object). A `webBuild` hook
1645
- * builds the web site first (before `wrangler deploy`) — how an app-side script ships web + worker.
1646
- *
1647
- * @param opts - Optional deploy options.
1648
- * @param opts.guided - Walk through each step interactively.
1649
- * @param opts.yes - Skip confirmation prompts (non-interactive / CI).
1650
- * @param opts.webBuild - Build the web site first (e.g. `() => webApp.cli.build()`), before deploy.
1651
- * @returns Resolves once the deploy completes.
1652
- * @example
1653
- * ```ts
1654
- * await api.deploy({ guided: true, webBuild: () => web.cli.build() });
1655
- * await api.deploy({ yes: true }); // CI
1656
- * await api.deploy(); // opts === undefined
1657
- * ```
1658
- */
1659
- deploy(opts) {
1660
- return ctx.require(deployPlugin).run(opts);
1661
- },
1662
- /**
1663
- * Verify the `.env` token (no sub) or print the config-derived token guidance (`"setup"`),
1664
- * rendered in Moku style. `setup` works without a token; verify reports the resolved account.
1665
- *
1666
- * @param sub - Pass "setup" to print guidance; omit to verify the current token.
1667
- * @returns Resolves once the check or guidance render completes.
1668
- * @example
1669
- * ```ts
1670
- * await api.auth("setup"); // print what token to create
1671
- * await api.auth(); // verify the current token
1672
- * ```
1673
- */
1674
- async auth(sub) {
1675
- const deploy = ctx.require(deployPlugin);
1676
- const ui = createBrandConsole();
1677
- if (sub === "setup") {
1678
- for (const line of deploy.tokenInstructions().split("\n")) ui.line(line);
1679
- return;
1680
- }
1681
- try {
1682
- const status = await deploy.verifyAuth();
1683
- ui.check(true, "token valid", `account "${status.account}" (${status.accountId})`);
1684
- } catch (error) {
1685
- ui.error(error instanceof Error ? error.message : String(error));
1686
- }
1687
- },
1688
- /**
1689
- * One-shot preflight report: token + account (verifyAuth) then infra drift (checkInfra),
1690
- * each as a branded check line. Stops after the token check when auth fails.
1691
- *
1692
- * @returns Resolves once the report is printed.
1693
- * @example
1694
- * ```ts
1695
- * await api.doctor();
1696
- * ```
1697
- */
1698
- async doctor() {
1699
- const deploy = ctx.require(deployPlugin);
1700
- const ui = createBrandConsole();
1701
- ui.heading("doctor");
1702
- let tokenOk = false;
1703
- try {
1704
- const status = await deploy.verifyAuth();
1705
- tokenOk = true;
1706
- ui.check(true, "token", `valid · account "${status.account}" (${status.accountId})`);
1707
- } catch (error) {
1708
- ui.check(false, "token", error instanceof Error ? error.message : String(error));
1709
- }
1710
- if (!tokenOk) {
1711
- ui.line("Run `auth setup` for the exact token to create.");
1712
- return;
1713
- }
1714
- try {
1715
- const plan = await deploy.checkInfra();
1716
- ui.check(true, "infra", `${plan.exists.length} exist, ${plan.missing.length} to create in "${plan.account}"`);
1717
- } catch (error) {
1718
- ui.check(false, "infra", error instanceof Error ? error.message : String(error));
1719
- }
1720
- },
1721
- /**
1722
- * Print the resolved Cloudflare account for the current `.env` token.
1723
- *
1724
- * @returns Resolves once the account summary is printed.
1725
- * @example
1726
- * ```ts
1727
- * await api.whoami();
1728
- * ```
1729
- */
1730
- async whoami() {
1731
- const ui = createBrandConsole();
1732
- try {
1733
- const status = await ctx.require(deployPlugin).verifyAuth();
1734
- ui.check(true, "account", `${status.account} (${status.accountId})`);
1735
- } catch (error) {
1736
- ui.error(error instanceof Error ? error.message : String(error));
1737
- }
1738
- },
1739
- /**
1740
- * Run an arbitrary wrangler command through the branded CLI (escape hatch). Streams its output.
1741
- *
1742
- * @param args - The wrangler arguments.
1743
- * @returns Resolves once wrangler exits.
1744
- * @example
1745
- * ```ts
1746
- * await api.wrangler(["kv", "namespace", "list"]);
1747
- * ```
1748
- */
1749
- async wrangler(args) {
1750
- createBrandConsole().heading(`wrangler ${args.join(" ")}`);
1751
- await ctx.require(deployPlugin).wrangler(args);
1752
- }
1753
- });
1754
- //#endregion
1755
- //#region src/plugins/cli/handlers.ts
1756
- /**
1757
- * Builds the hook handlers that turn global deploy events into a live progress TUI.
1758
- * Each logs a clean, prefix-free message via `ctx.log`; the branded log sink (installed
1759
- * by the cli plugin's onInit from `@moku-labs/common/cli`) adds the `›` marker, brand
1760
- * color, and stderr routing. Pure observers — print and return; never mutate state,
1761
- * never block the deploy pipeline (fire-and-forget, spec/07 §3,§4).
1762
- *
1763
- * @param ctx - CLI plugin context with injected log core API.
1764
- * @returns Hook map for the three global deploy events.
1765
- * @example
1766
- * ```ts
1767
- * const hooks = createCliHooks(ctx);
1768
- * hooks["deploy:phase"]({ phase: "detect" }); // logs "detect" → renders " › detect"
1769
- * hooks["provision:resource"]({ kind: "kv", name: "KV" }); // logs "kv KV" → " › kv KV"
1770
- * hooks["deploy:complete"]({ url: "https://x.workers.dev" }); // "deployed → https://x.workers.dev"
1771
- * ```
1772
- */
1773
- const createCliHooks = (ctx) => ({
1774
- /**
1775
- * Log one clean line per pipeline phase: "phase" or "phase · detail".
1776
- *
1777
- * @param p - The deploy:phase event payload.
1778
- * @example
1779
- * ```ts
1780
- * handler({ phase: "detect" }); // "detect"
1781
- * handler({ phase: "upload", detail: "3 files" }); // "upload · 3 files"
1782
- * ```
1783
- */
1784
- "deploy:phase"(p) {
1785
- ctx.log.info(p.detail ? `${p.phase} · ${p.detail}` : p.phase);
1786
- },
1787
- /**
1788
- * Log the infra preflight summary: "infra · N exist, M to create · account".
1789
- *
1790
- * @param p - The provision:plan event payload.
1791
- * @example
1792
- * ```ts
1793
- * handler({ exists: 2, missing: 1, account: "Play Co" }); // "infra · 2 exist, 1 to create · Play Co"
1794
- * ```
1795
- */
1796
- "provision:plan"(p) {
1797
- ctx.log.info(`infra · ${p.exists} exist, ${p.missing} to create · ${p.account}`);
1798
- },
1799
- /**
1800
- * Log one clean line per provisioned resource: "kind name".
1801
- *
1802
- * @param p - The provision:resource event payload.
1803
- * @example
1804
- * ```ts
1805
- * handler({ kind: "kv", name: "KV" }); // "kv KV"
1806
- * ```
1807
- */
1808
- "provision:resource"(p) {
1809
- ctx.log.info(`${p.kind} ${p.name}`);
1810
- },
1811
- /**
1812
- * Log one clean line per already-existing resource (skipped): "kind name (exists)".
1813
- *
1814
- * @param p - The provision:skip event payload.
1815
- * @example
1816
- * ```ts
1817
- * handler({ kind: "kv", name: "KV" }); // "kv KV (exists)"
1818
- * ```
1819
- */
1820
- "provision:skip"(p) {
1821
- ctx.log.info(`${p.kind} ${p.name} (exists)`);
1822
- },
1823
- /**
1824
- * Log one dev-session phase: "phase" or "phase · detail".
1825
- *
1826
- * @param p - The dev:phase event payload.
1827
- * @example
1828
- * ```ts
1829
- * handler({ phase: "serve", detail: "http://localhost:8787" }); // "serve · http://localhost:8787"
1830
- * ```
1831
- */
1832
- "dev:phase"(p) {
1833
- ctx.log.info(p.detail ? `${p.phase} · ${p.detail}` : p.phase);
1834
- },
1835
- /**
1836
- * Log the site rebuild result: "site <n> files · <ms>ms" (omits the count when unknown).
1837
- *
1838
- * @param p - The dev:rebuilt event payload.
1839
- * @example
1840
- * ```ts
1841
- * handler({ files: 12, ms: 240 }); // "site 12 files · 240ms"
1842
- * handler({ files: 0, ms: 240 }); // "site · 240ms"
1843
- * ```
1844
- */
1845
- "dev:rebuilt"(p) {
1846
- ctx.log.info(p.files > 0 ? `site ${String(p.files)} files · ${String(p.ms)}ms` : `site · ${String(p.ms)}ms`);
1847
- },
1848
- /**
1849
- * Log a non-fatal dev build failure via warn (the session keeps serving the last good build).
1850
- *
1851
- * @param p - The dev:error event payload.
1852
- * @example
1853
- * ```ts
1854
- * handler({ message: "build failed" }); // warn "build failed"
1855
- * ```
1856
- */
1857
- "dev:error"(p) {
1858
- ctx.log.warn(p.message);
1859
- },
1860
- /**
1861
- * Log the terminal success line with the deployed URL.
1862
- *
1863
- * @param p - The deploy:complete event payload.
1864
- * @example
1865
- * ```ts
1866
- * handler({ url: "https://my-worker.workers.dev" }); // "deployed → https://my-worker.workers.dev"
1867
- * ```
1868
- */
1869
- "deploy:complete"(p) {
1870
- ctx.log.info(`deployed → ${p.url}`);
1871
- }
1872
- });
1873
- /**
1874
- * Standard tier (node-only) — developer-facing CLI surface.
1875
- *
1876
- * Mounts `app.cli.dev()` and `app.cli.deploy()` as thin passthroughs to deployPlugin.
1877
- * Hooks subscribe to the global deploy:phase / provision:resource / deploy:complete events
1878
- * and print a live progress TUI via the injected ctx.log core API.
1879
- *
1880
- * Inline lambdas on `api`/`hooks` preserve event-name inference so the hook map keys
1881
- * are constrained to `WorkerEvents` keys (spec/15 §5).
1882
- *
1883
- * @see README.md
1884
- */
1885
- const cliPlugin = createPlugin("cli", {
1886
- depends: [deployPlugin],
1887
- config: { port: 8787 },
1888
- onInit: (ctx) => {
1889
- ctx.log.clearSinks();
1890
- ctx.log.addSink(brandedSink("info"));
1891
- },
1892
- api: (ctx) => createCliApi(ctx),
1893
- hooks: (ctx) => createCliHooks(ctx)
1894
- });
1895
- //#endregion
1
+ import { n as deployPlugin, t as cliPlugin } from "./cli-DgZv5A0G.mjs";
1896
2
  export { cliPlugin, deployPlugin };