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,85 +1,119 @@
1
1
  import { adminLines, effectImports, featuresLines, gitDependencies, gitImports, gitPackages, mergeLines, policyLines, repoHint, runtimeLines } from "./git-module.mjs";
2
2
  import { dropInPrefixes } from "./routes.mjs";
3
- import { ignoring, lines, listed, served, withCli, withCreatedTypes, withDependencies, withLines } from "./files.mjs";
4
- import { envExample, needHelper, needsOf, recordsPart, s3Part } from "./stores.mjs";
5
- import { inline, insertInto, itemsAt, jsonString, manifestText, nodeAt, parseJsonc, stringAt, withEntries } from "./jsonc.mjs";
6
- import { nextConfigOutput, nextJobFiles, nextJobRoutes, nextRouteFiles, nextSweepPath } from "./next.mjs";
3
+ import { ignoring, lines, served, withCli, withDependencies, withLines } from "./files.mjs";
4
+ import { envExample, needHelper, needsOf, postgresPart } from "./stores.mjs";
5
+ import { inline, itemsAt, manifestText, nodeAt, parseJsonc, stringAt, withEntries } from "./jsonc.mjs";
6
+ import { nextConfigOutput, nextRouteFiles } from "./next.mjs";
7
+ import { shellWord } from "./shell.mjs";
7
8
  import { vercelPackages } from "./metadata.mjs";
8
9
  import * as Redacted from "effect/Redacted";
9
- import * as Predicate from "effect/Predicate";
10
10
  // src/init/vercel.ts
11
11
  /**
12
- * What `init` writes for Git on Vercel's functions, without the app: `src/git.ts`, `api/git.ts`
13
- * for every URL, `api/jobs.ts` for the queue's deliveries and `api/jobs/sweep.ts` for the cron,
12
+ * What `init` writes for Git on Vercel, without the app: `src/git.ts`, `api/git.ts` for every URL
13
+ * on the Functions, the Daemon that runs every job, `daemon/main.mjs` and its `daemon/Dockerfile`,
14
14
  * and Git's part merged into `vercel.json`, `package.json`, `.gitignore` and `.env`.
15
15
  */
16
- /** The topic `src/git.ts` sends to and `vercel.json`'s trigger names. */
17
- const topic = "git-jobs";
18
- /** The routes `vercel.json` gives Git: every URL's, the queue's private one and the cron's. */
19
- const routes = {
20
- git: "api/git.ts",
21
- jobs: "api/jobs.ts",
22
- sweep: "/api/jobs/sweep"
23
- };
24
- /** A plan's longest function run, in seconds, and its cron's schedule: Hobby allows one a day. */
25
- const planLimits = {
26
- hobby: {
27
- maxDuration: 300,
28
- schedule: "0 4 * * *"
29
- },
30
- pro: {
31
- maxDuration: 800,
32
- schedule: "* * * * *"
33
- }
34
- };
35
- const limitsOf = (choices) => planLimits[choices.vercelPlan === "pro" ? "pro" : "hobby"];
36
- /** The store's and the bucket's parts, as `init/stores.ts` writes them; Blob's is Vercel's own. */
37
- const partsOf = (choices) => ({
38
- records: recordsPart(choices.records === "turso" ? "turso" : "postgres"),
39
- bucket: choices.bucket === "s3" ? s3Part : void 0
40
- });
41
- /** The variables the person sets: Postgres's or Turso's, then the bucket's, Blob's token its own. */
42
- const unsetOf = (choices) => {
43
- const { records, bucket } = partsOf(choices);
44
- return needsOf([records, bucket ?? { variables: ["BLOB_READ_WRITE_TOKEN"] }]);
16
+ /** The function `vercel.json` sends Git's URLs to. */
17
+ const routes = { git: "api/git.ts" };
18
+ /** The memory of api/git.ts and of the Daemon's instance, in MiB, as `vercel.json` sets both. */
19
+ const instanceMemory = 2048;
20
+ /**
21
+ * What `packs()` counts of `instanceMemory`: all but 512 MiB, for the runtime's own beside what
22
+ * Git charges. A Function's rss ran 206 to 417 MiB with one Blob put in parts (#3064).
23
+ */
24
+ const gitMemory = 1536;
25
+ /**
26
+ * The Daemon that runs every job: its name in `vercel.json`'s `daemons`, its entry and its
27
+ * `Dockerfile`, built from the project's root, so the image holds the server module the entry
28
+ * imports. It runs in the Functions' region, `--region`'s, beside the stores.
29
+ */
30
+ const daemon = {
31
+ name: "git",
32
+ entry: "daemon/main.mjs",
33
+ dockerfile: "daemon/Dockerfile"
45
34
  };
46
- /** The variables `src/git.ts` needs, as `.env.example` lists them: the secrets `init` made first. */
47
- const variablesOf = (choices) => [
48
- "ADMIN_TOKEN",
49
- "CRON_SECRET",
50
- ...unsetOf(choices)
51
- ];
52
35
  /**
53
- * `src/git.ts` on Vercel: Git's features and the drop-in's, as chosen, its runtime, and the job
54
- * queue's handler, which a route of its own takes, in Next.js too.
36
+ * Where a project without a framework publishes its static files: a folder of its own. Vercel
37
+ * refuses a Daemon whose root is the folder the app publishes, and with no `public/` its "Other"
38
+ * preset publishes the project's root, the Daemon's. Next.js publishes its build's output.
39
+ */
40
+ const staticOutput = "public";
41
+ /** Whether a `vercel.json`'s `outputDirectory` names the project's root, the Daemon's. */
42
+ const publishesRoot = (directory) => [
43
+ "",
44
+ ".",
45
+ "./"
46
+ ].includes(directory.trim());
47
+ /**
48
+ * Postgres's direct URL, which the Daemon takes: Neon's pooled `DATABASE_URL` is PgBouncer's
49
+ * transaction mode, which can't `LISTEN`. Neon's Vercel integration sets both.
50
+ */
51
+ const unpooled = "DATABASE_URL_UNPOOLED";
52
+ /** The variables the person sets: Postgres's, the Daemon's direct one, then Blob's token. */
53
+ const unset = needsOf([postgresPart, { variables: [unpooled, "BLOB_READ_WRITE_TOKEN"] }]);
54
+ /** The variables `src/git.ts` and the Daemon need, as `.env.example` lists them: the secret first. */
55
+ const variablesOf = () => ["ADMIN_TOKEN", ...unset];
56
+ /**
57
+ * `src/git.ts` on Vercel: Git's features and the drop-in's, as chosen, as `hostOver(store)`, which
58
+ * the Daemon's entry builds over its own store, and the Functions' `runtime`, over a store that
59
+ * runs no job.
55
60
  */
56
- const vercelGitModule = (choices, next) => {
57
- const jobsRoute = next === void 0 ? routes.jobs : nextJobRoutes(next).jobs;
58
- const postgres = choices.records === "postgres";
59
- const blob = choices.bucket === "vercel-blob";
60
- const { records, bucket } = partsOf(choices);
61
+ const vercelGitModule = (choices) => {
62
+ const records = postgresPart;
61
63
  const queue = choices.queue === "on";
62
- return lines(`// Git on Vercel's functions, ${served[choices.serve]}${queue ? ", with a merge queue on `main`" : ""}: records and jobs`, `// in ${postgres ? "Postgres" : "Turso"}, packs in ${blob ? "Vercel Blob" : "S3"}, and jobs woken by Vercel Queues. Written by \`ref0-git init\`, and`, "// yours to change: `init` rewrites it only while it reads as written, and `ref0-git doctor`", "// checks it.", choices.serve === "git" && repoHint, ...records.external, "", gitImports(choices), ...[
63
- records.infra,
64
- bucket?.infra,
65
- "import * as Vercel from '@ref0/infra/vercel';"
66
- ].filter(Predicate.isString).toSorted(), "import { xdiff } from '@ref0/xdiff-wasm/node';", effectImports(choices), "", needHelper("the project's Environment Variables"), "", adminLines, "// Functions don't run between requests: a commit that saves a job sends a queue message, and the", "// cron in `vercel.json` sweeps for any message that was lost.", `const wake = Vercel.layerQueues({ topic: '${topic}' });`, "", records.code, "", lines(bucket === void 0 ? "const bucket = Vercel.layerBlob();" : bucket.code, ""), mergeLines(choices), policyLines, featuresLines(choices, {
67
- merges: "{ xdiff: await xdiff() }",
68
- uploads: lines(` // Vercel refuses a body over 4.5 MB, so a larger push uploads its pack to ${blob ? "Blob" : "the bucket"}.`, " Git.layerUploads({ above: 4 * 1024 * 1024 }),")
69
- }), runtimeLines(choices, {
64
+ return lines(`// Git on Vercel, ${served[choices.serve]}${queue ? ", with a merge queue on `main`" : ""}: records and jobs`, `// in Postgres, packs in Vercel Blob, Git's URLs on the Functions and every job on the Daemon,`, `// \`${daemon.entry}\`. Written by \`ref0-git init\`, and yours to change: \`init\` rewrites it only`, "// while it reads as written, and `ref0-git doctor` checks it.", choices.serve === "git" && repoHint, ...records.external, "", gitImports(choices), records.infra, "import * as Vercel from '@ref0/infra/vercel';", "import xdiff from '@ref0/xdiff-wasm/xdiff.wasm';", effectImports(choices), "", needHelper("the project's Environment Variables").replace("const need =", "export const need ="), "", adminLines, lines("const bucket = Vercel.layerBlob();", ""), mergeLines(choices), policyLines, featuresLines(choices, {
65
+ merges: "{ xdiff }",
66
+ uploads: lines(" // Vercel refuses a body over 4.5 MB, so a larger push uploads its pack to Blob, and the", " // Daemon lands it.", " Git.layerUploads({ above: 4 * 1024 * 1024 }),")
67
+ }), records.code, "", runtimeLines(choices, {
70
68
  token: "need('ADMIN_TOKEN')",
71
69
  adapter: "Layer.merge(store, bucket)",
72
- maxDuration: limitsOf(choices).maxDuration
73
- }), `/** The job queue's route: \`${jobsRoute}\` runs what its messages and the cron's calls name. */`, "export const jobs = Vercel.toQueueHandler(runtime);", "");
70
+ maxDuration: 800,
71
+ memory: gitMemory,
72
+ over: {
73
+ type: "typeof serving",
74
+ store: "serving"
75
+ }
76
+ }));
74
77
  };
78
+ /** `daemon/main.mjs`'s import of the server module at `module`, from the project's root. */
79
+ const daemonImport = (module) => `../${module}`;
80
+ /**
81
+ * `daemon/main.mjs`: the Daemon's process, the host over Postgres's direct URL, woken by
82
+ * `NOTIFY` and its poller, running every job until `SIGTERM`. It's JavaScript, which Node 24 runs
83
+ * as it is, importing the server module's TypeScript, so `next build`'s type check never meets
84
+ * the `.ts` import Node needs.
85
+ */
86
+ const daemonEntry = (module) => lines("// Git's jobs on a Vercel Daemon: every job the Functions save runs here. It listens for", "// Postgres's NOTIFY, so a job starts at once, and its poller finds any it missed. Written by", "// `ref0-git init`, and yours to change.", "import pg from 'pg';", "", "import * as Postgres from '@ref0/infra/postgres';", "import * as Runner from '@ref0/infra/runner';", "", `import { hostOver, need } from '${daemonImport(module)}';`, "", `// Postgres's direct URL: a pooled one, PgBouncer's transaction mode, can't LISTEN.`, `const url = need('${unpooled}');`, "", "const runtime = hostOver(", " Postgres.layer({", " // A call waits at most 10 s for one of the pool's connections, then fails, never hangs.", " pool: new pg.Pool({ connectionString: url, connectionTimeoutMillis: 10_000 }),", " wake: Runner.layerPoller(),", " listen: url,", " }),", ");", "", "const stop = Runner.toJobRunner(runtime);", "", "// Vercel sends SIGTERM as a deploy replaces this instance, and ends it 30 s on: the runner claims", "// no more, and a try still running then is another instance's once its lease lapses.", "process.once('SIGTERM', () => {", " void stop()", " .then(() => runtime.dispose())", " .finally(() => process.exit(0));", "});", "");
87
+ /**
88
+ * The install `daemon/Dockerfile` runs, by the project's package manager: production's alone,
89
+ * where the manager can. Yarn 2 and on refuse `--production` on `install`, so past Yarn 1 the
90
+ * image takes the lockfile's whole install, as `packageManager` pins it through Corepack.
91
+ */
92
+ const installs = {
93
+ npm: "npm ci --omit=dev",
94
+ pnpm: "corepack enable && pnpm install --prod --frozen-lockfile",
95
+ yarn: "corepack enable && if yarn --version | grep -q \"^1\\.\"; then yarn install --production --frozen-lockfile; else yarn install --immutable; fi",
96
+ bun: "npm install --global bun && bun install --production --frozen-lockfile"
97
+ };
98
+ /**
99
+ * How the image starts the Daemon: Node, or under Yarn `yarn node`, which loads Plug'n'Play's
100
+ * resolution where Yarn 2 and on install with it, and is Node where they don't.
101
+ */
102
+ const startOf = (manager) => manager === "yarn" ? [
103
+ "yarn",
104
+ "node",
105
+ daemon.entry
106
+ ] : ["node", daemon.entry];
107
+ /** `daemon/Dockerfile`: Node 24, the project's production dependencies, and the Daemon's entry. */
108
+ const daemonDockerfile = (manager) => lines("# The Daemon's image, which Vercel builds from the project's root on each production deploy:", "# Node 24, the project's production dependencies, and daemon/main.mjs. Written by `ref0-git init`.", "FROM node:24-slim", "WORKDIR /app", "COPY . .", `RUN ${installs[manager]}`, `CMD [${startOf(manager).map((part) => JSON.stringify(part)).join(", ")}]`, "");
75
109
  /** What `api/git.ts` answers, for what it serves. */
76
110
  const handlerSays = {
77
111
  github: "The drop-in's URLs, then Git's REST and protocol, then a JSON `404`.",
78
112
  api: "Git's REST and protocol, then a JSON `404`.",
79
113
  git: "Git's protocol and sign-in, then a JSON `404`."
80
114
  };
81
- /** `api/git.ts`: every URL but the jobs' routes, by `vercel.json`'s rewrite. */
82
- const gitRoute = (choices) => lines("import { Git } from '@ref0/git';", "", "import { runtime } from '../src/git.ts';", "", `/** ${handlerSays[choices.serve]} */`, "const fetch = Git.toFetch(runtime);", "", "// Every URL but the jobs' routes comes here, by `vercel.json`'s rewrite.", "export {", ...[
115
+ /** `api/git.ts`: every URL, by `vercel.json`'s rewrite. */
116
+ const gitRoute = (choices) => lines("import { Git } from '@ref0/git';", "", "import { runtime } from '../src/git.ts';", "", `/** ${handlerSays[choices.serve]} */`, "const fetch = Git.toFetch(runtime);", "", "// Every URL but the functions' own comes here, by `vercel.json`'s rewrite.", "export {", ...[
83
117
  "DELETE",
84
118
  "GET",
85
119
  "HEAD",
@@ -87,10 +121,6 @@ const gitRoute = (choices) => lines("import { Git } from '@ref0/git';", "", "imp
87
121
  "POST",
88
122
  "PUT"
89
123
  ].map((method) => ` fetch as ${method},`), "};", "");
90
- /** `api/jobs.ts`: the queue's deliveries, on the function `vercel.json` gives its trigger. */
91
- const jobsRoute = lines("import { jobs } from '../src/git.ts';", "", "/** Vercel Queues' deliveries: `vercel.json` gives this function the trigger, which makes it private. */", "export const POST = jobs;", "");
92
- /** `api/jobs/sweep.ts`: the cron's call. */
93
- const sweepRoute = lines("import { jobs } from '../../src/git.ts';", "", "/** The cron's sweep, refused without `CRON_SECRET`: a message for each scope with work due. */", "export const GET = jobs;", "");
94
124
  /**
95
125
  * The files that hold secrets on Vercel: `.env`, which `init` writes, and `.env.local`, which
96
126
  * `vercel env pull` fills. `.gitignore` ends with them, and `init` refuses one Git tracks.
@@ -118,64 +148,45 @@ const rewriteSource = (choices) => {
118
148
  if (!github) return `${base}/:path*`;
119
149
  return `/((?:${base.slice(1).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:/|$)|api/(?:${dropInApi})${dropInRoot}|[^/]+/[^/]+\\.git/).*)`;
120
150
  };
121
- const vercelParts = (choices, next) => {
122
- const { maxDuration, schedule } = limitsOf(choices);
123
- if (next !== void 0) {
124
- const trigger = { experimentalTriggers: [{
125
- type: "queue/v2beta",
126
- topic
127
- }] };
128
- return {
129
- rewrite: void 0,
130
- functions: { [nextJobRoutes(next).jobs]: trigger },
131
- cron: {
132
- path: nextSweepPath,
133
- schedule
134
- }
135
- };
136
- }
137
- return {
138
- rewrite: {
139
- source: rewriteSource(choices),
140
- destination: "/api/git"
141
- },
142
- functions: {
143
- [routes.git]: { maxDuration },
144
- [routes.jobs]: {
145
- maxDuration,
146
- experimentalTriggers: [{
147
- type: "queue/v2beta",
148
- topic
149
- }]
150
- }
151
- },
152
- cron: {
153
- path: routes.sweep,
154
- schedule
155
- }
156
- };
151
+ /** The Daemon's entry in `daemons`: one instance of `instanceMemory` in `region`, built from the root. */
152
+ const daemonConfig = (region) => ({
153
+ root: "./",
154
+ entrypoint: daemon.dockerfile,
155
+ instances: { [region]: 1 },
156
+ resources: { requests: { memory: `${instanceMemory / 1024}Gi` } }
157
+ });
158
+ /** Git's rewrite to its function: none in Next.js, whose route files take Git's URLs. */
159
+ const rewriteOf = (choices, next) => next === void 0 ? {
160
+ source: rewriteSource(choices),
161
+ destination: "/api/git"
162
+ } : void 0;
163
+ const vercelParts = (choices, region, next) => next === void 0 ? {
164
+ regions: [region],
165
+ rewrite: rewriteOf(choices, next),
166
+ outputDirectory: staticOutput,
167
+ functions: { [routes.git]: {
168
+ maxDuration: 800,
169
+ memory: instanceMemory
170
+ } },
171
+ daemon: daemonConfig(region)
172
+ } : {
173
+ regions: [region],
174
+ rewrite: void 0,
175
+ outputDirectory: void 0,
176
+ functions: {},
177
+ daemon: daemonConfig(region)
157
178
  };
158
179
  /** `vercel.json` for a project `init` makes. */
159
- const vercelConfig = (choices, next) => {
160
- const { cron } = vercelParts(choices);
180
+ const vercelConfig = (choices, region, next) => {
161
181
  const rewrite = {
162
182
  source: rewriteSource(choices),
163
183
  destination: "/api/git"
164
184
  };
165
- const { maxDuration } = limitsOf(choices);
166
- if (next !== void 0) return mergeVercel("{\n \"$schema\": \"https://openapi.vercel.sh/vercel.json\"\n}\n", choices, next);
167
- return lines("{", " \"$schema\": \"https://openapi.vercel.sh/vercel.json\",", ` "rewrites": [${inline(rewrite)}],`, " \"functions\": {", ` "${routes.git}": { "maxDuration": ${maxDuration} },`, ` "${routes.jobs}": {`, ` "maxDuration": ${maxDuration},`, ` "experimentalTriggers": [{ "type": "queue/v2beta", "topic": "${topic}" }]`, " }", " },", ` "crons": [${inline(cron)}]`, "}", "");
185
+ if (next !== void 0) return mergeVercel("{\n \"$schema\": \"https://openapi.vercel.sh/vercel.json\"\n}\n", choices, region, next);
186
+ return lines("{", " \"$schema\": \"https://openapi.vercel.sh/vercel.json\",", ` "regions": ${inline([region.value])},`, ` "outputDirectory": "${staticOutput}",`, ` "rewrites": [${inline(rewrite)}],`, ` "functions": { "${routes.git}": { "maxDuration": 800, "memory": ${instanceMemory} } },`, ` "daemons": { "${daemon.name}": ${inline(daemonConfig(region.value))} }`, "}", "");
168
187
  };
169
188
  /** `text` with `node`'s value written as `value`. */
170
189
  const replaced = (text, node, value) => `${text.slice(0, node.start)}${inline(value)}${text.slice(node.end)}`;
171
- /** `text` with `value` at `key` of the item of `array` whose `match` is `wanted`, else the item added. */
172
- const withItem = (text, array, match, item, key) => {
173
- const found = itemsAt(parseJsonc(text), [array]).find((each) => stringAt(each, [match]) === item[match]);
174
- if (found === void 0) return withEntries(text, [array], [item]);
175
- const node = nodeAt(found, [key]);
176
- const value = item[key] ?? "";
177
- return node === void 0 ? insertInto(text, found, [`${jsonString(key)}: ${inline(value)}`]) : stringAt(found, [key]) === value ? text : replaced(text, node, value);
178
- };
179
190
  /**
180
191
  * `text` with Git's rewrite as its `rewrites`, when it has none. A list already there is the
181
192
  * project's: `init` never edits it, so a host's order and conditions, such as `has`, stay theirs,
@@ -187,7 +198,7 @@ const withRewrite = (text, rewrite) => nodeAt(parseJsonc(text), ["rewrites"]) ==
187
198
  * an earlier rewrite, such as a site's catch-all, takes Git's URLs, and an old source misses them.
188
199
  */
189
200
  const rewriteSteps = (text, choices, next) => {
190
- const { rewrite } = vercelParts(choices, next);
201
+ const rewrite = rewriteOf(choices, next);
191
202
  if (rewrite === void 0) return [];
192
203
  if (text === void 0 || nodeAt(parseJsonc(text), ["rewrites"]) === void 0) return [];
193
204
  const [first] = itemsAt(parseJsonc(text), ["rewrites"]);
@@ -198,8 +209,8 @@ const rewriteSteps = (text, choices, next) => {
198
209
  lines: [` ${inline(rewrite)},`]
199
210
  }];
200
211
  };
201
- /** A function's settings with Git's added where missing, and its `maxDuration` the plan's. */
202
- const withFunction = (text, path, wanted, maxDuration) => {
212
+ /** A function's settings with Git's added where missing, and its `maxDuration` Pro's. */
213
+ const withFunction = (text, path, wanted) => {
203
214
  const added = withEntries(text, ["functions"], { [path]: wanted });
204
215
  const withKeys = withEntries(added, ["functions", path], wanted);
205
216
  const duration = nodeAt(parseJsonc(withKeys), [
@@ -207,40 +218,59 @@ const withFunction = (text, path, wanted, maxDuration) => {
207
218
  path,
208
219
  "maxDuration"
209
220
  ]);
210
- return duration === void 0 || duration.kind !== "value" || duration.raw === String(maxDuration) ? withKeys : replaced(withKeys, duration, maxDuration);
221
+ return duration === void 0 || duration.kind !== "value" || duration.raw === String(800) ? withKeys : replaced(withKeys, duration, 800);
211
222
  };
212
- /** A project's `vercel.json` with Git's rewrite, functions and cron in it, at the plan's limits. */
213
- const mergeVercel = (text, choices, next) => {
214
- const { rewrite, functions, cron } = vercelParts(choices, next);
215
- const { maxDuration } = limitsOf(choices);
223
+ /**
224
+ * `text` with `regions` and the Daemon's `instances` in `region`: added where missing, and, when
225
+ * the person named it, with `--region` or at the prompt, moved there from another, keeping the
226
+ * Daemon's instance count. One read from `text` leaves it as it is.
227
+ */
228
+ const withRegion = (text, region) => {
229
+ const added = withEntries(text, [], { regions: [region.value] });
230
+ if (region.from === "detected") return added;
231
+ const tree = parseJsonc(added);
232
+ const regions = nodeAt(tree, ["regions"]);
233
+ const moved = regions === void 0 ? added : replaced(added, regions, [region.value]);
234
+ const instances = nodeAt(parseJsonc(moved), [
235
+ "daemons",
236
+ daemon.name,
237
+ "instances"
238
+ ]);
239
+ if (instances?.kind !== "object") return moved;
240
+ const count = instances.members.reduce((sum, member) => sum + (member.value.kind === "value" ? Number(member.value.raw) || 0 : 0), 0);
241
+ return replaced(moved, instances, { [region.value]: Math.max(count, 1) });
242
+ };
243
+ /**
244
+ * A project's `vercel.json` with Git's region, rewrite, output directory, function and Daemon in
245
+ * it. A Daemon of Git's name, or an `outputDirectory`, already there is the project's: `init` adds
246
+ * only what it lacks, and `doctor` names an output directory that's the project's root. Its region
247
+ * moves only when `--region` names another.
248
+ */
249
+ const mergeVercel = (text, choices, region, next) => {
250
+ const { rewrite, outputDirectory, functions, daemon: wanted } = vercelParts(choices, region.value, next);
216
251
  return [
252
+ (from) => withRegion(from, region),
253
+ (from) => outputDirectory === void 0 ? from : withEntries(from, [], { outputDirectory }),
217
254
  (from) => rewrite === void 0 ? from : withRewrite(from, rewrite),
218
- ...Object.entries(functions).map(([path, wanted]) => (from) => withFunction(from, path, wanted, maxDuration)),
219
- (from) => withItem(from, "crons", "path", cron, "schedule")
255
+ ...Object.entries(functions).map(([path, settings]) => (from) => withFunction(from, path, settings)),
256
+ (from) => withEntries(withEntries(from, ["daemons"], { [daemon.name]: wanted }), ["daemons", daemon.name], wanted)
220
257
  ].reduce((from, step) => step(from), text);
221
258
  };
222
- /** Git's packages, their peers and the store's and bucket's clients, as `package.json` names them. */
259
+ /** Git's packages, their peers, and Postgres's and Blob's clients, as `package.json` names them. */
223
260
  const dependenciesOf = (choices, vendor) => {
224
- const { records, bucket } = partsOf(choices);
225
261
  const named = [
226
- ...records.dependencies,
262
+ ...postgresPart.dependencies,
227
263
  ...gitDependencies(choices, vendor),
228
- ...bucket?.dependencies ?? []
264
+ ["@vercel/blob", vercelPackages["@vercel/blob"]]
229
265
  ];
230
- if (choices.bucket === "vercel-blob") named.push(["@vercel/blob", vercelPackages["@vercel/blob"]]);
231
- named.push(["@vercel/queue", vercelPackages["@vercel/queue"]]);
232
266
  return Object.fromEntries(named);
233
267
  };
234
268
  /** The types `src/git.ts` is checked with. */
235
- const devDependenciesOf = (choices) => {
236
- const { records } = partsOf(choices);
237
- const named = [
238
- ["@types/node", vercelPackages["@types/node"]],
239
- ...records.devDependencies,
240
- ["typescript", vercelPackages.typescript]
241
- ];
242
- return Object.fromEntries(named);
243
- };
269
+ const devDependencies = Object.fromEntries([
270
+ ["@types/node", vercelPackages["@types/node"]],
271
+ ...postgresPart.devDependencies,
272
+ ["typescript", vercelPackages.typescript]
273
+ ]);
244
274
  const mergePackage = (choices, name, vendor) => (current) => {
245
275
  if (current === void 0) {
246
276
  const made = {
@@ -248,87 +278,146 @@ const mergePackage = (choices, name, vendor) => (current) => {
248
278
  private: true,
249
279
  type: "module",
250
280
  dependencies: dependenciesOf(choices, vendor),
251
- devDependencies: devDependenciesOf(choices)
281
+ devDependencies
252
282
  };
253
283
  return withCli(`${manifestText(made)}\n`, vendor);
254
284
  }
255
- return withEntries(withCli(withDependencies(current, dependenciesOf(choices, vendor)), vendor), ["devDependencies"], devDependenciesOf(choices));
285
+ return withEntries(withCli(withDependencies(current, dependenciesOf(choices, vendor)), vendor), ["devDependencies"], devDependencies);
256
286
  };
287
+ /** `vercel env add`'s command for `name` in `environment`, as the next step quotes it. */
288
+ const envAdd = (name, environment) => `\`vercel env add ${name} ${environment}\``;
289
+ /** The private Blob store's name `init` makes, for the project `name`. */
290
+ const blobStoreOf = (name) => `${name}-packs`;
291
+ /** Neon's database's name `init` makes, for the project `name`. */
292
+ const neonDatabaseOf = (name) => `${name}-db`;
293
+ /**
294
+ * `vercel`'s arguments that make the project's private Blob store in `region`, connected to each
295
+ * of its environments, as `--yes` connects it. It sets BLOB_READ_WRITE_TOKEN.
296
+ */
297
+ const blobStoreArgs = (name, region) => [
298
+ "blob",
299
+ "create-store",
300
+ blobStoreOf(name),
301
+ "--access",
302
+ "private",
303
+ "--region",
304
+ region,
305
+ "--yes"
306
+ ];
257
307
  /**
258
- * The next step's words, as docs/deploy/vercel.md's steps: Neon and a private Blob store set their
259
- * own variables, and Neon's URL takes `sslmode=verify-full`; each other is set for Production,
260
- * which the deploy runs, and for Development, which `vercel env pull` brings to `.env.local` for
261
- * `doctor`; and the two secrets `init` made in `.env` for Production only.
308
+ * `vercel`'s arguments that make Neon's Postgres in `region` through Vercel's integration,
309
+ * connected to each of the project's environments, with no Neon Auth, which Git doesn't use. It
310
+ * sets DATABASE_URL and DATABASE_URL_UNPOOLED, and Neon bills the team for it.
262
311
  */
263
- const nextOf = (choices) => {
264
- const postgres = choices.records === "postgres";
265
- const blob = choices.bucket === "vercel-blob";
266
- const stores = [postgres && "Neon", blob && "a private Blob store"].filter(Predicate.isString);
267
- const storeSet = [postgres && "DATABASE_URL", blob && "BLOB_READ_WRITE_TOKEN"].filter(Predicate.isString);
268
- const both = unsetOf(choices).filter((name) => !storeSet.includes(name));
269
- const add = (name, environment) => `\`vercel env add ${name} ${environment}\``;
270
- const said = [
271
- stores.length > 0 && `Connect ${listed(stores)} to the project, which ${storeSet.length === 1 ? "sets" : "set"} ${listed(storeSet)}`,
272
- postgres && "change DATABASE_URL's sslmode=require to sslmode=verify-full for Production and Development",
273
- both.length > 0 && `set ${listed(both)} for Production and Development: ${both.flatMap((name) => [add(name, "production"), add(name, "development")]).join(", ")}`,
274
- `set ADMIN_TOKEN and CRON_SECRET for Production: ${add("ADMIN_TOKEN", "production")}, ${add("CRON_SECRET", "production")}`
275
- ].filter(Predicate.isString).join(", then ");
276
- return `${said.charAt(0).toUpperCase()}${said.slice(1)}. Link the folder, pull Development's with \`vercel env pull\`, then check it`;
312
+ const neonArgs = (name, region) => [
313
+ "integration",
314
+ "add",
315
+ "neon",
316
+ "--name",
317
+ neonDatabaseOf(name),
318
+ "--meta",
319
+ `region=${region}`,
320
+ "--meta",
321
+ "auth=false"
322
+ ];
323
+ /**
324
+ * `vercel` with `args`, as a sentence quotes the command to paste: run in `dir`, the folder `init`
325
+ * was given, with `--cwd`, so it reaches that folder's project from where `init` ran.
326
+ */
327
+ const vercelCommand = (args, dir) => `\`${[
328
+ "vercel",
329
+ ...args,
330
+ ...dir === void 0 ? [] : ["--cwd", dir]
331
+ ].map(shellWord).join(" ")}\``;
332
+ /** `items` as a sentence lists them: `a`, `a and b`, `a, b and c`. */
333
+ const listed = (items) => items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1) ?? ""}`;
334
+ /** The stores' clauses of the next step in `region`: none when nothing's left to make or set. */
335
+ const storesClauses = (region, name, left, dir) => {
336
+ const neon = left.postgres;
337
+ const names = [...neon ? ["Neon"] : [], ...left.blob ? ["a private Blob store"] : []];
338
+ const commands = [...neon ? [vercelCommand(neonArgs(name, region), dir)] : [], ...left.blob ? [vercelCommand(blobStoreArgs(name, region), dir)] : []];
339
+ const sets = [...neon ? ["DATABASE_URL", unpooled] : [], ...left.blob ? ["BLOB_READ_WRITE_TOKEN"] : []];
340
+ const where = `in ${region}, where the Functions and the Daemon run, since a store's region is fixed when it's made and each request and job crosses to it`;
341
+ const making = names.length === 0 ? void 0 : `make ${listed(names)} ${where}: ${listed(commands)}. ${names.length === 1 ? "It sets" : "They set"} ${listed(sets)}${neon ? `: the Functions take DATABASE_URL, and the Daemon ${unpooled}. For a Postgres of your own instead, set DATABASE_URL, its pooled URL, and ${unpooled}, a direct one that can LISTEN, for Production and Development, and init makes no Neon` : ""}`;
342
+ return making === void 0 ? [] : [making];
277
343
  };
344
+ /**
345
+ * The next step's words, as docs/deploy/vercel.md's steps: Vercel needs Pro, which a Daemon's
346
+ * month takes, and Daemons are in beta; Neon and a private Blob store, made in the Functions' and
347
+ * the Daemon's region, since a store's is fixed when it's made and each request and job crosses
348
+ * to it, set their own variables, the Functions taking DATABASE_URL and the Daemon its direct one;
349
+ * Neon's URLs take `sslmode=verify-full`; the secret `init` made in `.env` goes to Production; and
350
+ * a preview runs no job, so it takes no push past 4.5 MB.
351
+ */
352
+ const vercelNextOf = (region, name, left = {
353
+ linked: false,
354
+ blob: true,
355
+ postgres: true
356
+ }, dir) => `On Vercel Pro, whose Daemons are in beta, ${[
357
+ ...left.linked ? [] : [`link the folder with ${vercelCommand(["link"], dir)}`],
358
+ ...region === void 0 ? [`make Neon and a private Blob store in one region, then run init again with --region and it`] : storesClauses(region, name, left, dir),
359
+ `make DATABASE_URL's and ${unpooled}'s sslmode verify-full for Production and Development, where Neon's say require, so pg checks the server's certificate and name`,
360
+ `set ADMIN_TOKEN for Production: ${envAdd("ADMIN_TOKEN", "production")}. Pull Development's with \`vercel env pull\`, then check it`,
361
+ "deploy to production, where the Daemon runs every job. A preview runs none, so it takes no push past 4.5 MB"
362
+ ].join(", then ")}`;
278
363
  /** Everything `init` writes for `choices` on Vercel, with `secret` making each new secret. */
279
364
  const vercelOutput = (choices, project, secret, vendor) => {
280
365
  const next = project.framework?.name === "next" ? project.framework : void 0;
281
- const { maxDuration } = limitsOf(choices);
366
+ const module = next?.serverModule ?? "src/git.ts";
282
367
  const config = next === void 0 ? {
283
368
  files: [],
284
369
  manual: []
285
- } : nextConfigOutput(choices, next, project.created === true);
286
- const routeFiles = next === void 0 ? [
287
- {
288
- path: routes.git,
289
- kind: "whole",
290
- text: gitRoute(choices)
291
- },
292
- {
293
- path: routes.jobs,
294
- kind: "whole",
295
- text: jobsRoute
296
- },
297
- {
298
- path: "api/jobs/sweep.ts",
299
- kind: "whole",
300
- text: sweepRoute
301
- }
302
- ] : [...nextRouteFiles(choices, next, maxDuration), ...nextJobFiles(next, maxDuration)];
370
+ } : nextConfigOutput(choices, next);
371
+ const routeFiles = next === void 0 ? [{
372
+ path: routes.git,
373
+ kind: "whole",
374
+ text: gitRoute(choices)
375
+ }] : nextRouteFiles(choices, next, 800);
376
+ const { region } = project;
303
377
  return {
304
378
  files: [
305
- {
379
+ ...region === void 0 ? [] : [{
306
380
  path: "vercel.json",
307
381
  kind: "merge",
308
- merge: (current) => current === void 0 ? vercelConfig(choices, next) : mergeVercel(current, choices, next)
309
- },
382
+ merge: (current) => current === void 0 ? vercelConfig(choices, region, next) : mergeVercel(current, choices, region, next)
383
+ }],
310
384
  {
311
385
  path: "package.json",
312
386
  kind: "merge",
313
- merge: (current) => withCreatedTypes(project.created)(mergePackage(choices, project.name, vendor)(current))
387
+ merge: mergePackage(choices, project.name, vendor)
314
388
  },
315
389
  {
316
- path: next?.serverModule ?? "src/git.ts",
390
+ path: module,
317
391
  kind: "whole",
318
- text: vercelGitModule(choices, next)
392
+ text: vercelGitModule(choices)
319
393
  },
320
394
  ...routeFiles,
395
+ ...next === void 0 ? [{
396
+ path: `${staticOutput}/.gitkeep`,
397
+ kind: "whole",
398
+ text: ""
399
+ }] : [],
400
+ {
401
+ path: daemon.entry,
402
+ kind: "whole",
403
+ text: daemonEntry(module)
404
+ },
405
+ {
406
+ path: daemon.dockerfile,
407
+ kind: "whole",
408
+ text: daemonDockerfile(project.packageManager.value)
409
+ },
321
410
  ...config.files,
322
411
  {
323
412
  path: ".env.example",
324
413
  kind: "whole",
325
- text: envExample(["What src/git.ts reads. Set each in the project's Environment Variables; `vercel env pull`", "writes them to .env.local, and `init` made ADMIN_TOKEN and CRON_SECRET in .env."], variablesOf(choices))
414
+ text: envExample([`What ${module} and ${daemon.entry} read. Set each in the project's Environment Variables;`, "`vercel env pull` writes them to .env.local, and `init` made ADMIN_TOKEN in .env."], variablesOf())
326
415
  },
327
416
  {
328
417
  path: ".env",
329
418
  kind: "merge",
330
- secrets: ["ADMIN_TOKEN", "CRON_SECRET"],
331
- merge: (current) => withLines(current, [`ADMIN_TOKEN=${Redacted.value(secret())}`, `CRON_SECRET=${Redacted.value(secret())}`], (line) => line.split("=")[0] ?? "")
419
+ secrets: ["ADMIN_TOKEN"],
420
+ merge: (current) => withLines(current, [`ADMIN_TOKEN=${Redacted.value(secret())}`], (line) => line.split("=")[0] ?? "")
332
421
  },
333
422
  {
334
423
  path: ".gitignore",
@@ -338,43 +427,55 @@ const vercelOutput = (choices, project, secret, vendor) => {
338
427
  ],
339
428
  manual: [...rewriteSteps(project.vercelJson, choices, next), ...config.manual],
340
429
  packages: gitPackages(choices),
341
- secret: "ADMIN_TOKEN and CRON_SECRET, made for vercel dev, in .env",
342
- needs: unsetOf(choices),
343
- next: nextOf(choices)
430
+ secret: "ADMIN_TOKEN, made for vercel dev, in .env",
431
+ needs: unset,
432
+ next: vercelNextOf(region?.value, project.name)
344
433
  };
345
434
  };
346
435
  /**
347
- * What `doctor` finds wrong in a `vercel.json` against `choices`: the rewrite to `api/git`, each
348
- * function's `maxDuration` at the plan's, the queue's trigger on `api/jobs.ts`, and the cron.
436
+ * What `doctor` finds wrong in a `vercel.json` against `choices`: the rewrite to `api/git`, its
437
+ * function's `maxDuration` at Pro's, an output directory apart from the Daemon's root, and the
438
+ * Daemon, with one instance or more, built from `daemon/Dockerfile`.
349
439
  */
350
440
  const vercelProblems = (text, choices, next) => {
351
441
  if (text === void 0) return ["vercel.json is missing"];
352
442
  const tree = parseJsonc(text);
353
443
  if (tree === void 0) return ["vercel.json isn't JSON"];
354
- const { rewrite, cron } = vercelParts(choices, next);
355
- const { maxDuration } = limitsOf(choices);
356
- const jobsRoute = next === void 0 ? routes.jobs : nextJobRoutes(next).jobs;
444
+ const rewrite = rewriteOf(choices, next);
357
445
  const rewrites = itemsAt(tree, ["rewrites"]);
358
446
  const gitAt = rewrite === void 0 ? 0 : rewrites.findIndex((each) => stringAt(each, ["destination"]) === rewrite.destination && stringAt(each, ["source"]) === rewrite.source);
359
- const longest = (path) => {
360
- const found = nodeAt(tree, [
361
- "functions",
362
- path,
363
- "maxDuration"
364
- ]);
365
- return found?.kind === "value" ? Number(found.raw) : void 0;
366
- };
367
- const triggered = itemsAt(tree, [
447
+ const longest = nodeAt(tree, [
368
448
  "functions",
369
- jobsRoute,
370
- "experimentalTriggers"
371
- ]).some((each) => stringAt(each, ["type"])?.startsWith("queue/") === true && stringAt(each, ["topic"]) === "git-jobs");
372
- const schedule = itemsAt(tree, ["crons"]).filter((each) => stringAt(each, ["path"]) === cron.path).map((each) => stringAt(each, ["schedule"]))[0];
449
+ routes.git,
450
+ "maxDuration"
451
+ ]);
452
+ const output = stringAt(tree, ["outputDirectory"]);
453
+ const instances = nodeAt(tree, [
454
+ "daemons",
455
+ daemon.name,
456
+ "instances"
457
+ ]);
458
+ const counted = instances?.kind === "object" ? instances.members.map((member) => ({
459
+ key: member.key,
460
+ count: member.value.kind === "value" ? Number(member.value.raw) : 0
461
+ })) : [];
462
+ const counts = counted.map(({ count }) => count);
463
+ const region = stringAt(itemsAt(tree, ["regions"])[0], []);
464
+ const daemonRegions = counted.filter(({ count }) => count > 0).map(({ key }) => key);
373
465
  return [
374
466
  ...gitAt === -1 && rewrite !== void 0 ? [`no rewrite of ${rewrite.source} to ${rewrite.destination}`] : gitAt > 0 ? [`a rewrite comes before Git's, so it takes Git's URLs first: move Git's to the top`] : [],
375
- ...(next === void 0 ? [routes.git, routes.jobs] : []).flatMap((path) => longest(path) === maxDuration ? [] : [`${path}'s maxDuration isn't ${maxDuration}`]),
376
- ...triggered ? [] : [`${jobsRoute} has no queue trigger on ${topic}`],
377
- ...schedule === void 0 ? [`no cron calls ${cron.path}`] : schedule === cron.schedule ? [] : [`the cron on ${cron.path} runs at ${schedule}, not ${cron.schedule}`]
467
+ ...next !== void 0 || longest?.kind === "value" && Number(longest.raw) === 800 ? [] : [`${routes.git}'s maxDuration isn't 800`],
468
+ ...next !== void 0 || output !== void 0 && !publishesRoot(output) ? [] : [`the app publishes the project's root, the Daemon's, which Vercel refuses: set outputDirectory to ${staticOutput}`],
469
+ ...nodeAt(tree, ["daemons", daemon.name]) === void 0 ? [`no Daemon ${daemon.name} runs Git's jobs`] : [
470
+ ...stringAt(tree, [
471
+ "daemons",
472
+ daemon.name,
473
+ "entrypoint"
474
+ ]) === daemon.dockerfile ? [] : [`the Daemon ${daemon.name} isn't built from ${daemon.dockerfile}`],
475
+ ...counts.some((count) => count > 0) ? [] : [`the Daemon ${daemon.name} runs no instance`],
476
+ ...region === void 0 || daemonRegions.length === 0 || daemonRegions.includes(region) ? [] : [`the Daemon ${daemon.name} runs in ${daemonRegions.join(", ")}, apart from the Functions in ${region}: run init again with --region and your stores' region`]
477
+ ],
478
+ ...region === void 0 ? ["no regions, so the Functions run in Vercel's default, wherever the stores are: run init again with --region and your stores' region"] : []
378
479
  ];
379
480
  };
380
- export { mergeVercel, planLimits, routes, secretFiles, topic, variablesOf, vercelGitModule, vercelOutput, vercelProblems };
481
+ export { blobStoreArgs, blobStoreOf, daemon, gitMemory, instanceMemory, mergeVercel, neonArgs, neonDatabaseOf, routes, secretFiles, staticOutput, unpooled, variablesOf, vercelCommand, vercelGitModule, vercelNextOf, vercelOutput, vercelProblems };