@moku-labs/web 0.1.0-alpha.4 → 0.2.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/bin/moku.mjs DELETED
@@ -1,1383 +0,0 @@
1
- #!/usr/bin/env bun
2
- import { a as runWrangler, c as readWranglerConfig, l as writeWranglerConfig, n as WRANGLER_ACTION_SHA, o as diffWranglerConfig, r as buildWranglerArgs, s as generateWranglerConfig, t as MOKU_WRANGLER_VERSION } from "../wrangler-BlZWVmX9.mjs";
3
- import { existsSync, mkdirSync, readFileSync, statSync, watch } from "node:fs";
4
- import { writeFile } from "node:fs/promises";
5
- import { dirname, extname, join, normalize, resolve, sep } from "node:path";
6
- import { parseArgs } from "node:util";
7
-
8
- //#region src/bin/help.ts
9
- /** @file Help text and banner formatters for the moku CLI. */
10
- /**
11
- * Format the banner line shown before any output.
12
- *
13
- * @param version - The package version.
14
- * @returns The banner string.
15
- */
16
- const formatBanner = (version) => `moku v${version}`;
17
- /**
18
- * Format the top-level help text listing all commands and global flags.
19
- *
20
- * @returns The help text.
21
- */
22
- const formatHelp = () => `
23
- Usage: moku <command> [options]
24
-
25
- Commands:
26
- build [folder] Build static site (default folder: src/)
27
- dev [folder] Start dev server with watch + rebuild
28
- preview [folder] Build and serve site for local preview
29
- deploy [folder] Deploy dist/ to Cloudflare Pages (run \`deploy init\` once first)
30
-
31
- Options:
32
- --version Show version number
33
- --help, -h Show help
34
-
35
- Run moku <command> --help for command-specific options.`.trim();
36
- /**
37
- * Format the help text for `moku build`.
38
- *
39
- * @returns The help text.
40
- */
41
- const formatBuildHelp = () => `
42
- Usage: moku build [folder] [options]
43
-
44
- Arguments:
45
- folder Source folder containing main.ts (default: src/)
46
-
47
- Options:
48
- --verbose, -v Show detailed build output
49
- --mode <mode> Build mode: ssg, spa, hybrid
50
- --help, -h Show help`.trim();
51
- /**
52
- * Format the help text for `moku dev`.
53
- *
54
- * @returns The help text.
55
- */
56
- const formatDevHelp = () => `
57
- Usage: moku dev [folder] [options]
58
-
59
- Arguments:
60
- folder Source folder containing main.ts (default: src/)
61
-
62
- Options:
63
- --verbose, -v Show detailed build output
64
- --port, -p <n> Server port (default: 4173)
65
- --help, -h Show help`.trim();
66
- /**
67
- * Format the help text for `moku deploy`.
68
- *
69
- * @returns The help text.
70
- */
71
- const formatDeployHelp = () => `
72
- Usage: moku deploy [folder] [options]
73
- moku deploy init [folder] [options]
74
-
75
- Arguments:
76
- folder Source folder containing main.ts (default: src/)
77
-
78
- Deploy options:
79
- --build Run \`moku build\` before deploying
80
- --branch <name> Branch to deploy to (default: from wrangler.jsonc workflow)
81
- --help, -h Show help
82
-
83
- Init options:
84
- --ci Also generate .github/workflows/deploy.yml
85
- --force Overwrite existing files (warns on slug change)
86
- --create-project Transactionally create the Cloudflare project before writing wrangler.jsonc
87
- --check Diff only, no writes; exits non-zero on drift
88
- --branch <name> Override the auto-detected default branch
89
- --help, -h Show help`.trim();
90
- /**
91
- * Format the help text for `moku preview`.
92
- *
93
- * @returns The help text.
94
- */
95
- const formatPreviewHelp = () => `
96
- Usage: moku preview [folder] [options]
97
-
98
- Arguments:
99
- folder Source folder containing main.ts (default: src/)
100
-
101
- Options:
102
- --port, -p <n> Server port (default: 3000)
103
- --help, -h Show help`.trim();
104
-
105
- //#endregion
106
- //#region src/bin/parse.ts
107
- /** @file Argument parsers for the moku CLI built on node:util parseArgs. */
108
- const VALID_MODES = new Set([
109
- "ssg",
110
- "spa",
111
- "hybrid"
112
- ]);
113
- const MIN_PORT = 1;
114
- const MAX_PORT = 65535;
115
- const DEFAULT_DEV_PORT = 4173;
116
- const DEFAULT_PREVIEW_PORT = 3e3;
117
- /**
118
- * Classify the top-level invocation into version / help / unknown-flag / command.
119
- *
120
- * @param argv - The argv slice (already stripped of `process.argv[0..1]`).
121
- * @returns A {@link TopLevel} discriminant.
122
- */
123
- const parseTopLevel = (argv) => {
124
- if (argv.length === 0) return { kind: "help" };
125
- const [first, ...rest] = argv;
126
- if (first === void 0) return { kind: "help" };
127
- if (first === "--version") return { kind: "version" };
128
- if (first === "--help" || first === "-h") return { kind: "help" };
129
- if (first.startsWith("-")) return {
130
- kind: "unknown-flag",
131
- flag: first
132
- };
133
- return {
134
- kind: "command",
135
- command: first,
136
- rest
137
- };
138
- };
139
- const parsePort = (value, fallback) => {
140
- if (value === void 0) return {
141
- ok: true,
142
- value: fallback
143
- };
144
- const port = Number.parseInt(value, 10);
145
- if (!Number.isFinite(port) || `${port}` !== value) return {
146
- ok: false,
147
- message: `Invalid port: ${value}. Must be a number.`
148
- };
149
- if (port < MIN_PORT || port > MAX_PORT) return {
150
- ok: false,
151
- message: `Invalid port: ${port}. Must be ${MIN_PORT}-${MAX_PORT}.`
152
- };
153
- return {
154
- ok: true,
155
- value: port
156
- };
157
- };
158
- /**
159
- * Parse `moku build` arguments.
160
- *
161
- * @param argv - Argv after the `build` keyword.
162
- * @returns A {@link ParseResult} carrying a {@link BuildArgs} or an error message.
163
- */
164
- const parseBuild = (argv) => {
165
- try {
166
- const { values, positionals } = parseArgs({
167
- args: argv,
168
- options: {
169
- verbose: {
170
- type: "boolean",
171
- short: "v",
172
- default: false
173
- },
174
- mode: { type: "string" },
175
- help: {
176
- type: "boolean",
177
- short: "h",
178
- default: false
179
- }
180
- },
181
- allowPositionals: true,
182
- strict: true
183
- });
184
- if (values.mode !== void 0 && !VALID_MODES.has(values.mode)) return {
185
- ok: false,
186
- message: `Invalid mode: ${values.mode}. Must be one of: ssg, spa, hybrid.`
187
- };
188
- const mode = values.mode;
189
- return {
190
- ok: true,
191
- value: {
192
- folder: positionals[0] ?? "src",
193
- verbose: values.verbose,
194
- help: values.help,
195
- ...mode === void 0 ? {} : { mode }
196
- }
197
- };
198
- } catch (error) {
199
- return {
200
- ok: false,
201
- message: error.message
202
- };
203
- }
204
- };
205
- /**
206
- * Parse `moku dev` arguments.
207
- *
208
- * @param argv - Argv after the `dev` keyword.
209
- * @returns A {@link ParseResult} carrying a {@link DevArgs} or an error message.
210
- */
211
- const parseDev = (argv) => {
212
- try {
213
- const { values, positionals } = parseArgs({
214
- args: argv,
215
- options: {
216
- verbose: {
217
- type: "boolean",
218
- short: "v",
219
- default: false
220
- },
221
- port: {
222
- type: "string",
223
- short: "p"
224
- },
225
- help: {
226
- type: "boolean",
227
- short: "h",
228
- default: false
229
- }
230
- },
231
- allowPositionals: true,
232
- strict: true
233
- });
234
- const port = parsePort(values.port, DEFAULT_DEV_PORT);
235
- if (!port.ok) return port;
236
- return {
237
- ok: true,
238
- value: {
239
- folder: positionals[0] ?? "src",
240
- verbose: values.verbose,
241
- help: values.help,
242
- port: port.value
243
- }
244
- };
245
- } catch (error) {
246
- return {
247
- ok: false,
248
- message: error.message
249
- };
250
- }
251
- };
252
- /**
253
- * Parse `moku deploy` arguments.
254
- *
255
- * @param argv - Argv after the `deploy` keyword (NOT including `init`).
256
- * @returns A {@link ParseResult} carrying a {@link DeployArgs} or an error message.
257
- */
258
- const parseDeploy = (argv) => {
259
- try {
260
- const { values, positionals } = parseArgs({
261
- args: argv,
262
- options: {
263
- build: {
264
- type: "boolean",
265
- default: false
266
- },
267
- branch: { type: "string" },
268
- help: {
269
- type: "boolean",
270
- short: "h",
271
- default: false
272
- }
273
- },
274
- allowPositionals: true,
275
- strict: true
276
- });
277
- return {
278
- ok: true,
279
- value: {
280
- folder: positionals[0] ?? "src",
281
- help: values.help,
282
- build: values.build,
283
- ...values.branch === void 0 ? {} : { branch: values.branch }
284
- }
285
- };
286
- } catch (error) {
287
- return {
288
- ok: false,
289
- message: error.message
290
- };
291
- }
292
- };
293
- /**
294
- * Parse `moku deploy init` arguments.
295
- *
296
- * @param argv - Argv after the `deploy init` keywords.
297
- * @returns A {@link ParseResult} carrying a {@link DeployInitArgs} or an error message.
298
- */
299
- const parseDeployInit = (argv) => {
300
- try {
301
- const { values, positionals } = parseArgs({
302
- args: argv,
303
- options: {
304
- ci: {
305
- type: "boolean",
306
- default: false
307
- },
308
- force: {
309
- type: "boolean",
310
- default: false
311
- },
312
- "create-project": {
313
- type: "boolean",
314
- default: false
315
- },
316
- check: {
317
- type: "boolean",
318
- default: false
319
- },
320
- branch: { type: "string" },
321
- help: {
322
- type: "boolean",
323
- short: "h",
324
- default: false
325
- }
326
- },
327
- allowPositionals: true,
328
- strict: true
329
- });
330
- return {
331
- ok: true,
332
- value: {
333
- folder: positionals[0] ?? "src",
334
- help: values.help,
335
- ci: values.ci,
336
- force: values.force,
337
- createProject: values["create-project"],
338
- check: values.check,
339
- ...values.branch === void 0 ? {} : { branch: values.branch }
340
- }
341
- };
342
- } catch (error) {
343
- return {
344
- ok: false,
345
- message: error.message
346
- };
347
- }
348
- };
349
- /**
350
- * Parse `moku preview` arguments.
351
- *
352
- * @param argv - Argv after the `preview` keyword.
353
- * @returns A {@link ParseResult} carrying a {@link PreviewArgs} or an error message.
354
- */
355
- const parsePreview = (argv) => {
356
- try {
357
- const { values, positionals } = parseArgs({
358
- args: argv,
359
- options: {
360
- port: {
361
- type: "string",
362
- short: "p"
363
- },
364
- help: {
365
- type: "boolean",
366
- short: "h",
367
- default: false
368
- }
369
- },
370
- allowPositionals: true,
371
- strict: true
372
- });
373
- const port = parsePort(values.port, DEFAULT_PREVIEW_PORT);
374
- if (!port.ok) return port;
375
- return {
376
- ok: true,
377
- value: {
378
- folder: positionals[0] ?? "src",
379
- help: values.help,
380
- port: port.value
381
- }
382
- };
383
- } catch (error) {
384
- return {
385
- ok: false,
386
- message: error.message
387
- };
388
- }
389
- };
390
-
391
- //#endregion
392
- //#region src/bin/version.ts
393
- const parseSemver = (raw) => {
394
- const stripped = raw.split(/[+-]/, 1)[0] ?? raw;
395
- const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(stripped);
396
- if (match === null) return null;
397
- return {
398
- major: Number(match[1]),
399
- minor: Number(match[2]),
400
- patch: Number(match[3])
401
- };
402
- };
403
- const compareSemver = (a, b) => {
404
- if (a.major !== b.major) return a.major - b.major;
405
- if (a.minor !== b.minor) return a.minor - b.minor;
406
- return a.patch - b.patch;
407
- };
408
- const satisfiesRange = (actual, min, prefix) => {
409
- if (prefix === "^") return actual.major === min.major && compareSemver(actual, min) >= 0;
410
- if (prefix === "~") {
411
- if (actual.major !== min.major || actual.minor !== min.minor) return false;
412
- return actual.patch >= min.patch;
413
- }
414
- return compareSemver(actual, min) >= 0;
415
- };
416
- const splitRange = (engine) => {
417
- const trimmed = engine.trim();
418
- const match = /^(>=|\^|~)(.+)$/.exec(trimmed);
419
- if (match === null) return {
420
- prefix: ">=",
421
- rawMin: trimmed
422
- };
423
- return {
424
- prefix: match[1],
425
- rawMin: match[2] ?? ""
426
- };
427
- };
428
- /**
429
- * Check whether a Bun runtime version satisfies a simple engines range.
430
- *
431
- * Supports `>=A.B.C`, `^A.B.C`, `~A.B.C`. Returns ok=true if `engine` is
432
- * undefined (no constraint). Pre-release suffixes on `bunVersion` are stripped
433
- * for the comparison.
434
- *
435
- * @param bunVersion - The current `Bun.version` string.
436
- * @param engine - The `engines.bun` field from package.json (or undefined).
437
- * @returns A {@link VersionCheck} with `ok: false` carrying a user-facing message.
438
- */
439
- const checkBunVersion = (bunVersion, engine) => {
440
- if (engine === void 0) return { ok: true };
441
- const actual = parseSemver(bunVersion);
442
- if (actual === null) return {
443
- ok: false,
444
- message: `Unable to parse Bun version: ${bunVersion}`
445
- };
446
- const { prefix, rawMin } = splitRange(engine);
447
- const min = parseSemver(rawMin);
448
- if (min === null) return {
449
- ok: false,
450
- message: `Unable to parse engine range: ${engine}`
451
- };
452
- if (satisfiesRange(actual, min, prefix)) return { ok: true };
453
- return {
454
- ok: false,
455
- message: `Bun ${bunVersion} does not satisfy engines.bun "${engine}". Install Bun ${rawMin} or newer.`
456
- };
457
- };
458
-
459
- //#endregion
460
- //#region src/bin/cli.ts
461
- /** @file runCli — pure dispatch over injected deps. Tested without spawning subprocesses. */
462
- /**
463
- * Top-level CLI dispatcher.
464
- *
465
- * Exit codes:
466
- * 0 - success
467
- * 1 - config / discovery error
468
- * 2 - build / runtime error
469
- * 3 - invalid arguments
470
- * 4 - unsupported runtime
471
- *
472
- * @param argv - Argv slice (already stripped of `node`/`bun` + script path).
473
- * @param deps - Injected dependencies.
474
- * @returns The exit code wrapper.
475
- */
476
- const runCli = async (argv, deps) => {
477
- const top = parseTopLevel(argv);
478
- if (top.kind === "version") {
479
- deps.stdout(deps.version);
480
- return { code: 0 };
481
- }
482
- if (top.kind === "help") {
483
- deps.stdout(formatBanner(deps.version));
484
- deps.stdout(formatHelp());
485
- return { code: 0 };
486
- }
487
- if (top.kind === "unknown-flag") {
488
- deps.stderr(`Unknown flag: ${top.flag}`);
489
- deps.stdout(formatHelp());
490
- return { code: 3 };
491
- }
492
- const versionCheck = checkBunVersion(deps.bunVersion, deps.bunEngine);
493
- if (!versionCheck.ok) {
494
- deps.stderr(versionCheck.message);
495
- return { code: 4 };
496
- }
497
- deps.stdout(formatBanner(deps.version));
498
- switch (top.command) {
499
- case "build": return deps.buildCommand(top.rest);
500
- case "dev": return deps.devCommand(top.rest);
501
- case "preview": return deps.previewCommand(top.rest);
502
- case "deploy": return deps.deployCommand(top.rest);
503
- default:
504
- deps.stderr(`Unknown command: ${top.command}`);
505
- deps.stdout(formatHelp());
506
- return { code: 3 };
507
- }
508
- };
509
-
510
- //#endregion
511
- //#region src/bin/commands/prepare.ts
512
- /**
513
- * Parse argv, branch on help/error, then load the app. Reduces command
514
- * complexity by hiding the four-way branch behind a single discriminant.
515
- *
516
- * @param options - Parser + loader + cwd.
517
- * @returns A {@link PreparedOutcome}.
518
- */
519
- const prepareApp = async (options) => {
520
- const parsed = options.parse(options.argv);
521
- if (!parsed.ok) return {
522
- kind: "bad-args",
523
- message: parsed.message
524
- };
525
- if (parsed.value.help) return { kind: "help" };
526
- const loaded = await options.loadApp({
527
- cwd: options.cwd,
528
- folder: parsed.value.folder
529
- });
530
- if (!loaded.ok) return {
531
- kind: "load-failed",
532
- message: loaded.message
533
- };
534
- return {
535
- kind: "ready",
536
- args: parsed.value,
537
- app: loaded.value
538
- };
539
- };
540
- /**
541
- * Time a build run and report it.
542
- *
543
- * @param app - The loaded CliApp.
544
- * @param stdout - Output channel.
545
- * @returns Exit code (0 ok, 2 build failure) and message already emitted.
546
- */
547
- const runBuildOnce = async (app, stdout, stderr) => {
548
- const start = performance.now();
549
- try {
550
- await app.build.run();
551
- } catch (error) {
552
- stderr(`Build failed: ${error.message}`);
553
- return { code: 2 };
554
- }
555
- stdout(`Built in ${Math.round((performance.now() - start) / 100) / 10}s`);
556
- return { code: 0 };
557
- };
558
-
559
- //#endregion
560
- //#region src/bin/commands/build.ts
561
- /** @file `moku build` command — load app, run app.build.run(), report timing. */
562
- /**
563
- * Run the build subcommand.
564
- *
565
- * @param argv - Argv after the `build` keyword.
566
- * @param deps - Injected IO / loader dependencies.
567
- * @returns Exit code: 0 ok, 1 config error, 2 build error, 3 arg error.
568
- */
569
- const buildCommand = async (argv, deps) => {
570
- const prepared = await prepareApp({
571
- argv,
572
- parse: parseBuild,
573
- loadApp: deps.loadApp,
574
- cwd: deps.cwd
575
- });
576
- if (prepared.kind === "help") {
577
- deps.stdout(formatBuildHelp());
578
- return { code: 0 };
579
- }
580
- if (prepared.kind === "bad-args") {
581
- deps.stderr(prepared.message);
582
- deps.stdout(formatBuildHelp());
583
- return { code: 3 };
584
- }
585
- if (prepared.kind === "load-failed") {
586
- deps.stderr(prepared.message);
587
- return { code: 1 };
588
- }
589
- return runBuildOnce(prepared.app, deps.stdout, deps.stderr);
590
- };
591
-
592
- //#endregion
593
- //#region src/plugins/deploy/generators/github-workflow.ts
594
- /** @file deploy plugin GitHub Actions workflow generator — SHA-pinned, single-source-of-truth wrangler version. */
595
- /** Pinned SHAs for the standard runner actions. Update on each plugin release. */
596
- const CHECKOUT_ACTION_SHA = "11bd71901bbe5b1630ceea73d27597364c9af683";
597
- const SETUP_BUN_ACTION_SHA = "4bc047ad259df6fc24a6c9b0f9a0cb08cf17fbe5";
598
- /**
599
- * Generate the textual contents of `.github/workflows/deploy.yml`.
600
- *
601
- * Notes baked in:
602
- * - SHA-pinned actions (supply-chain hygiene).
603
- * - `wranglerVersion` pinned via {@link MOKU_WRANGLER_VERSION} — single SoT with `ensureWrangler()`.
604
- * - Command line uses `buildWranglerArgs(...)` so runtime and CI emit identical argv.
605
- * - No `--project-name` flag — wrangler reads `name` from `wrangler.jsonc`.
606
- * - Two-step pattern: `bun run moku build` then `wrangler-action` (enables Actions cache reuse).
607
- * - `gitHubToken` enables GitHub Deployments status updates on PRs and commits.
608
- *
609
- * @param input - Target, outdir, and branch.
610
- * @returns YAML text suitable for writing to `.github/workflows/deploy.yml`.
611
- */
612
- const generateGitHubWorkflow = (input) => {
613
- const args = buildWranglerArgs(input.target, input.outdir, input.branch).join(" ");
614
- return `# .github/workflows/deploy.yml — generated by \`moku deploy init --ci\`.
615
- # To re-sync after config changes, run \`moku deploy init --ci --force\`.
616
-
617
- name: Deploy
618
-
619
- on:
620
- push:
621
- branches: [${input.branch}]
622
- workflow_dispatch:
623
-
624
- permissions:
625
- contents: read
626
-
627
- jobs:
628
- deploy:
629
- runs-on: ubuntu-latest
630
- steps:
631
- - uses: actions/checkout@${CHECKOUT_ACTION_SHA}
632
- - uses: oven-sh/setup-bun@${SETUP_BUN_ACTION_SHA}
633
- - run: bun install --frozen-lockfile
634
- # Two-step pattern (build then deploy) enables GitHub Actions cache reuse.
635
- - run: bun run moku build
636
- - uses: cloudflare/wrangler-action@${WRANGLER_ACTION_SHA}
637
- with:
638
- apiToken: \${{ secrets.CLOUDFLARE_API_TOKEN }}
639
- accountId: \${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
640
- wranglerVersion: "${MOKU_WRANGLER_VERSION}"
641
- gitHubToken: \${{ secrets.GITHUB_TOKEN }}
642
- # buildWranglerArgs() — keep aligned with runtime argv. wrangler.jsonc#name is SSoT
643
- # for the project name, so we deliberately do NOT pass --project-name here.
644
- command: ${args}
645
- `;
646
- };
647
- /** Resolve the workflow path inside `cwd`. */
648
- const workflowPath = (cwd) => join(cwd, ".github", "workflows", "deploy.yml");
649
- /** Check whether `.github/workflows/deploy.yml` exists in `cwd`. */
650
- const githubWorkflowExists = (cwd) => existsSync(workflowPath(cwd));
651
- /** Write the generated workflow file, creating `.github/workflows/` as needed. */
652
- const writeGitHubWorkflow = async (cwd, content) => {
653
- const path = workflowPath(cwd);
654
- mkdirSync(dirname(path), { recursive: true });
655
- await writeFile(path, content, "utf8");
656
- };
657
-
658
- //#endregion
659
- //#region src/plugins/deploy/slug.ts
660
- /** @file deploy plugin slug derivation — Cloudflare Pages project-name validation + slugification. */
661
- /**
662
- * Cloudflare Pages project-name regex: lowercase alphanumerics and dashes only,
663
- * 1–58 chars, no leading/trailing dash, no underscores. Source: workers-sdk #3222.
664
- */
665
- const CLOUDFLARE_PROJECT_NAME_REGEX = /^[a-z0-9][a-z0-9-]{0,56}[a-z0-9]$/;
666
- const MAX_PROJECT_NAME_LENGTH = 58;
667
- /**
668
- * Derive a Cloudflare Pages–valid project slug from an arbitrary site name.
669
- *
670
- * Algorithm: lowercase → replace non-alphanumeric with `-` → collapse repeated
671
- * dashes → strip leading/trailing dashes → truncate to 58 chars → strip
672
- * trailing dashes again after truncation.
673
- *
674
- * @param siteName - The consumer-facing site name (typically `site.name`).
675
- * @returns A slug matching {@link CLOUDFLARE_PROJECT_NAME_REGEX}.
676
- * @throws Error when the input slugifies to an empty string or fails regex validation.
677
- */
678
- const slugify = (siteName) => {
679
- const raw = siteName.toLowerCase().replaceAll(/[^a-z0-9-]/g, "-").replaceAll(/-+/g, "-").replace(/^-+/, "").replace(/-+$/, "").slice(0, MAX_PROJECT_NAME_LENGTH).replace(/-+$/, "");
680
- if (raw === "") throw new Error(`deploy: cannot derive a Cloudflare project slug from "${siteName}" — result is empty after sanitization`);
681
- if (!CLOUDFLARE_PROJECT_NAME_REGEX.test(raw)) throw new Error(`deploy: derived slug "${raw}" does not match Cloudflare Pages project-name regex`);
682
- return raw;
683
- };
684
- /**
685
- * Validate that an explicit project name matches Cloudflare's rules.
686
- *
687
- * @param name - Candidate project name.
688
- * @throws Error if the name violates {@link CLOUDFLARE_PROJECT_NAME_REGEX}.
689
- */
690
- const assertValidProjectName = (name) => {
691
- if (!CLOUDFLARE_PROJECT_NAME_REGEX.test(name)) throw new Error(`deploy: project name "${name}" must match ^[a-z0-9][a-z0-9-]{0,56}[a-z0-9]$ (1–58 chars, lowercase alphanumerics and dashes only, no leading/trailing dash, no underscores)`);
692
- };
693
-
694
- //#endregion
695
- //#region src/plugins/deploy/init.ts
696
- /** @file deploy plugin init orchestrator — branch detection, slug derivation, generators, checklist. */
697
- const DEFAULT_BRANCH = "main";
698
- const sanitizedProcessEnv = () => {
699
- const out = {};
700
- for (const [k, v] of Object.entries(process.env)) if (typeof v === "string") out[k] = v;
701
- return out;
702
- };
703
- const getBun = () => globalThis;
704
- const runGitSymbolicRef = async () => {
705
- const { Bun: bun } = getBun();
706
- if (bun === void 0) return null;
707
- try {
708
- const proc = bun.spawn([
709
- "git",
710
- "symbolic-ref",
711
- "refs/remotes/origin/HEAD"
712
- ], {
713
- env: sanitizedProcessEnv(),
714
- stdout: "pipe",
715
- stderr: "pipe"
716
- });
717
- const stdout = await new Response(proc.stdout).text();
718
- if (await proc.exited !== 0) return null;
719
- return stdout.trim().match(/refs\/remotes\/origin\/(.+)$/)?.[1] ?? null;
720
- } catch {
721
- return null;
722
- }
723
- };
724
- const runGitInitDefaultBranch = async () => {
725
- const { Bun: bun } = getBun();
726
- if (bun === void 0) return null;
727
- try {
728
- const proc = bun.spawn([
729
- "git",
730
- "config",
731
- "--get",
732
- "init.defaultBranch"
733
- ], {
734
- env: sanitizedProcessEnv(),
735
- stdout: "pipe",
736
- stderr: "pipe"
737
- });
738
- const stdout = (await new Response(proc.stdout).text()).trim();
739
- return await proc.exited === 0 && stdout !== "" ? stdout : null;
740
- } catch {
741
- return null;
742
- }
743
- };
744
- /** Spawn `git symbolic-ref` with a fallback to `git config --get init.defaultBranch`. */
745
- const defaultDetectDefaultBranch = async () => {
746
- const primary = await runGitSymbolicRef();
747
- if (primary !== null) return primary;
748
- return await runGitInitDefaultBranch() ?? DEFAULT_BRANCH;
749
- };
750
- /** Format a drift list as a printable diff block. */
751
- const formatDriftReport = (drift) => {
752
- if (drift.length === 0) return "No drift detected.";
753
- const lines = ["Drift detected:"];
754
- for (const entry of drift) {
755
- lines.push(` ${entry.field}:`);
756
- lines.push(` - ${entry.current}`);
757
- lines.push(` + ${entry.proposed}`);
758
- }
759
- return lines.join("\n");
760
- };
761
- /** Print the post-init setup checklist to stdout. */
762
- const printChecklist = (stdout, slug, branch, createdProject) => {
763
- stdout("");
764
- stdout("Cloudflare Pages deploy — setup checklist");
765
- stdout("");
766
- stdout("1. Find your account ID:");
767
- stdout(" https://dash.cloudflare.com → string after dash.cloudflare.com/ in the URL.");
768
- stdout("");
769
- if (createdProject) stdout(`2. Pages project '${slug}' already exists (created by --create-project).`);
770
- else {
771
- stdout("2. Create the Pages project (skip if already created):");
772
- stdout(` wrangler pages project create ${slug}`);
773
- }
774
- stdout("");
775
- stdout("3. Mint a Cloudflare API token:");
776
- stdout(" https://dash.cloudflare.com/profile/api-tokens");
777
- stdout(" → Create Token → Custom Token →");
778
- stdout(" → Permissions: Account → Cloudflare Pages → Edit (NOT \"Read\" — Read causes silent 403)");
779
- stdout(" Click \"Create Token\", copy the value (shown only once).");
780
- stdout("");
781
- stdout("4. Add GitHub Actions secrets:");
782
- stdout(" Settings → Secrets and variables → Actions → New repository secret");
783
- stdout(" CLOUDFLARE_API_TOKEN = (the token from step 3)");
784
- stdout(" CLOUDFLARE_ACCOUNT_ID = (the ID from step 1)");
785
- stdout("");
786
- stdout("5. (Optional) Place _headers and _redirects in `public/` to control Cloudflare response headers and redirects.");
787
- stdout("");
788
- stdout(`6. Push to ${branch} — the generated workflow fires automatically.`);
789
- stdout("");
790
- stdout("Tip: run `moku deploy init --check` in release CI to assert config freshness.");
791
- stdout("Note: Cloudflare dashboard git-push auto-build does NOT recognize wrangler.jsonc — use this workflow.");
792
- };
793
- const defaultPromptYesNo = async (_message, defaultYes) => Promise.resolve(defaultYes);
794
- /** Warn-and-overwrite branch of the slug drift decision (interactive "n" or `--force`). */
795
- const warnSlugChanged = (ctx, existingName, slug) => {
796
- ctx.log.warn("deploy:init:slug-changed", {
797
- existing: existingName,
798
- computed: slug,
799
- note: `Project rename: run \`wrangler pages project create ${slug}\`. The old project remains deployed under ${existingName}.pages.dev.`
800
- });
801
- };
802
- const promptKeepExisting = async (ctx, existingName, slug) => {
803
- return (ctx.promptYesNo ?? defaultPromptYesNo)(`${`wrangler.jsonc#name = "${existingName}" (existing) vs slug("${ctx.siteName}") = "${slug}" (computed).`}\nKeep existing? [Y/n]`, true);
804
- };
805
- /** Internal "should we write wrangler.jsonc?" decision around the diff-on-rename gate. */
806
- const resolveSlugWriteDecision = async (ctx, options, existing, slug, interactive) => {
807
- if (existing === null || existing.name === slug) return true;
808
- if (options.force === true) {
809
- warnSlugChanged(ctx, existing.name, slug);
810
- return true;
811
- }
812
- if (!interactive) {
813
- ctx.log.info("deploy:init:slug-keep-existing", {
814
- existing: existing.name,
815
- computed: slug
816
- });
817
- return false;
818
- }
819
- if (await promptKeepExisting(ctx, existing.name, slug)) return false;
820
- warnSlugChanged(ctx, existing.name, slug);
821
- return true;
822
- };
823
- /** Run `wrangler pages project create` for the `--create-project` flag. Treats "already exists" as success. */
824
- const tryCreateCloudflareProject = async (ctx, slug) => {
825
- const env = ctx.env ?? sanitizedProcessEnv();
826
- try {
827
- await runWrangler([
828
- "pages",
829
- "project",
830
- "create",
831
- slug
832
- ], env, ctx.spawn);
833
- return true;
834
- } catch (error) {
835
- const wranglerError = error instanceof Error ? error : new Error(String(error));
836
- if (/already exists/i.test(wranglerError.message)) return true;
837
- throw wranglerError;
838
- }
839
- };
840
- /** Maybe write the GitHub Actions workflow file. */
841
- const maybeWriteWorkflow = async (ctx, options, cwd, branch) => {
842
- if (options.ci !== true) return;
843
- if (githubWorkflowExists(cwd) && options.force !== true) {
844
- ctx.log.info("deploy:init:workflow-skipped", { reason: "exists; pass --force to overwrite" });
845
- return;
846
- }
847
- await writeGitHubWorkflow(cwd, generateGitHubWorkflow({
848
- target: ctx.config.target,
849
- outdir: ctx.config.outdir,
850
- branch
851
- }));
852
- };
853
- /** Emit the "no build plugin registered" informational warning when appropriate. */
854
- const maybeWarnMissingBuild = (ctx) => {
855
- if (!ctx.buildPluginRegistered && ctx.config.outdir === "dist") ctx.log.warn("deploy:init:no-build-plugin", { note: "No 'build' plugin registered and no explicit outdir set — using default 'dist'. Configure pluginConfigs.deploy.outdir if your build output lives elsewhere." });
856
- };
857
- /** Handle the `--check` short-circuit. */
858
- const handleCheckMode = (ctx, cwd, slug, outdir, branch) => {
859
- const drift = diffWranglerConfig(readWranglerConfig(cwd), {
860
- slug,
861
- outdir
862
- });
863
- ctx.stdout(formatDriftReport(drift));
864
- return {
865
- slug,
866
- outdir,
867
- branch,
868
- drift,
869
- wroteFiles: false
870
- };
871
- };
872
- const resolveInitInputs = async (ctx, options) => {
873
- const detectBranch = ctx.detectDefaultBranch ?? defaultDetectDefaultBranch;
874
- const branch = options.branch ?? await detectBranch();
875
- const slug = ctx.config.projectName ?? slugify(ctx.siteName);
876
- assertValidProjectName(slug);
877
- const interactive = options.interactive ?? Boolean(process.stdout.isTTY);
878
- return {
879
- branch,
880
- slug,
881
- outdir: ctx.config.outdir,
882
- interactive
883
- };
884
- };
885
- /** Compose the writable artifacts step — wrangler.jsonc + workflow + warnings. */
886
- const writeArtifacts = async (ctx, options, cwd, inputs, writeJsonc) => {
887
- if (writeJsonc) await writeWranglerConfig(cwd, generateWranglerConfig({
888
- slug: inputs.slug,
889
- outdir: inputs.outdir
890
- }));
891
- await maybeWriteWorkflow(ctx, options, cwd, inputs.branch);
892
- maybeWarnMissingBuild(ctx);
893
- };
894
- /**
895
- * Run `moku deploy init`.
896
- *
897
- * @param ctx - {@link InitContext} carrying logger, stdout, and injectable spawn/git deps.
898
- * @param options - {@link InitOptions} flag set.
899
- * @returns A {@link InitResult} summarizing what happened.
900
- */
901
- const runInit = async (ctx, options = {}) => {
902
- const cwd = options.cwd ?? process.cwd();
903
- const inputs = await resolveInitInputs(ctx, options);
904
- if (options.check === true) return handleCheckMode(ctx, cwd, inputs.slug, inputs.outdir, inputs.branch);
905
- const writeJsonc = await resolveSlugWriteDecision(ctx, options, readWranglerConfig(cwd), inputs.slug, inputs.interactive);
906
- const projectCreated = options.createProject === true ? await tryCreateCloudflareProject(ctx, inputs.slug) : void 0;
907
- await writeArtifacts(ctx, options, cwd, inputs, writeJsonc);
908
- const wroteFiles = writeJsonc || options.ci === true;
909
- if (wroteFiles) printChecklist(ctx.stdout, inputs.slug, inputs.branch, projectCreated === true);
910
- return {
911
- slug: inputs.slug,
912
- outdir: inputs.outdir,
913
- branch: inputs.branch,
914
- wroteFiles,
915
- ...projectCreated === void 0 ? {} : { projectCreated }
916
- };
917
- };
918
-
919
- //#endregion
920
- //#region src/bin/commands/deploy.ts
921
- /** @file `moku deploy` command — load app, run app.deploy.run() or runInit(). */
922
- /**
923
- * Top-level dispatcher for `moku deploy` and `moku deploy init`.
924
- *
925
- * @param argv - Argv after the `deploy` keyword.
926
- * @param deps - Injected IO + loader dependencies.
927
- * @returns Exit code: 0 ok, 1 load error, 2 deploy error, 3 arg error.
928
- */
929
- const deployCommand = async (argv, deps) => {
930
- const [first, ...rest] = argv;
931
- if (first === "init") return runInitCommand(rest, deps);
932
- return runDeployCommand(argv, deps);
933
- };
934
- const runDeployCommand = async (argv, deps) => {
935
- const prepared = await prepareApp({
936
- argv,
937
- parse: parseDeploy,
938
- loadApp: deps.loadApp,
939
- cwd: deps.cwd
940
- });
941
- if (prepared.kind === "help") {
942
- deps.stdout(formatDeployHelp());
943
- return { code: 0 };
944
- }
945
- if (prepared.kind === "bad-args") {
946
- deps.stderr(prepared.message);
947
- deps.stdout(formatDeployHelp());
948
- return { code: 3 };
949
- }
950
- if (prepared.kind === "load-failed") {
951
- deps.stderr(prepared.message);
952
- return { code: 1 };
953
- }
954
- if (prepared.app.deploy === void 0) {
955
- deps.stderr("deploy: this app does not register the deploy plugin.");
956
- return { code: 1 };
957
- }
958
- try {
959
- const result = await prepared.app.deploy.run({
960
- ...prepared.args.branch === void 0 ? {} : { branch: prepared.args.branch },
961
- build: prepared.args.build
962
- });
963
- deps.stdout(`Deployed to ${result.url} (branch=${result.branch}, ${result.durationMs}ms)`);
964
- return { code: 0 };
965
- } catch (error) {
966
- deps.stderr(`Deploy failed: ${error.message}`);
967
- return { code: 2 };
968
- }
969
- };
970
- const resolveDeployConfig = (app) => {
971
- const fromAppConfig = app.config?.deploy;
972
- if (fromAppConfig !== void 0) return fromAppConfig;
973
- return {
974
- target: "pages",
975
- outdir: "dist",
976
- productionBranch: "main"
977
- };
978
- };
979
- const makeInitLogger = (deps) => ({
980
- info: (event, data) => deps.stdout(`[info] ${event} ${data ? JSON.stringify(data) : ""}`),
981
- warn: (event, data) => deps.stderr(`[warn] ${event} ${data ? JSON.stringify(data) : ""}`),
982
- error: (event, data) => deps.stderr(`[error] ${event} ${data ? JSON.stringify(data) : ""}`)
983
- });
984
- const runInitForPreparedApp = async (deps, app, args) => {
985
- const siteName = app.site?.name() ?? "";
986
- if (siteName === "") {
987
- deps.stderr("deploy init: site.name is empty — set it in your app config.");
988
- return { code: 1 };
989
- }
990
- try {
991
- const result = await runInit({
992
- siteName,
993
- config: resolveDeployConfig(app),
994
- buildPluginRegistered: app.build !== void 0,
995
- log: makeInitLogger(deps),
996
- stdout: deps.stdout
997
- }, {
998
- cwd: deps.cwd,
999
- ci: args.ci,
1000
- force: args.force,
1001
- createProject: args.createProject,
1002
- check: args.check,
1003
- ...args.branch === void 0 ? {} : { branch: args.branch }
1004
- });
1005
- if (args.check && result.drift !== void 0 && result.drift.length > 0) return { code: 2 };
1006
- return { code: 0 };
1007
- } catch (error) {
1008
- deps.stderr(`Deploy init failed: ${error.message}`);
1009
- return { code: 2 };
1010
- }
1011
- };
1012
- const runInitCommand = async (argv, deps) => {
1013
- const prepared = await prepareApp({
1014
- argv,
1015
- parse: parseDeployInit,
1016
- loadApp: deps.loadApp,
1017
- cwd: deps.cwd
1018
- });
1019
- if (prepared.kind === "help") {
1020
- deps.stdout(formatDeployHelp());
1021
- return { code: 0 };
1022
- }
1023
- if (prepared.kind === "bad-args") {
1024
- deps.stderr(prepared.message);
1025
- deps.stdout(formatDeployHelp());
1026
- return { code: 3 };
1027
- }
1028
- if (prepared.kind === "load-failed") {
1029
- deps.stderr(prepared.message);
1030
- return { code: 1 };
1031
- }
1032
- return runInitForPreparedApp(deps, prepared.app, prepared.args);
1033
- };
1034
-
1035
- //#endregion
1036
- //#region src/bin/commands/dev.ts
1037
- /** @file `moku dev` command — watch + invalidate + rebuild + serve loop. */
1038
- const makeRebuildHandler = (app, deps) => async (paths) => {
1039
- if (app.content !== void 0) app.content.invalidate(paths);
1040
- try {
1041
- await app.build.run();
1042
- deps.stdout(`[dev] Rebuilt (${paths.length} change${paths.length === 1 ? "" : "s"})`);
1043
- } catch (error) {
1044
- deps.stderr(`[dev] Rebuild failed: ${error.message}`);
1045
- }
1046
- };
1047
- const startDevServer = (app, deps, port) => {
1048
- const outdir = app.config?.build?.outdir ?? "dist";
1049
- const defaultLocale = app.config?.i18n?.defaultLocale ?? "en";
1050
- return deps.serve({
1051
- rootDir: resolve(deps.cwd, outdir),
1052
- port,
1053
- defaultLocale
1054
- });
1055
- };
1056
- /**
1057
- * Run the dev subcommand.
1058
- *
1059
- * Builds once, then watches `contentDir` and on each batch invalidates
1060
- * content paths BEFORE calling `app.build.run()` (hard rule from CLAUDE.md).
1061
- *
1062
- * @param argv - Argv after the `dev` keyword.
1063
- * @param deps - Injected IO / loader / watch / serve dependencies.
1064
- * @returns Exit code: 0 ok, 1 config error, 2 build error, 3 arg error.
1065
- */
1066
- const devCommand = async (argv, deps) => {
1067
- const prepared = await prepareApp({
1068
- argv,
1069
- parse: parseDev,
1070
- loadApp: deps.loadApp,
1071
- cwd: deps.cwd
1072
- });
1073
- if (prepared.kind === "help") {
1074
- deps.stdout(formatDevHelp());
1075
- return { code: 0 };
1076
- }
1077
- if (prepared.kind === "bad-args") {
1078
- deps.stderr(prepared.message);
1079
- deps.stdout(formatDevHelp());
1080
- return { code: 3 };
1081
- }
1082
- if (prepared.kind === "load-failed") {
1083
- deps.stderr(prepared.message);
1084
- return { code: 1 };
1085
- }
1086
- try {
1087
- await prepared.app.build.run();
1088
- } catch (error) {
1089
- deps.stderr(`Initial build failed: ${error.message}`);
1090
- return { code: 2 };
1091
- }
1092
- const handle = startDevServer(prepared.app, deps, prepared.args.port);
1093
- deps.stdout(`[dev] Serving at http://localhost:${handle.port}`);
1094
- deps.watch({
1095
- rootDir: deps.cwd,
1096
- contentDir: resolve(deps.cwd, "content"),
1097
- onChange: makeRebuildHandler(prepared.app, deps)
1098
- });
1099
- return { code: 0 };
1100
- };
1101
-
1102
- //#endregion
1103
- //#region src/bin/commands/preview.ts
1104
- /** @file `moku preview` command — build once, then serve the outdir. */
1105
- const startPreviewServer = (app, cwd, port, serve) => {
1106
- const outdir = app.config?.build?.outdir ?? "dist";
1107
- const defaultLocale = app.config?.i18n?.defaultLocale ?? "en";
1108
- return serve({
1109
- rootDir: resolve(cwd, outdir),
1110
- port,
1111
- defaultLocale
1112
- });
1113
- };
1114
- /**
1115
- * Run the preview subcommand.
1116
- *
1117
- * @param argv - Argv after the `preview` keyword.
1118
- * @param deps - Injected IO / loader / serve dependencies.
1119
- * @returns Exit code: 0 ok, 1 config error, 2 build error, 3 arg error.
1120
- */
1121
- const previewCommand = async (argv, deps) => {
1122
- const prepared = await prepareApp({
1123
- argv,
1124
- parse: parsePreview,
1125
- loadApp: deps.loadApp,
1126
- cwd: deps.cwd
1127
- });
1128
- if (prepared.kind === "help") {
1129
- deps.stdout(formatPreviewHelp());
1130
- return { code: 0 };
1131
- }
1132
- if (prepared.kind === "bad-args") {
1133
- deps.stderr(prepared.message);
1134
- deps.stdout(formatPreviewHelp());
1135
- return { code: 3 };
1136
- }
1137
- if (prepared.kind === "load-failed") {
1138
- deps.stderr(prepared.message);
1139
- return { code: 1 };
1140
- }
1141
- const build = await runBuildOnce(prepared.app, deps.stdout, deps.stderr);
1142
- if (build.code !== 0) return build;
1143
- const handle = startPreviewServer(prepared.app, deps.cwd, prepared.args.port, deps.serve);
1144
- deps.stdout(`[preview] Serving at http://localhost:${handle.port}`);
1145
- return { code: 0 };
1146
- };
1147
-
1148
- //#endregion
1149
- //#region src/bin/load-app.ts
1150
- /** @file Discovers and dynamically imports the consumer's main.ts entry. */
1151
- /**
1152
- * Dynamically import `{cwd}/{folder}/main.ts` and return its default export.
1153
- *
1154
- * Returns a structured result rather than throwing; the CLI maps errors to
1155
- * exit codes.
1156
- *
1157
- * @param options - The cwd and folder to look in.
1158
- * @returns A {@link LoadResult}.
1159
- */
1160
- const loadApp = async (options) => {
1161
- const mainPath = resolve(options.cwd, options.folder, "main.ts");
1162
- if (!existsSync(mainPath)) return {
1163
- ok: false,
1164
- message: `main.ts not found at ${mainPath}. Run \`moku <command> <folder>\` with the correct path.`,
1165
- path: mainPath
1166
- };
1167
- try {
1168
- const mod = await import(mainPath);
1169
- if (mod.default === void 0) return {
1170
- ok: false,
1171
- message: `${mainPath} has no default export. Export your createApp() result as default.`,
1172
- path: mainPath
1173
- };
1174
- return {
1175
- ok: true,
1176
- value: mod.default,
1177
- path: mainPath
1178
- };
1179
- } catch (error) {
1180
- return {
1181
- ok: false,
1182
- message: `Failed to import ${mainPath}: ${error.message}`,
1183
- path: mainPath
1184
- };
1185
- }
1186
- };
1187
-
1188
- //#endregion
1189
- //#region src/bin/serve.ts
1190
- /** @file Static file handler used by `moku preview` and `moku dev`. */
1191
- const MIME_TYPES = new Map([
1192
- [".html", "text/html; charset=utf-8"],
1193
- [".css", "text/css; charset=utf-8"],
1194
- [".js", "application/javascript; charset=utf-8"],
1195
- [".mjs", "application/javascript; charset=utf-8"],
1196
- [".json", "application/json; charset=utf-8"],
1197
- [".svg", "image/svg+xml"],
1198
- [".png", "image/png"],
1199
- [".jpg", "image/jpeg"],
1200
- [".jpeg", "image/jpeg"],
1201
- [".gif", "image/gif"],
1202
- [".webp", "image/webp"],
1203
- [".ico", "image/x-icon"],
1204
- [".txt", "text/plain; charset=utf-8"],
1205
- [".xml", "application/xml; charset=utf-8"],
1206
- [".woff", "font/woff"],
1207
- [".woff2", "font/woff2"]
1208
- ]);
1209
- const mimeFor = (path) => MIME_TYPES.get(extname(path).toLowerCase()) ?? "application/octet-stream";
1210
- const isPathInside = (parent, child) => `${child}${sep}`.startsWith(`${parent}${sep}`);
1211
- const resolveTarget = (rootDir, urlPath) => {
1212
- const target = resolve(rootDir, normalize(`./${decodeURIComponent(urlPath).replaceAll("\\", "/").replace(/\/+/g, "/")}`));
1213
- if (!isPathInside(rootDir, target) && target !== rootDir) return null;
1214
- return target;
1215
- };
1216
- const resolveFilePath = (target, urlPath) => {
1217
- const candidate = urlPath.endsWith("/") ? resolve(target, "index.html") : target;
1218
- if (!existsSync(candidate)) return null;
1219
- if (!statSync(candidate).isDirectory()) return candidate;
1220
- const indexed = resolve(candidate, "index.html");
1221
- return existsSync(indexed) ? indexed : null;
1222
- };
1223
- const fileResponse = (path) => new Response(readFileSync(path), { headers: { "content-type": mimeFor(path) } });
1224
- /**
1225
- * Build a fetch-style handler that serves files from `rootDir`.
1226
- *
1227
- * Behavior:
1228
- * - Bare `/` redirects (307) to `/{defaultLocale}/`.
1229
- * - Paths ending in `/` look for `index.html`.
1230
- * - Path traversal attempts return 403.
1231
- * - Missing files return 404.
1232
- *
1233
- * @param options - The root directory and default locale.
1234
- * @returns A `(request: Request) => Promise<Response>` handler.
1235
- */
1236
- const createStaticHandler = (options) => {
1237
- const root = resolve(options.rootDir);
1238
- return async (request) => {
1239
- const url = new URL(request.url);
1240
- if (url.pathname === "/") return new Response(null, {
1241
- status: 307,
1242
- headers: { location: `/${options.defaultLocale}/` }
1243
- });
1244
- const target = resolveTarget(root, url.pathname);
1245
- if (target === null) return new Response("Forbidden", { status: 403 });
1246
- const filePath = resolveFilePath(target, url.pathname);
1247
- if (filePath === null) return new Response("Not Found", { status: 404 });
1248
- return fileResponse(filePath);
1249
- };
1250
- };
1251
-
1252
- //#endregion
1253
- //#region src/bin/watch.ts
1254
- /**
1255
- * Create a trailing-edge debounced change batcher.
1256
- *
1257
- * Each `push(path)` (re)starts the debounce timer. When the timer fires the
1258
- * collected unique paths are passed to `onFlush` and a new batch begins.
1259
- * `flush()` drains immediately; `dispose()` cancels any pending flush without
1260
- * invoking the callback.
1261
- *
1262
- * @param options - Debounce window + flush callback.
1263
- * @returns The {@link ChangeBatcher} handle.
1264
- */
1265
- const createChangeBatcher = (options) => {
1266
- let pending = /* @__PURE__ */ new Set();
1267
- let timer = null;
1268
- const clearTimer = () => {
1269
- if (timer !== null) {
1270
- clearTimeout(timer);
1271
- timer = null;
1272
- }
1273
- };
1274
- const drain = () => {
1275
- clearTimer();
1276
- if (pending.size === 0) return;
1277
- const batch = [...pending];
1278
- pending = /* @__PURE__ */ new Set();
1279
- options.onFlush(batch);
1280
- };
1281
- return {
1282
- push: (path) => {
1283
- pending.add(path);
1284
- clearTimer();
1285
- timer = setTimeout(drain, options.debounceMs);
1286
- },
1287
- flush: drain,
1288
- dispose: () => {
1289
- clearTimer();
1290
- pending = /* @__PURE__ */ new Set();
1291
- }
1292
- };
1293
- };
1294
-
1295
- //#endregion
1296
- //#region src/bin/moku.ts
1297
- /** @file moku CLI entry — wires runtime IO to runCli. NOT a plugin. */
1298
- const findPackageJson = () => {
1299
- const candidates = [
1300
- resolve(import.meta.dir, "..", "..", "package.json"),
1301
- resolve(import.meta.dir, "..", "package.json"),
1302
- resolve(process.cwd(), "package.json")
1303
- ];
1304
- for (const candidate of candidates) if (existsSync(candidate)) return JSON.parse(readFileSync(candidate, "utf8"));
1305
- return {};
1306
- };
1307
- const pkg = findPackageJson();
1308
- const stdout = (line) => {
1309
- process.stdout.write(`${line}\n`);
1310
- };
1311
- const stderr = (line) => {
1312
- process.stderr.write(`${line}\n`);
1313
- };
1314
- const serveStatic = (options) => {
1315
- const handler = createStaticHandler({
1316
- rootDir: options.rootDir,
1317
- defaultLocale: options.defaultLocale
1318
- });
1319
- const server = Bun.serve({
1320
- port: options.port,
1321
- fetch: handler
1322
- });
1323
- return {
1324
- port: server.port ?? options.port,
1325
- stop: () => server.stop()
1326
- };
1327
- };
1328
- const startWatcher = (options) => {
1329
- const batcher = createChangeBatcher({
1330
- debounceMs: 50,
1331
- onFlush: (paths) => options.onChange(paths)
1332
- });
1333
- if (!existsSync(options.contentDir)) return { stop: () => batcher.dispose() };
1334
- const watcher = watch(options.contentDir, { recursive: true }, (_event, filename) => {
1335
- if (filename !== null) batcher.push(filename.toString());
1336
- });
1337
- return { stop: () => {
1338
- watcher.close();
1339
- batcher.dispose();
1340
- } };
1341
- };
1342
- const main = async () => {
1343
- const result = await runCli(process.argv.slice(2), {
1344
- cwd: process.cwd(),
1345
- version: pkg.version ?? "0.0.0",
1346
- bunVersion: Bun.version,
1347
- bunEngine: pkg.engines?.bun,
1348
- stdout,
1349
- stderr,
1350
- buildCommand: (argv) => buildCommand(argv, {
1351
- cwd: process.cwd(),
1352
- stdout,
1353
- stderr,
1354
- loadApp
1355
- }),
1356
- devCommand: (argv) => devCommand(argv, {
1357
- cwd: process.cwd(),
1358
- stdout,
1359
- stderr,
1360
- loadApp,
1361
- watch: startWatcher,
1362
- serve: serveStatic
1363
- }),
1364
- previewCommand: (argv) => previewCommand(argv, {
1365
- cwd: process.cwd(),
1366
- stdout,
1367
- stderr,
1368
- loadApp,
1369
- serve: serveStatic
1370
- }),
1371
- deployCommand: (argv) => deployCommand(argv, {
1372
- cwd: process.cwd(),
1373
- stdout,
1374
- stderr,
1375
- loadApp
1376
- })
1377
- });
1378
- process.exit(result.code);
1379
- };
1380
- main();
1381
-
1382
- //#endregion
1383
- export { };