hazo_env 0.15.3 → 0.17.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 (67) hide show
  1. package/CHANGE_LOG.md +120 -0
  2. package/README.md +333 -0
  3. package/dist/bin.d.ts +3 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +17 -0
  6. package/dist/cli.js +178 -17
  7. package/dist/deploy/build.d.ts +1 -1
  8. package/dist/deploy/build.d.ts.map +1 -1
  9. package/dist/deploy/build.js +51 -14
  10. package/dist/deploy/clean.d.ts +2 -1
  11. package/dist/deploy/clean.d.ts.map +1 -1
  12. package/dist/deploy/clean.js +36 -6
  13. package/dist/deploy/generate-readme-cli.d.ts +3 -0
  14. package/dist/deploy/generate-readme-cli.d.ts.map +1 -0
  15. package/dist/deploy/generate-readme-cli.js +40 -0
  16. package/dist/deploy/help.d.ts +55 -0
  17. package/dist/deploy/help.d.ts.map +1 -0
  18. package/dist/deploy/help.js +545 -0
  19. package/dist/deploy/idle-slots.d.ts +42 -0
  20. package/dist/deploy/idle-slots.d.ts.map +1 -0
  21. package/dist/deploy/idle-slots.js +136 -0
  22. package/dist/deploy/index.d.ts +5 -0
  23. package/dist/deploy/index.d.ts.map +1 -1
  24. package/dist/deploy/index.js +5 -0
  25. package/dist/deploy/init.d.ts +14 -0
  26. package/dist/deploy/init.d.ts.map +1 -1
  27. package/dist/deploy/init.js +14 -1
  28. package/dist/deploy/preflight.d.ts +26 -0
  29. package/dist/deploy/preflight.d.ts.map +1 -0
  30. package/dist/deploy/preflight.js +91 -0
  31. package/dist/deploy/rollback.d.ts +10 -1
  32. package/dist/deploy/rollback.d.ts.map +1 -1
  33. package/dist/deploy/rollback.js +25 -1
  34. package/dist/deploy/share.d.ts +28 -0
  35. package/dist/deploy/share.d.ts.map +1 -0
  36. package/dist/deploy/share.js +53 -0
  37. package/dist/deploy/shared-dirs.d.ts +128 -0
  38. package/dist/deploy/shared-dirs.d.ts.map +1 -0
  39. package/dist/deploy/shared-dirs.js +486 -0
  40. package/dist/deploy/status.d.ts +8 -0
  41. package/dist/deploy/status.d.ts.map +1 -1
  42. package/dist/deploy/status.js +6 -0
  43. package/dist/deploy/switch.d.ts.map +1 -1
  44. package/dist/deploy/switch.js +25 -0
  45. package/dist/deploy/types.d.ts +18 -0
  46. package/dist/deploy/types.d.ts.map +1 -1
  47. package/dist/deploy/verify.d.ts.map +1 -1
  48. package/dist/deploy/verify.js +7 -1
  49. package/dist/envsync/engine.d.ts.map +1 -1
  50. package/dist/envsync/engine.js +21 -7
  51. package/dist/envsync/paths.d.ts +22 -0
  52. package/dist/envsync/paths.d.ts.map +1 -1
  53. package/dist/envsync/paths.js +55 -0
  54. package/dist/peer-hint.d.ts +8 -0
  55. package/dist/peer-hint.d.ts.map +1 -0
  56. package/dist/peer-hint.js +49 -0
  57. package/dist/resolve/config-hint.d.ts +2 -0
  58. package/dist/resolve/config-hint.d.ts.map +1 -0
  59. package/dist/resolve/config-hint.js +23 -0
  60. package/dist/resolve/connect.d.ts.map +1 -1
  61. package/dist/resolve/connect.js +2 -1
  62. package/dist/resolve/deploy.d.ts.map +1 -1
  63. package/dist/resolve/deploy.js +167 -1
  64. package/dist/resolve/envsync.d.ts +16 -0
  65. package/dist/resolve/envsync.d.ts.map +1 -1
  66. package/dist/resolve/envsync.js +19 -0
  67. package/package.json +4 -3
@@ -0,0 +1,42 @@
1
+ import type { CommandRunner } from './types.js';
2
+ export declare const IDLE_SLOT_TARGETS: readonly ["node_modules", ".next"];
3
+ export interface IdleSlotTargetResult {
4
+ name: (typeof IDLE_SLOT_TARGETS)[number];
5
+ path: string;
6
+ /** Measured size in bytes (0 when absent). */
7
+ bytes: number;
8
+ /** True when the target was absent, or left alone because it is a symlink. */
9
+ skipped: boolean;
10
+ skipReason?: string;
11
+ /** True once actually removed (only with `yes`). */
12
+ removed: boolean;
13
+ error?: string;
14
+ }
15
+ export interface IdleSlotResult {
16
+ app_name: string;
17
+ slot_dir: string;
18
+ eligible: boolean;
19
+ /** Why the slot was skipped (only when !eligible). */
20
+ skipReason?: string;
21
+ targets: IdleSlotTargetResult[];
22
+ /** Measured bytes (dry run) or bytes actually reclaimed (`yes`). */
23
+ bytes: number;
24
+ }
25
+ export interface RunCleanIdleSlotsOptions {
26
+ /** Actually delete. Default false (dry run: measure and report only). */
27
+ yes?: boolean;
28
+ /** Directory treated as "current" for the cwd safety check. Defaults to process.cwd(). */
29
+ cwd?: string;
30
+ }
31
+ export interface RunCleanIdleSlotsResult {
32
+ dryRun: boolean;
33
+ slots: IdleSlotResult[];
34
+ totalBytes: number;
35
+ warnings: string[];
36
+ }
37
+ export declare class IdleSlotsAbortError extends Error {
38
+ constructor(message: string);
39
+ }
40
+ /** See this file's header. Throws IdleSlotsAbortError only when PM2 state can't be read. */
41
+ export declare function runCleanIdleSlots(runner: CommandRunner, opts?: RunCleanIdleSlotsOptions): RunCleanIdleSlotsResult;
42
+ //# sourceMappingURL=idle-slots.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idle-slots.d.ts","sourceRoot":"","sources":["../../src/deploy/idle-slots.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,aAAa,EAAe,MAAM,YAAY,CAAC;AAE7D,eAAO,MAAM,iBAAiB,oCAAqC,CAAC;AAEpE,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,CAAC,CAAC;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,8CAA8C;IAC9C,KAAK,EAAE,MAAM,CAAC;IACd,8EAA8E;IAC9E,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,oDAAoD;IACpD,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,OAAO,CAAC;IAClB,sDAAsD;IACtD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,oBAAoB,EAAE,CAAC;IAChC,oEAAoE;IACpE,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,wBAAwB;IACvC,yEAAyE;IACzE,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,0FAA0F;IAC1F,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,uBAAuB;IACtC,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,cAAc,EAAE,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,qBAAa,mBAAoB,SAAQ,KAAK;gBAChC,OAAO,EAAE,MAAM;CAI5B;AAuGD,4FAA4F;AAC5F,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,wBAA6B,GAAG,uBAAuB,CAoBrH"}
@@ -0,0 +1,136 @@
1
+ // hazo_env/src/deploy/idle-slots.ts — `deploy clean --idle-slots`
2
+ //
3
+ // A host running several blue-green apps keeps a full standby checkout per
4
+ // app, each with its own `node_modules` + `.next` — easily 1 GB+ apiece of
5
+ // disk that nothing is using between deploys. This reclaims exactly those
6
+ // two folders from every app's IDLE standby slot, across every state file
7
+ // in ~/.hazo-deploy (not just the current app's), so it runs from anywhere
8
+ // and needs no [deploy] config in cwd.
9
+ //
10
+ // Safety, per slot (any one skips it, with the reason reported):
11
+ // - it is any app's live_dir;
12
+ // - it is (or contains) the current working directory;
13
+ // - a PM2 process's pm2_env.pm_cwd is (or is inside) it;
14
+ // - its last_build is newer than last_switch (built but not yet switched —
15
+ // clearing it would force a rebuild before `deploy switch`).
16
+ // If `pm2 jlist` can't be read, the whole run aborts: without it nothing
17
+ // proves a slot is idle. Only `node_modules` and `.next` are ever removed —
18
+ // never data/, config, .env*, or shared dirs; a target that is a symlink is
19
+ // left alone (it may point into shared storage). Dry-run by default; pass
20
+ // `yes` to delete. All measurement/removal goes through CommandRunner.
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { getStateDir } from './state.js';
24
+ export const IDLE_SLOT_TARGETS = ['node_modules', '.next'];
25
+ export class IdleSlotsAbortError extends Error {
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = 'IdleSlotsAbortError';
29
+ }
30
+ }
31
+ function isSameOrInside(child, parent) {
32
+ const rel = path.relative(parent, child);
33
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
34
+ }
35
+ function readAllStates(warnings) {
36
+ const dir = getStateDir();
37
+ if (!fs.existsSync(dir))
38
+ return [];
39
+ const states = [];
40
+ for (const file of fs.readdirSync(dir).filter((f) => f.endsWith('.json')).sort()) {
41
+ try {
42
+ const state = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf-8'));
43
+ if (state && typeof state.standby_dir === 'string' && typeof state.live_dir === 'string') {
44
+ states.push(state);
45
+ }
46
+ else {
47
+ warnings.push(`skipping state file ${file}: missing live_dir/standby_dir`);
48
+ }
49
+ }
50
+ catch {
51
+ warnings.push(`skipping state file ${file}: not valid JSON`);
52
+ }
53
+ }
54
+ return states;
55
+ }
56
+ function queryPm2Cwds(runner) {
57
+ const result = runner.spawn('pm2 jlist');
58
+ if (result.code !== 0) {
59
+ throw new IdleSlotsAbortError(`pm2 jlist failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'} — cannot prove any slot is idle, nothing cleaned.`);
60
+ }
61
+ let parsed;
62
+ try {
63
+ parsed = JSON.parse(result.stdout);
64
+ }
65
+ catch {
66
+ throw new IdleSlotsAbortError('pm2 jlist returned unparsable JSON — cannot prove any slot is idle, nothing cleaned.');
67
+ }
68
+ if (!Array.isArray(parsed)) {
69
+ throw new IdleSlotsAbortError('pm2 jlist did not return a list — cannot prove any slot is idle, nothing cleaned.');
70
+ }
71
+ return parsed
72
+ .filter((p) => typeof p.pm2_env?.pm_cwd === 'string')
73
+ .map((p) => ({ name: p.name ?? '(unnamed)', cwd: path.resolve(p.pm2_env.pm_cwd) }));
74
+ }
75
+ function skipReasonFor(state, slot, cwd, liveDirs, pm2Cwds) {
76
+ if (!fs.existsSync(slot))
77
+ return 'slot directory does not exist';
78
+ if (liveDirs.includes(slot))
79
+ return 'it is a live_dir';
80
+ if (isSameOrInside(cwd, slot))
81
+ return 'it is the current working directory';
82
+ const proc = pm2Cwds.find((p) => isSameOrInside(p.cwd, slot));
83
+ if (proc)
84
+ return `PM2 process "${proc.name}" is running from it`;
85
+ if (state.last_build && (!state.last_switch || Date.parse(state.last_build) > Date.parse(state.last_switch))) {
86
+ return `pending build (last_build ${state.last_build} is newer than last_switch ${state.last_switch ?? '(never)'}) — clearing it would force a rebuild before switch`;
87
+ }
88
+ return undefined;
89
+ }
90
+ function measureKb(runner, absPath) {
91
+ const result = runner.spawn(`du -sk ${JSON.stringify(absPath)}`);
92
+ if (result.code !== 0)
93
+ return undefined;
94
+ const kb = Number(result.stdout.trim().split(/\s+/)[0]);
95
+ return Number.isFinite(kb) ? kb : undefined;
96
+ }
97
+ function processTarget(runner, slot, name, yes, warnings) {
98
+ const absPath = path.join(slot, name);
99
+ if (runner.spawn(`test -L ${JSON.stringify(absPath)}`).code === 0) {
100
+ return { name, path: absPath, bytes: 0, skipped: true, skipReason: 'symlink — left alone (may point at shared storage)', removed: false };
101
+ }
102
+ const kb = measureKb(runner, absPath);
103
+ if (kb === undefined) {
104
+ return { name, path: absPath, bytes: 0, skipped: true, skipReason: 'not present', removed: false };
105
+ }
106
+ const bytes = kb * 1024;
107
+ if (!yes)
108
+ return { name, path: absPath, bytes, skipped: false, removed: false };
109
+ const rm = runner.spawn(`rm -rf ${JSON.stringify(absPath)}`);
110
+ if (rm.code !== 0) {
111
+ const error = rm.stderr.trim() || `exit ${rm.code}`;
112
+ warnings.push(`failed to remove ${absPath}: ${error}`);
113
+ return { name, path: absPath, bytes: 0, skipped: false, removed: false, error };
114
+ }
115
+ return { name, path: absPath, bytes, skipped: false, removed: true };
116
+ }
117
+ /** See this file's header. Throws IdleSlotsAbortError only when PM2 state can't be read. */
118
+ export function runCleanIdleSlots(runner, opts = {}) {
119
+ const yes = opts.yes === true;
120
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
121
+ const warnings = [];
122
+ const states = readAllStates(warnings);
123
+ const pm2Cwds = states.length > 0 ? queryPm2Cwds(runner) : [];
124
+ const liveDirs = states.map((s) => path.resolve(s.live_dir));
125
+ const slots = states.map((state) => {
126
+ const slot = path.resolve(state.standby_dir);
127
+ const skipReason = skipReasonFor(state, slot, cwd, liveDirs, pm2Cwds);
128
+ if (skipReason) {
129
+ return { app_name: state.app_name, slot_dir: slot, eligible: false, skipReason, targets: [], bytes: 0 };
130
+ }
131
+ const targets = IDLE_SLOT_TARGETS.map((name) => processTarget(runner, slot, name, yes, warnings));
132
+ const bytes = targets.reduce((sum, t) => sum + t.bytes, 0);
133
+ return { app_name: state.app_name, slot_dir: slot, eligible: true, targets, bytes };
134
+ });
135
+ return { dryRun: !yes, slots, totalBytes: slots.reduce((sum, s) => sum + s.bytes, 0), warnings };
136
+ }
@@ -4,6 +4,7 @@ export * from './runner.js';
4
4
  export * from './peer.js';
5
5
  export * from './pm2-start.js';
6
6
  export * from './sidecar.js';
7
+ export * from './shared-dirs.js';
7
8
  export * from './clean.js';
8
9
  export * from './status.js';
9
10
  export * from './init.js';
@@ -11,4 +12,8 @@ export * from './build.js';
11
12
  export * from './verify.js';
12
13
  export * from './switch.js';
13
14
  export * from './rollback.js';
15
+ export * from './share.js';
16
+ export * from './help.js';
17
+ export * from './preflight.js';
18
+ export * from './idle-slots.js';
14
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/deploy/index.ts"],"names":[],"mappings":"AAUA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/deploy/index.ts"],"names":[],"mappings":"AAUA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC"}
@@ -14,6 +14,7 @@ export * from './runner.js';
14
14
  export * from './peer.js';
15
15
  export * from './pm2-start.js';
16
16
  export * from './sidecar.js';
17
+ export * from './shared-dirs.js';
17
18
  export * from './clean.js';
18
19
  export * from './status.js';
19
20
  export * from './init.js';
@@ -21,3 +22,7 @@ export * from './build.js';
21
22
  export * from './verify.js';
22
23
  export * from './switch.js';
23
24
  export * from './rollback.js';
25
+ export * from './share.js';
26
+ export * from './help.js';
27
+ export * from './preflight.js';
28
+ export * from './idle-slots.js';
@@ -1,4 +1,5 @@
1
1
  import type { CommandRunner, DeployConfig } from './types.js';
2
+ import type { EnsureLinkResult } from './shared-dirs.js';
2
3
  export interface RunInitOptions {
3
4
  /** Directory to treat as "current" (the live dir). Defaults to process.cwd(). */
4
5
  cwd?: string;
@@ -11,6 +12,19 @@ export interface RunInitResult {
11
12
  originUrl: string;
12
13
  envFilesCopied: string[];
13
14
  envFilesMissing: string[];
15
+ /**
16
+ * Shared-dirs (ticket 03 of the deploy-shared-dirs spec) enforcement
17
+ * results for the freshly-cloned peer — see shared-dirs.ts's
18
+ * `ensureLinks`. `[]` when `config.shared_dirs` is empty (feature off;
19
+ * every existing caller of `runInit` is unaffected).
20
+ */
21
+ sharedDirsLinked: EnsureLinkResult[];
22
+ /**
23
+ * Slot dirs whose `.git/info/exclude` gained a `config/hazo_env_config.ini`
24
+ * entry (the INI is per-slot, so it must never be committed). Local to each
25
+ * clone, so it never dirties a tracked .gitignore.
26
+ */
27
+ configExcludedFrom: string[];
14
28
  }
15
29
  /**
16
30
  * Create the peer (standby) directory: resolve its path, abort if it
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/deploy/init.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAgD3E,MAAM,WAAW,cAAc;IAC7B,iFAAiF;IACjF,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,eAAe,EAAE,MAAM,EAAE,CAAC;CAC3B;AA0CD;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,cAAmB,GAAG,aAAa,CA8C7G"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/deploy/init.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAgDzD,MAAM,WAAW,cAAc;IAC7B,iFAAiF;IACjF,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B;;;;;OAKG;IACH,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;IACrC;;;;OAIG;IACH,kBAAkB,EAAE,MAAM,EAAE,CAAC;CAC9B;AA0CD;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,cAAmB,GAAG,aAAa,CA4D7G"}
@@ -18,6 +18,8 @@ import { HazoConfig } from 'hazo_config/server';
18
18
  import { resolvePeerDir } from './peer.js';
19
19
  import { writeState } from './state.js';
20
20
  import { getEnv } from '../index.client.js';
21
+ import { ensureLinks } from './shared-dirs.js';
22
+ import { excludeDeployConfigFromGit } from './preflight.js';
21
23
  const CONFIG_RELATIVE_PATH = path.join('config', 'hazo_env_config.ini');
22
24
  // Matches resolve/files.ts's DEFAULT_DATA_ROOT — kept as a local literal
23
25
  // rather than importing that module, since resolveFilesConfig()/
@@ -119,6 +121,16 @@ export function runInit(config, runner, opts = {}) {
119
121
  fs.mkdirSync(path.dirname(peerIniPath), { recursive: true });
120
122
  fs.writeFileSync(peerIniPath, swappedIni, 'utf-8');
121
123
  ensurePeerDataDir(config, peerIniPath, peerDir);
124
+ // Ticket 03 (deploy-shared-dirs): create the shared-dir symlinks in the
125
+ // freshly-cloned peer so it's correct from its first `deploy build` (user
126
+ // story 22). `allowCreate` only — never `allowReplaceEmpty` here: a fresh
127
+ // clone legitimately has nothing at these paths yet (missing -> created);
128
+ // anything else (a tracked real/non-empty dir, or someone else's link)
129
+ // means the repo itself is in an unexpected state, and `ensureLinks`
130
+ // throws its typed `SharedDirError` (with a "run deploy share" hint)
131
+ // straight through — init is not the place to silently fix that up. A
132
+ // no-op when `shared_dirs` is empty (feature off).
133
+ const sharedDirsLinked = config.shared_dirs.length > 0 ? ensureLinks(config, peerDir, { allowCreate: true }) : [];
122
134
  const envFilesCopied = [];
123
135
  const envFilesMissing = [];
124
136
  for (const envFile of config.env_files) {
@@ -133,6 +145,7 @@ export function runInit(config, runner, opts = {}) {
133
145
  envFilesMissing.push(envFile);
134
146
  }
135
147
  }
148
+ const configExcludedFrom = [currentDir, peerDir].filter((dir) => excludeDeployConfigFromGit(dir));
136
149
  const state = {
137
150
  app_name: config.app_name,
138
151
  live_dir: currentDir,
@@ -141,5 +154,5 @@ export function runInit(config, runner, opts = {}) {
141
154
  staging_port: config.staging_port,
142
155
  };
143
156
  writeState(state);
144
- return { currentDir, peerDir, originUrl, envFilesCopied, envFilesMissing };
157
+ return { currentDir, peerDir, originUrl, envFilesCopied, envFilesMissing, sharedDirsLinked, configExcludedFrom };
145
158
  }
@@ -0,0 +1,26 @@
1
+ import type { CommandRunner } from './types.js';
2
+ export declare const DEPLOY_CONFIG_RELATIVE_PATH: string;
3
+ /** Default number of trailing output lines shown for a failed command. */
4
+ export declare const FAILURE_OUTPUT_TAIL_LINES = 40;
5
+ /**
6
+ * Warning text when `cwd/package.json` exists but lists hazo_env in neither
7
+ * dependencies nor devDependencies; undefined otherwise (including when
8
+ * there is no package.json at all).
9
+ */
10
+ export declare function cliDependencyWarning(cwd: string): string | undefined;
11
+ /** True when config/hazo_env_config.ini is tracked by git in `cwd`. */
12
+ export declare function isDeployConfigGitTracked(runner: CommandRunner, cwd: string): boolean;
13
+ export declare const TRACKED_DEPLOY_CONFIG_MESSAGE: string;
14
+ /**
15
+ * Add the per-slot config path to `<dir>/.git/info/exclude` (local to that
16
+ * clone, so it never dirties a tracked .gitignore). Returns true if an entry
17
+ * was added; false if `dir` isn't a git checkout or the entry already exists.
18
+ */
19
+ export declare function excludeDeployConfigFromGit(dir: string): boolean;
20
+ /**
21
+ * Describe a failed CommandRunner.exec: the error's first line plus the tail
22
+ * of the command's captured stdout+stderr (execSync errors carry both as
23
+ * properties). Falls back to the plain message when no output was captured.
24
+ */
25
+ export declare function commandFailureDetail(e: unknown, tailLines?: number): string;
26
+ //# sourceMappingURL=preflight.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preflight.d.ts","sourceRoot":"","sources":["../../src/deploy/preflight.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,eAAO,MAAM,2BAA2B,QAA6C,CAAC;AAEtF,0EAA0E;AAC1E,eAAO,MAAM,yBAAyB,KAAK,CAAC;AAE5C;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAcpE;AAED,uEAAuE;AACvE,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAGpF;AAED,eAAO,MAAM,6BAA6B,QAOmE,CAAC;AAE9G;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAW/D;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,SAA4B,GAAG,MAAM,CAc9F"}
@@ -0,0 +1,91 @@
1
+ // hazo_env/src/deploy/preflight.ts — Operator-mistake checks shared by deploy commands
2
+ //
3
+ // Each helper encodes a failure mode hit on a real deploy (GoTimer, 2026-11):
4
+ // - hazo_env not listed in the app's package.json: works once via a manual
5
+ // install, then `deploy build`'s own `npm ci` removes it and the next
6
+ // `npx hazo_env` fetches a standalone copy that can't resolve its peers.
7
+ // - config/hazo_env_config.ini tracked in git: `dir_suffix` differs per
8
+ // slot, so a tracked copy is either overwritten by `git pull` (wrong
9
+ // suffix) or blocks the pull against the slot's untracked copy.
10
+ // - a failed install/build reporting only Next's last line ("Failed to type
11
+ // check.") because the actual tsc errors went to stdout, which execSync
12
+ // keeps on the error object rather than in its message.
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ export const DEPLOY_CONFIG_RELATIVE_PATH = path.join('config', 'hazo_env_config.ini');
16
+ /** Default number of trailing output lines shown for a failed command. */
17
+ export const FAILURE_OUTPUT_TAIL_LINES = 40;
18
+ /**
19
+ * Warning text when `cwd/package.json` exists but lists hazo_env in neither
20
+ * dependencies nor devDependencies; undefined otherwise (including when
21
+ * there is no package.json at all).
22
+ */
23
+ export function cliDependencyWarning(cwd) {
24
+ const pkgPath = path.join(cwd, 'package.json');
25
+ if (!fs.existsSync(pkgPath))
26
+ return undefined;
27
+ let pkg;
28
+ try {
29
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ if (pkg.dependencies?.hazo_env || pkg.devDependencies?.hazo_env)
35
+ return undefined;
36
+ return ('hazo_env is not in this app\'s package.json — the build\'s own `npm ci` will remove it, so the next ' +
37
+ '`npx hazo_env` will fetch a standalone copy that cannot load its peers. Add it: npm i -D hazo_env');
38
+ }
39
+ /** True when config/hazo_env_config.ini is tracked by git in `cwd`. */
40
+ export function isDeployConfigGitTracked(runner, cwd) {
41
+ const result = runner.spawn(`git ls-files --error-unmatch ${DEPLOY_CONFIG_RELATIVE_PATH}`, { cwd });
42
+ return result.code === 0;
43
+ }
44
+ export const TRACKED_DEPLOY_CONFIG_MESSAGE = `${DEPLOY_CONFIG_RELATIVE_PATH} is tracked in git, but it is per-slot (dir_suffix differs between blue ` +
45
+ `and green) — a pull would overwrite this slot's copy or conflict with it. Untrack it from the repo and ` +
46
+ `ignore it, then re-run:\n` +
47
+ ` git rm --cached ${DEPLOY_CONFIG_RELATIVE_PATH}\n` +
48
+ ` echo "${DEPLOY_CONFIG_RELATIVE_PATH}" >> .gitignore\n` +
49
+ ` git commit -m "untrack per-slot hazo_env config" && git push\n` +
50
+ `Keep each slot's local copy (restore it from the peer slot with dir_suffix swapped if a pull deleted it).`;
51
+ /**
52
+ * Add the per-slot config path to `<dir>/.git/info/exclude` (local to that
53
+ * clone, so it never dirties a tracked .gitignore). Returns true if an entry
54
+ * was added; false if `dir` isn't a git checkout or the entry already exists.
55
+ */
56
+ export function excludeDeployConfigFromGit(dir) {
57
+ const gitDir = path.join(dir, '.git');
58
+ if (!fs.existsSync(gitDir) || !fs.statSync(gitDir).isDirectory())
59
+ return false;
60
+ const entry = DEPLOY_CONFIG_RELATIVE_PATH.split(path.sep).join('/');
61
+ const excludePath = path.join(gitDir, 'info', 'exclude');
62
+ const existing = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, 'utf-8') : '';
63
+ if (existing.split('\n').some((line) => line.trim() === entry || line.trim() === `/${entry}`))
64
+ return false;
65
+ fs.mkdirSync(path.dirname(excludePath), { recursive: true });
66
+ const prefix = existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
67
+ fs.appendFileSync(excludePath, `${prefix}# per-slot blue/green deploy config (hazo_env)\n${entry}\n`, 'utf-8');
68
+ return true;
69
+ }
70
+ /**
71
+ * Describe a failed CommandRunner.exec: the error's first line plus the tail
72
+ * of the command's captured stdout+stderr (execSync errors carry both as
73
+ * properties). Falls back to the plain message when no output was captured.
74
+ */
75
+ export function commandFailureDetail(e, tailLines = FAILURE_OUTPUT_TAIL_LINES) {
76
+ const message = e instanceof Error ? e.message : String(e);
77
+ if (!e || typeof e !== 'object')
78
+ return message;
79
+ const { stdout, stderr } = e;
80
+ const output = [stdout, stderr]
81
+ .map((s) => (typeof s === 'string' ? s : Buffer.isBuffer(s) ? s.toString('utf-8') : ''))
82
+ .filter((s) => s.trim().length > 0)
83
+ .join('\n')
84
+ .trimEnd();
85
+ if (!output)
86
+ return message;
87
+ const lines = output.split('\n');
88
+ const tail = lines.slice(-tailLines);
89
+ const header = lines.length > tailLines ? `last ${tailLines} of ${lines.length} output lines` : 'command output';
90
+ return `${message.split('\n')[0]}\n--- ${header} ---\n${tail.join('\n')}`;
91
+ }
@@ -20,10 +20,19 @@ export interface RunRollbackResult {
20
20
  export declare class RollbackAbortError extends Error {
21
21
  constructor(message: string);
22
22
  }
23
+ export interface RunRollbackOptions {
24
+ /**
25
+ * Bypass the shared-dirs drift check below — mirrors switch.ts's
26
+ * `--force`, which already bypasses that file's own build-recency check.
27
+ * Use only when the operator has independently verified the drifted
28
+ * slot is safe to promote.
29
+ */
30
+ force?: boolean;
31
+ }
23
32
  /**
24
33
  * Reverse the last `deploy switch`: put the previously-live build back on
25
34
  * the production port. See this file's header for the full step-by-step
26
35
  * rationale.
27
36
  */
28
- export declare function runRollback(config: DeployConfig, runner: CommandRunner): RunRollbackResult;
37
+ export declare function runRollback(config: DeployConfig, runner: CommandRunner, opts?: RunRollbackOptions): RunRollbackResult;
29
38
  //# sourceMappingURL=rollback.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rollback.d.ts","sourceRoot":"","sources":["../../src/deploy/rollback.ts"],"names":[],"mappings":"AAkFA,OAAO,EAAgB,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE3E,MAAM,WAAW,iBAAiB;IAChC,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,WAAW,CAAC;IACnB,6GAA6G;IAC7G,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,kHAAkH;IAClH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,QAAQ,EAAE,iBAAiB,EAAE,CAAC;CAC/B;AAED,uEAAuE;AACvE,qBAAa,kBAAmB,SAAQ,KAAK;gBAC/B,OAAO,EAAE,MAAM;CAI5B;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,GAAG,iBAAiB,CA2H1F"}
1
+ {"version":3,"file":"rollback.d.ts","sourceRoot":"","sources":["../../src/deploy/rollback.ts"],"names":[],"mappings":"AAkFA,OAAO,EAAgB,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAGpE,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAc3E,MAAM,WAAW,iBAAiB;IAChC,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,WAAW,CAAC;IACnB,6GAA6G;IAC7G,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,kHAAkH;IAClH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,QAAQ,EAAE,iBAAiB,EAAE,CAAC;CAC/B;AAED,uEAAuE;AACvE,qBAAa,kBAAmB,SAAQ,KAAK;gBAC/B,OAAO,EAAE,MAAM;CAI5B;AAED,MAAM,WAAW,kBAAkB;IACjC;;;;;OAKG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,MAAM,EAAE,YAAY,EACpB,MAAM,EAAE,aAAa,EACrB,IAAI,GAAE,kBAAuB,GAC5B,iBAAiB,CA0InB"}
@@ -80,6 +80,18 @@ import path from 'node:path';
80
80
  import { readState, updateState } from './state.js';
81
81
  import { promoteDirFresh, PromoteDirFreshError } from './pm2-start.js';
82
82
  import { syncSidecars } from './sidecar.js';
83
+ import { inspectSharedDirs } from './shared-dirs.js';
84
+ /**
85
+ * Describe every `shared_dirs` entry that isn't `linked` in BOTH slots —
86
+ * mirrors switch.ts's identical helper (duplicated rather than shared: a
87
+ * two-line pure function isn't worth adding a third cross-import between
88
+ * these two sibling command files for).
89
+ */
90
+ function describeSharedDirDrift(inspections) {
91
+ return inspections
92
+ .filter((i) => i.live.state !== 'linked' || i.standby.state !== 'linked')
93
+ .map((i) => `"${i.dir}" (live=${i.live.state}, standby=${i.standby.state})`);
94
+ }
83
95
  /** Thrown when there's nothing to roll back, or a fatal step fails. */
84
96
  export class RollbackAbortError extends Error {
85
97
  constructor(message) {
@@ -92,7 +104,7 @@ export class RollbackAbortError extends Error {
92
104
  * the production port. See this file's header for the full step-by-step
93
105
  * rationale.
94
106
  */
95
- export function runRollback(config, runner) {
107
+ export function runRollback(config, runner, opts = {}) {
96
108
  // Step 1: read state.
97
109
  const state = readState(config.app_name);
98
110
  if (!state) {
@@ -125,6 +137,18 @@ export function runRollback(config, runner) {
125
137
  }
126
138
  const currentLiveDir = path.resolve(state.live_dir);
127
139
  const restoreDir = path.resolve(state.previous_live_dir);
140
+ // Shared dirs (ticket 03, deploy-shared-dirs spec, user story 28): the
141
+ // same re-verification switch.ts applies before promoting, applied here
142
+ // in the opposite direction. Read-only (`inspectSharedDirs`) — ANY
143
+ // non-`linked` state in either slot aborts; only `opts.force` overrides.
144
+ // A no-op when shared_dirs is empty (feature off).
145
+ if (config.shared_dirs.length > 0 && !opts.force) {
146
+ const drift = describeSharedDirDrift(inspectSharedDirs(config, { live: currentLiveDir, standby: restoreDir }));
147
+ if (drift.length > 0) {
148
+ throw new RollbackAbortError(`Shared dir(s) not fully linked in both slots: ${drift.join(', ')}. Run "hazo-env deploy share" to fix, ` +
149
+ `or pass --force to override.`);
150
+ }
151
+ }
128
152
  // Step 4: read the restored dir's git ref FIRST, before anything is
129
153
  // stopped/started — mirrors switch.ts step 2 (see header).
130
154
  const gitRef = runner.exec('git rev-parse HEAD', { cwd: restoreDir }).trim();
@@ -0,0 +1,28 @@
1
+ import type { MigrateSharedDirsResult } from './shared-dirs.js';
2
+ import type { DeployConfig } from './types.js';
3
+ export interface RunShareOptions {
4
+ /** Directory to treat as the only slot when no state file exists yet. Defaults to process.cwd(). */
5
+ cwd?: string;
6
+ /** Preview the full report without writing, renaming, or linking anything. Default: false. */
7
+ dryRun?: boolean;
8
+ }
9
+ export interface RunShareResult extends MigrateSharedDirsResult {
10
+ liveDir: string;
11
+ /** `undefined` when there is no peer to merge from (no state file, or the standby dir no longer exists on disk). */
12
+ standbyDir?: string;
13
+ stateFound: boolean;
14
+ }
15
+ /**
16
+ * Resolve live/standby and run the one-time shared-dirs migration.
17
+ *
18
+ * - State file found: live/standby come from it, exactly as recorded —
19
+ * regardless of which one `cwd` actually is. The standby dir is only used
20
+ * if it still exists on disk (a peer that was removed by hand is treated
21
+ * as "no peer", same as pre-`deploy init`), so a stale state file can
22
+ * never cause a symlink to be created inside a directory that isn't
23
+ * there.
24
+ * - No state file (never ran `deploy init`): `cwd` is the only slot; there
25
+ * is no peer to merge from.
26
+ */
27
+ export declare function runShare(config: DeployConfig, opts?: RunShareOptions): RunShareResult;
28
+ //# sourceMappingURL=share.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"share.d.ts","sourceRoot":"","sources":["../../src/deploy/share.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,MAAM,WAAW,eAAe;IAC9B,oGAAoG;IACpG,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,8FAA8F;IAC9F,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,cAAe,SAAQ,uBAAuB;IAC7D,OAAO,EAAE,MAAM,CAAC;IAChB,oHAAoH;IACpH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,YAAY,EAAE,IAAI,GAAE,eAAoB,GAAG,cAAc,CAwBzF"}
@@ -0,0 +1,53 @@
1
+ // hazo_env/src/deploy/share.ts — `deploy share`: resolve live/standby from
2
+ // state, then delegate to shared-dirs.ts's `migrateSharedDirs` for the
3
+ // actual filesystem work.
4
+ //
5
+ // Mirrors how init.ts/build.ts resolve directories before calling into
6
+ // shared-dirs.ts's `ensureLinks`: this file's only job is figuring out
7
+ // which two directories play "live" and "standby" — tolerating a missing
8
+ // state file or a peer that was never created (user stories 7/20) — it
9
+ // never touches a shared-dir path itself.
10
+ //
11
+ // Per the spec, `deploy share` is runnable from EITHER slot: the live/
12
+ // standby roles always come from the state file's own `live_dir`/
13
+ // `standby_dir` labels (which side wins a content conflict), never from
14
+ // `cwd` — `cwd` only matters as the single-slot fallback when no state file
15
+ // exists yet.
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { readState } from './state.js';
19
+ import { migrateSharedDirs } from './shared-dirs.js';
20
+ /**
21
+ * Resolve live/standby and run the one-time shared-dirs migration.
22
+ *
23
+ * - State file found: live/standby come from it, exactly as recorded —
24
+ * regardless of which one `cwd` actually is. The standby dir is only used
25
+ * if it still exists on disk (a peer that was removed by hand is treated
26
+ * as "no peer", same as pre-`deploy init`), so a stale state file can
27
+ * never cause a symlink to be created inside a directory that isn't
28
+ * there.
29
+ * - No state file (never ran `deploy init`): `cwd` is the only slot; there
30
+ * is no peer to merge from.
31
+ */
32
+ export function runShare(config, opts = {}) {
33
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
34
+ const dryRun = opts.dryRun ?? false;
35
+ const state = readState(config.app_name);
36
+ let liveDir;
37
+ let standbyDir;
38
+ const stateFound = !!state;
39
+ if (state) {
40
+ liveDir = path.resolve(state.live_dir);
41
+ const candidateStandby = path.resolve(state.standby_dir);
42
+ standbyDir = fs.existsSync(candidateStandby) ? candidateStandby : undefined;
43
+ }
44
+ else {
45
+ liveDir = cwd;
46
+ standbyDir = undefined;
47
+ }
48
+ if (config.shared_dirs.length === 0) {
49
+ return { dryRun, dirs: [], liveDir, standbyDir, stateFound };
50
+ }
51
+ const result = migrateSharedDirs(config, { live: liveDir, standby: standbyDir, dryRun });
52
+ return { ...result, liveDir, standbyDir, stateFound };
53
+ }