saasaloy 0.6.0 → 0.7.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 (57) hide show
  1. package/README.md +7 -7
  2. package/dist/index.js +3952 -1899
  3. package/dist/index.js.map +1 -1
  4. package/package.json +2 -1
  5. package/schemas/manifest.schema.json +32 -1
  6. package/schemas/registry-item.schema.json +57 -2
  7. package/schemas/saasaloy-lock.schema.json +9 -0
  8. package/schemas/saasaloy.schema.json +12 -0
  9. package/templates/base/AGENTS.md +118 -63
  10. package/templates/base/README.md +16 -1
  11. package/templates/base/_agents/skills/saasaloy-config/SKILL.md +131 -0
  12. package/templates/base/_agents/skills/saasaloy-deploy/SKILL.md +280 -0
  13. package/templates/base/_agents/skills/saasaloy-design/SKILL.md +21 -11
  14. package/templates/base/_agents/skills/saasaloy-env/SKILL.md +8 -7
  15. package/templates/base/_agents/skills/saasaloy-landing-copy/SKILL.md +10 -9
  16. package/templates/base/_agents/skills/saasaloy-setup/SKILL.md +30 -22
  17. package/templates/base/_agents/skills/saasaloy-testing/SKILL.md +85 -0
  18. package/templates/base/_gitignore +4 -0
  19. package/templates/base/_prettierignore +5 -0
  20. package/templates/base/_saasaloy-base.json +6 -2
  21. package/templates/base/apps/web/package.json +1 -0
  22. package/templates/base/apps/web/src/layouts/Layout.astro +2 -1
  23. package/templates/base/apps/web/src/pages/privacy.astro +2 -0
  24. package/templates/base/apps/web/src/pages/terms.astro +2 -0
  25. package/templates/base/docs/runbook-deploy.md +72 -0
  26. package/templates/base/oxlint.config.mjs +62 -0
  27. package/templates/base/package.json +7 -4
  28. package/templates/base/packages/config/package.json +19 -0
  29. package/templates/base/packages/config/src/define.test.ts +134 -0
  30. package/templates/base/packages/config/src/define.ts +135 -0
  31. package/templates/base/packages/config/src/index.ts +34 -0
  32. package/templates/base/packages/config/src/project.ts +25 -0
  33. package/templates/base/packages/config/src/sections/app.ts +27 -0
  34. package/templates/base/packages/config/src/sections.ts +22 -0
  35. package/templates/base/packages/config/tsconfig.json +4 -0
  36. package/templates/base/packages/env/package.json +2 -1
  37. package/templates/base/packages/env/src/deploy.ts +3 -2
  38. package/templates/base/packages/env/src/services.test.ts +27 -11
  39. package/templates/base/packages/tooling/package.json +21 -0
  40. package/templates/base/packages/tooling/src/deploy-production.test.ts +923 -0
  41. package/templates/base/packages/tooling/src/deploy-production.ts +1041 -0
  42. package/templates/base/packages/tooling/src/deploy.config.ts +30 -0
  43. package/templates/base/packages/tooling/src/link-skills.test.ts +126 -0
  44. package/templates/base/packages/tooling/src/link-skills.ts +142 -0
  45. package/templates/base/packages/tooling/src/release.test.ts +205 -0
  46. package/templates/base/packages/tooling/src/release.ts +228 -0
  47. package/templates/base/packages/tooling/src/targets.ts +38 -0
  48. package/templates/base/packages/tooling/src/types.ts +78 -0
  49. package/templates/base/packages/tooling/tsconfig.json +11 -0
  50. package/templates/base/packages/ui/package.json +4 -2
  51. package/templates/base/packages/ui/src/blocks/footer.tsx +5 -3
  52. package/templates/base/packages/ui/src/containers/README.md +6 -5
  53. package/templates/base/packages/ui/src/content/landing.ts +2 -4
  54. package/templates/base/packages/ui/src/index.ts +10 -5
  55. package/templates/base/saasaloy.json +2 -1
  56. package/templates/base/turbo.json +1 -5
  57. package/templates/base/vitest.config.ts +5 -1
@@ -0,0 +1,1041 @@
1
+ #!/usr/bin/env node
2
+ import { execFileSync, spawn } from "node:child_process";
3
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { parseJsonc } from "@repo/env/deploy";
7
+ import { deployConfig } from "./deploy.config.ts";
8
+ import { DEPLOY_TARGETS, SMOKE_CHECKS } from "./targets.ts";
9
+ import type {
10
+ ChangelogSection,
11
+ DeployConfig,
12
+ DeployTarget,
13
+ SmokeCheck,
14
+ } from "./types.ts";
15
+
16
+ // `pnpm deploy:production`: the one command that puts a commit live.
17
+ //
18
+ // pnpm deploy:production gates, then every Worker in order, smoke, tag
19
+ // pnpm deploy:production --dry-run report every gate, the order and the smoke
20
+ // checks; build, upload, migrate and tag nothing
21
+ // pnpm deploy:production --migrate run the production migration first
22
+ // pnpm deploy:production --skip-ci "<reason>" pass the CI gate, with the reason in the tag
23
+ // pnpm deploy:production --only <service> one Worker and its smoke checks, no tag
24
+ //
25
+ // The gates come from `deploy.config.ts`: the branch is on its list, the tree is clean,
26
+ // HEAD is the same commit as its branch on origin, the CI workflow passed on HEAD (when
27
+ // the config names one), and a migration file changed since the last deploy tag needs
28
+ // `--migrate`. A failed gate stops a real deploy before anything builds, and the message
29
+ // names the command that clears it.
30
+ //
31
+ // The Workers deploy one at a time in `DEPLOY_TARGETS` order, so a frontend never goes
32
+ // live ahead of the api route it calls. Each runs its own `deploy` script
33
+ // (`env-deploy <service>`). The smoke checks then ask each custom domain for the answers
34
+ // `SMOKE_CHECKS` lists, and only a run where every step passed tags HEAD with an
35
+ // annotated `<prefix><UTC yyyymmdd-hhmm>` tag and pushes it. The newest tag is what is
36
+ // live: a hotfix branches from it, and `git log <tag>..main` lists what the next deploy
37
+ // ships.
38
+ //
39
+ // `pnpm release` runs before this command and tags the release commit `v<version>`. The
40
+ // deploy names that version in its output and its tag message. A HEAD that is not a
41
+ // release commit still deploys, with a warning, so a hotfix never waits on the changelog.
42
+
43
+ export interface Options {
44
+ dryRun: boolean;
45
+ migrate: boolean;
46
+ skipCi?: string;
47
+ only?: string;
48
+ }
49
+
50
+ const USAGE =
51
+ 'Usage: pnpm deploy:production [--dry-run] [--migrate] [--skip-ci "<reason>"] [--only <service>]';
52
+
53
+ /** A flag's value, or undefined when the next word is missing, blank or another flag. */
54
+ function flagValue(args: string[], index: number): string | undefined {
55
+ const value = args[index + 1]?.trim();
56
+ return value === undefined || value === "" || value.startsWith("--")
57
+ ? undefined
58
+ : value;
59
+ }
60
+
61
+ export function parseArgs(argv: string[]): Options {
62
+ const options: Options = { dryRun: false, migrate: false };
63
+ // pnpm passes a `--` through when the caller writes one before the flags.
64
+ const args = argv.filter((arg) => arg !== "--");
65
+ for (let index = 0; index < args.length; index += 1) {
66
+ const arg = args[index];
67
+ if (arg === "--dry-run") {
68
+ options.dryRun = true;
69
+ } else if (arg === "--migrate") {
70
+ options.migrate = true;
71
+ } else if (arg === "--skip-ci") {
72
+ const reason = flagValue(args, index);
73
+ if (reason === undefined) {
74
+ throw new Error(`--skip-ci needs a reason.\n${USAGE}`);
75
+ }
76
+ options.skipCi = reason;
77
+ index += 1;
78
+ } else if (arg === "--only") {
79
+ const service = flagValue(args, index);
80
+ if (service === undefined) {
81
+ throw new Error(`--only needs a service.\n${USAGE}`);
82
+ }
83
+ options.only = service;
84
+ index += 1;
85
+ } else {
86
+ throw new Error(`Unknown argument ${arg ?? ""}.\n${USAGE}`);
87
+ }
88
+ }
89
+ return options;
90
+ }
91
+
92
+ // ---- Config --------------------------------------------------------------------------------
93
+
94
+ export interface ResolvedRelease {
95
+ tagPrefix: string;
96
+ githubRelease: boolean;
97
+ preMajor: boolean;
98
+ changelogSections: ChangelogSection[] | undefined;
99
+ }
100
+
101
+ export interface ResolvedConfig {
102
+ branches: string[];
103
+ tagPrefix: string;
104
+ ciWorkflow: string | undefined;
105
+ migrations: string;
106
+ release: ResolvedRelease;
107
+ }
108
+
109
+ /**
110
+ * The config with a default for every key it lacks. `deploy.config.ts` is the project's
111
+ * and never changes after init, so a key this engine learns later is absent there.
112
+ */
113
+ export function resolveConfig(config: DeployConfig): ResolvedConfig {
114
+ return {
115
+ branches: config.branches ?? ["main", "hotfix-*"],
116
+ tagPrefix: config.tagPrefix ?? "deploy-",
117
+ ciWorkflow: config.ciWorkflow,
118
+ migrations: config.migrations ?? "packages/db/migrations/*.sql",
119
+ release: {
120
+ tagPrefix: config.release?.tagPrefix ?? "v",
121
+ githubRelease: config.release?.githubRelease ?? true,
122
+ preMajor: config.release?.preMajor ?? true,
123
+ changelogSections: config.release?.changelogSections,
124
+ },
125
+ };
126
+ }
127
+
128
+ function branchAllowed(branch: string, patterns: string[]): boolean {
129
+ return patterns.some((pattern) =>
130
+ pattern.endsWith("*")
131
+ ? branch.startsWith(pattern.slice(0, -1))
132
+ : branch === pattern
133
+ );
134
+ }
135
+
136
+ // ---- Gates ---------------------------------------------------------------------------------
137
+
138
+ /** The CI workflow's runs on HEAD, reduced to the one fact the gate needs. */
139
+ export type CiState = "passed" | "running" | "failed" | "missing";
140
+
141
+ export interface CiRun {
142
+ status: string;
143
+ conclusion: string;
144
+ }
145
+
146
+ export function ciState(runs: CiRun[]): CiState {
147
+ if (runs.some((run) => run.conclusion === "success")) {
148
+ return "passed";
149
+ }
150
+ if (runs.some((run) => run.status !== "completed")) {
151
+ return "running";
152
+ }
153
+ return runs.length === 0 ? "missing" : "failed";
154
+ }
155
+
156
+ /** What the gates read from git, GitHub and the workspace. */
157
+ export interface Facts {
158
+ branch: string;
159
+ dirty: string[];
160
+ head: string;
161
+ /** The commit the branch names on origin, or undefined when origin has no such branch. */
162
+ remoteHead?: string | undefined;
163
+ /** `off` when the config names no CI workflow, or `--skip-ci` passed the gate. */
164
+ ci: CiState | "off";
165
+ /** The newest deploy tag HEAD descends from. */
166
+ lastTag?: string | undefined;
167
+ /** Migration files changed since `lastTag`, or every one when there is no tag yet. */
168
+ newMigrations: string[];
169
+ /** Whether the project has a `@repo/db` workspace to migrate. */
170
+ hasDb: boolean;
171
+ release: ReleaseFacts;
172
+ }
173
+
174
+ /** What git says about the release tags, which the deploy names and never gates on. */
175
+ export interface ReleaseFacts {
176
+ /** The release tag on HEAD itself, when HEAD is a release commit. */
177
+ onHead?: string | undefined;
178
+ /** The newest release tag HEAD descends from. */
179
+ latest?: string | undefined;
180
+ /** The commits after `latest`, one `git log --oneline` row each. */
181
+ after: string[];
182
+ /** Whether `latest` is newer than the last deploy tag. */
183
+ sinceDeploy: boolean;
184
+ }
185
+
186
+ export interface Gate {
187
+ name: string;
188
+ state: "ok" | "fail" | "off";
189
+ /** What passed, or what failed and the command that clears it. */
190
+ detail: string;
191
+ }
192
+
193
+ function branchGate(facts: Facts, config: ResolvedConfig): Gate {
194
+ const allowed = config.branches.join(", ");
195
+ if (branchAllowed(facts.branch, config.branches)) {
196
+ return {
197
+ name: "Branch",
198
+ state: "ok",
199
+ detail: `The branch ${facts.branch} may deploy (${allowed}).`,
200
+ };
201
+ }
202
+ const first = config.branches[0] ?? "main";
203
+ return {
204
+ name: "Branch",
205
+ state: "fail",
206
+ detail: `The branch is ${facts.branch}, and a deploy starts only from ${allowed}. Run: git switch ${first}`,
207
+ };
208
+ }
209
+
210
+ function treeGate(facts: Facts): Gate {
211
+ if (facts.dirty.length === 0) {
212
+ return { name: "Tree", state: "ok", detail: "The tree is clean." };
213
+ }
214
+ return {
215
+ name: "Tree",
216
+ state: "fail",
217
+ detail: `The tree has uncommitted changes (${facts.dirty.join(", ")}), so the tag would not record what goes live. Run: git commit, or git stash push -u`,
218
+ };
219
+ }
220
+
221
+ function originGate(facts: Facts): Gate {
222
+ const { branch } = facts;
223
+ if (facts.remoteHead === undefined) {
224
+ return {
225
+ name: "Origin",
226
+ state: "fail",
227
+ detail: `origin has no ${branch}. Run: git push -u origin ${branch}`,
228
+ };
229
+ }
230
+ if (facts.remoteHead !== facts.head) {
231
+ return {
232
+ name: "Origin",
233
+ state: "fail",
234
+ detail: `HEAD (${facts.head.slice(0, 7)}) is not origin/${branch} (${facts.remoteHead.slice(0, 7)}). Run: git pull --ff-only, or git push`,
235
+ };
236
+ }
237
+ return {
238
+ name: "Origin",
239
+ state: "ok",
240
+ detail: `HEAD is origin/${branch} (${facts.head.slice(0, 7)}).`,
241
+ };
242
+ }
243
+
244
+ function ciGate(facts: Facts, options: Options, config: ResolvedConfig): Gate {
245
+ if (config.ciWorkflow === undefined) {
246
+ return {
247
+ name: "CI",
248
+ state: "off",
249
+ detail:
250
+ "CI gate: off. packages/tooling/src/deploy.config.ts names no ciWorkflow.",
251
+ };
252
+ }
253
+ if (options.skipCi !== undefined) {
254
+ return {
255
+ name: "CI",
256
+ state: "off",
257
+ detail: `CI gate: skipped (${options.skipCi}). The reason goes into the tag message.`,
258
+ };
259
+ }
260
+ const workflow = config.ciWorkflow;
261
+ if (facts.ci === "passed") {
262
+ return { name: "CI", state: "ok", detail: `${workflow} passed on HEAD.` };
263
+ }
264
+ const why = {
265
+ failed: `${workflow} failed on HEAD. Fix it, push, and wait for a green run: gh run watch.`,
266
+ missing: `${workflow} has no run on HEAD. Push the commit and wait for the run: gh run watch.`,
267
+ off: `The run did not read ${workflow}. Run the deploy again.`,
268
+ running: `${workflow} is still running on HEAD. Run: gh run watch, then deploy again.`,
269
+ }[facts.ci];
270
+ return {
271
+ name: "CI",
272
+ state: "fail",
273
+ detail: `${why} When GitHub Actions itself is down, run: pnpm deploy:production --skip-ci "<reason>"`,
274
+ };
275
+ }
276
+
277
+ function migrationGate(facts: Facts, options: Options): Gate {
278
+ if (options.migrate && !facts.hasDb) {
279
+ return {
280
+ name: "Migrations",
281
+ state: "fail",
282
+ detail:
283
+ "--migrate needs the @repo/db workspace, and this project has none. Run the deploy without --migrate.",
284
+ };
285
+ }
286
+ const count = facts.newMigrations.length;
287
+ if (count > 0 && !options.migrate) {
288
+ const since = facts.lastTag ?? "the first commit (no deploy tag yet)";
289
+ return {
290
+ name: "Migrations",
291
+ state: "fail",
292
+ detail: `${count} migration file(s) changed since ${since}. Read the SQL, then run: pnpm deploy:production --migrate`,
293
+ };
294
+ }
295
+ if (count > 0) {
296
+ return {
297
+ name: "Migrations",
298
+ state: "ok",
299
+ detail: `${count} migration file(s) changed, and --migrate runs them first.`,
300
+ };
301
+ }
302
+ return {
303
+ name: "Migrations",
304
+ state: "ok",
305
+ detail: options.migrate
306
+ ? "No migration file changed. --migrate runs the migration anyway."
307
+ : `No migration file changed since ${facts.lastTag ?? "the first commit (no deploy tag yet)"}.`,
308
+ };
309
+ }
310
+
311
+ /** Every gate, passed or not. */
312
+ export function gateReport(
313
+ facts: Facts,
314
+ options: Options,
315
+ config: ResolvedConfig
316
+ ): Gate[] {
317
+ return [
318
+ branchGate(facts, config),
319
+ treeGate(facts),
320
+ originGate(facts),
321
+ ciGate(facts, options, config),
322
+ migrationGate(facts, options),
323
+ ];
324
+ }
325
+
326
+ /** Every reason the deploy may not start. An empty list means every gate passed. */
327
+ export function gateProblems(
328
+ facts: Facts,
329
+ options: Options,
330
+ config: ResolvedConfig
331
+ ): string[] {
332
+ return gateReport(facts, options, config)
333
+ .filter((gate) => gate.state === "fail")
334
+ .map((gate) => gate.detail);
335
+ }
336
+
337
+ // ---- Targets and smoke checks --------------------------------------------------------------
338
+
339
+ const TARGETS_FILE = "packages/tooling/src/targets.ts";
340
+
341
+ /**
342
+ * The deploy order. `deployable` is every workspace under `apps/` with a wrangler config
343
+ * and a `deploy` script. A workspace with no row, a row for a service that does not
344
+ * deploy, and a service listed twice each stop the deploy: the engine refuses rather
345
+ * than guess where a Worker goes in the order.
346
+ */
347
+ export function orderTargets(
348
+ targets: readonly DeployTarget[],
349
+ deployable: readonly string[]
350
+ ): { order: string[]; problems: string[] } {
351
+ const problems: string[] = [];
352
+ const seen = new Set<string>();
353
+ for (const target of targets) {
354
+ if (seen.has(target.service)) {
355
+ problems.push(
356
+ `DEPLOY_TARGETS lists ${target.service} twice. Keep one row in ${TARGETS_FILE}.`
357
+ );
358
+ }
359
+ seen.add(target.service);
360
+ if (!deployable.includes(target.service)) {
361
+ problems.push(
362
+ `DEPLOY_TARGETS names ${target.service}, and apps/${target.service} is not a workspace with a wrangler.jsonc and a deploy script. Remove the row from ${TARGETS_FILE}.`
363
+ );
364
+ }
365
+ }
366
+ for (const service of deployable) {
367
+ if (!seen.has(service)) {
368
+ problems.push(
369
+ `apps/${service} deploys and has no DEPLOY_TARGETS row, so its place in the order is unknown. Add { service: "${service}", order: <number> } to ${TARGETS_FILE}.`
370
+ );
371
+ }
372
+ }
373
+ const order = targets
374
+ .filter((target) => deployable.includes(target.service))
375
+ .toSorted((a, b) => a.order - b.order || a.service.localeCompare(b.service))
376
+ .map((target) => target.service)
377
+ .filter((service, index, all) => all.indexOf(service) === index);
378
+ return { order, problems };
379
+ }
380
+
381
+ /** Rows that name a service that does not deploy, or reuse an id. */
382
+ export function smokeRowProblems(
383
+ checks: readonly SmokeCheck[],
384
+ deployable: readonly string[]
385
+ ): string[] {
386
+ const problems: string[] = [];
387
+ const seen = new Set<string>();
388
+ for (const check of checks) {
389
+ if (seen.has(check.id)) {
390
+ problems.push(
391
+ `SMOKE_CHECKS lists ${check.id} twice. Keep one row in ${TARGETS_FILE}.`
392
+ );
393
+ }
394
+ seen.add(check.id);
395
+ if (!deployable.includes(check.service)) {
396
+ problems.push(
397
+ `SMOKE_CHECKS row ${check.id} names ${check.service}, which does not deploy. Remove the row from ${TARGETS_FILE}.`
398
+ );
399
+ }
400
+ }
401
+ return problems;
402
+ }
403
+
404
+ /** A smoke check with the full URL it requests. */
405
+ export interface SmokeRequest extends SmokeCheck {
406
+ url: string;
407
+ }
408
+
409
+ function isRecord(value: unknown): value is Record<string, unknown> {
410
+ return typeof value === "object" && value !== null && !Array.isArray(value);
411
+ }
412
+
413
+ /** The hosts of the `routes[]` entries that set `custom_domain: true`. */
414
+ function customDomains(wranglerConfig: unknown): string[] {
415
+ if (!isRecord(wranglerConfig) || !Array.isArray(wranglerConfig.routes)) {
416
+ return [];
417
+ }
418
+ const routes: unknown[] = wranglerConfig.routes;
419
+ return routes.flatMap((route) =>
420
+ isRecord(route) &&
421
+ route.custom_domain === true &&
422
+ typeof route.pattern === "string"
423
+ ? [route.pattern.replace(/\/+$/, "")]
424
+ : []
425
+ );
426
+ }
427
+
428
+ /**
429
+ * One request per custom domain of `service` and smoke check for it. A service with no
430
+ * custom domain gets none: a `workers.dev` address is never guessed.
431
+ */
432
+ export function smokeUrls(
433
+ service: string,
434
+ wranglerConfig: unknown,
435
+ checks: readonly SmokeCheck[]
436
+ ): SmokeRequest[] {
437
+ const own = checks.filter((check) => check.service === service);
438
+ return customDomains(wranglerConfig).flatMap((host) =>
439
+ own.map((check) => ({ ...check, url: `https://${host}${check.path}` }))
440
+ );
441
+ }
442
+
443
+ export function smokeProblem(
444
+ request: SmokeRequest,
445
+ status: number,
446
+ body: string
447
+ ): string | undefined {
448
+ if (status !== request.status) {
449
+ return `${request.url} answered ${status}, expected ${request.status}.`;
450
+ }
451
+ if (request.body !== undefined && !body.includes(request.body)) {
452
+ return `${request.url} answered ${status} without ${request.body} in the body.`;
453
+ }
454
+ return undefined;
455
+ }
456
+
457
+ // ---- Release -------------------------------------------------------------------------------
458
+
459
+ /** The version a deploy names: the release tag on HEAD, or how far HEAD is past one. */
460
+ export function releaseLabel(release: ReleaseFacts): string {
461
+ if (release.onHead !== undefined) {
462
+ return release.onHead;
463
+ }
464
+ if (release.latest === undefined) {
465
+ return "no release tag";
466
+ }
467
+ return `${release.after.length} commit(s) after ${release.latest}`;
468
+ }
469
+
470
+ /**
471
+ * The warning a deploy prints when HEAD is not a release commit, or undefined when it is.
472
+ * CHANGELOG.md then does not list everything the deploy ships. It never stops the
473
+ * deploy, so an urgent hotfix goes out first and gets its release after.
474
+ */
475
+ export function releaseWarning(
476
+ release: ReleaseFacts,
477
+ lastTag?: string
478
+ ): string | undefined {
479
+ if (release.onHead !== undefined) {
480
+ return undefined;
481
+ }
482
+ const advice =
483
+ "Stop and run pnpm release first, unless this is an urgent hotfix.";
484
+ if (release.latest === undefined) {
485
+ return `HEAD has no release tag yet, so CHANGELOG.md does not list what this deploy ships. ${advice}`;
486
+ }
487
+ const what = release.sinceDeploy
488
+ ? `HEAD is ${release.after.length} commit(s) past ${release.latest}`
489
+ : `No release since the last deploy tag (${lastTag ?? "none"}), and HEAD is ${release.after.length} commit(s) past ${release.latest}`;
490
+ const rows = release.after.map((row) => `\n ${row}`).join("");
491
+ return `${what}, so CHANGELOG.md does not list these commits:${rows}\n${advice}`;
492
+ }
493
+
494
+ // ---- Tag -----------------------------------------------------------------------------------
495
+
496
+ /** `deploy-20261023-1430`, in UTC, so tags sort in the order the deploys happened. */
497
+ export function tagName(now: Date, prefix: string): string {
498
+ const iso = now.toISOString();
499
+ return `${prefix}${iso.slice(0, 10).replaceAll("-", "")}-${iso.slice(11, 16).replace(":", "")}`;
500
+ }
501
+
502
+ const MIGRATE = ["--filter", "@repo/db", "run", "db:prod:migrate"];
503
+
504
+ export function tagMessage(
505
+ head: string,
506
+ options: Options,
507
+ services: readonly string[],
508
+ release: string
509
+ ): string {
510
+ const lines = [
511
+ `Production deploy of ${head.slice(0, 7)} (${release}): ${services.join(", ")}.`,
512
+ ];
513
+ if (options.migrate) {
514
+ lines.push(`Ran pnpm ${MIGRATE.join(" ")} first.`);
515
+ }
516
+ if (options.skipCi !== undefined) {
517
+ lines.push(`CI gate skipped: ${options.skipCi}`);
518
+ }
519
+ return lines.join("\n");
520
+ }
521
+
522
+ // ---- The run -------------------------------------------------------------------------------
523
+
524
+ /** A workspace under `apps/` that deploys. */
525
+ export interface Workspace {
526
+ /** The directory name under `apps/`, which is also its `SERVICES` name. */
527
+ service: string;
528
+ /** The `name` in its `package.json`, for `pnpm --filter`. */
529
+ packageName: string;
530
+ }
531
+
532
+ export interface Answer {
533
+ status: number;
534
+ text: () => Promise<string>;
535
+ }
536
+
537
+ /** Every side effect the run has, so a test can fake each one. */
538
+ export interface Io {
539
+ /** Run git and answer its trimmed stdout. Throws when git exits non-zero. */
540
+ git: (args: string[]) => string;
541
+ /** Run gh and answer its stdout. Throws when gh exits non-zero. */
542
+ gh: (args: string[]) => string;
543
+ /** Run a command at the repository root with inherited output, and answer its exit code. */
544
+ run: (command: string, args: string[]) => Promise<number>;
545
+ fetch: (url: string) => Promise<Answer>;
546
+ sleep: (ms: number) => Promise<void>;
547
+ say: (text: string) => void;
548
+ now: () => Date;
549
+ /** Every workspace under `apps/` with a wrangler config and a `deploy` script. */
550
+ workspaces: () => Workspace[];
551
+ /** The parsed `apps/<service>/wrangler.jsonc`, or undefined when there is none. */
552
+ wranglerConfig: (service: string) => unknown;
553
+ /** Whether `packages/db` holds the `@repo/db` workspace. */
554
+ hasDb: () => boolean;
555
+ }
556
+
557
+ export interface Project {
558
+ config: DeployConfig;
559
+ targets: readonly DeployTarget[];
560
+ smokeChecks: readonly SmokeCheck[];
561
+ }
562
+
563
+ const SMOKE_TRIES = 3;
564
+ const SMOKE_PAUSE_MS = 5000;
565
+ const ENV_CHECK = ["packages/env/src/deploy.ts", "--check"];
566
+
567
+ function tryGit(io: Io, args: string[]): string | undefined {
568
+ try {
569
+ return io.git(args);
570
+ } catch {
571
+ return undefined;
572
+ }
573
+ }
574
+
575
+ function splitLines(text: string | undefined): string[] {
576
+ return (text ?? "").split("\n").filter((line) => line.trim() !== "");
577
+ }
578
+
579
+ function readCi(io: Io, workflow: string, head: string): CiState {
580
+ const output = io.gh([
581
+ "run",
582
+ "list",
583
+ "--workflow",
584
+ workflow,
585
+ "--commit",
586
+ head,
587
+ "--json",
588
+ "status,conclusion",
589
+ ]);
590
+ const parsed: unknown = JSON.parse(output);
591
+ const runs = Array.isArray(parsed)
592
+ ? parsed.filter(isRecord).map((run) => ({
593
+ status: typeof run.status === "string" ? run.status : "",
594
+ conclusion: typeof run.conclusion === "string" ? run.conclusion : "",
595
+ }))
596
+ : [];
597
+ return ciState(runs);
598
+ }
599
+
600
+ function readFacts(io: Io, options: Options, config: ResolvedConfig): Facts {
601
+ // A repository with no commit has no HEAD, and every git read below would fail with
602
+ // git's own "ambiguous argument 'HEAD'". Name the gate and its fix instead.
603
+ const head = tryGit(io, ["rev-parse", "HEAD"]);
604
+ if (head === undefined) {
605
+ const first = config.branches[0] ?? "main";
606
+ throw new Error(
607
+ `The deploy did not start, because this repository has no commit yet, so there is nothing to deploy or tag. Run: git add -A && git commit -m "chore: first commit", then git push -u origin ${first}`
608
+ );
609
+ }
610
+ const branch = io.git(["rev-parse", "--abbrev-ref", "HEAD"]);
611
+ tryGit(io, ["fetch", "--quiet", "origin", branch]);
612
+ const lastTag = tryGit(io, [
613
+ "describe",
614
+ "--tags",
615
+ "--match",
616
+ `${config.tagPrefix}*`,
617
+ "--abbrev=0",
618
+ "HEAD",
619
+ ]);
620
+ const migrationArgs =
621
+ lastTag === undefined
622
+ ? ["ls-files", "--", config.migrations]
623
+ : ["diff", "--name-only", lastTag, "HEAD", "--", config.migrations];
624
+ const needsCi =
625
+ config.ciWorkflow !== undefined && options.skipCi === undefined;
626
+ return {
627
+ release: readRelease(io, config, lastTag),
628
+ branch,
629
+ // The status column starts with a space, so the path starts at the fourth character.
630
+ // Drop the status code by shape, not by width: a reader that trims the output takes
631
+ // the leading space off the first line (" M a" becomes "M a").
632
+ dirty: splitLines(io.git(["status", "--porcelain"])).map((line) =>
633
+ line.replace(/^\s*\S{1,2}\s+/, "")
634
+ ),
635
+ head,
636
+ remoteHead: tryGit(io, ["rev-parse", "--verify", `origin/${branch}`]),
637
+ ci:
638
+ needsCi && config.ciWorkflow !== undefined
639
+ ? readCi(io, config.ciWorkflow, head)
640
+ : "off",
641
+ lastTag,
642
+ newMigrations: splitLines(io.git(migrationArgs)),
643
+ hasDb: io.hasDb(),
644
+ };
645
+ }
646
+
647
+ function readRelease(
648
+ io: Io,
649
+ config: ResolvedConfig,
650
+ lastTag: string | undefined
651
+ ): ReleaseFacts {
652
+ const match = `${config.release.tagPrefix}*`;
653
+ const onHead = tryGit(io, [
654
+ "describe",
655
+ "--tags",
656
+ "--exact-match",
657
+ "--match",
658
+ match,
659
+ "HEAD",
660
+ ]);
661
+ const latest =
662
+ onHead ??
663
+ tryGit(io, ["describe", "--tags", "--match", match, "--abbrev=0", "HEAD"]);
664
+ if (latest === undefined) {
665
+ return { onHead, latest, after: [], sinceDeploy: false };
666
+ }
667
+ // The release is new when the last deploy tag does not already contain it.
668
+ const sinceDeploy =
669
+ lastTag === undefined ||
670
+ tryGit(io, ["merge-base", "--is-ancestor", latest, lastTag]) === undefined;
671
+ return {
672
+ onHead,
673
+ latest,
674
+ after:
675
+ onHead === undefined
676
+ ? splitLines(tryGit(io, ["log", "--oneline", `${latest}..HEAD`]))
677
+ : [],
678
+ sinceDeploy,
679
+ };
680
+ }
681
+
682
+ async function step(
683
+ io: Io,
684
+ title: string,
685
+ command: string,
686
+ args: string[]
687
+ ): Promise<void> {
688
+ io.say(`\n== ${title}: ${command} ${args.join(" ")}`);
689
+ if ((await io.run(command, args)) !== 0) {
690
+ throw new Error(`${title} failed. No deploy tag was written.`);
691
+ }
692
+ }
693
+
694
+ /** Each smoke request for `services`, and a line for each service that has none. */
695
+ function smokePlan(
696
+ io: Io,
697
+ services: readonly string[],
698
+ checks: readonly SmokeCheck[]
699
+ ): { requests: SmokeRequest[]; notes: string[] } {
700
+ const requests: SmokeRequest[] = [];
701
+ const notes: string[] = [];
702
+ for (const service of services) {
703
+ const own = checks.filter((check) => check.service === service);
704
+ if (own.length === 0) {
705
+ notes.push(`${service} has no smoke check in ${TARGETS_FILE}.`);
706
+ continue;
707
+ }
708
+ const found = smokeUrls(service, io.wranglerConfig(service), checks);
709
+ if (found.length === 0) {
710
+ notes.push(
711
+ `${service} has no custom domain (a routes[] entry with custom_domain: true in apps/${service}/wrangler.jsonc), so its ${own.length} smoke check(s) are skipped.`
712
+ );
713
+ }
714
+ requests.push(...found);
715
+ }
716
+ return { requests, notes };
717
+ }
718
+
719
+ async function smoke(io: Io, requests: SmokeRequest[]): Promise<string[]> {
720
+ const problems: string[] = [];
721
+ for (const request of requests) {
722
+ let problem: string | undefined = "no answer";
723
+ // A custom domain can serve the old version for a few seconds after an upload.
724
+ for (
725
+ let attempt = 0;
726
+ attempt < SMOKE_TRIES && problem !== undefined;
727
+ attempt += 1
728
+ ) {
729
+ if (attempt > 0) {
730
+ await io.sleep(SMOKE_PAUSE_MS);
731
+ }
732
+ try {
733
+ const answer = await io.fetch(request.url);
734
+ problem = smokeProblem(request, answer.status, await answer.text());
735
+ } catch (error) {
736
+ problem = `${request.url} did not answer: ${error instanceof Error ? error.message : String(error)}`;
737
+ }
738
+ }
739
+ io.say(`${problem === undefined ? "ok " : "FAIL"} ${request.url}`);
740
+ if (problem !== undefined) {
741
+ problems.push(problem);
742
+ }
743
+ }
744
+ return problems;
745
+ }
746
+
747
+ function rollbackLines(workspaces: readonly Workspace[]): string {
748
+ return workspaces
749
+ .map(
750
+ (workspace) =>
751
+ ` pnpm --filter ${workspace.packageName} exec env-deploy --run ${workspace.service} -- wrangler rollback`
752
+ )
753
+ .join("\n");
754
+ }
755
+
756
+ function list(items: readonly string[]): string {
757
+ return items.map((item) => `- ${item}`).join("\n");
758
+ }
759
+
760
+ /** Run the deploy, or the dry run. Throws with the reason when the run must exit 1. */
761
+ export async function deployProduction(
762
+ options: Options,
763
+ io: Io,
764
+ project: Project
765
+ ): Promise<void> {
766
+ const config = resolveConfig(project.config);
767
+ const workspaces = io.workspaces();
768
+ const deployable = workspaces.map((workspace) => workspace.service);
769
+
770
+ const planned = orderTargets(project.targets, deployable);
771
+ const planProblems = [
772
+ ...planned.problems,
773
+ ...smokeRowProblems(project.smokeChecks, deployable),
774
+ ];
775
+ if (
776
+ options.only !== undefined &&
777
+ planned.problems.length === 0 &&
778
+ !planned.order.includes(options.only)
779
+ ) {
780
+ planProblems.push(
781
+ `--only ${options.only} is not a deploy target. Choose ${planned.order.join(", ") || "none"}.`
782
+ );
783
+ }
784
+ if (planProblems.length > 0) {
785
+ throw new Error(
786
+ `The deploy did not start, because the targets are wrong:\n${list(planProblems)}`
787
+ );
788
+ }
789
+ const services = options.only === undefined ? planned.order : [options.only];
790
+ const chosen = services.flatMap((service) =>
791
+ workspaces.filter((workspace) => workspace.service === service)
792
+ );
793
+
794
+ const facts = readFacts(io, options, config);
795
+ const release = releaseLabel(facts.release);
796
+ io.say(`Branch ${facts.branch} at ${facts.head.slice(0, 7)} (${release}).`);
797
+ if (facts.lastTag === undefined) {
798
+ io.say("No deploy tag yet. This deploy writes the first one.");
799
+ } else {
800
+ const shipped = tryGit(io, ["log", "--oneline", `${facts.lastTag}..HEAD`]);
801
+ io.say(`Last deploy: ${facts.lastTag}. Commits this deploy ships:`);
802
+ io.say(
803
+ shipped === undefined || shipped === ""
804
+ ? " (none, a redeploy of the same commit)"
805
+ : shipped
806
+ );
807
+ }
808
+ if (facts.newMigrations.length > 0) {
809
+ io.say(
810
+ `Migration files since the last deploy:\n ${facts.newMigrations.join("\n ")}`
811
+ );
812
+ }
813
+
814
+ const warning = releaseWarning(facts.release, facts.lastTag);
815
+ if (warning !== undefined) {
816
+ io.say(`\nWarning: ${warning}`);
817
+ }
818
+
819
+ const gates = gateReport(facts, options, config);
820
+ io.say("\nGates:");
821
+ for (const gate of gates) {
822
+ io.say(` ${gate.state.padEnd(4)} ${gate.detail}`);
823
+ }
824
+ const problems = gates
825
+ .filter((gate) => gate.state === "fail")
826
+ .map((gate) => gate.detail);
827
+
828
+ const order = services
829
+ .map((service) => {
830
+ const target = project.targets.find((each) => each.service === service);
831
+ return `${service} (${target?.order ?? "?"})`;
832
+ })
833
+ .join(", ");
834
+ io.say(`\nDeploy order: ${order}`);
835
+
836
+ const plan = smokePlan(io, services, project.smokeChecks);
837
+ io.say("\nSmoke checks:");
838
+ for (const request of plan.requests) {
839
+ io.say(
840
+ ` ${request.service}: ${request.url} answers ${request.status}${request.body === undefined ? "" : ` with ${request.body}`}`
841
+ );
842
+ }
843
+ for (const note of plan.notes) {
844
+ io.say(` ${note}`);
845
+ }
846
+
847
+ if (options.dryRun) {
848
+ io.say(`\n== Env check: node ${ENV_CHECK.join(" ")}`);
849
+ const envExit = await io.run("node", ENV_CHECK);
850
+ if (envExit !== 0) {
851
+ io.say("A real deploy would stop at the env check above.");
852
+ }
853
+ if (options.migrate) {
854
+ io.say(
855
+ `\nA real deploy runs pnpm ${MIGRATE.join(" ")} here. The dry run does not.`
856
+ );
857
+ }
858
+ const stops =
859
+ envExit === 0 ? problems : [...problems, "The env check failed."];
860
+ io.say(
861
+ stops.length > 0
862
+ ? `\nDry run done. A real deploy would stop:\n${list(stops)}`
863
+ : "\nDry run done. Every gate passed. Nothing was built, uploaded, migrated or tagged."
864
+ );
865
+ return;
866
+ }
867
+
868
+ if (problems.length > 0) {
869
+ throw new Error(
870
+ `The deploy did not start. Clear each gate, then run it again:\n${list(problems)}`
871
+ );
872
+ }
873
+
874
+ await step(io, "Env check", "node", ENV_CHECK);
875
+ if (options.migrate) {
876
+ await step(io, "Migrate", "pnpm", MIGRATE);
877
+ }
878
+ const deployed: Workspace[] = [];
879
+ for (const workspace of chosen) {
880
+ try {
881
+ await step(io, `Deploy ${workspace.service}`, "pnpm", [
882
+ "--filter",
883
+ workspace.packageName,
884
+ "run",
885
+ "deploy",
886
+ ]);
887
+ } catch (error) {
888
+ const live =
889
+ deployed.length > 0
890
+ ? `\nThese Workers are already live on the new commit. Roll one back with:\n${rollbackLines(deployed)}`
891
+ : "";
892
+ throw new Error(
893
+ `${error instanceof Error ? error.message : String(error)}${live}`,
894
+ { cause: error }
895
+ );
896
+ }
897
+ deployed.push(workspace);
898
+ }
899
+
900
+ io.say("\n== Smoke checks");
901
+ const failed = await smoke(io, plan.requests);
902
+ if (failed.length > 0) {
903
+ throw new Error(
904
+ `The Workers are live, and a smoke check failed:\n${list(failed)}\nNo deploy tag was written. Fix and deploy again, or roll each Worker back:\n${rollbackLines(deployed)}`
905
+ );
906
+ }
907
+
908
+ if (options.only !== undefined) {
909
+ io.say(
910
+ `\n${options.only} is live. A one-Worker deploy writes no tag, because the other Workers may run an older commit.`
911
+ );
912
+ return;
913
+ }
914
+ const tag = tagName(io.now(), config.tagPrefix);
915
+ io.git([
916
+ "tag",
917
+ "--annotate",
918
+ tag,
919
+ "--message",
920
+ tagMessage(facts.head, options, services, release),
921
+ ]);
922
+ try {
923
+ io.git(["push", "--quiet", "origin", tag]);
924
+ } catch (error) {
925
+ throw new Error(
926
+ `Deployed ${facts.head.slice(0, 7)} and wrote the tag ${tag}, and the push failed, so the tag is local only. The Workers stay live. Run: git push origin ${tag}`,
927
+ { cause: error }
928
+ );
929
+ }
930
+ io.say(
931
+ `\nDeployed ${facts.head.slice(0, 7)} (${release}) and pushed the tag ${tag}.`
932
+ );
933
+ }
934
+
935
+ // ---- The real side effects -----------------------------------------------------------------
936
+
937
+ function readJson(file: string): unknown {
938
+ return parseJsonc(readFileSync(file, "utf-8"));
939
+ }
940
+
941
+ function wranglerFile(dir: string): string | undefined {
942
+ return ["wrangler.jsonc", "wrangler.json"]
943
+ .map((name) => path.join(dir, name))
944
+ .find((file) => existsSync(file));
945
+ }
946
+
947
+ function findWorkspaces(root: string): Workspace[] {
948
+ const apps = path.join(root, "apps");
949
+ if (!existsSync(apps)) {
950
+ return [];
951
+ }
952
+ return readdirSync(apps, { withFileTypes: true })
953
+ .filter((entry) => entry.isDirectory())
954
+ .flatMap((entry) => {
955
+ const dir = path.join(apps, entry.name);
956
+ const manifest = path.join(dir, "package.json");
957
+ if (!existsSync(manifest) || wranglerFile(dir) === undefined) {
958
+ return [];
959
+ }
960
+ const parsed = readJson(manifest);
961
+ const scripts = isRecord(parsed) ? parsed.scripts : undefined;
962
+ const name = isRecord(parsed) ? parsed.name : undefined;
963
+ return isRecord(scripts) &&
964
+ typeof scripts.deploy === "string" &&
965
+ typeof name === "string"
966
+ ? [{ service: entry.name, packageName: name }]
967
+ : [];
968
+ })
969
+ .toSorted((a, b) => a.service.localeCompare(b.service));
970
+ }
971
+
972
+ function hasDbWorkspace(root: string): boolean {
973
+ const manifest = path.join(root, "packages/db/package.json");
974
+ if (!existsSync(manifest)) {
975
+ return false;
976
+ }
977
+ const parsed = readJson(manifest);
978
+ return isRecord(parsed) && parsed.name === "@repo/db";
979
+ }
980
+
981
+ function nodeIo(root: string): Io {
982
+ const exec = (command: string, args: string[]): string =>
983
+ execFileSync(command, args, {
984
+ cwd: root,
985
+ encoding: "utf-8",
986
+ // A failed read is a fact the gates report, so git's own stderr stays out of it.
987
+ stdio: ["ignore", "pipe", "pipe"],
988
+ });
989
+ return {
990
+ // Only the trailing newline goes: `status --porcelain` starts a line with a space.
991
+ git: (args) => exec("git", args).trimEnd(),
992
+ gh: (args) => exec("gh", args),
993
+ run: async (command, args) =>
994
+ // `spawn` reports through events, not a promise, so this wraps it in one.
995
+ // oxlint-disable-next-line promise/avoid-new
996
+ await new Promise((resolve, reject) => {
997
+ const child = spawn(command, args, { cwd: root, stdio: "inherit" });
998
+ child.on("error", reject);
999
+ child.on("exit", (code, signal) => {
1000
+ resolve(code ?? (signal ? 1 : 0));
1001
+ });
1002
+ }),
1003
+ fetch: async (url) => await fetch(url, { redirect: "manual" }),
1004
+ sleep: async (ms) => {
1005
+ await delay(ms);
1006
+ },
1007
+ say: (text) => {
1008
+ process.stdout.write(`${text}\n`);
1009
+ },
1010
+ now: () => new Date(),
1011
+ workspaces: () => findWorkspaces(root),
1012
+ wranglerConfig: (service) => {
1013
+ const file = wranglerFile(path.join(root, "apps", service));
1014
+ return file === undefined ? undefined : readJson(file);
1015
+ },
1016
+ hasDb: () => hasDbWorkspace(root),
1017
+ };
1018
+ }
1019
+
1020
+ async function main(): Promise<void> {
1021
+ const options = parseArgs(process.argv.slice(2));
1022
+ const root = execFileSync("git", ["rev-parse", "--show-toplevel"], {
1023
+ encoding: "utf-8",
1024
+ }).trim();
1025
+ await deployProduction(options, nodeIo(root), {
1026
+ config: deployConfig,
1027
+ targets: DEPLOY_TARGETS,
1028
+ smokeChecks: SMOKE_CHECKS,
1029
+ });
1030
+ }
1031
+
1032
+ if (import.meta.main) {
1033
+ try {
1034
+ await main();
1035
+ } catch (error) {
1036
+ process.stderr.write(
1037
+ `\n${error instanceof Error ? error.message : String(error)}\n`
1038
+ );
1039
+ process.exitCode = 1;
1040
+ }
1041
+ }