ref0-git 0.27.0 → 0.29.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.
Files changed (49) hide show
  1. package/app/apps/github/README.md +1 -5
  2. package/app/apps/github/package.json +0 -1
  3. package/app/apps/github/src/signin/auth.ts +17 -89
  4. package/app/apps/github/src/signin/credentials.ts +10 -14
  5. package/app/apps/github/src/signin/guarded-write.ts +19 -0
  6. package/app/apps/github/src/signin/owner-names.ts +11 -41
  7. package/app/apps/github/src/signin/unborn.ts +20 -30
  8. package/app/apps/github/tsconfig.json +0 -2
  9. package/app/pnpm-workspace.yaml +14 -34
  10. package/dist/cli/documents.mjs +39 -25
  11. package/dist/cli/keys.mjs +9 -3
  12. package/dist/cli/node.mjs +1 -2
  13. package/dist/cli/runtime.mjs +3 -4
  14. package/dist/cli/setup.mjs +216 -468
  15. package/dist/cli/tools-node.mjs +8 -7
  16. package/dist/cli/tools.mjs +3 -3
  17. package/dist/cli/vercel-stores.mjs +287 -0
  18. package/dist/init/app.mjs +4 -37
  19. package/dist/init/choices.mjs +62 -209
  20. package/dist/init/cloudflare.mjs +1 -2
  21. package/dist/init/detect.mjs +77 -167
  22. package/dist/init/files.mjs +2 -12
  23. package/dist/init/frameworks.mjs +50 -174
  24. package/dist/init/git-module.mjs +5 -1
  25. package/dist/init/metadata.mjs +4 -22
  26. package/dist/init/next.mjs +13 -66
  27. package/dist/init/output.mjs +3 -6
  28. package/dist/init/plan.mjs +1 -29
  29. package/dist/init/routes.mjs +1 -78
  30. package/dist/init/stores.mjs +6 -35
  31. package/dist/init/template.mjs +14 -49
  32. package/dist/init/templates.mjs +30 -115
  33. package/dist/init/vercel-regions.mjs +87 -0
  34. package/dist/init/vercel.mjs +313 -212
  35. package/dist/init/versions.mjs +3 -3
  36. package/package.json +5 -11
  37. package/app/apps/github/migrations/postgres/0001_auth.sql +0 -53
  38. package/app/apps/github/src/camo/lookup.ts +0 -23
  39. package/app/apps/github/src/camo/node.ts +0 -50
  40. package/app/apps/github/src/signin/person-lock.ts +0 -104
  41. package/dist/cli/sqlite.mjs +0 -28
  42. package/dist/init/astro.mjs +0 -49
  43. package/dist/init/create.mjs +0 -152
  44. package/dist/init/mounts.mjs +0 -104
  45. package/dist/init/node-app.mjs +0 -196
  46. package/dist/init/node.mjs +0 -446
  47. package/dist/init/nuxt.mjs +0 -240
  48. package/dist/init/react-router.mjs +0 -59
  49. package/dist/init/sveltekit.mjs +0 -141
@@ -1,20 +1,16 @@
1
1
  import { choices, movesOf, platformOf, recovered, saysOf, settle, withDefaults } from "../init/choices.mjs";
2
2
  import { appOutput, checkedManifest, copied, entered } from "../init/app.mjs";
3
- import { nodeAppOutput, startOrigin } from "../init/node-app.mjs";
4
3
  import { adminsVar, configParts, gitClasses, gitSecrets } from "../init/cloudflare.mjs";
5
4
  import { platforms } from "../init/template.mjs";
6
5
  import { pnpmManual, withPnpmOverrides, wroteOf } from "../init/files.mjs";
7
- import { keepsData, mainOrigin, nodeNeeds, routed, routedFindings } from "../init/node.mjs";
8
6
  import { detect } from "../init/detect.mjs";
7
+ import { nextFindings } from "../init/next.mjs";
9
8
  import { outputOf as outputOf$1, secretFilesOf } from "../init/output.mjs";
9
+ import { plan } from "../init/plan.mjs";
10
10
  import { appPackages, peerPackages, release } from "../init/metadata.mjs";
11
- import { detectFrameworks, frameworkFor, newFramework, othersRow } from "../init/frameworks.mjs";
12
- import { creatable, createCommand, createFailed, createPlatforms, created, creatorFolder, creators } from "../init/create.mjs";
13
- import { nuxtFindings, nuxtJobsPlugin } from "../init/nuxt.mjs";
14
- import { nextFindings, nextJobRoutes } from "../init/next.mjs";
15
- import { svelteBodyLimit, svelteStart } from "../init/sveltekit.mjs";
16
- import { variablesOf, vercelProblems } from "../init/vercel.mjs";
17
- import { addedTo, plan } from "../init/plan.mjs";
11
+ import { variablesOf, vercelNextOf, vercelProblems } from "../init/vercel.mjs";
12
+ import { neonRegionOf, regionQuestion, settleRegion, vercelRegions } from "../init/vercel-regions.mjs";
13
+ import { itemsAt, parseJsonc, stringAt } from "../init/jsonc.mjs";
18
14
  import { dropInPrefixes } from "../init/routes.mjs";
19
15
  import { contentNamed, published, unpacked } from "../init/versions.mjs";
20
16
  import { catalogOf } from "../init/workspace.mjs";
@@ -26,10 +22,10 @@ import { outdated, vendored } from "./vendor.mjs";
26
22
  import { Folders } from "./folders.mjs";
27
23
  import { gitRun } from "./git.mjs";
28
24
  import { node } from "./node.mjs";
29
- import { Sqlite } from "./sqlite.mjs";
30
25
  import { CliModes, answer, cliDocument, field, nextDocument, printable, receipt, say, secrets, stderrText } from "./output.mjs";
31
26
  import { initKeysDocument, initKeysFields, initKeysNext, keysOnInit } from "./keys.mjs";
32
27
  import { select } from "./prompt.mjs";
28
+ import { storesAsked, storesDocument, storesFields, storesFindings, storesFound, storesLeftOf, storesMade } from "./vercel-stores.mjs";
33
29
  import * as Effect from "effect/Effect";
34
30
  import * as Exit from "effect/Exit";
35
31
  import * as Redacted from "effect/Redacted";
@@ -96,10 +92,9 @@ const folderOf = /* @__PURE__ */ Effect.fnUntraced(function* (dir) {
96
92
  };
97
93
  });
98
94
  /** The project in `folder`, or the failure that says why Git can't go there. */
99
- const projectIn = (view, platform, framework) => {
100
- const found = detect(view, platform, framework);
101
- if (!("reason" in found)) return Effect.succeed(found);
102
- return Effect.fail(found.reason === "not_on_platform" ? usageFailure(found.reason, found.headline) : failure(found.reason, found.headline));
95
+ const projectIn = (view) => {
96
+ const found = detect(view);
97
+ return "reason" in found ? Effect.fail(failure(found.reason, found.headline)) : Effect.succeed(found);
103
98
  };
104
99
  /** 32 random bytes, as hex: a secret only the folder holds, which nothing printed may show. */
105
100
  const madeSecret = () => {
@@ -114,7 +109,7 @@ const madeSecret = () => {
114
109
  * `overrides` it can't merge into is a manual step instead.
115
110
  */
116
111
  const outputOf = (choices, project, source, vendor, pnpm) => {
117
- const output = choices.app === "ref0" && source.app !== void 0 ? (choices.platform === "node" ? nodeAppOutput : appOutput)(choices, project.name, source.app, madeSecret, vendor) : outputOf$1(choices, project, madeSecret, vendor);
112
+ const output = choices.app === "ref0" && source.app !== void 0 ? appOutput(choices, project.name, source.app, madeSecret, vendor) : outputOf$1(choices, project, madeSecret, vendor);
118
113
  if (pnpm === void 0) return output;
119
114
  const manual = pnpmManual(pnpm.workspace, vendor);
120
115
  if (manual !== void 0) return {
@@ -384,14 +379,12 @@ const asRun = () => process.argv.slice(2);
384
379
  const valueFlags = /* @__PURE__ */ new Set([
385
380
  "serve",
386
381
  "platform",
387
- "records",
388
382
  "objects",
389
- "bucket",
390
383
  "base-path",
391
384
  "name",
392
385
  "package-manager",
393
- "from-checkout",
394
- "vercel-plan"
386
+ "region",
387
+ "from-checkout"
395
388
  ].map((flag) => `--${flag}`));
396
389
  /**
397
390
  * `args` without each of `flags`, and the value of one that takes a value, as the next argument
@@ -400,25 +393,15 @@ const valueFlags = /* @__PURE__ */ new Set([
400
393
  const without = (args, flags) => args.filter((arg, at) => !flags.some((flag) => arg === flag || arg.startsWith(`${flag}=`)) && !(flags.includes(args[at - 1] ?? "") && valueFlags.has(args[at - 1] ?? "")));
401
394
  /** Every spelling of each choice's flag, as `init` takes it. */
402
395
  const choiceFlags = choices.flatMap((choice) => [`--${choice.flag}`, `--no-${choice.flag}`]);
403
- /** The flags whose answers follow the platform's, which a move back to Cloudflare could refuse. */
404
- const platformFlags = [
405
- "--records",
406
- "--bucket",
407
- "--vercel-plan"
408
- ];
409
396
  /**
410
- * The ways out of `app_held`, as commands: this one serving GitHub on Cloudflare, which keeps the app, or the
411
- * same flags for a new folder beside this one, for Git without it.
397
+ * The ways out of `app_held`, as commands: this one serving GitHub on Cloudflare, which keeps the
398
+ * app, or the same flags for a new folder beside this one, for Git without it.
412
399
  */
413
400
  const keepOrMove = (folder) => {
414
401
  const [command = "init", ...rest] = asRun();
415
402
  const at = rest.findIndex((arg, index) => folder.argv.includes(arg) && !valueFlags.has(rest[index - 1] ?? ""));
416
403
  const flags = rest.filter((_, index) => index !== at);
417
- const serving = without(flags.filter((arg) => arg !== "--no-app"), [
418
- "--serve",
419
- "--platform",
420
- ...platformFlags
421
- ]);
404
+ const serving = without(flags.filter((arg) => arg !== "--no-app"), ["--serve", "--platform"]);
422
405
  return {
423
406
  says: "Keep the app, serving GitHub, or set up Git without it in a new folder",
424
407
  run: [[
@@ -465,18 +448,15 @@ const written = /* @__PURE__ */ Effect.fnUntraced(function* (folder, steps) {
465
448
  * The plan carried out: printed under `--dry-run`; refused whole when a file differs, so nothing
466
449
  * changes; else written, installed, and said, with the next step `doctor`.
467
450
  */
468
- const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, project, settled, output, steps, packed, create) {
451
+ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, project, settled, output, steps, packed, storing) {
469
452
  const mode = yield* CliModes;
470
- const manager = Option.getOrElse(flags.packageManager, () => project.packageManager.value);
471
- const doctorStep = {
472
- says: output.next,
473
- run: [["doctor", ...folder.argv]]
474
- };
453
+ const manager = project.packageManager.value;
454
+ const saysAfter = (stores) => stores === void 0 ? output.next : vercelNextOf(stores.plan.region, stores.plan.name, storesLeftOf(stores), folder.argv[0]);
475
455
  const differs = steps.filter((step) => step.action === "differs");
476
456
  const changes = steps.filter((step) => step.text !== void 0 && step.action !== "unchanged");
477
457
  const installed = yield* (yield* FileSystem.FileSystem).exists(`${folder.path}/node_modules/@ref0/git`).pipe(Effect.orElseSucceed(() => false));
478
458
  const installing = flags.install && !flags.dryRun && !output.manual.some((step) => step.path === "pnpm-workspace.yaml") && (changes.some((step) => step.path === "package.json") || !installed);
479
- const signing = settled.platform.value === "cloudflare" && settled.objects.value === "packs" && settled.bucket.value === "r2";
459
+ const signing = settled.platform.value === "cloudflare" && settled.objects.value === "packs";
480
460
  const keysRun = [["doctor", ...folder.argv], ["keys", ...folder.argv]];
481
461
  const keysStep = {
482
462
  says: `${output.next}; once it's deployed, put R2's keys on it, so its LFS links sign straight to the bucket`,
@@ -486,7 +466,11 @@ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, proje
486
466
  says: `${output.next}; once it's deployed, put R2's keys on it: keys mints a Cloudflare token; run it yourself`,
487
467
  run: keysRun
488
468
  };
489
- const nextOf = (keys) => {
469
+ const nextOf = (keys, stores) => {
470
+ const doctorStep = {
471
+ says: saysAfter(stores),
472
+ run: [["doctor", ...folder.argv]]
473
+ };
490
474
  const recovery = initKeysNext(keys);
491
475
  if (recovery !== void 0) return {
492
476
  says: `${recovery.says}; then check it`,
@@ -495,74 +479,58 @@ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, proje
495
479
  if (!signing || keys?.kind === "put" || keys?.kind === "present") return doctorStep;
496
480
  return keys?.kind === "notAsked" ? notAskedStep : keysStep;
497
481
  };
498
- const documentOf = (ran, keys) => ({
482
+ const needsAfter = (stores) => {
483
+ if (stores === void 0) return output.needs;
484
+ const left = storesLeftOf(stores);
485
+ return output.needs.filter((name) => name === "BLOB_READ_WRITE_TOKEN" ? left.blob : name === "DATABASE_URL" || name === "DATABASE_URL_UNPOOLED" ? left.postgres : true);
486
+ };
487
+ const documentOf = (ran, keys, stores) => ({
499
488
  folder: folder.path,
500
489
  project: project.project,
501
490
  dryRun: flags.dryRun,
502
491
  moves: movesOf(settled),
503
492
  choices: {
504
- ...Object.fromEntries(Object.entries(settled).filter(([key, each]) => key !== "vercelPlan" || each.value !== "none")),
505
- framework: project.framework === void 0 ? null : create === void 0 ? {
493
+ ...settled,
494
+ framework: project.framework === void 0 ? null : {
506
495
  value: project.framework.name,
507
496
  from: "detected",
508
497
  detectedFrom: "package.json"
509
- } : {
510
- value: project.framework.name,
511
- from: "flag"
512
498
  },
513
499
  name: {
514
500
  value: project.name,
515
501
  from: "detected"
516
502
  },
517
- packageManager: Option.isSome(flags.packageManager) ? {
518
- value: manager,
519
- from: "flag"
520
- } : project.packageManager
503
+ packageManager: project.packageManager,
504
+ region: project.region ?? null
521
505
  },
522
- files: steps.map((step) => {
523
- const added = flags.dryRun && create !== void 0 && step.action === "merge" && step.path === "package.json" && step.from !== void 0 && step.text !== void 0 ? addedTo(step.from, step.text) : void 0;
524
- return {
525
- path: step.path,
526
- action: step.action,
527
- secrets: step.secrets,
528
- content: flags.dryRun && step.secrets === void 0 && step.action === "create" ? step.text : void 0,
529
- patch: added === void 0 && (flags.dryRun || step.action === "differs") ? step.patch : void 0,
530
- adds: added,
531
- edit: step.edit
532
- };
533
- }),
506
+ files: steps.map((step) => ({
507
+ path: step.path,
508
+ action: step.action,
509
+ secrets: step.secrets,
510
+ content: flags.dryRun && step.secrets === void 0 && step.action === "create" ? step.text : void 0,
511
+ patch: flags.dryRun || step.action === "differs" ? step.patch : void 0
512
+ })),
534
513
  manual: output.manual,
535
- needs: output.needs,
536
- create: create === void 0 ? void 0 : {
537
- command: {
538
- line: create.command.line,
539
- argv: create.command.argv
540
- },
541
- exit: create.exit
542
- },
514
+ needs: needsAfter(stores),
543
515
  install: {
544
516
  manager,
545
517
  packages: output.packages.map((each) => `${each}@${release}`),
546
518
  ran
547
519
  },
548
520
  keys: initKeysDocument(keys),
549
- nextStep: nextDocument(nextOf(keys))
521
+ ...stores !== void 0 && { stores: storesDocument(stores) },
522
+ nextStep: nextDocument(nextOf(keys, stores))
550
523
  });
551
524
  const manualLines = output.manual.flatMap((step) => [
552
525
  "",
553
526
  ` ${step.says}, in ${step.path}:`,
554
527
  ...step.lines
555
528
  ]);
556
- const editLines = steps.flatMap(({ path, edit }) => edit === void 0 ? [] : [
557
- "",
558
- ...edit.adds.length > 0 ? [` Adds after \`${edit.anchor}\`, in ${path}:`, ...edit.adds] : [],
559
- ...edit.swaps.map((swap) => ` Swaps ${swap.from} for ${swap.to}, in ${path}`)
560
- ]);
561
529
  if (flags.dryRun) {
562
- if (mode.json) return yield* cliDocument(initJson, documentOf(false));
530
+ const stores = storing === void 0 ? void 0 : yield* storesMade(storing.plan, storing.asked);
531
+ if (mode.json) return yield* cliDocument(initJson, documentOf(false, void 0, stores));
563
532
  if (manualLines.length > 0) yield* say(...manualLines);
564
- if (editLines.length > 0) yield* say(...editLines);
565
- return yield* answer([...create === void 0 ? [] : [`run\t${create.command.line}`], ...steps.map((step) => `${step.action}\t${step.path}`)].join("\n"));
533
+ return yield* answer(steps.map((step) => `${step.action}\t${step.path}`).join("\n"));
566
534
  }
567
535
  if (differs.length > 0) {
568
536
  if (!mode.json) yield* say(...differs.flatMap((step) => ["", ...(step.patch ?? "").trimEnd().split("\n")]));
@@ -592,6 +560,16 @@ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, proje
592
560
  const wrote = yield* written(folder.path, steps);
593
561
  if (packed !== void 0) yield* outdated(packed, folder.path);
594
562
  const kept = wroteOf(wrote, settled.app.value === "ref0");
563
+ const canceledHaving = (during, says = "Check it") => new CliFailure({
564
+ class: "cancelled",
565
+ reason: "canceled",
566
+ headline: `Canceled${during}, having written ${kept}`,
567
+ next: {
568
+ says,
569
+ run: [["doctor", ...folder.argv]]
570
+ }
571
+ });
572
+ cancelled.left = canceledHaving("");
595
573
  const installStep = {
596
574
  says: `Run \`${manager} install\` in ${printable(folder.path)}, then check it`,
597
575
  run: [["doctor", ...folder.argv]]
@@ -605,7 +583,7 @@ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, proje
605
583
  });
606
584
  yield* say(` Installing ${output.packages.length} packages with ${manager}...`);
607
585
  const status = yield* install(manager, folder.path);
608
- delete cancelled.left;
586
+ cancelled.left = canceledHaving("");
609
587
  if (status !== 0) return yield* failure("install_failed", `${manager} install failed, after init wrote ${kept}`, installStep);
610
588
  }
611
589
  if (output.manual.length > 0) {
@@ -622,12 +600,27 @@ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, proje
622
600
  }));
623
601
  }
624
602
  const keys = signing ? yield* keysOnInit(folder, platforms.cloudflare.signing, flags.keys) : void 0;
625
- if (mode.json) return yield* cliDocument(initJson, documentOf(installing, keys));
603
+ if (storing?.asked.kind === "make") cancelled.left = canceledHaving(" while init made the stores", "A store Vercel began may still be made: read the project's Production with `vercel env ls production` before you run init again, then check it");
604
+ const stores = storing === void 0 ? void 0 : yield* storesMade(storing.plan, storing.asked);
605
+ cancelled.left = canceledHaving("");
606
+ const storeFields = stores === void 0 ? [] : storesFields(stores);
607
+ const failedStores = stores === void 0 ? [] : [...stores.blob.state === "failed" ? [`the Blob store (${stores.blob.why ?? ""})`] : [], ...stores.postgres.state === "failed" ? [`Neon's Postgres (${stores.postgres.why ?? ""})`] : []];
608
+ if (stores !== void 0 && failedStores.length > 0) {
609
+ if (!mode.json) yield* say(...storeFields.map(field));
610
+ return yield* Effect.fail(new CliFailure({
611
+ class: "failed",
612
+ reason: "store_failed",
613
+ headline: `Git's files are written, and init couldn't make ${failedStores.join(" or ")}`,
614
+ next: nextOf(keys, stores),
615
+ data: documentOf(installing, keys, stores)
616
+ }));
617
+ }
618
+ if (mode.json) return yield* cliDocument(initJson, documentOf(installing, keys, stores));
626
619
  if (!mode.stdoutTerminal || !mode.interactive) yield* answer(folder.path);
627
620
  if (changes.length === 0) return yield* receipt({
628
621
  done: `Nothing to change: ${printable(folder.path)} is set up as init writes it`,
629
- fields: initKeysFields(keys),
630
- next: nextOf(keys)
622
+ fields: [...initKeysFields(keys), ...storeFields],
623
+ next: nextOf(keys, stores)
631
624
  });
632
625
  const secret = changes.some((step) => step.secrets !== void 0);
633
626
  yield* receipt({
@@ -635,114 +628,12 @@ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, proje
635
628
  fields: [
636
629
  ["Wrote", kept],
637
630
  ...secret ? [["Secret", output.secret]] : [],
638
- ...output.needs.length > 0 ? [["Still needed", output.needs.join(", ")]] : [],
639
- ...initKeysFields(keys)
631
+ ...needsAfter(stores).length > 0 ? [["Still needed", needsAfter(stores).join(", ")]] : [],
632
+ ...initKeysFields(keys),
633
+ ...storeFields
640
634
  ],
641
- next: nextOf(keys)
642
- });
643
- });
644
- /**
645
- * `--framework` read against the folder, before anything else is: in a project with frameworks,
646
- * one of them, which detection then takes; in a folder holding at most `.git`, the new app to
647
- * make; anywhere else, refused.
648
- */
649
- const framed = /* @__PURE__ */ Effect.fnUntraced(function* (named, app, view) {
650
- if (named === void 0) return void 0;
651
- if (Option.isSome(app)) return yield* usageFailure("app_choices_conflict", `--framework ${named} and ${app.value ? "--app" : "--no-app"} are one choice: pass one of them`);
652
- const found = detectFrameworks(view);
653
- if (found.length > 0) {
654
- const picked = frameworkFor(found, named);
655
- if (picked !== void 0 && "reason" in picked) return yield* usageFailure(picked.reason, picked.headline);
656
- return;
657
- }
658
- yield* holdsAtMostGit(named, view.entries);
659
- return {
660
- name: named,
661
- says: newFramework(named).says
662
- };
663
- });
664
- /**
665
- * A create command runs in place, where a file it writes, or one beside it, would stop it, and
666
- * create-nuxt's `--force` would write over it: the folder may hold `.git` alone.
667
- */
668
- const holdsAtMostGit = (named, entries) => {
669
- const present = entries.filter((entry) => entry !== ".git");
670
- return present.length === 0 ? Effect.void : failure("framework_needs_new_project", `--framework ${named} runs its create command in a folder holding at most .git, and this one holds ${present.join(", ")}`, {
671
- says: `Move ${present.length === 1 ? "it" : "them"} aside, or run init in an empty folder`,
672
- run: [asRun()]
673
- });
674
- };
675
- /**
676
- * `named`'s create command run in `folder`, first: with stdin closed and its output on stderr. A
677
- * failed one, or one that left no `package.json` naming the framework, is `create_failed`, and
678
- * what it left stays. Answers the folder as it left it.
679
- */
680
- const createIn = /* @__PURE__ */ Effect.fnUntraced(function* (folder, named, command) {
681
- const [program = "npx", ...args] = command.argv;
682
- yield* (yield* FileSystem.FileSystem).makeDirectory(folder, { recursive: true }).pipe(Effect.mapError(diskFailed(`make ${printable(folder)}`)));
683
- yield* holdsAtMostGit(named, (yield* viewOf(folder)).entries);
684
- cancelled.left = new CliFailure({
685
- class: "cancelled",
686
- reason: "canceled",
687
- headline: `Canceled during ${creators[named]}, before init wrote anything`,
688
- next: void 0
635
+ next: nextOf(keys, stores)
689
636
  });
690
- yield* say(` Running ${command.line}...`);
691
- const ended = yield* runChild([program, ...args], folder);
692
- delete cancelled.left;
693
- const view = yield* viewOf(folder);
694
- if (ended.exit !== 0 || !created(named, view.read("package.json"))) {
695
- const left = view.entries.filter((entry) => entry !== ".git");
696
- const refused = createFailed(named, command, ended, left);
697
- return yield* new CliFailure({
698
- class: "failed",
699
- reason: refused.reason,
700
- headline: refused.headline,
701
- next: {
702
- says: left.length === 0 ? "Run init again" : `Remove ${left.join(", ")}, which it left, then run init again`,
703
- run: [asRun()]
704
- },
705
- data: refused.data
706
- });
707
- }
708
- return {
709
- view,
710
- created: {
711
- command,
712
- exit: ended.exit
713
- }
714
- };
715
- });
716
- /**
717
- * The folder Git goes in, and its project: as found, or, for `--framework`, as its create command
718
- * leaves it, run first, or under `--dry-run` as its template would.
719
- */
720
- const madeFor = /* @__PURE__ */ Effect.fnUntraced(function* (creating, flags, folder, view, project, chosen) {
721
- if (creating === void 0) return {
722
- view,
723
- project,
724
- created: void 0
725
- };
726
- const manager = Option.getOrElse(flags.packageManager, () => project.packageManager.value);
727
- const command = createCommand(creating.name, ".", manager, chosen.platform);
728
- const left = flags.dryRun ? {
729
- view: creatorFolder(creating.name, view, project.name),
730
- created: {
731
- command,
732
- exit: null
733
- }
734
- } : yield* createIn(folder, creating.name, command);
735
- const after = yield* projectIn(left.view, chosen.platform);
736
- return {
737
- view: left.view,
738
- project: {
739
- ...after,
740
- name: project.name,
741
- project: project.project,
742
- created: true
743
- },
744
- created: left.created
745
- };
746
637
  });
747
638
  const init = Command.make("init", {
748
639
  dir: dirArgument("The folder to set up, made when it doesn't exist: the current one when left out"),
@@ -751,28 +642,10 @@ const init = Command.make("init", {
751
642
  "api",
752
643
  "git"
753
644
  ], "What to serve: GitHub's APIs, Git's REST, or Git's protocol only"),
645
+ platform: literals("platform", ["cloudflare", "vercel"], "Where it runs"),
754
646
  app: toggle("app", "Add the web app, or --no-app for only the APIs"),
755
- framework: literals("framework", creatable, "Make a new app with the framework's own create command, in an empty folder, then add Git to it"),
756
- platform: literals("platform", [
757
- "cloudflare",
758
- "vercel",
759
- "node"
760
- ], "Where it runs"),
761
- records: literals("records", [
762
- "durable-objects",
763
- "postgres",
764
- "turso",
765
- "sqlite"
766
- ], "Where Git keeps its records"),
767
- objects: literals("objects", ["packs", "loose"], "Packs in a bucket, or loose objects in the records"),
768
- bucket: literals("bucket", [
769
- "r2",
770
- "vercel-blob",
771
- "s3",
772
- "disk"
773
- ], "The packs' bucket"),
647
+ objects: literals("objects", ["packs", "loose"], "Packs in the platform's bucket, or loose objects in the records"),
774
648
  queue: toggle("queue", "Run a merge queue on main, or --no-queue"),
775
- vercelPlan: literals("vercel-plan", ["hobby", "pro"], "The Vercel team's plan, which sets the cron's schedule and a function's longest run"),
776
649
  basePath: Flag.String("base-path").pipe(Flag.withDescription("The path Git's URLs are under, such as /git"), Flag.withMetavar("PATH"), Flag.optional),
777
650
  name: Flag.String("name").pipe(Flag.withDescription("The Worker's name"), Flag.withMetavar("NAME"), Flag.optional),
778
651
  packageManager: literals("package-manager", [
@@ -781,37 +654,37 @@ const init = Command.make("init", {
781
654
  "yarn",
782
655
  "bun"
783
656
  ], "The package manager that installs it"),
657
+ region: literals("region", vercelRegions, "On Vercel, the region the Functions and the Daemon run in, where your database and Blob store are or will be, as each request and job crosses to them: init asks for it, and a run that can't ask stops without it"),
784
658
  install: Flag.Boolean("install").pipe(Flag.withDescription("Install the packages once the files are written, or --no-install"), Flag.withDefault(true)),
785
659
  yes: Flag.Boolean("yes").pipe(Flag.withDescription("Take the recommended answer for each choice the flags and the folder leave open"), Flag.withDefault(false)),
786
660
  fromCheckout: Flag.String("from-checkout").pipe(Flag.withDescription("Take the app, Git's packages and ref0-git from a ref-0/git checkout, packed into vendor/, until they're on npm"), Flag.withMetavar("DIR"), Flag.optional),
787
661
  dryRun: Flag.Boolean("dry-run").pipe(Flag.withDescription("Print the plan, each file and its action, and change nothing"), Flag.withDefault(false)),
788
- keys: Flag.Boolean("keys").pipe(Flag.withDescription("On Cloudflare with R2, put R2's keys on a deployed Worker that lacks them, when a person runs init at a terminal, or --no-keys"), Flag.withDefault(true))
662
+ keys: Flag.Boolean("keys").pipe(Flag.withDescription("On Cloudflare with packs in R2, put R2's keys on a deployed Worker that lacks them, when a person runs init at a terminal, or --no-keys"), Flag.withDefault(true)),
663
+ stores: toggle("stores", "On Vercel, make the linked project's private Blob store and Neon's Postgres in --region, each where its Production lacks it: Neon bills the team, and a Postgres of your own, both DATABASE_URL and DATABASE_URL_UNPOOLED set, takes none. Without it, init asks a person at a terminal and makes none in any other run, or with --no-stores, and its next step names the commands")
789
664
  }, /* @__PURE__ */ Effect.fnUntraced(function* (flags) {
790
665
  const mode = yield* CliModes;
791
666
  const fileSystem = yield* FileSystem.FileSystem;
792
667
  const folder = yield* folderOf(flags.dir);
793
668
  const view = yield* viewOf(folder.path);
794
- const creating = yield* framed(Option.getOrUndefined(flags.framework), flags.app, view);
795
- const project = yield* projectIn(view, Option.getOrUndefined(flags.platform), Option.getOrUndefined(flags.framework));
796
- const newApp = creating && {
797
- says: creating.says,
798
- platforms: createPlatforms[creating.name]
799
- };
800
- const named = Option.getOrUndefined(flags.name);
801
- const placed = named === void 0 ? project : {
669
+ const project = yield* projectIn(view);
670
+ const managed = {
802
671
  ...project,
803
- name: named
672
+ name: Option.getOrElse(flags.name, () => project.name),
673
+ packageManager: Option.match(flags.packageManager, {
674
+ onNone: () => project.packageManager,
675
+ onSome: (value) => ({
676
+ value,
677
+ from: "flag"
678
+ })
679
+ })
804
680
  };
805
681
  const flagged = {
806
682
  serve: Option.getOrUndefined(flags.serve),
807
- app: creating === void 0 ? Option.getOrUndefined(Option.map(flags.app, (on) => on ? "ref0" : "none")) : "framework",
808
683
  platform: Option.getOrUndefined(flags.platform),
809
- records: Option.getOrUndefined(flags.records),
684
+ app: Option.getOrUndefined(Option.map(flags.app, (on) => on ? "ref0" : "none")),
810
685
  objects: Option.getOrUndefined(flags.objects),
811
- bucket: Option.getOrUndefined(flags.bucket),
812
686
  queue: Option.getOrUndefined(Option.map(flags.queue, (on) => on ? "on" : "off")),
813
- basePath: Option.getOrUndefined(flags.basePath),
814
- vercelPlan: Option.getOrUndefined(flags.vercelPlan)
687
+ basePath: Option.getOrUndefined(flags.basePath)
815
688
  };
816
689
  const given = Object.fromEntries(Object.entries(flagged).filter(([, value]) => value !== void 0));
817
690
  cancelled.left = new CliFailure({
@@ -821,13 +694,36 @@ const init = Command.make("init", {
821
694
  next: void 0
822
695
  });
823
696
  if (!mode.json) yield* say(field(["Folder", printable(project.says)]));
824
- const others = othersRow(project.frameworks, project.framework);
825
- if (!mode.json && project.framework !== void 0) yield* say(field(["Framework", printable(project.framework.row)]), ...others === void 0 ? [] : [field(["", printable(others)])]);
697
+ if (!mode.json && project.framework !== void 0) yield* say(field(["Framework", printable(project.framework.row)]));
826
698
  const { settled, chosen, open, conflicts } = yield* settle(given, project.detected, project.project, flags.yes, (choice, offers) => mode.interactive ? select(choice.row, choice.question, offers.map((offer, at) => ({
827
699
  value: offer.value,
828
700
  label: `${offer.says}${at === 0 ? " (recommended)" : ""}: ${offer.why}`
829
- }))) : Effect.succeed(void 0), newApp, project.framework?.says ?? newApp?.says).pipe(Effect.mapError((refused) => usageFailure(refused.reason, refused.headline, refused.reason === "app_held" ? keepOrMove(folder) : void 0)));
701
+ }))) : Effect.succeed(void 0), project.framework?.says).pipe(Effect.mapError((refused) => usageFailure(refused.reason, refused.headline, refused.reason === "app_held" ? keepOrMove(folder) : void 0)));
830
702
  const openChoices = choices.filter((choice) => open.includes(choice.key));
703
+ if (Option.isSome(flags.region) && chosen.platform !== "vercel") return yield* usageFailure("not_on_platform", "--region places Vercel's Functions and Daemon: on Cloudflare, a Worker runs near each request", given.platform === void 0 && project.detected.platform === void 0 ? {
704
+ says: "Run it on Vercel",
705
+ run: [[
706
+ ...asRun(),
707
+ "--platform",
708
+ "vercel"
709
+ ]]
710
+ } : {
711
+ says: "Run it without --region",
712
+ run: [without(asRun(), ["--region"])]
713
+ });
714
+ const storeFlags = ["--stores", "--no-stores"];
715
+ if (Option.isSome(flags.stores) && chosen.platform !== "vercel") return yield* usageFailure("not_on_platform", "--stores makes Vercel's Blob store and Postgres: on Cloudflare, init names R2's bucket and D1 in wrangler.jsonc", given.platform === void 0 && project.detected.platform === void 0 ? {
716
+ says: "Run it on Vercel",
717
+ run: [[
718
+ ...asRun(),
719
+ "--platform",
720
+ "vercel"
721
+ ]]
722
+ } : {
723
+ says: `Run it without ${flags.stores.value ? "--stores" : "--no-stores"}`,
724
+ run: [without(asRun(), storeFlags)]
725
+ });
726
+ const regionOpen = chosen.platform === "vercel" && Option.isNone(flags.region) && project.region === void 0;
831
727
  const settling = conflicts.filter((each) => each.change[0] === each.by[0]);
832
728
  const shown = settling.length > 0 ? settling : conflicts;
833
729
  const settles = recovered(given, project.detected, project.project, conflicts);
@@ -855,8 +751,11 @@ const init = Command.make("init", {
855
751
  if (open.length > 0) return yield* Effect.fail(new CliFailure({
856
752
  class: "usage",
857
753
  reason: "choices_open",
858
- headline: `init can't ask here, and ${open.length} ${open.length === 1 ? "choice is" : "choices are"} open: ${openChoices.map((choice) => `--${choice.flag}`).join(", ")}`,
859
- next: {
754
+ headline: `init can't ask here, and ${open.length} ${open.length === 1 ? "choice is" : "choices are"} open: ${openChoices.map((choice) => `--${choice.flag}`).join(", ")}${regionOpen ? ", and on Vercel --region, which has no default" : ""}`,
755
+ next: regionOpen ? {
756
+ says: "See the regions --region takes, then name it with the rest",
757
+ run: [["init", "--help"]]
758
+ } : {
860
759
  says: "Take the recommended answers, or name each one",
861
760
  run: [[...asRun(), "--yes"], [...asRun(), ...openChoices.flatMap((choice) => choice.named(chosen[choice.key]))]]
862
761
  },
@@ -865,16 +764,40 @@ const init = Command.make("init", {
865
764
  recommended: Object.fromEntries(open.map((key) => [key, chosen[key]]))
866
765
  }
867
766
  }));
767
+ const placed = {
768
+ ...managed,
769
+ region: chosen.platform === "vercel" ? yield* settleRegion(Option.getOrUndefined(flags.region), project.region, mode.interactive && !flags.yes ? (offers) => select("Region", regionQuestion, offers.map((offer) => ({
770
+ value: offer.value,
771
+ label: `${offer.says}: ${offer.why}`
772
+ }))) : void 0).pipe(Effect.mapError((refused) => usageFailure(refused.reason, refused.headline, {
773
+ says: "See the regions --region takes",
774
+ run: [["init", "--help"]]
775
+ }))) : void 0
776
+ };
868
777
  const context = {
869
778
  project: project.project,
870
779
  chosen,
871
- folder: platformOf(project.detected),
872
- creating: newApp,
873
- framework: project.framework?.says ?? newApp?.says
780
+ framework: project.framework?.says
874
781
  };
875
782
  const rows = mode.json ? [] : choices.filter((each) => settled[each.key].from !== "prompt" && (each.shown?.(context) ?? true));
876
783
  for (const choice of rows) yield* say(rowOf(choice, settled[choice.key], context));
784
+ if (!mode.json && placed.region !== void 0 && placed.region.from !== "prompt") yield* say(field(["Region", `${placed.region.value}${regionFrom[placed.region.from]}`]));
877
785
  if (!mode.json) yield* say(...movesOf(settled).map((move) => ` ${move}`));
786
+ const storesPlan = placed.region === void 0 ? void 0 : {
787
+ folder: folder.path,
788
+ ...folder.argv[0] !== void 0 && { dir: folder.argv[0] },
789
+ name: placed.name,
790
+ region: placed.region.value
791
+ };
792
+ const storing = storesPlan === void 0 ? void 0 : {
793
+ plan: storesPlan,
794
+ asked: yield* storesAsked(storesPlan, {
795
+ stores: flags.stores,
796
+ yes: flags.yes,
797
+ dryRun: flags.dryRun,
798
+ again: asRun()
799
+ })
800
+ };
878
801
  const source = yield* sourceOf(Option.getOrUndefined(flags.fromCheckout), chosen.app === "ref0" || project.held?.app === "ref0");
879
802
  const packing = source.checkout === void 0 || flags.dryRun ? void 0 : yield* packedFrom(source.checkout);
880
803
  if (packing?.kind === "failed") return yield* failure("install_failed", `${packing.why}, so init wrote nothing`, {
@@ -883,15 +806,14 @@ const init = Command.make("init", {
883
806
  });
884
807
  const packed = packing?.packed;
885
808
  return yield* Effect.ensuring(Effect.gen(function* () {
886
- const made = yield* madeFor(creating, flags, folder.path, view, placed, chosen);
887
809
  const vendor = source.checkout === void 0 ? void 0 : packed?.vendor ?? (yield* plannedVendor(source.checkout));
888
- const pnpm = Option.getOrElse(flags.packageManager, () => made.project.packageManager.value) === "pnpm" ? { workspace: made.view.read("pnpm-workspace.yaml") } : void 0;
889
- const output = outputOf(chosen, made.project, source, vendor, pnpm);
810
+ const pnpm = placed.packageManager.value === "pnpm" ? { workspace: view.read("pnpm-workspace.yaml") } : void 0;
811
+ const output = outputOf(chosen, placed, source, vendor, pnpm);
890
812
  const held = project.held === void 0 ? void 0 : outputOf({
891
813
  ...chosen,
892
814
  ...project.held
893
- }, made.project, source, vendor, pnpm);
894
- const steps = plan(output.files, held?.files, made.view.read);
815
+ }, placed, source, vendor, pnpm);
816
+ const steps = plan(output.files, held?.files, view.read);
895
817
  const links = [];
896
818
  const vendorFolders = new Set([...vendor?.values() ?? []].map((at) => at.slice(0, at.lastIndexOf("/"))));
897
819
  for (const at of [...steps.map((step) => step.path), ...vendorFolders]) if (yield* linked(folder.path, at)) links.push(at);
@@ -904,7 +826,7 @@ const init = Command.make("init", {
904
826
  says: "Take it out of Git's index, keeping the file, then run init again",
905
827
  run: [asRun()]
906
828
  });
907
- return yield* finish(flags, folder, made.project, settled, output, steps, packed, made.created);
829
+ return yield* finish(flags, folder, placed, settled, output, steps, packed, storing);
908
830
  }), packed === void 0 ? Effect.void : fileSystem.remove(packed.folder, {
909
831
  recursive: true,
910
832
  force: true
@@ -1212,6 +1134,11 @@ const verify = /* @__PURE__ */ Effect.fnUntraced(function* (hostOption) {
1212
1134
  */
1213
1135
  const devVars = (view, files = [".dev.vars"]) => new Set(files.flatMap((file) => [...(view.read(file) ?? "").matchAll(/^[ \t]*([A-Za-z_][\w.-]*)[ \t]*=[ \t]*\S/gm)].map((line) => line[1] ?? "")));
1214
1136
  /**
1137
+ * `name`'s value in the first of `files` that sets it, unquoted: read for what it names, such as a
1138
+ * database's host, and never printed.
1139
+ */
1140
+ const devVar = (view, files, name) => files.map((file) => new RegExp(`^[ \\t]*${name}[ \\t]*=[ \\t]*(\\S.*)$`, "m").exec(view.read(file) ?? "")?.[1]).find((value) => value !== void 0)?.trim().replace(/^(["'])(.*)\1$/, "$2");
1141
+ /**
1215
1142
  * Whether a Start app's route file `name`, as `api.v3.$.ts`, takes one of the drop-in's root
1216
1143
  * prefixes: its name, `.` read as `/`, is the prefix or under it, as Start reads a flat route.
1217
1144
  */
@@ -1240,247 +1167,70 @@ const installedFinding = (project, disk) => ({
1240
1167
  says: disk.installed ? "Git's packages, in node_modules" : `Git's packages aren't installed: run \`${project.packageManager.value} install\``,
1241
1168
  blocks: "running it"
1242
1169
  });
1243
- /** `folder`'s `Disk`, for `chosen`: the app's local SQLite is read only where it keeps its records. */
1244
- const diskOf = /* @__PURE__ */ Effect.fnUntraced(function* (folder, project, chosen) {
1170
+ /** `folder`'s `Disk`. */
1171
+ const diskOf = /* @__PURE__ */ Effect.fnUntraced(function* (folder) {
1245
1172
  const fs = yield* FileSystem.FileSystem;
1246
- const sqlite = yield* Sqlite;
1247
- const { database } = platforms.node;
1248
- const listed = (at) => Effect.flatMap(fs.exists(at), (there) => there ? fs.readDirectory(at) : Effect.succeed([]));
1249
- const data = `${folder}/.data`;
1250
- const dataWritable = yield* fs.exists(data).pipe(Effect.flatMap((there) => fs.access(there ? data : folder, { writable: true })), Effect.as(true), Effect.orElseSucceed(() => false));
1251
- const local = chosen.platform === "node" && project.held?.app === "ref0" && chosen.records === "sqlite";
1252
- const file = `${folder}/${database.file}`;
1253
- const migrated = local ? yield* sqlite.migrated(file).pipe(Effect.mapError((unreadable) => failure("database_unreadable", `${printable(database.file)} isn't a SQLite database doctor can read: ${printable(String(unreadable.cause))}`, "Check the file, then run `npm run migrate` again"))) : /* @__PURE__ */ new Set();
1173
+ const routes = `${folder}/src/routes`;
1254
1174
  return {
1255
1175
  installed: yield* fs.exists(`${folder}/node_modules/@ref0/git`),
1256
- dataWritable,
1257
- sources: yield* listed(`${folder}/src`),
1258
- routes: yield* listed(`${folder}/src/routes`),
1259
- migrations: (yield* listed(`${folder}/${database.migrations}`)).filter((each) => each.endsWith(".sql")),
1260
- migrated
1176
+ routes: (yield* fs.exists(routes)) ? yield* fs.readDirectory(routes) : []
1261
1177
  };
1262
1178
  }, (reading, folder) => Effect.catchTag(reading, "PlatformError", (error) => Effect.fail(diskFailed(`read ${printable(folder)}`)(error))));
1263
- const starters = {
1264
- next: (framework) => ({
1265
- file: framework.instrumentation,
1266
- path: "instrumentation.ts",
1267
- lines: "register()",
1268
- server: "next start",
1269
- start: (manager) => `\`${manager} start\`, which loads .env`
1270
- }),
1271
- sveltekit: (framework) => ({
1272
- file: framework.hooks?.server,
1273
- path: "src/hooks.server.ts",
1274
- lines: "init hook",
1275
- server: "adapter-node's server",
1276
- start: (manager) => `\`${manager} start\`, which loads .env`
1277
- }),
1278
- nuxt: (framework) => ({
1279
- file: framework.nitro?.plugin,
1280
- path: nuxtJobsPlugin,
1281
- lines: "Nitro plugin",
1282
- server: "Nitro's Node server",
1283
- start: () => "`node .output/server/index.mjs`"
1284
- }),
1285
- astro: () => void 0,
1286
- "react-router": () => void 0,
1287
- hono: () => void 0,
1288
- express: () => void 0,
1289
- fastify: () => void 0
1290
- };
1291
- const startersOf = (framework) => starters[framework.name](framework);
1292
- /**
1293
- * How a person starts a routed framework's build, whose server module loads `.env` itself:
1294
- * Astro's template has no start script, so `@astrojs/node`'s standalone server, and React Router's
1295
- * template's `start` runs `react-router-serve`.
1296
- */
1297
- const routedStart = (framework, manager) => framework?.name === "astro" ? "`node ./dist/server/entry.mjs`" : `\`${manager} start\``;
1298
- /** `doctor`'s SvelteKit checks: adapter-node's body limit, and `hooks.ts`'s reroute of `gh`'s root URLs. */
1299
- const svelteFindings = (view, framework, chosen) => {
1300
- const lifted = svelteBodyLimit((path) => view.read(path), process.env);
1301
- const universal = framework.hooks?.universal;
1302
- const rerouted = universal !== void 0 && universal.text.includes("gitRoot");
1303
- const { adapter } = framework;
1304
- return [
1305
- {
1306
- check: "Adapter",
1307
- ok: adapter?.name === "node",
1308
- says: adapter?.name === "node" ? `${adapter.file} builds with adapter-node, whose server runs Git's jobs between requests` : `${adapter?.file ?? "vite.config.ts"} builds with ${adapter === void 0 ? "no adapter" : `adapter-${adapter.name}`}: build with adapter-node, as init printed, so node build serves Git and runs its jobs`,
1309
- blocks: "node build, and Git's jobs"
1310
- },
1311
- {
1312
- check: "Body limit",
1313
- ok: lifted !== void 0,
1314
- says: lifted !== void 0 ? `${lifted} sets BODY_SIZE_LIMIT=Infinity for node build, which lifts adapter-node's 512 KB for every route: set it where the server runs too` : `node build keeps a body limit, adapter-node's 512 KB unless BODY_SIZE_LIMIT says another: start it with ${svelteStart}, and set BODY_SIZE_LIMIT=Infinity in .env and where the server runs`,
1315
- blocks: "pushes over 512 KB"
1316
- },
1317
- ...chosen.serve === "github" ? [{
1318
- check: "Root URLs",
1319
- ok: rerouted,
1320
- says: rerouted ? `${universal.path} reroutes gh's /<owner>/<repo>.git/ URLs to ${chosen.basePath}` : `${universal?.path ?? "No src/hooks.ts"} reroutes no /<owner>/<repo>.git/ URL, so gh repo clone gets SvelteKit's 404: add the reroute init printed`,
1321
- blocks: "gh repo clone and gh pr checkout"
1322
- }] : []
1323
- ];
1324
- };
1325
- /** The Node checks every server shares: `.data` writable, the packages installed and `.env` set. */
1326
- const localFindings = (project, chosen, disk, view) => {
1327
- const variables = [...gitSecrets, ...nodeNeeds(chosen)];
1328
- const set = devVars(view, [".env"]);
1329
- const unset = variables.filter((name) => !set.has(name));
1330
- const canWrite = disk.dataWritable;
1331
- return [
1332
- ...keepsData(chosen) ? [{
1333
- check: "Data",
1334
- ok: canWrite,
1335
- says: canWrite ? ".data, writable" : "This process can't write .data",
1336
- blocks: "starting it: Git keeps its records and packs there"
1337
- }] : [],
1338
- installedFinding(project, disk),
1339
- {
1340
- check: "Variables",
1341
- ok: unset.length === 0,
1342
- says: unset.length === 0 ? `${variables.join(", ")}, set in .env` : `${unset.join(", ")} ${unset.length === 1 ? "is" : "are"} not set in .env`,
1343
- blocks: "starting it: src/git.ts stops without them"
1344
- }
1345
- ];
1346
- };
1347
- /**
1348
- * What `doctor` finds in a Node project `init` set up: its files, a server that serves Git and
1349
- * runs its jobs, a data folder it can write, the dependencies installed, and `.env`'s variables.
1350
- */
1351
- const nodeFindings = (view, project, chosen, disk, source) => {
1352
- if (project.held?.app === "ref0") return nodeAppFindings(view, project, chosen, disk, source);
1353
- const { sources } = disk;
1354
- const entry = sources.find((file) => {
1355
- const text = file === "git.ts" ? "" : view.read(`src/${file}`) ?? "";
1356
- return /from ['"]\.\/git\.ts['"]/.test(text) && /\b(?:toNode(?:Handler|Middleware)|toFetch)\(/.test(text) && /\btoJobRunner\(/.test(text);
1357
- });
1358
- const framework = project.framework;
1359
- const starter = framework === void 0 ? void 0 : startersOf(framework);
1360
- const starts = starter?.file;
1361
- const started = starts !== void 0 && /\btoJobRunner\(/.test(starts.text);
1362
- if (routed(project.framework)) return [
1363
- filesFinding(view, project, chosen, source),
1364
- ...routedFindings(chosen, project, project.framework),
1365
- ...localFindings(project, chosen, disk, view)
1366
- ];
1367
- return [
1368
- filesFinding(view, project, chosen, source),
1369
- starter === void 0 ? {
1370
- check: "Entry",
1371
- ok: entry !== void 0,
1372
- says: entry === void 0 ? "No file in src/ serves src/git.ts and starts its jobs: add the lines init printed" : `src/${entry} serves Git and runs its jobs`,
1373
- blocks: "serving Git: nothing answers its URLs or runs its jobs"
1374
- } : {
1375
- check: "Jobs",
1376
- ok: started,
1377
- says: started ? `${starts.path} starts Git's jobs in each server process` : `${starts?.path ?? `No ${starter.path}`} starts no Git jobs: add the ${starter.lines} lines init printed`,
1378
- blocks: "Git's jobs: pushes land, but nothing packs, merges or sends events"
1379
- },
1380
- ...framework?.name === "next" ? nextFindings(view.read, chosen) : [],
1381
- ...framework?.name === "sveltekit" ? svelteFindings(view, framework, chosen) : [],
1382
- ...framework?.name === "nuxt" ? nuxtFindings(framework) : [],
1383
- ...starter === void 0 ? [] : [{
1384
- check: "Push timeout",
1385
- ok: true,
1386
- says: `${starter.server} keeps Node's 300 s requestTimeout, so a push that takes longer to upload is cut off: serve Git from your own node:http server to lift it`
1387
- }],
1388
- ...starter === void 0 && project.layout.kind !== "own" ? [{
1389
- check: "Push timeout",
1390
- ok: true,
1391
- says: "Your server keeps Node's 300 s requestTimeout unless it sets one, so a push that takes longer to upload is cut off: set its requestTimeout, as src/main.ts does"
1392
- }] : [],
1393
- ...localFindings(project, chosen, disk, view)
1394
- ];
1395
- };
1396
- /**
1397
- * What `doctor` finds in the app on Node: its files, the jobs' plugin and the server's entry, its
1398
- * tables, the packages installed, and the variables it reads from `.env`, by name only.
1399
- */
1400
- const nodeAppFindings = (view, project, chosen, disk, source) => {
1401
- const { database, entry: entryPath, jobs } = platforms.node;
1402
- const plugin = view.read(jobs) ?? "";
1403
- const entry = view.read(entryPath) ?? "";
1404
- const runs = /\btoJobRunner\(/.test(plugin) && /from ['"]\.\/git\.ts['"]/.test(entry);
1405
- const files = disk.migrations;
1406
- const local = chosen.records === "sqlite";
1407
- const { migrated } = disk;
1408
- const missing = files.filter((each) => !migrated.has(each));
1409
- const variables = [...platforms.node.required, ...nodeNeeds(chosen)];
1410
- const set = devVars(view, [platforms.node.secretFile]);
1411
- const unset = variables.filter((name) => !set.has(name));
1412
- const data = keepsData(chosen);
1413
- const canWrite = disk.dataWritable;
1414
- return [
1415
- filesFinding(view, project, chosen, source),
1416
- {
1417
- check: "Entry",
1418
- ok: runs,
1419
- says: runs ? `${entryPath} serves the app and Git, and ${jobs} runs Git's jobs` : `${jobs} doesn't start Git's jobs, or ${entryPath} doesn't serve src/git.ts: run init again`,
1420
- blocks: "serving Git: nothing answers its URLs or runs its jobs"
1421
- },
1422
- local ? {
1423
- check: "Migrations",
1424
- ok: missing.length === 0,
1425
- says: missing.length === 0 ? `${database.file} holds ${files.join(", ")}` : `${database.file} lacks ${missing.join(", ")}: run \`npm run migrate\``,
1426
- blocks: "signing in: the app keeps its people there"
1427
- } : {
1428
- check: "Migrations",
1429
- ok: true,
1430
- says: `Run \`npm run migrate\` once ${chosen.records === "postgres" ? "DATABASE_URL is" : "Turso's variables are"} set: it makes the app's tables, and skips those it has`
1431
- },
1432
- ...data ? [{
1433
- check: "Data",
1434
- ok: canWrite,
1435
- says: canWrite ? ".data, writable" : "This process can't write .data",
1436
- blocks: "starting it: the app keeps its records there"
1437
- }] : [],
1438
- installedFinding(project, disk),
1439
- {
1440
- check: "Variables",
1441
- ok: unset.length === 0,
1442
- says: unset.length === 0 ? `${variables.join(", ")}, set in .env` : `${unset.join(", ")} ${unset.length === 1 ? "is" : "are"} not set in .env`,
1443
- blocks: "starting it: src/git.ts and src/env.ts stop without them"
1444
- }
1445
- ];
1446
- };
1447
- /**
1448
- * What `doctor` finds in a project `init` set up: its files as the plan has them, the Worker's
1449
- * bindings, migrations and exports, the dependencies installed, and its local secrets.
1450
- */
1451
1179
  /**
1452
1180
  * What `doctor` finds in a Vercel project `init` set up: its files, `vercel.json`'s rewrite,
1453
- * limits, trigger and cron against the plan, the packages installed, and which variables are set
1454
- * locally, by name only: the project's own are on Vercel, which `doctor` doesn't reach.
1181
+ * Next.js's when it's one, its packages, the variables `.env.example` lists, as set locally, by
1182
+ * name only, and, from `stores`, what the linked project's Production holds and where its Blob
1183
+ * store is. A `vercel` command its words quote runs in `dir`, the folder as `doctor` was given it.
1455
1184
  */
1456
- const vercelFindingsOf = (view, project, disk, chosen, source) => {
1185
+ const vercelFindingsOf = (view, project, disk, chosen, source, stores, dir) => {
1457
1186
  const next = project.framework?.name === "next" ? project.framework : void 0;
1458
1187
  const problems = vercelProblems(view.read("vercel.json"), chosen, next);
1459
1188
  const set = devVars(view, [".env", ".env.local"]);
1460
- const unset = variablesOf(chosen).filter((name) => !set.has(name) && process.env[name] === void 0);
1189
+ const unset = variablesOf().filter((name) => !set.has(name) && process.env[name] === void 0);
1190
+ const functions = functionsRegionOf(view.read("vercel.json"));
1191
+ const region = regionFinding(functions, devVar(view, [".env.local", ".env"], "DATABASE_URL") ?? process.env["DATABASE_URL"]);
1461
1192
  return [
1462
1193
  filesFinding(view, project, chosen, source),
1463
1194
  {
1464
1195
  check: "Config",
1465
1196
  ok: problems.length === 0,
1466
- says: problems.length === 0 ? next === void 0 ? "vercel.json sends Git's URLs to api/git.ts, wakes api/jobs.ts and sweeps on its cron" : `vercel.json wakes ${nextJobRoutes(next).jobs} and sweeps on its cron` : `vercel.json: ${problems.join("; ")}`,
1467
- blocks: "deploying: Git's URLs, jobs or sweep would miss their functions"
1197
+ says: problems.length === 0 ? next === void 0 ? "vercel.json sends Git's URLs to api/git.ts, and its Daemon runs every job" : "vercel.json's Daemon runs every job" : `vercel.json: ${problems.join("; ")}`,
1198
+ blocks: "deploying: Git's URLs would miss their function, or its jobs their Daemon"
1468
1199
  },
1469
1200
  ...next === void 0 ? [] : nextFindings(view.read, chosen),
1470
1201
  installedFinding(project, disk),
1202
+ ...region === void 0 ? [] : [region],
1203
+ ...storesFindings(stores, functions, dir),
1471
1204
  {
1472
1205
  check: "Variables",
1473
1206
  ok: unset.length === 0,
1474
1207
  says: unset.length === 0 ? "Each variable .env.example lists is set in .env or .env.local: `vercel env pull` fills .env.local from Development, so see Production's with `vercel env ls production`" : `${unset.join(", ")} ${unset.length === 1 ? "isn't" : "aren't"} set in .env or .env.local, which \`vercel env pull\` fills from Development: set each for Production and Development, then pull again`,
1475
- blocks: "deploying: src/git.ts stops without them"
1476
- },
1477
- {
1478
- check: "Vercel plan",
1479
- ok: true,
1480
- says: chosen.vercelPlan === "pro" ? "Pro: the cron sweeps each minute, and a clone may run 800 s" : "Hobby: a lost queue message can wait up to a day for the daily sweep: --vercel-plan pro sweeps each minute"
1208
+ blocks: "deploying: src/git.ts and the Daemon stop without them"
1481
1209
  }
1482
1210
  ];
1483
1211
  };
1212
+ /** The region `vercel.json`'s `regions` places the Functions in, its first. */
1213
+ const functionsRegionOf = (config) => stringAt(itemsAt(parseJsonc(config ?? ""), ["regions"])[0], []);
1214
+ /**
1215
+ * Whether the Neon database at `url` is in `functions`, the Functions' region: each request and
1216
+ * job crosses to it. It never blocks, since a database far away still answers, and there's none to
1217
+ * check without a Neon URL.
1218
+ */
1219
+ const regionFinding = (functions, url) => {
1220
+ const neon = url === void 0 ? void 0 : neonRegionOf(url);
1221
+ if (functions === void 0 || neon === void 0) return void 0;
1222
+ return {
1223
+ check: "Region",
1224
+ ok: true,
1225
+ says: neon.beside === functions ? `Neon's database is in ${neon.aws}, beside the Functions and the Daemon in ${functions}` : `Neon's database is in ${neon.aws}, apart from the Functions and the Daemon in ${functions}, so each request and job crosses to it: run init again with --region ${neon.beside}`
1226
+ };
1227
+ };
1228
+ /** What the receipt's Region row says of where its region came from. */
1229
+ const regionFrom = {
1230
+ flag: ", from --region",
1231
+ detected: ", from vercel.json",
1232
+ prompt: ""
1233
+ };
1484
1234
  /** The choices `doctor` checks a project against: what it holds, on its platform, else the defaults. */
1485
1235
  const chosenOf = (project) => {
1486
1236
  const platform = platformOf(project.detected);
@@ -1490,9 +1240,8 @@ const chosenOf = (project) => {
1490
1240
  ...held
1491
1241
  }, project.project);
1492
1242
  };
1493
- const findingsOf = (view, project, chosen, disk, source) => {
1494
- if (chosen.platform === "vercel") return vercelFindingsOf(view, project, disk, chosen, source);
1495
- if (chosen.platform === "node") return nodeFindings(view, project, chosen, disk, source);
1243
+ /** What `doctor` finds in a Cloudflare project `init` set up. */
1244
+ const cloudflareFindingsOf = (view, project, chosen, disk, source) => {
1496
1245
  const { main, bindings, classes: made, buckets, databases } = configParts(project.config?.file ?? "wrangler.jsonc", project.config?.text ?? "");
1497
1246
  const classesBound = gitClasses.every((each) => bindings.includes(each.name) && made.includes(each.class_name));
1498
1247
  const entry = main === void 0 ? "" : view.read(main) ?? "";
@@ -1573,24 +1322,23 @@ const setupCommands = [init, Command.make("doctor", {
1573
1322
  const project = yield* projectIn(view);
1574
1323
  const source = yield* sourceOf(void 0, project.held?.app === "ref0");
1575
1324
  const chosen = chosenOf(project);
1576
- const disk = yield* diskOf(folder.path, project, chosen);
1577
- const found = findingsOf(view, project, chosen, disk, source);
1578
- const blocking = found.filter((finding) => !finding.ok);
1325
+ const disk = yield* diskOf(folder.path);
1326
+ const found = chosen.platform === "vercel" ? vercelFindingsOf(view, project, disk, chosen, source, yield* storesFound(folder.path), folder.argv[0]) : cloudflareFindingsOf(view, project, chosen, disk, source);
1327
+ const blocking = found.filter((finding) => !finding.ok && finding.skipped !== true);
1579
1328
  const mode = yield* CliModes;
1580
1329
  if (!mode.json) yield* answer(found.map((finding) => field([finding.check, finding.says])).join("\n"));
1581
1330
  if (blocking.length > 0) return yield* failure("not_ready", blocking.map((finding) => `${finding.check}: ${finding.says}, which blocks ${finding.blocks ?? "deploying"}`).join("; "), {
1582
1331
  says: "Add what's missing, then check again",
1583
1332
  run: [["init", ...folder.argv]]
1584
1333
  }, found);
1585
- const vercel = withDefaults(project.held ?? {}, project.project).platform === "vercel";
1586
- const starter = project.framework === void 0 ? void 0 : startersOf(project.framework);
1587
1334
  const base = (project.held?.basePath ?? "/").replace(/\/+$/, "");
1588
- const served = platformOf(project.detected) === "node" && starter === void 0 && !routed(project.framework) && project.layout.kind !== "mount" ? project.held?.app === "ref0" ? startOrigin : mainOrigin : void 0;
1589
- const signIn = served === void 0 ? "sign in to it with its admin token, <host> being where it's served" : "sign in to it with its admin token";
1590
- const tokenFiles = secretFilesOf(withDefaults(project.held ?? {}, project.project));
1591
- const bootstrapped = platformOf(project.detected) !== "node" && !vercel && project.held?.app !== "ref0";
1335
+ const signIn = "sign in to it with its admin token, <host> being where it's served";
1336
+ const secrets = secretsOf(chosen).join(" and ");
1337
+ const vercel = chosen.platform === "vercel";
1338
+ const tokenFiles = secretFilesOf(chosen);
1339
+ const bootstrapped = !vercel && project.held?.app !== "ref0";
1592
1340
  const next = bootstrapped ? {
1593
- says: `Set ${adminsVar} in the Worker's vars to your login, deploy it with \`wrangler deploy\`, set ${secretsOf(withDefaults(project.held ?? {}, project.project)).join(" and ")} with \`wrangler secret put\`, sign in to it with that bootstrap secret, <host> being where it's served, and mint your admin token. Then sign in with yours, run \`doctor --verify\`, and delete ${gitSecrets.join(" and ")}`,
1341
+ says: `Set ${adminsVar} in the Worker's vars to your login, deploy it with \`wrangler deploy\`, set ${secrets} with \`wrangler secret put\`, sign in to it with that bootstrap secret, <host> being where it's served, and mint your admin token. Then sign in with yours, run \`doctor --verify\`, and delete ${gitSecrets.join(" and ")}`,
1594
1342
  run: [[
1595
1343
  "login",
1596
1344
  `<host>${base}`,
@@ -1610,10 +1358,10 @@ const setupCommands = [init, Command.make("doctor", {
1610
1358
  ]],
1611
1359
  stdinFrom: "ADMIN_TOKEN"
1612
1360
  } : {
1613
- says: platformOf(project.detected) === "node" ? starter !== void 0 ? `Build it with \`${project.packageManager.value} run build\`, start it with ${starter.start(project.packageManager.value)}, ${signIn}, then push a scratch repo through it` : routed(project.framework) ? `Build it with \`${project.packageManager.value} run build\`, start it with ${routedStart(project.framework, project.packageManager.value)}, ${signIn}, then push a scratch repo through it` : project.layout.kind === "mount" ? `Start your server with \`node --env-file-if-exists=.env\`, which loads what src/git.ts reads, ${signIn}, then push a scratch repo through it` : `Start it with \`${project.packageManager.value} start\`, ${project.held?.app === "ref0" ? "sign up on it, setting APP_ORIGIN to where it's served first" : signIn}, then push a scratch repo through it` : vercel ? `Check Production has each variable with \`vercel env ls production\`, deploy it with Vercel's CLI or a Git import, ${signIn}, then push a scratch repo through it` : `Set APP_ORIGIN to where it's served, make AUTH_DB with \`wrangler d1 create\`, deploy it with \`wrangler deploy\`, set ${secretsOf(withDefaults(project.held ?? {}, project.project)).join(" and ")} with \`wrangler secret put\`, ${signIn}, then push a scratch repo through it`,
1361
+ says: vercel ? `Check Production has each variable with \`vercel env ls production\`, deploy it with Vercel's CLI or a Git import, ${signIn}, then push a scratch repo through it` : `Set APP_ORIGIN to where it's served, make AUTH_DB with \`wrangler d1 create\`, deploy it with \`wrangler deploy\`, set ${secrets} with \`wrangler secret put\`, ${signIn}, then push a scratch repo through it`,
1614
1362
  run: [[
1615
1363
  "login",
1616
- `${served ?? "<host>"}${base}`,
1364
+ `<host>${base}`,
1617
1365
  "--with-token"
1618
1366
  ], ["doctor", "--verify"]],
1619
1367
  stdinFrom: "ADMIN_TOKEN"