hazo_env 0.10.4 → 0.11.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 (53) hide show
  1. package/CHANGE_LOG.md +69 -0
  2. package/config/hazo_env_config.ini.sample +61 -0
  3. package/dist/cli.js +315 -0
  4. package/dist/deploy/build.d.ts +90 -0
  5. package/dist/deploy/build.d.ts.map +1 -0
  6. package/dist/deploy/build.js +299 -0
  7. package/dist/deploy/clean.d.ts +63 -0
  8. package/dist/deploy/clean.d.ts.map +1 -0
  9. package/dist/deploy/clean.js +135 -0
  10. package/dist/deploy/index.d.ts +6 -0
  11. package/dist/deploy/index.d.ts.map +1 -0
  12. package/dist/deploy/index.js +6 -0
  13. package/dist/deploy/init.d.ts +20 -0
  14. package/dist/deploy/init.d.ts.map +1 -0
  15. package/dist/deploy/init.js +80 -0
  16. package/dist/deploy/peer.d.ts +18 -0
  17. package/dist/deploy/peer.d.ts.map +1 -0
  18. package/dist/deploy/peer.js +48 -0
  19. package/dist/deploy/pm2-start.d.ts +88 -0
  20. package/dist/deploy/pm2-start.d.ts.map +1 -0
  21. package/dist/deploy/pm2-start.js +196 -0
  22. package/dist/deploy/rollback.d.ts +18 -0
  23. package/dist/deploy/rollback.d.ts.map +1 -0
  24. package/dist/deploy/rollback.js +167 -0
  25. package/dist/deploy/runner.d.ts +8 -0
  26. package/dist/deploy/runner.d.ts.map +1 -0
  27. package/dist/deploy/runner.js +35 -0
  28. package/dist/deploy/state.d.ts +19 -0
  29. package/dist/deploy/state.d.ts.map +1 -0
  30. package/dist/deploy/state.js +52 -0
  31. package/dist/deploy/status.d.ts +54 -0
  32. package/dist/deploy/status.d.ts.map +1 -0
  33. package/dist/deploy/status.js +182 -0
  34. package/dist/deploy/switch.d.ts +27 -0
  35. package/dist/deploy/switch.d.ts.map +1 -0
  36. package/dist/deploy/switch.js +152 -0
  37. package/dist/deploy/types.d.ts +96 -0
  38. package/dist/deploy/types.d.ts.map +1 -0
  39. package/dist/deploy/types.js +16 -0
  40. package/dist/deploy/verify.d.ts +41 -0
  41. package/dist/deploy/verify.d.ts.map +1 -0
  42. package/dist/deploy/verify.js +214 -0
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +3 -0
  46. package/dist/resolve/connect.d.ts.map +1 -1
  47. package/dist/resolve/connect.js +15 -1
  48. package/dist/resolve/deploy.d.ts +8 -0
  49. package/dist/resolve/deploy.d.ts.map +1 -0
  50. package/dist/resolve/deploy.js +121 -0
  51. package/dist/types/index.d.ts +10 -0
  52. package/dist/types/index.d.ts.map +1 -1
  53. package/package.json +3 -3
@@ -0,0 +1,54 @@
1
+ import type { CommandRunner, DeployConfig } from './types.js';
2
+ /** Snapshot of one directory's role in the blue/green pair. */
3
+ export interface DeployDirStatus {
4
+ role: 'live' | 'standby';
5
+ dir: string;
6
+ port: number;
7
+ /** Whether a PM2 process with a matching cwd is currently online. */
8
+ running: boolean;
9
+ pid?: number;
10
+ pm2Status?: string;
11
+ }
12
+ export interface DeployStatusResult {
13
+ appName: string;
14
+ /** False when no state file exists yet (fresh setup, before `deploy init`). */
15
+ stateFound: boolean;
16
+ live?: DeployDirStatus;
17
+ standby?: DeployDirStatus;
18
+ diskFreeMb?: number;
19
+ memoryFreeMb?: number;
20
+ minMemoryMb: number;
21
+ memoryLow: boolean;
22
+ lastSwitch?: string;
23
+ lastBuild?: string;
24
+ lastBuildStatus?: 'success' | 'failed';
25
+ /** Non-fatal problems encountered while gathering status (pm2 unavailable, unparsable df output, ...). */
26
+ warnings: string[];
27
+ }
28
+ /**
29
+ * Exported so `deploy clean` (src/deploy/clean.ts) can reuse the same
30
+ * free-memory probe for its swap-suggestion trigger instead of duplicating
31
+ * this platform-specific (/proc/meminfo vs vm_stat) parsing logic.
32
+ */
33
+ export declare function queryMemoryFreeMb(runner: CommandRunner, warnings: string[]): number | undefined;
34
+ /**
35
+ * Exported so `deploy build` (src/deploy/build.ts) can reuse the same
36
+ * `df`-based free-disk probe for its post-cleanup threshold check instead of
37
+ * duplicating this parsing logic — mirrors `queryMemoryFreeMb`'s export.
38
+ */
39
+ export declare function queryDiskFreeMb(runner: CommandRunner, dir: string, warnings: string[]): number | undefined;
40
+ export interface RunStatusOptions {
41
+ /** Directory to check disk free space on. Defaults to process.cwd(). */
42
+ cwd?: string;
43
+ }
44
+ /**
45
+ * Gather structured deploy status: which dir is live/standby, their ports
46
+ * and PM2 running state, disk/memory free, and the last build/switch info
47
+ * from the state file. Returns data only — src/cli.ts formats and prints it.
48
+ *
49
+ * Gracefully handles a missing state file (fresh setup, before `deploy
50
+ * init`): `stateFound` is false and `live`/`standby` are omitted, but
51
+ * disk/memory are still reported.
52
+ */
53
+ export declare function runStatus(config: DeployConfig, runner: CommandRunner, opts?: RunStatusOptions): DeployStatusResult;
54
+ //# sourceMappingURL=status.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../../src/deploy/status.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAE3E,+DAA+D;AAC/D,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,qEAAqE;IACrE,OAAO,EAAE,OAAO,CAAC;IACjB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,UAAU,EAAE,OAAO,CAAC;IACpB,IAAI,CAAC,EAAE,eAAe,CAAC;IACvB,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,OAAO,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,eAAe,CAAC,EAAE,SAAS,GAAG,QAAQ,CAAC;IACvC,0GAA0G;IAC1G,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAsHD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,SAAS,CAe/F;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,SAAS,CAO1G;AAED,MAAM,WAAW,gBAAgB;IAC/B,wEAAwE;IACxE,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CACvB,MAAM,EAAE,YAAY,EACpB,MAAM,EAAE,aAAa,EACrB,IAAI,GAAE,gBAAqB,GAC1B,kBAAkB,CAoCpB"}
@@ -0,0 +1,182 @@
1
+ // hazo_env/src/deploy/status.ts — `deploy status` data gathering
2
+ //
3
+ // The first end-to-end deploy subcommand: resolves config, reads the state
4
+ // file, and queries PM2/disk/memory — all through the injected CommandRunner
5
+ // (the ONLY touchpoint for child_process is src/deploy/runner.ts; this file
6
+ // must never import node:child_process directly). Mirrors envsync/engine.ts's
7
+ // split of "compute structured data" from "format for console" — src/cli.ts
8
+ // does the printing, this file only returns data.
9
+ import path from 'node:path';
10
+ import { readState } from './state.js';
11
+ /**
12
+ * Query `pm2 jlist` and parse the JSON process list. Returns an empty list
13
+ * (plus a warning) rather than throwing when pm2 isn't installed/running or
14
+ * emits unparsable output — status should degrade gracefully, not crash.
15
+ */
16
+ function queryPm2Processes(runner, warnings) {
17
+ const result = runner.spawn('pm2 jlist');
18
+ if (result.code !== 0) {
19
+ warnings.push(`pm2 jlist failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'}`);
20
+ return [];
21
+ }
22
+ try {
23
+ const parsed = JSON.parse(result.stdout);
24
+ return Array.isArray(parsed) ? parsed : [];
25
+ }
26
+ catch {
27
+ warnings.push('pm2 jlist returned unparsable JSON');
28
+ return [];
29
+ }
30
+ }
31
+ /**
32
+ * Find the PM2 process whose cwd matches `dir`, if any.
33
+ *
34
+ * This depends on `pm2_env.pm_cwd` being set, which PM2 only does when
35
+ * `cwd` is passed explicitly to `pm2 start` (see the contract noted next
36
+ * to `DeployState['pm2_process']` in types.ts). If a later task's
37
+ * `pm2 start` invocation omits `cwd`, `pm_cwd` defaults to wherever
38
+ * `pm2 start` itself ran from and this match silently fails (reports
39
+ * "not running" with no error).
40
+ */
41
+ function findPm2ProcessForDir(processes, dir) {
42
+ const target = path.resolve(dir);
43
+ return processes.find((p) => p.pm2_env?.pm_cwd && path.resolve(p.pm2_env.pm_cwd) === target);
44
+ }
45
+ function dirStatus(role, dir, port, processes) {
46
+ const proc = findPm2ProcessForDir(processes, dir);
47
+ const status = proc?.pm2_env?.status;
48
+ return {
49
+ role,
50
+ dir,
51
+ port,
52
+ running: status === 'online',
53
+ pid: proc?.pid,
54
+ pm2Status: status,
55
+ };
56
+ }
57
+ /**
58
+ * Parse `df -k <dir>` output into free MB. Expects the standard two-line
59
+ * form (header + one data line) with "Available" as the 4th column.
60
+ */
61
+ function parseDiskFreeMb(dfOutput, warnings) {
62
+ const lines = dfOutput.trim().split('\n').filter((l) => l.trim().length > 0);
63
+ if (lines.length < 2) {
64
+ warnings.push('df output had no data line to parse');
65
+ return undefined;
66
+ }
67
+ const columns = lines[1].trim().split(/\s+/);
68
+ const availableKb = Number(columns[3]);
69
+ if (!Number.isFinite(availableKb)) {
70
+ warnings.push(`df output's Available column was not numeric: "${lines[1]}"`);
71
+ return undefined;
72
+ }
73
+ return Math.round(availableKb / 1024);
74
+ }
75
+ /** Parse `/proc/meminfo` output into free MB, preferring MemAvailable over MemFree. */
76
+ function parseMeminfoFreeMb(meminfo, warnings) {
77
+ const available = meminfo.match(/^MemAvailable:\s+(\d+)\s*kB/m);
78
+ const free = meminfo.match(/^MemFree:\s+(\d+)\s*kB/m);
79
+ const match = available ?? free;
80
+ if (!match) {
81
+ warnings.push('/proc/meminfo did not contain MemAvailable or MemFree');
82
+ return undefined;
83
+ }
84
+ return Math.round(Number(match[1]) / 1024);
85
+ }
86
+ /**
87
+ * Parse macOS `vm_stat` output into free MB: (free pages) * page size.
88
+ * vm_stat reports in pages, with the page size given in its header line,
89
+ * e.g. "Mach Virtual Memory Statistics: (page size of 4096 bytes)".
90
+ */
91
+ function parseVmStatFreeMb(vmStat, warnings) {
92
+ const pageSizeMatch = vmStat.match(/page size of (\d+) bytes/);
93
+ const freePagesMatch = vmStat.match(/^Pages free:\s+(\d+)\.?/m);
94
+ if (!pageSizeMatch || !freePagesMatch) {
95
+ warnings.push('vm_stat output was missing page size or "Pages free" line');
96
+ return undefined;
97
+ }
98
+ const pageSize = Number(pageSizeMatch[1]);
99
+ const freePages = Number(freePagesMatch[1]);
100
+ if (!Number.isFinite(pageSize) || !Number.isFinite(freePages)) {
101
+ warnings.push('vm_stat output had non-numeric page size or free page count');
102
+ return undefined;
103
+ }
104
+ return Math.round((freePages * pageSize) / (1024 * 1024));
105
+ }
106
+ /**
107
+ * Exported so `deploy clean` (src/deploy/clean.ts) can reuse the same
108
+ * free-memory probe for its swap-suggestion trigger instead of duplicating
109
+ * this platform-specific (/proc/meminfo vs vm_stat) parsing logic.
110
+ */
111
+ export function queryMemoryFreeMb(runner, warnings) {
112
+ if (process.platform === 'darwin') {
113
+ const result = runner.spawn('vm_stat');
114
+ if (result.code !== 0) {
115
+ warnings.push(`vm_stat failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'}`);
116
+ return undefined;
117
+ }
118
+ return parseVmStatFreeMb(result.stdout, warnings);
119
+ }
120
+ const result = runner.spawn('cat /proc/meminfo');
121
+ if (result.code !== 0) {
122
+ warnings.push(`reading /proc/meminfo failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'}`);
123
+ return undefined;
124
+ }
125
+ return parseMeminfoFreeMb(result.stdout, warnings);
126
+ }
127
+ /**
128
+ * Exported so `deploy build` (src/deploy/build.ts) can reuse the same
129
+ * `df`-based free-disk probe for its post-cleanup threshold check instead of
130
+ * duplicating this parsing logic — mirrors `queryMemoryFreeMb`'s export.
131
+ */
132
+ export function queryDiskFreeMb(runner, dir, warnings) {
133
+ const result = runner.spawn(`df -k ${JSON.stringify(dir)}`);
134
+ if (result.code !== 0) {
135
+ warnings.push(`df failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'}`);
136
+ return undefined;
137
+ }
138
+ return parseDiskFreeMb(result.stdout, warnings);
139
+ }
140
+ /**
141
+ * Gather structured deploy status: which dir is live/standby, their ports
142
+ * and PM2 running state, disk/memory free, and the last build/switch info
143
+ * from the state file. Returns data only — src/cli.ts formats and prints it.
144
+ *
145
+ * Gracefully handles a missing state file (fresh setup, before `deploy
146
+ * init`): `stateFound` is false and `live`/`standby` are omitted, but
147
+ * disk/memory are still reported.
148
+ */
149
+ export function runStatus(config, runner, opts = {}) {
150
+ const warnings = [];
151
+ const state = readState(config.app_name);
152
+ const processes = queryPm2Processes(runner, warnings);
153
+ const cwd = opts.cwd ?? process.cwd();
154
+ const diskFreeMb = queryDiskFreeMb(runner, cwd, warnings);
155
+ const memoryFreeMb = queryMemoryFreeMb(runner, warnings);
156
+ const memoryLow = memoryFreeMb !== undefined && memoryFreeMb < config.min_memory_mb;
157
+ if (!state) {
158
+ return {
159
+ appName: config.app_name,
160
+ stateFound: false,
161
+ diskFreeMb,
162
+ memoryFreeMb,
163
+ minMemoryMb: config.min_memory_mb,
164
+ memoryLow,
165
+ warnings,
166
+ };
167
+ }
168
+ return {
169
+ appName: config.app_name,
170
+ stateFound: true,
171
+ live: dirStatus('live', state.live_dir, state.live_port, processes),
172
+ standby: dirStatus('standby', state.standby_dir, state.staging_port, processes),
173
+ diskFreeMb,
174
+ memoryFreeMb,
175
+ minMemoryMb: config.min_memory_mb,
176
+ memoryLow,
177
+ lastSwitch: state.last_switch,
178
+ lastBuild: state.last_build,
179
+ lastBuildStatus: state.last_build_status,
180
+ warnings,
181
+ };
182
+ }
@@ -0,0 +1,27 @@
1
+ import type { CommandRunner, DeployConfig, DeployState } from './types.js';
2
+ export interface PostSwitchHookResult {
3
+ cmd: string;
4
+ status: 'pass' | 'fail';
5
+ detail: string;
6
+ }
7
+ export interface RunSwitchResult {
8
+ previousLiveDir: string;
9
+ newLiveDir: string;
10
+ newStandbyDir: string;
11
+ prodPort: number;
12
+ stagingPort: number;
13
+ /** True iff a staging PM2 process was found and stopped (false if it was already stopped/absent). */
14
+ stagingStopped: boolean;
15
+ postSwitchHooks: PostSwitchHookResult[];
16
+ state: DeployState;
17
+ }
18
+ /** Thrown when there's nothing to switch (no state file yet) or a fatal step fails. */
19
+ export declare class SwitchAbortError extends Error {
20
+ constructor(message: string);
21
+ }
22
+ /**
23
+ * Promote the standby directory to live. See this file's header for the
24
+ * full step-by-step rationale.
25
+ */
26
+ export declare function runSwitch(config: DeployConfig, runner: CommandRunner): RunSwitchResult;
27
+ //# sourceMappingURL=switch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"switch.d.ts","sourceRoot":"","sources":["../../src/deploy/switch.ts"],"names":[],"mappings":"AA8DA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE3E,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,qGAAqG;IACrG,cAAc,EAAE,OAAO,CAAC;IACxB,eAAe,EAAE,oBAAoB,EAAE,CAAC;IACxC,KAAK,EAAE,WAAW,CAAC;CACpB;AAED,uFAAuF;AACvF,qBAAa,gBAAiB,SAAQ,KAAK;gBAC7B,OAAO,EAAE,MAAM;CAI5B;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,GAAG,eAAe,CAqFtF"}
@@ -0,0 +1,152 @@
1
+ // hazo_env/src/deploy/switch.ts — `deploy switch`: promote standby to live
2
+ //
3
+ // Makes the already-built, already-verified standby app live. This is the
4
+ // task that WRITES the new live/standby assignment — see build.ts's header
5
+ // for the bug (fixed there) that this file must not repeat: "live" is read
6
+ // from the state file (the authoritative source), never inferred from the
7
+ // blue/green directory-naming convention.
8
+ //
9
+ // Flow (see task-7 brief + the task-7 review fix-round for the full
10
+ // rationale):
11
+ // 1. Read state. No state file -> abort ("deploy init" hasn't run).
12
+ // 2. Read the git ref of the (about-to-be-promoted) standby dir FIRST,
13
+ // before anything is stopped/started — it's read-only, so there's no
14
+ // ordering reason to delay it, and reading it late (after the pm2 swap
15
+ // and hooks have already run) would leave state stale relative to
16
+ // reality if this read happened to fail.
17
+ // 3. Delete the current live PM2 process (`pm2 delete <app_name>` in the
18
+ // live dir) — see "pm2 delete, not stop" below for why `delete` (not
19
+ // `stop`) is required here. "process not found" (nothing registered —
20
+ // e.g. after a reboot without `pm2 save`, or a prior manual delete) is
21
+ // tolerated as non-fatal; any other failure aborts.
22
+ // 4. Delete the staging PM2 process (`pm2 delete <app_name>-staging`,
23
+ // matching build.ts's naming) if still registered — `pm2 stop` here
24
+ // would leave it registered with its `pm_cwd` pointing at THIS cycle's
25
+ // standby dir, so the NEXT `deploy build`'s `startNamedPm2Process` call
26
+ // for the same `-staging` name would restart that stale registration
27
+ // in place instead of creating a fresh one, silently health-checking
28
+ // the OLD build on the next cycle (same bug class as step 3, applied to
29
+ // the staging name). Non-fatal: the operator may have already deleted
30
+ // it, or `deploy build` may not have left it running.
31
+ // 5. Start the standby app on the PRODUCTION port under the PLAIN app name,
32
+ // via the shared `startNamedPm2Process` helper (see pm2-start.ts) — NOT
33
+ // a direct `pm2 start ecosystem.config.js --name ...`, which does not
34
+ // actually rename the process when starting from a config file (the
35
+ // same root-cause bug task 5/build.ts hit, fixed the same way here). On
36
+ // failure, attempts to restart the OLD live build (from the now-deleted
37
+ // live dir) so production isn't left down, and reports plainly whether
38
+ // that restoration succeeded.
39
+ // 6. Run post-switch hooks (`config.post_switch_cmds`), each independently
40
+ // non-fatal: a failing indexnow/cache-purge hook must never block the
41
+ // switch from completing or the state from updating.
42
+ // 7. Update state atomically: standby becomes live, (old) live becomes
43
+ // standby, `previous_live_dir` = the OLD live dir (for `deploy
44
+ // rollback`), `last_switch` + the git ref read in step 2 recorded.
45
+ //
46
+ // pm2 delete, not stop: `pm2 stop <app_name>` leaves the process
47
+ // REGISTERED (merely stopped) with its `pm_cwd` still pointing at the OLD
48
+ // live dir. Starting the standby app afterwards under that same
49
+ // `<app_name>` then doesn't create a fresh registration — pm2 sees the name
50
+ // is already registered and just restarts IT, from its existing (old,
51
+ // live-dir) `pm_cwd`, leaving production on the OLD build while the state
52
+ // file claims the standby dir is live. `pm2 delete` actually deregisters
53
+ // the old process, so `startNamedPm2Process`'s start (step 5) creates a
54
+ // genuinely fresh registration with the correct `pm_cwd`. There is only
55
+ // ever one `<app_name>` registration at a time, so there's no "preserve it
56
+ // for rollback" benefit to `stop` either — `deploy rollback` (task 8) will
57
+ // need to delete-then-fresh-start from `previous_live_dir` the same way, in
58
+ // the opposite direction.
59
+ import path from 'node:path';
60
+ import { readState, updateState } from './state.js';
61
+ import { promoteDirFresh, PromoteDirFreshError } from './pm2-start.js';
62
+ /** Thrown when there's nothing to switch (no state file yet) or a fatal step fails. */
63
+ export class SwitchAbortError extends Error {
64
+ constructor(message) {
65
+ super(message);
66
+ this.name = 'SwitchAbortError';
67
+ }
68
+ }
69
+ /**
70
+ * Promote the standby directory to live. See this file's header for the
71
+ * full step-by-step rationale.
72
+ */
73
+ export function runSwitch(config, runner) {
74
+ // Step 1: read state — the ONLY source of truth for which dir is live vs.
75
+ // standby. Never infer this from the blue/green naming convention here
76
+ // (see build.ts's header for why that was a critical bug there).
77
+ const state = readState(config.app_name);
78
+ if (!state) {
79
+ throw new SwitchAbortError(`No deploy state found for "${config.app_name}" — nothing to switch. Run "deploy init" first.`);
80
+ }
81
+ const oldLiveDir = path.resolve(state.live_dir);
82
+ const oldStandbyDir = path.resolve(state.standby_dir);
83
+ // Step 2: read the new live dir's git ref FIRST, before anything is
84
+ // stopped/started — read-only, so no ordering reason to delay it, and
85
+ // delaying it risks a late failure leaving state stale relative to a
86
+ // switch that already happened in reality (see header).
87
+ const gitRef = runner.exec('git rev-parse HEAD', { cwd: oldStandbyDir }).trim();
88
+ // Steps 3-5: delete (not stop — see header) the current live PM2
89
+ // registration, delete (same reason) the staging registration left by
90
+ // `deploy build`'s health check against the dir now being promoted (a
91
+ // stale one there would make the NEXT `deploy build`'s reuse of
92
+ // `<app>-staging` restart it in place instead of registering fresh — see
93
+ // promoteDirFresh's own header), then fresh-start the standby app on the
94
+ // production port via the shared helper (a direct `pm2 start
95
+ // ecosystem.config.js --name ...` does not actually rename the process —
96
+ // see header). On failure, promoteDirFresh itself attempts to bring the
97
+ // OLD live build back up so production isn't silently left down, and
98
+ // reports plainly whether that worked.
99
+ let stagingStopped;
100
+ try {
101
+ const result = promoteDirFresh(runner, {
102
+ fromDir: oldLiveDir,
103
+ toDir: oldStandbyDir,
104
+ name: config.app_name,
105
+ port: config.prod_port,
106
+ stagingName: `${config.app_name}-staging`,
107
+ toLabel: 'standby app',
108
+ fromLabel: 'the previous live build',
109
+ });
110
+ stagingStopped = result.stagingDeleted;
111
+ }
112
+ catch (e) {
113
+ if (e instanceof PromoteDirFreshError) {
114
+ throw new SwitchAbortError(e.message);
115
+ }
116
+ throw e;
117
+ }
118
+ // Step 6: post-switch hooks, each independently non-fatal.
119
+ const postSwitchHooks = [];
120
+ for (const cmd of config.post_switch_cmds) {
121
+ try {
122
+ const output = runner.exec(cmd, { cwd: oldStandbyDir });
123
+ postSwitchHooks.push({ cmd, status: 'pass', detail: output });
124
+ }
125
+ catch (e) {
126
+ postSwitchHooks.push({ cmd, status: 'fail', detail: e instanceof Error ? e.message : String(e) });
127
+ }
128
+ }
129
+ // Step 7: update state atomically. previous_live_dir = the OLD live dir
130
+ // (for "deploy rollback" — task 8), not the new one. git_ref was already
131
+ // resolved in step 2, before anything was touched.
132
+ const newState = updateState(config.app_name, {
133
+ live_dir: oldStandbyDir,
134
+ live_port: config.prod_port,
135
+ standby_dir: oldLiveDir,
136
+ staging_port: config.staging_port,
137
+ previous_live_dir: oldLiveDir,
138
+ last_switch: new Date().toISOString(),
139
+ git_ref: gitRef,
140
+ pm2_process: config.app_name,
141
+ });
142
+ return {
143
+ previousLiveDir: oldLiveDir,
144
+ newLiveDir: oldStandbyDir,
145
+ newStandbyDir: oldLiveDir,
146
+ prodPort: config.prod_port,
147
+ stagingPort: config.staging_port,
148
+ stagingStopped,
149
+ postSwitchHooks,
150
+ state: newState,
151
+ };
152
+ }
@@ -0,0 +1,96 @@
1
+ /** Resolved `[deploy]` INI section, with defaults applied. */
2
+ export interface DeployConfig {
3
+ /** Logical app name — also the state file name (~/.hazo-deploy/<app_name>.json). Required, no default. */
4
+ app_name: string;
5
+ /** Suffix distinguishing live/standby sibling dirs (e.g. "green" for "gotimer-green"). Required, no default. */
6
+ dir_suffix: string;
7
+ /** Production PM2 port. Default: 3000 */
8
+ prod_port: number;
9
+ /** Staging port used during build/verify before switch. Default: 3001 */
10
+ staging_port: number;
11
+ /** Path (relative to app root) hit for health checks. Default: /api/health */
12
+ health_url: string;
13
+ /** Minimum free disk (MB) required before a build proceeds. Default: 1024 */
14
+ min_disk_mb: number;
15
+ /** Minimum free memory (MB) required before a build proceeds. Default: 512 */
16
+ min_memory_mb: number;
17
+ /** Git branch pulled by `deploy build` (overridable via --branch). Default: main */
18
+ branch: string;
19
+ /** How the standby DB is provisioned: "auto" infers from [db.*] driver. Default: auto */
20
+ db_strategy: 'auto' | 'copy' | 'shared';
21
+ /** Shell command that builds the app. Default: npm run build */
22
+ build_cmd: string;
23
+ /** Shell command that installs dependencies. Default: npm ci */
24
+ install_cmd: string;
25
+ /** Shell command run before the build (cache busting etc). Default: rm -rf .next */
26
+ pre_build_cmd: string;
27
+ /**
28
+ * Optional shell command run after DB setup during `deploy build` (Task 5).
29
+ * Migrations are project-specific — this package has no generic
30
+ * cross-project migration runner — so an empty string (the default) means
31
+ * "skip"; `deploy build` logs that it's assuming the consuming app's own
32
+ * schema bootstrap runs automatically at startup and moves on.
33
+ */
34
+ migrate_cmd?: string;
35
+ /** Shell commands run after a successful switch (indexnow, CDN purge, ...). May be empty. */
36
+ post_switch_cmds: string[];
37
+ }
38
+ /** Result of a single command execution. */
39
+ export interface CommandResult {
40
+ code: number;
41
+ stdout: string;
42
+ stderr: string;
43
+ }
44
+ /**
45
+ * All external command execution (git, npm, pm2, cp, system checks) flows
46
+ * through this interface. The production implementation (runner.ts) wraps
47
+ * child_process.execSync/spawnSync; tests inject a mock that records calls
48
+ * and returns configurable results. This is the single testing seam for the
49
+ * entire deploy module.
50
+ */
51
+ export interface CommandRunner {
52
+ /** Run `cmd` and return trimmed stdout. Throws on non-zero exit. */
53
+ exec(cmd: string, opts?: {
54
+ cwd?: string;
55
+ env?: Record<string, string>;
56
+ }): string;
57
+ /** Run `cmd` and return the full result (exit code, stdout, stderr) without throwing. */
58
+ spawn(cmd: string, opts?: {
59
+ cwd?: string;
60
+ env?: Record<string, string>;
61
+ }): CommandResult;
62
+ }
63
+ /**
64
+ * Persisted deploy state at ~/.hazo-deploy/<app_name>.json. Tracks which
65
+ * directory is currently live vs. standby, their ports, timestamps of the
66
+ * last build/switch, and enough history to support `deploy rollback`.
67
+ */
68
+ export interface DeployState {
69
+ app_name: string;
70
+ live_dir: string;
71
+ live_port: number;
72
+ standby_dir: string;
73
+ staging_port: number;
74
+ /** ISO timestamp of the last successful switch, if any. */
75
+ last_switch?: string;
76
+ /** ISO timestamp of the last build attempt, if any. */
77
+ last_build?: string;
78
+ last_build_status?: 'success' | 'failed';
79
+ /** Previous live_dir, retained for `deploy rollback`. */
80
+ previous_live_dir?: string;
81
+ /** Git ref (branch or sha) built into the current standby/live dir. */
82
+ git_ref?: string;
83
+ /** PM2 process name managing this app, read from ecosystem.config.js. */
84
+ pm2_process?: string;
85
+ }
86
+ /**
87
+ * Contract for any task that invokes `pm2 start` for this app (build,
88
+ * switch, ...): `deploy status` identifies which directory a PM2 process
89
+ * belongs to by matching `pm2_env.pm_cwd` against `live_dir`/`standby_dir`.
90
+ * PM2 only populates `pm_cwd` correctly when `cwd` is passed explicitly to
91
+ * `pm2 start` (e.g. `--cwd <dir>` or `cwd: <dir>` in ecosystem.config.js) —
92
+ * otherwise it defaults to wherever `pm2 start` itself was invoked from,
93
+ * which silently breaks status's directory matching with no error. Every
94
+ * `pm2 start` call for this app MUST pass `cwd` explicitly.
95
+ */
96
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/deploy/types.ts"],"names":[],"mappings":"AAMA,8DAA8D;AAC9D,MAAM,WAAW,YAAY;IAC3B,0GAA0G;IAC1G,QAAQ,EAAE,MAAM,CAAC;IACjB,gHAAgH;IAChH,UAAU,EAAE,MAAM,CAAC;IACnB,yCAAyC;IACzC,SAAS,EAAE,MAAM,CAAC;IAClB,yEAAyE;IACzE,YAAY,EAAE,MAAM,CAAC;IACrB,8EAA8E;IAC9E,UAAU,EAAE,MAAM,CAAC;IACnB,6EAA6E;IAC7E,WAAW,EAAE,MAAM,CAAC;IACpB,8EAA8E;IAC9E,aAAa,EAAE,MAAM,CAAC;IACtB,oFAAoF;IACpF,MAAM,EAAE,MAAM,CAAC;IACf,yFAAyF;IACzF,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAC;IACxC,gEAAgE;IAChE,SAAS,EAAE,MAAM,CAAC;IAClB,gEAAgE;IAChE,WAAW,EAAE,MAAM,CAAC;IACpB,oFAAoF;IACpF,aAAa,EAAE,MAAM,CAAC;IACtB;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,6FAA6F;IAC7F,gBAAgB,EAAE,MAAM,EAAE,CAAC;CAC5B;AAED,4CAA4C;AAC5C,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,aAAa;IAC5B,oEAAoE;IACpE,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,GAAG,MAAM,CAAC;IACjF,yFAAyF;IACzF,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,GAAG,aAAa,CAAC;CAC1F;AAED;;;;GAIG;AACH,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,2DAA2D;IAC3D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,uDAAuD;IACvD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,SAAS,GAAG,QAAQ,CAAC;IACzC,yDAAyD;IACzD,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;;;GASG"}
@@ -0,0 +1,16 @@
1
+ // hazo_env/src/deploy/types.ts — Types for the deploy module (blue-green orchestration)
2
+ //
3
+ // These shapes are load-bearing for every later deploy task (build/verify/
4
+ // switch/rollback/status/clean/init) — do not rename or restructure fields
5
+ // without updating the whole plan.
6
+ export {};
7
+ /**
8
+ * Contract for any task that invokes `pm2 start` for this app (build,
9
+ * switch, ...): `deploy status` identifies which directory a PM2 process
10
+ * belongs to by matching `pm2_env.pm_cwd` against `live_dir`/`standby_dir`.
11
+ * PM2 only populates `pm_cwd` correctly when `cwd` is passed explicitly to
12
+ * `pm2 start` (e.g. `--cwd <dir>` or `cwd: <dir>` in ecosystem.config.js) —
13
+ * otherwise it defaults to wherever `pm2 start` itself was invoked from,
14
+ * which silently breaks status's directory matching with no error. Every
15
+ * `pm2 start` call for this app MUST pass `cwd` explicitly.
16
+ */
@@ -0,0 +1,41 @@
1
+ import type { CommandRunner, DeployConfig } from './types.js';
2
+ export type VerifyCheckName = 'health' | 'typescript' | 'migration-parity';
3
+ export type VerifyCheckStatus = 'pass' | 'fail' | 'skipped';
4
+ export interface VerifyCheckResult {
5
+ name: VerifyCheckName;
6
+ status: VerifyCheckStatus;
7
+ detail: string;
8
+ }
9
+ export interface RunVerifyOptions {
10
+ /** Directory to run `tsc`/resolve the standby db path from. Defaults to process.cwd(). */
11
+ cwd?: string;
12
+ /**
13
+ * Health check retry count. Default: 2.
14
+ *
15
+ * `deploy build`'s health check defaults to 8 retries because it runs
16
+ * immediately after `pm2 start`, before the app has necessarily finished
17
+ * booting. `deploy verify` is re-run against an app that (per this
18
+ * command's own contract) should already be up and running — a long retry
19
+ * budget here would just mask "the app isn't actually running" behind a
20
+ * slow failure. A couple of quick retries still absorbs a brief blip
21
+ * without turning a single bad health check into a 12-second wait.
22
+ */
23
+ healthCheckAttempts?: number;
24
+ /** Delay between health check retries, in ms. Default: 500. */
25
+ healthCheckDelayMs?: number;
26
+ /** Shell command used for the TypeScript check. Default: "npx tsc --noEmit". */
27
+ tscCmd?: string;
28
+ }
29
+ export interface RunVerifyResult {
30
+ checks: VerifyCheckResult[];
31
+ /** True iff no check has status "fail" (a "skipped" check does not count against this). */
32
+ allPassed: boolean;
33
+ }
34
+ /**
35
+ * Run all three verify checks against `cwd` (the standby directory, which
36
+ * should already be running on `config.staging_port`). Every check runs
37
+ * regardless of whether an earlier one failed — see this file's header for
38
+ * why `verify` doesn't abort-on-first-failure the way `deploy build` does.
39
+ */
40
+ export declare function runVerify(config: DeployConfig, runner: CommandRunner, opts?: RunVerifyOptions): RunVerifyResult;
41
+ //# sourceMappingURL=verify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../../src/deploy/verify.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAe9D,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,YAAY,GAAG,kBAAkB,CAAC;AAC3E,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;AAE5D,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,eAAe,CAAC;IACtB,MAAM,EAAE,iBAAiB,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,0FAA0F;IAC1F,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;;;;;;;OAUG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,gFAAgF;IAChF,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,iBAAiB,EAAE,CAAC;IAC5B,2FAA2F;IAC3F,SAAS,EAAE,OAAO,CAAC;CACpB;AAiID;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,gBAAqB,GAAG,eAAe,CA2DnH"}