@moku-labs/web 0.1.0-alpha.1 → 0.1.0-alpha.4

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.
Files changed (33) hide show
  1. package/README.md +36 -1
  2. package/dist/bin/moku.cjs +575 -1
  3. package/dist/bin/moku.mjs +576 -2
  4. package/dist/chunk-DQk6qfdC.mjs +18 -0
  5. package/dist/{factory-CixCpR9C.cjs → factory-CMOo4n6a.cjs} +13 -1
  6. package/dist/{factory-BBVQO5ZG.d.mts → factory-DRFGSslp.d.mts} +26 -2
  7. package/dist/{factory-DwpBwjDk.mjs → factory-DiKypQqs.mjs} +2 -2
  8. package/dist/{factory-D0m7Xil2.d.cts → factory-k-YoScgB.d.cts} +26 -2
  9. package/dist/{index-CWdZdegx.d.mts → index-DH3jlpNi.d.mts} +215 -61
  10. package/dist/{route-builder-Lv6HUVvP.d.cts → index-DaY7vTuo.d.cts} +215 -61
  11. package/dist/index.cjs +75 -3
  12. package/dist/index.d.cts +41 -40
  13. package/dist/index.d.mts +41 -40
  14. package/dist/index.mjs +6 -5
  15. package/dist/plugins/head/build.d.cts +1 -1
  16. package/dist/plugins/head/build.d.mts +1 -1
  17. package/dist/plugins/head/build.mjs +1 -1
  18. package/dist/plugins/spa/index.cjs +1 -1
  19. package/dist/plugins/spa/index.d.cts +1 -1
  20. package/dist/plugins/spa/index.d.mts +1 -1
  21. package/dist/plugins/spa/index.mjs +1 -1
  22. package/dist/{primitives-BBo4wxUL.d.cts → primitives-DKgZfRAO.d.mts} +4 -2
  23. package/dist/{primitives-kuZFxqV7.d.mts → primitives-yZqQkOVR.d.cts} +4 -2
  24. package/dist/{project-C1vtMxE8.cjs → project-B8z4jeMC.cjs} +307 -5
  25. package/dist/{project-BTNUWbGQ.mjs → project-guCYpUeD.mjs} +232 -8
  26. package/dist/test.cjs +2 -2
  27. package/dist/test.d.cts +1 -1
  28. package/dist/test.d.mts +1 -1
  29. package/dist/test.mjs +2 -2
  30. package/dist/wrangler-BlZWVmX9.mjs +369 -0
  31. package/dist/wrangler-Bomk9mU-.cjs +423 -0
  32. package/package.json +9 -1
  33. /package/dist/{primitives-gO5i1tD8.mjs → primitives-Dhko-oLM.mjs} +0 -0
package/dist/bin/moku.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env bun
2
- import { existsSync, readFileSync, statSync, watch } from "node:fs";
3
- import { extname, normalize, resolve, sep } from "node:path";
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";
4
6
  import { parseArgs } from "node:util";
5
7
 
6
8
  //#region src/bin/help.ts
@@ -24,6 +26,7 @@ Commands:
24
26
  build [folder] Build static site (default folder: src/)
25
27
  dev [folder] Start dev server with watch + rebuild
26
28
  preview [folder] Build and serve site for local preview
29
+ deploy [folder] Deploy dist/ to Cloudflare Pages (run \`deploy init\` once first)
27
30
 
28
31
  Options:
29
32
  --version Show version number
@@ -61,6 +64,30 @@ Options:
61
64
  --port, -p <n> Server port (default: 4173)
62
65
  --help, -h Show help`.trim();
63
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
+ /**
64
91
  * Format the help text for `moku preview`.
65
92
  *
66
93
  * @returns The help text.
@@ -223,6 +250,103 @@ const parseDev = (argv) => {
223
250
  }
224
251
  };
225
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
+ /**
226
350
  * Parse `moku preview` arguments.
227
351
  *
228
352
  * @param argv - Argv after the `preview` keyword.
@@ -375,6 +499,7 @@ const runCli = async (argv, deps) => {
375
499
  case "build": return deps.buildCommand(top.rest);
376
500
  case "dev": return deps.devCommand(top.rest);
377
501
  case "preview": return deps.previewCommand(top.rest);
502
+ case "deploy": return deps.deployCommand(top.rest);
378
503
  default:
379
504
  deps.stderr(`Unknown command: ${top.command}`);
380
505
  deps.stdout(formatHelp());
@@ -464,6 +589,449 @@ const buildCommand = async (argv, deps) => {
464
589
  return runBuildOnce(prepared.app, deps.stdout, deps.stderr);
465
590
  };
466
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
+
467
1035
  //#endregion
468
1036
  //#region src/bin/commands/dev.ts
469
1037
  /** @file `moku dev` command — watch + invalidate + rebuild + serve loop. */
@@ -799,6 +1367,12 @@ const main = async () => {
799
1367
  stderr,
800
1368
  loadApp,
801
1369
  serve: serveStatic
1370
+ }),
1371
+ deployCommand: (argv) => deployCommand(argv, {
1372
+ cwd: process.cwd(),
1373
+ stdout,
1374
+ stderr,
1375
+ loadApp
802
1376
  })
803
1377
  });
804
1378
  process.exit(result.code);
@@ -0,0 +1,18 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) {
6
+ __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: true
9
+ });
10
+ }
11
+ if (!no_symbols) {
12
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
13
+ }
14
+ return target;
15
+ };
16
+
17
+ //#endregion
18
+ export { __exportAll as t };
@@ -1,4 +1,4 @@
1
- const require_project = require('./project-C1vtMxE8.cjs');
1
+ const require_project = require('./project-B8z4jeMC.cjs');
2
2
  const require_primitives = require('./primitives-BYUp6kae.cjs');
3
3
  const require_plugins_head_build = require('./plugins/head/build.cjs');
4
4
  let _moku_labs_core = require("@moku-labs/core");
@@ -1666,6 +1666,12 @@ Object.defineProperty(exports, 'createSpaState', {
1666
1666
  return createSpaState;
1667
1667
  }
1668
1668
  });
1669
+ Object.defineProperty(exports, 'env', {
1670
+ enumerable: true,
1671
+ get: function () {
1672
+ return env;
1673
+ }
1674
+ });
1669
1675
  Object.defineProperty(exports, 'head', {
1670
1676
  enumerable: true,
1671
1677
  get: function () {
@@ -1678,6 +1684,12 @@ Object.defineProperty(exports, 'i18n', {
1678
1684
  return i18n;
1679
1685
  }
1680
1686
  });
1687
+ Object.defineProperty(exports, 'log', {
1688
+ enumerable: true,
1689
+ get: function () {
1690
+ return log;
1691
+ }
1692
+ });
1681
1693
  Object.defineProperty(exports, 'registerSpaEvents', {
1682
1694
  enumerable: true,
1683
1695
  get: function () {