@kaynooo/stack-tools 0.0.0-stage → 0.1.2

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -2
  3. package/dist/cli.js +976 -0
  4. package/package.json +31 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo <kaynooo@kevyn.fr>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # stack
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Two stack helpers for Claude Code: a stable port per service name, and an audit of a compose release setup against its `release.config.ts`.
4
+
5
+ ```sh
6
+ bun install -g @kaynooo/stack-tools
7
+ ```
8
+
9
+ ## Commands
10
+
11
+ | Command | What it does |
12
+ | --- | --- |
13
+ | `stack port <name>` | prints the port the name always hashes to (FNV-1a, 1024-65535), so a service keeps the same port on every machine |
14
+ | `stack audit [dir]` | cross-checks `release.config.ts` in `dir` (the current directory) against the compose files it syncs |
15
+
16
+ `stack port` takes `--min` and `--max` to change the range. When something on this machine already listens on the port it says so on stderr; the number is still printed and the exit code stays 0.
17
+
18
+ ## Audit
19
+
20
+ The checks, in the order they are reported:
21
+
22
+ - `sync` and `build`: every `deploySyncFiles` entry, `sourceDir`, `buildContext`, `dockerfile` and buildSecret `src` (a leading `~` is the home directory) exists, and a buildSecret `env` is set in the shell.
23
+ - `compose`: `docker compose config` succeeds on the base file and on each overlay merged over it. The base is the shortest compose file name among `deploySyncFiles`.
24
+ - `env`: every `${VAR}` without a default is in `requiredServerEnv`, and every listed key is referenced.
25
+ - `version`: each `versionEnv` is interpolated by a compose file, and each `*_VERSION` a compose file interpolates is declared by a release.
26
+ - `image`, `restart` and `post-deploy`: services the config names exist, and registry images are built by a release.
27
+ - `health` and `routing`: restarted services have a healthcheck, ports and traefik labels live in overlays, and `composeArgs` does not drop them.
28
+ - `layout`, `nuxt` and `gitignore`: bind mounts appear in the base file's header, `NUXT_*` variables match the runtime config, and `.release-logs` and `.release-worktrees` are ignored.
29
+
30
+ Exit codes: 0 no error (warnings allowed), 1 at least one error, 2 no `release.config.ts`. `--json` prints `{ root, composeFiles, findings }` where a finding is `{ level, check, message }`.
31
+
32
+ It needs docker for `docker compose config`. When the package `release.config.ts` imports `defineConfig` from is not installed, a stand-in that returns its argument is used.
package/dist/cli.js ADDED
@@ -0,0 +1,976 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import process7 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process2 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/style.ts
12
+ import process from "process";
13
+
14
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
+ function x(s) {
16
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
17
+ if (!/^[a-f0-9]+$/.test(r))
18
+ return [0, 0, 0];
19
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
20
+ if (t === 3 || t === 4) {
21
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
22
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
23
+ }
24
+ if (t !== 6 && t !== 8)
25
+ throw Error(`Invalid hex color length: ${t}`);
26
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
27
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
28
+ throw Error(`Invalid hex color value: ${s}`);
29
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
30
+ }
31
+ function A(s) {
32
+ let [r, t, n, a] = s;
33
+ if (a)
34
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
35
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
36
+ }
37
+ function R(s, r, t) {
38
+ s = (s % 360 + 360) % 360, t /= 100;
39
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
40
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
41
+ return Math.round(255 * y);
42
+ };
43
+ return [a(0), a(8), a(4)];
44
+ }
45
+ function k(s) {
46
+ let [r, t, n] = s;
47
+ r /= 255, t /= 255, n /= 255;
48
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
49
+ if (a !== b) {
50
+ let u = a - b;
51
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
52
+ o = (t - n) / u + (t < n ? 6 : 0);
53
+ else if (a === t)
54
+ o = (n - r) / u + 2;
55
+ else
56
+ o = (r - t) / u + 4;
57
+ o /= 6;
58
+ }
59
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
60
+ }
61
+ function H(s, r, t) {
62
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
63
+ let n = (a) => {
64
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
65
+ return Math.round(255 * o);
66
+ };
67
+ return [n(5), n(3), n(1)];
68
+ }
69
+ function f(s) {
70
+ let [r, t, n] = s;
71
+ r /= 255, t /= 255, n /= 255;
72
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
73
+ if (o !== 0) {
74
+ if (a === r)
75
+ y = (t - n) / o + (t < n ? 6 : 0);
76
+ else if (a === t)
77
+ y = (n - r) / o + 2;
78
+ else
79
+ y = (r - t) / o + 4;
80
+ y /= 6;
81
+ }
82
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
83
+ }
84
+ function O(s) {
85
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
86
+ if (a === 1)
87
+ return [0, 0, 0, 100];
88
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
89
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
90
+ }
91
+ function v(s, r, t, n) {
92
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
93
+ }
94
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
95
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
96
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
97
+ function T(s) {
98
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
99
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
100
+ }
101
+ function M(s, r, t) {
102
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
103
+ return [u(o), u(y), u(c)];
104
+ }
105
+ function d(s) {
106
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
107
+ return [i(r, 4), i(a, 4), i(b, 2)];
108
+ }
109
+ function C(s, r, t) {
110
+ let n = t * Math.PI / 180;
111
+ return M(s, r * Math.cos(n), r * Math.sin(n));
112
+ }
113
+ function l(s) {
114
+ let r = s / 255;
115
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
116
+ }
117
+
118
+ class e {
119
+ r;
120
+ g;
121
+ b;
122
+ a;
123
+ constructor(s, r, t, n = 1) {
124
+ this.r = s, this.g = r, this.b = t, this.a = n;
125
+ }
126
+ static from(s, r) {
127
+ if (s === "hex") {
128
+ let [t, n, a, b] = x(r);
129
+ return new e(t, n, a, b);
130
+ }
131
+ if (s === "rgb") {
132
+ if (Array.isArray(r)) {
133
+ let [o, y, c, u] = r;
134
+ return new e(o, y, c, u);
135
+ }
136
+ let { r: t, g: n, b: a, a: b } = r;
137
+ return new e(t, n, a, b);
138
+ }
139
+ if (s === "hsl") {
140
+ let t, n, a, b;
141
+ if (Array.isArray(r))
142
+ [t, n, a, b] = r;
143
+ else
144
+ ({ h: t, s: n, l: a, a: b } = r);
145
+ let [o, y, c] = R(t, n, a);
146
+ return new e(o, y, c, b);
147
+ }
148
+ if (s === "hsv") {
149
+ let t, n, a, b;
150
+ if (Array.isArray(r))
151
+ [t, n, a, b] = r;
152
+ else
153
+ ({ h: t, s: n, v: a, a: b } = r);
154
+ let [o, y, c] = H(t, n, a);
155
+ return new e(o, y, c, b);
156
+ }
157
+ if (s === "cmyk") {
158
+ let t, n, a, b, o;
159
+ if (Array.isArray(r))
160
+ [t, n, a, b, o] = r;
161
+ else
162
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
163
+ let [y, c, u] = v(t, n, a, b);
164
+ return new e(y, c, u, o);
165
+ }
166
+ if (s === "oklch") {
167
+ let t, n, a, b;
168
+ if (Array.isArray(r))
169
+ [t, n, a, b] = r;
170
+ else
171
+ ({ l: t, c: n, h: a, a: b } = r);
172
+ let [o, y, c] = C(t, n, a);
173
+ return new e(o, y, c, b);
174
+ }
175
+ if (s === "oklab") {
176
+ let t, n, a, b;
177
+ if (Array.isArray(r))
178
+ [t, n, a, b] = r;
179
+ else
180
+ ({ l: t, a: n, b: a, alpha: b } = r);
181
+ let [o, y, c] = M(t, n, a);
182
+ return new e(o, y, c, b);
183
+ }
184
+ throw Error("Invalid input");
185
+ }
186
+ to(s) {
187
+ switch (s) {
188
+ case "rgb":
189
+ return [this.r, this.g, this.b];
190
+ case "rgba":
191
+ return [this.r, this.g, this.b, this.a];
192
+ case "hex":
193
+ return A([this.r, this.g, this.b]);
194
+ case "hexa":
195
+ return A([this.r, this.g, this.b, this.a]);
196
+ case "hsl":
197
+ return k([this.r, this.g, this.b]);
198
+ case "hsla":
199
+ return [...k([this.r, this.g, this.b]), this.a];
200
+ case "hsv":
201
+ return f([this.r, this.g, this.b]);
202
+ case "hsva":
203
+ return [...f([this.r, this.g, this.b]), this.a];
204
+ case "cmyk":
205
+ return O([this.r, this.g, this.b]);
206
+ case "cmyka":
207
+ return [...O([this.r, this.g, this.b]), this.a];
208
+ case "oklch":
209
+ return d([this.r, this.g, this.b]);
210
+ case "oklcha":
211
+ return [...d([this.r, this.g, this.b]), this.a];
212
+ case "oklab":
213
+ return T([this.r, this.g, this.b]);
214
+ case "oklaba":
215
+ return [...T([this.r, this.g, this.b]), this.a];
216
+ default:
217
+ return [this.r, this.g, this.b];
218
+ }
219
+ }
220
+ getLuminance() {
221
+ let s = l(this.r), r = l(this.g), t = l(this.b);
222
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
223
+ }
224
+ contrastRatio(s) {
225
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
226
+ return (n + 0.05) / (a + 0.05);
227
+ }
228
+ bestContrastForeground() {
229
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
230
+ return t >= n ? s : r;
231
+ }
232
+ }
233
+
234
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
235
+ var r = 39;
236
+ var o = 49;
237
+ var f2 = "\x1B[";
238
+ var C2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
239
+ let [a, l, s] = e.from("hex", i).to("rgb");
240
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
241
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
242
+ var b = new Set(["", "1", "2", "3", "true"]);
243
+ function h(i, n = globalThis.process?.env ?? {}) {
244
+ if (n.FORCE_COLOR !== undefined)
245
+ return b.has(n.FORCE_COLOR);
246
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
247
+ return false;
248
+ return i?.isTTY === true;
249
+ }
250
+ function d2(i, n, a) {
251
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
252
+ return n;
253
+ let l = "", s = "";
254
+ for (let g = 0, y = i.length;g < y; g++) {
255
+ let [c, p] = i[g];
256
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
257
+ }
258
+ return l + n + s;
259
+ }
260
+ function u(i, n = []) {
261
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
262
+ let g = C2[s];
263
+ if (Array.isArray(g))
264
+ return u(i, [...n, g]);
265
+ if (typeof g === "function")
266
+ return (...y) => u(i, [...n, g(...y)]);
267
+ throw Error(`Unknown style: ${String(s)}`);
268
+ } });
269
+ }
270
+ function le(i = {}) {
271
+ return u(i);
272
+ }
273
+ var t = le();
274
+
275
+ // ../kit/src/style.ts
276
+ function takesControlCodes(stream, env = process.env) {
277
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
278
+ }
279
+ function paint(stream, env = process.env) {
280
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
281
+ }
282
+ var STATUSES = {
283
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
284
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
285
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
286
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
287
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
288
+ };
289
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
290
+
291
+ // ../kit/src/format.ts
292
+ function upTo(text, separator) {
293
+ const end = text.indexOf(separator);
294
+ return end === -1 ? text : text.slice(0, end);
295
+ }
296
+ var ESCAPE = String.fromCharCode(27);
297
+ function printJson(value) {
298
+ console.log(JSON.stringify(value, undefined, 2));
299
+ }
300
+
301
+ // ../kit/src/args.ts
302
+ function jsonOption(holds) {
303
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
304
+ }
305
+
306
+ class Exit extends Error {
307
+ code;
308
+ hint;
309
+ constructor(message, code, hint) {
310
+ super(message);
311
+ this.code = code;
312
+ this.hint = hint;
313
+ }
314
+ }
315
+ function fail(message, code = 2, hint) {
316
+ throw new Exit(message, code, hint);
317
+ }
318
+
319
+ class UsageError extends Exit {
320
+ constructor(message) {
321
+ super(message, 2);
322
+ }
323
+ }
324
+ function badUsage(message) {
325
+ throw new UsageError(message);
326
+ }
327
+
328
+ class HelpShown extends Exit {
329
+ constructor() {
330
+ super("help shown", 0);
331
+ }
332
+ }
333
+
334
+ class Completing {
335
+ options;
336
+ constructor(options) {
337
+ this.options = options;
338
+ }
339
+ }
340
+ var completion = { active: false };
341
+ var OPTIONAL = /\[[^\]]+\]/g;
342
+ var USAGE_PREFIX = /^usage:\s*/i;
343
+ function usageLine(usage, colors = paint(process2.stdout)) {
344
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
345
+ }
346
+ function helpText(usage, options, colors = paint(process2.stdout)) {
347
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors)].join(`
348
+ `);
349
+ }
350
+ function optionRows(options, colors = paint(process2.stdout)) {
351
+ const rows = Object.entries(options).map(([name, option]) => {
352
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
353
+ const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
354
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description };
355
+ });
356
+ const width = Math.max(0, ...rows.map((row) => row.width));
357
+ return rows.map((row) => ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
358
+ }
359
+ function parse(args, usage, options, settings = {}) {
360
+ const all = { ...options, help: { type: "boolean", short: "h", description: "show this help" } };
361
+ if (completion.active)
362
+ throw new Completing(all);
363
+ const separator = settings.rest === true ? args.indexOf("--") : -1;
364
+ const own = separator === -1 ? args : args.slice(0, separator);
365
+ const rest = separator === -1 ? undefined : args.slice(separator + 1);
366
+ let parsed;
367
+ try {
368
+ parsed = parseArgs({ args: own, options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
369
+ } catch (error) {
370
+ badUsage(parseError(error));
371
+ }
372
+ if (parsed.values.help === true) {
373
+ console.log(helpText(usage, all));
374
+ throw new HelpShown;
375
+ }
376
+ if (settings.positionals !== undefined)
377
+ checkPositionals(parsed.positionals, settings.positionals);
378
+ return { ...parsed, positionals: parsed.positionals, rest };
379
+ }
380
+ function checkPositionals(given, names) {
381
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
382
+ const required = names.filter((name) => !name.startsWith("[")).length;
383
+ if (given.length < required)
384
+ badUsage(`missing ${names[given.length]}`);
385
+ if (!variadic && given.length > names.length)
386
+ badUsage(`unexpected argument ${given[names.length]}`);
387
+ }
388
+ function parseError(error) {
389
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
390
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
391
+ }
392
+ function wholeNumber(value, name, fallback, min = 1) {
393
+ if (value === undefined)
394
+ return fallback;
395
+ const number = Number(value);
396
+ if (!Number.isInteger(number) || number < min)
397
+ badUsage(`--${name} takes a whole number from ${min}, not ${value}`);
398
+ return number;
399
+ }
400
+ // ../kit/src/cli.ts
401
+ import process3 from "process";
402
+
403
+ // ../kit/src/text.ts
404
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
405
+ function distance(a, b) {
406
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
407
+ for (const [i, left] of [...a].entries()) {
408
+ const current = [i + 1];
409
+ for (const [j, right] of [...b].entries())
410
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
411
+ previous = current;
412
+ }
413
+ return previous[b.length] ?? 0;
414
+ }
415
+
416
+ // ../kit/src/cli.ts
417
+ function closest(name, names) {
418
+ const started = names.find((known) => known.startsWith(name));
419
+ if (started !== undefined)
420
+ return started;
421
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
422
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
423
+ }
424
+ async function help({ path, header, commands, defaultCommand }, stream) {
425
+ const colors = paint(stream);
426
+ const width = Math.max(...Object.keys(commands).map((name) => name.length));
427
+ const prefix = path.join(" ");
428
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
429
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
430
+ return [
431
+ header(colors),
432
+ "",
433
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
434
+ "",
435
+ colors.bold("Commands:"),
436
+ ...Object.entries(commands).map(([name, { summary }]) => ` ${colors.cyan(name.padEnd(width))} ${colors.dim(summary)}`),
437
+ ...options === undefined || Object.keys(options).length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(options, colors)],
438
+ "",
439
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
440
+ ].join(`
441
+ `);
442
+ }
443
+ function printError(prefix, message, hint, cause) {
444
+ const colors = paint(process3.stderr);
445
+ const styled = takesControlCodes(process3.stderr);
446
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
447
+ const under = (label, text, tint) => text === undefined ? "" : `
448
+ ${styled ? tint(label) : `${label}:`} ${text}`;
449
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
450
+ }
451
+ function reportThrown(prefix, error, redact = (text) => text) {
452
+ if (error instanceof HelpShown)
453
+ return 0;
454
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
455
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
456
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
457
+ printError(prefix, redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
458
+ return error instanceof Exit ? error.code : 1;
459
+ }
460
+ async function dispatch(level, argv, { version, redact }) {
461
+ const [name, ...args] = argv;
462
+ const prefix = level.path.join(" ");
463
+ if (name === undefined && level.path.length > 1) {
464
+ console.error(await help(level, process3.stderr));
465
+ return 2;
466
+ }
467
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
468
+ console.log(await help(level, process3.stdout));
469
+ return 0;
470
+ }
471
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
472
+ console.log(version);
473
+ return 0;
474
+ }
475
+ let command = level.commands[level.aliases?.[name] ?? name];
476
+ let rest = args;
477
+ if (command === undefined && level.defaultCommand !== undefined) {
478
+ command = level.commands[level.defaultCommand];
479
+ rest = argv;
480
+ }
481
+ if (command === undefined) {
482
+ const meant = closest(name, Object.keys(level.commands));
483
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
484
+ return 2;
485
+ }
486
+ if ("commands" in command) {
487
+ const { summary } = command;
488
+ return dispatch({ path: [...level.path, name], header: (colors) => `${colors.bold(`${prefix} ${name}`)} ${summary}`, commands: command.commands, aliases: command.aliases, defaultCommand: undefined }, rest, { version, redact });
489
+ }
490
+ try {
491
+ return await command.run(rest);
492
+ } catch (error) {
493
+ return reportThrown(`${prefix} ${name}`, error, redact);
494
+ }
495
+ }
496
+ var COMPLETE = "__complete";
497
+ var FILES = "__files__";
498
+ async function optionsOf(run) {
499
+ completion.active = true;
500
+ try {
501
+ await run([]);
502
+ } catch (error) {
503
+ if (error instanceof Completing)
504
+ return error.options;
505
+ } finally {
506
+ completion.active = false;
507
+ }
508
+ return {};
509
+ }
510
+ async function leafCandidates(run, words) {
511
+ if (!(words.at(-1) ?? "").startsWith("-"))
512
+ return [FILES];
513
+ return Object.entries(await optionsOf(run)).map(([name, option]) => `--${name} ${option.description}`);
514
+ }
515
+ async function candidates(commands, aliases, defaultCommand, words) {
516
+ const [word = "", ...rest] = words;
517
+ const command = commands[aliases?.[word] ?? word];
518
+ if (rest.length === 0 && !word.startsWith("-"))
519
+ return Object.entries(commands).map(([name, { summary }]) => `${name} ${summary}`);
520
+ if (command === undefined) {
521
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
522
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
523
+ }
524
+ return "commands" in command ? candidates(command.commands, command.aliases, undefined, rest) : leafCandidates(command.run, rest);
525
+ }
526
+ async function printCandidates(found) {
527
+ for (const line of await found)
528
+ console.log(line);
529
+ return 0;
530
+ }
531
+ async function runCli(cli, argv = process3.argv.slice(2)) {
532
+ if (argv[0] === COMPLETE)
533
+ return printCandidates(candidates(cli.commands, cli.aliases, cli.defaultCommand, argv.slice(1)));
534
+ return dispatch({ path: [cli.name], header: (colors) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${cli.about}`, commands: cli.commands, aliases: cli.aliases, defaultCommand: cli.defaultCommand }, argv, { version: cli.version, redact: cli.redact });
535
+ }
536
+ // package.json
537
+ var version = "0.1.2";
538
+
539
+ // src/commands/audit.ts
540
+ import { homedir } from "os";
541
+ import { resolve as resolve2 } from "path";
542
+ import process6 from "process";
543
+
544
+ // src/audit/compose.ts
545
+ import { join } from "path";
546
+ import process5 from "process";
547
+ var dockerCompose = async (root, files) => {
548
+ const args = ["docker", "compose", "--project-directory", root, ...files.flatMap((file) => ["-f", join(root, file)]), "config", "--no-interpolate", "--format", "json"];
549
+ const run = Bun.spawn(args, { stdout: "pipe", stderr: "pipe", env: { ...process5.env, COMPOSE_FILE: "" } });
550
+ const [out, err, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
551
+ const last = err.trim().split(`
552
+ `).at(-1) ?? "";
553
+ if (code !== 0)
554
+ throw new Error(last !== "" ? last : `exited with ${code}`);
555
+ return JSON.parse(out);
556
+ };
557
+
558
+ // src/audit/render.ts
559
+ import { basename } from "path";
560
+ var line = (finding) => ` ${finding.level === "error" ? "x" : "!"} [${finding.check}] ${finding.message}`;
561
+ function errorsOf(result) {
562
+ return result.findings.filter((finding) => finding.level === "error");
563
+ }
564
+ function render(result) {
565
+ const errors = errorsOf(result);
566
+ const warnings = result.findings.filter((finding) => finding.level === "warn");
567
+ if (result.findings.length === 0)
568
+ return `ok ${basename(result.root)}: compose ${result.composeFiles.join(", ")} and release.config.ts agree.`;
569
+ return [
570
+ ...errors.length > 0 ? ["Errors", ...errors.map(line), ""] : [],
571
+ ...warnings.length > 0 ? ["Warnings", ...warnings.map(line), ""] : [],
572
+ `${errors.length} error(s), ${warnings.length} warning(s)`
573
+ ].join(`
574
+ `);
575
+ }
576
+
577
+ // src/audit/run.ts
578
+ import { existsSync as existsSync3 } from "fs";
579
+ import { join as join4 } from "path";
580
+
581
+ // src/audit/checks.ts
582
+ import { existsSync, readFileSync } from "fs";
583
+ import { join as join2, resolve } from "path";
584
+ var ENV_REF = /\$\{([A-Z_]\w*)(\s*:?[-?][^}]*)?\}/gi;
585
+ var YAML_FILE = /\.ya?ml$/;
586
+ var LEADING_DOT_SLASH = /^\.\//;
587
+ var SERVICES_KEY = /^services:/m;
588
+ var EXEC_SERVICE = /\{compose\}(?:\s+--\S+)*\s+(?:exec|run)\s+(?:-\S+\s+)*([\w-]+)/;
589
+ var services = (model) => Object.entries(model?.services ?? {});
590
+ function before(text, separator) {
591
+ const at = text.indexOf(separator);
592
+ return at < 0 ? text : text.slice(0, at);
593
+ }
594
+ var stripDotSlash = (file) => file.replace(LEADING_DOT_SLASH, "");
595
+ function composeLayout(root, config) {
596
+ const composeFiles = (config.deploySyncFiles ?? []).map(stripDotSlash).filter((file) => YAML_FILE.test(file) && existsSync(join2(root, file)));
597
+ const [base] = composeFiles.toSorted((a, b) => a.length - b.length);
598
+ return { composeFiles, base, overlays: composeFiles.filter((file) => file !== base) };
599
+ }
600
+ function syncFindings(root, config) {
601
+ return (config.deploySyncFiles ?? []).filter((file) => !existsSync(join2(root, stripDotSlash(file)))).map((file) => ({ level: "error", check: "sync", message: `deploySyncFiles entry does not exist: ${file}` }));
602
+ }
603
+ function buildFindings(root, releases, env, home) {
604
+ const findings = [];
605
+ const missing = (release, key) => {
606
+ const path = release[key];
607
+ if (path !== undefined && path !== "" && !existsSync(join2(root, path)))
608
+ findings.push({ level: "error", check: "build", message: `${release.slug}: ${key} does not exist: ${path}` });
609
+ };
610
+ for (const release of releases) {
611
+ missing(release, "sourceDir");
612
+ missing(release, "buildContext");
613
+ missing(release, "dockerfile");
614
+ for (const secret of release.buildSecrets ?? []) {
615
+ if (secret.src !== undefined && secret.src !== "") {
616
+ const path = secret.src.startsWith("~") ? join2(home, secret.src.slice(1)) : resolve(root, secret.src);
617
+ if (!existsSync(path))
618
+ findings.push({ level: "error", check: "build", message: `${release.slug}: buildSecret "${secret.id}" src does not exist: ${secret.src}` });
619
+ }
620
+ if (secret.env !== undefined && secret.env !== "" && (env[secret.env] ?? "") === "")
621
+ findings.push({ level: "warn", check: "build", message: `${release.slug}: buildSecret "${secret.id}" reads $${secret.env}, unset in this shell` });
622
+ }
623
+ }
624
+ return findings;
625
+ }
626
+ function envRefs(root, composeFiles) {
627
+ return composeFiles.flatMap((file) => [...readFileSync(join2(root, file), "utf8").matchAll(ENV_REF)].map((match) => ({ name: match[1], defaulted: Boolean(match[2]), file })));
628
+ }
629
+ function envFindings(refs, required) {
630
+ const findings = [];
631
+ const level = required.length > 0 ? "error" : "warn";
632
+ for (const name of new Set(refs.filter((ref) => !ref.defaulted).map((ref) => ref.name))) {
633
+ if (!name.endsWith("_VERSION") && !required.includes(name))
634
+ findings.push({ level, check: "env", message: `\${${name}} has no default in ${refs.find((ref) => ref.name === name)?.file} and is not in requiredServerEnv` });
635
+ }
636
+ for (const name of required) {
637
+ if (!refs.some((ref) => ref.name === name))
638
+ findings.push({ level: "warn", check: "env", message: `requiredServerEnv lists ${name}, which no compose file references` });
639
+ }
640
+ return findings;
641
+ }
642
+ function versionFindings(refs, releases) {
643
+ const findings = [];
644
+ const inCompose = new Set(refs.filter((ref) => ref.name.endsWith("_VERSION")).map((ref) => ref.name));
645
+ const inConfig = new Set(releases.map((release) => release.versionEnv).filter((name) => typeof name === "string" && name !== ""));
646
+ for (const name of inConfig) {
647
+ if (!inCompose.has(name))
648
+ findings.push({ level: "error", check: "version", message: `versionEnv ${name} is never interpolated by a compose file` });
649
+ }
650
+ for (const name of inCompose) {
651
+ if (!inConfig.has(name))
652
+ findings.push({ level: "error", check: "version", message: `compose interpolates \${${name}}, which no release declares as versionEnv` });
653
+ }
654
+ return findings;
655
+ }
656
+ function imageFindings(config, releases, model) {
657
+ const registry = config.registry ?? "";
658
+ if (registry === "")
659
+ return [];
660
+ const declared = new Set(releases.filter((release) => release.image !== undefined && release.image !== "").map((release) => `${registry}/${release.image}`));
661
+ const findings = [];
662
+ for (const [name, service] of services(model)) {
663
+ const repo = service.image === undefined ? undefined : before(service.image, ":");
664
+ if (repo !== undefined && repo.startsWith(registry) && !declared.has(repo))
665
+ findings.push({ level: "warn", check: "image", message: `service "${name}" pulls ${repo}, which no release in this config builds` });
666
+ }
667
+ return findings;
668
+ }
669
+ function restartFindings(config, releases, model, base) {
670
+ const known = new Set(Object.keys(model?.services ?? {}));
671
+ const findings = [];
672
+ for (const release of releases) {
673
+ for (const service of release.restartServices ?? []) {
674
+ if (!known.has(service))
675
+ findings.push({ level: "error", check: "restart", message: `${release.slug}: restartServices names "${service}", absent from ${base}` });
676
+ }
677
+ }
678
+ for (const server of config.servers ?? []) {
679
+ for (const [slug, override] of Object.entries(server.releaseOverrides ?? {})) {
680
+ for (const service of override.restartServices ?? []) {
681
+ if (!known.has(service))
682
+ findings.push({ level: "error", check: "restart", message: `server ${server.name}: releaseOverrides.${slug} names service "${service}", absent from ${base}` });
683
+ }
684
+ }
685
+ }
686
+ return findings;
687
+ }
688
+ function postDeployFindings(releases, model, base) {
689
+ const known = new Set(Object.keys(model?.services ?? {}));
690
+ const findings = [];
691
+ for (const release of releases) {
692
+ for (const command of release.postDeployCommands ?? []) {
693
+ const target = EXEC_SERVICE.exec(command)?.[1];
694
+ if (target !== undefined && !known.has(target))
695
+ findings.push({ level: "warn", check: "post-deploy", message: `${release.slug}: post-deploy command targets service "${target}", absent from ${base}` });
696
+ }
697
+ }
698
+ return findings;
699
+ }
700
+ var gatedServices = (releases) => new Set(releases.flatMap((release) => release.restartServices ?? []));
701
+ function healthFindings(gated, model) {
702
+ return [...gated].filter((name) => {
703
+ const service = model?.services?.[name];
704
+ return service !== undefined && (service.healthcheck === undefined || service.healthcheck === null);
705
+ }).map((name) => ({ level: "warn", check: "health", message: `service "${name}" is restarted by a release but declares no healthcheck, so --wait will not gate it` }));
706
+ }
707
+ function routingFindings(config, gated, model, base, overlays) {
708
+ if (overlays.length === 0)
709
+ return [];
710
+ const findings = [];
711
+ for (const name of gated) {
712
+ const service = model?.services?.[name];
713
+ if (service === undefined)
714
+ continue;
715
+ if (service.ports !== undefined && service.ports.length > 0)
716
+ findings.push({ level: "error", check: "routing", message: `service "${name}" publishes ports in ${base}; publishing belongs in an overlay` });
717
+ if (Object.keys(service.labels ?? {}).some((key) => key.startsWith("traefik.")))
718
+ findings.push({ level: "error", check: "routing", message: `service "${name}" carries traefik labels in ${base}; routing belongs in an overlay` });
719
+ }
720
+ const composeArgs = config.composeArgs ?? [];
721
+ if (composeArgs.length > 0)
722
+ findings.push({ level: "error", check: "routing", message: `composeArgs is set (${composeArgs.join(" ")}) while ${overlays.length} overlay(s) exist: -f overrides each server's COMPOSE_FILE and drops them` });
723
+ for (const server of config.servers ?? []) {
724
+ if (server.composeArgs !== undefined && server.composeArgs.length > 0)
725
+ findings.push({ level: "warn", check: "routing", message: `server ${server.name} sets composeArgs; prefer its own COMPOSE_FILE` });
726
+ }
727
+ return findings;
728
+ }
729
+ function layoutFindings(root, base, model) {
730
+ if (base === undefined)
731
+ return [];
732
+ const header = readFileSync(join2(root, base), "utf8").split(SERVICES_KEY)[0] ?? "";
733
+ const findings = [];
734
+ for (const [name, service] of services(model)) {
735
+ for (const volume of service.volumes ?? []) {
736
+ const source = typeof volume === "string" ? before(volume, ":") : volume.source;
737
+ if (source?.startsWith(".") === true && !header.includes(stripDotSlash(source)))
738
+ findings.push({ level: "warn", check: "layout", message: `service "${name}" bind-mounts ${source}, absent from the header's expected server layout` });
739
+ }
740
+ }
741
+ return findings;
742
+ }
743
+ function gitignoreFindings(root) {
744
+ const path = join2(root, ".gitignore");
745
+ const text = existsSync(path) ? readFileSync(path, "utf8") : "";
746
+ return [".release-logs", ".release-worktrees"].filter((entry) => !text.includes(entry)).map((entry) => ({ level: "warn", check: "gitignore", message: `${entry}/ is not in .gitignore` }));
747
+ }
748
+
749
+ // src/audit/nuxt.ts
750
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
751
+ import { basename as basename2, join as join3 } from "path";
752
+ var CAMEL_BOUNDARY = /([a-z0-9])([A-Z])/g;
753
+ var KEY = /([A-Z_]\w*)\s*(?:\?\s*)?:/gi;
754
+ var OPENS_BRACE = /^\s*\{/;
755
+ var envVarFor = (key) => key.replace(CAMEL_BOUNDARY, "$1_$2").toUpperCase();
756
+ function braceBody(text, from) {
757
+ const open = text.indexOf("{", from);
758
+ if (open < 0)
759
+ return;
760
+ let depth = 0;
761
+ for (let i = open;i < text.length; i++) {
762
+ if (text[i] === "{")
763
+ depth++;
764
+ else if (text[i] === "}" && --depth === 0)
765
+ return { body: text.slice(open + 1, i), end: i };
766
+ }
767
+ return;
768
+ }
769
+ function leafPaths(body, prefix = []) {
770
+ const paths = [];
771
+ const key = new RegExp(KEY);
772
+ for (let match = key.exec(body);match !== null; match = key.exec(body)) {
773
+ const name = match[1];
774
+ const after = match.index + match[0].length;
775
+ if (OPENS_BRACE.test(body.slice(after))) {
776
+ const inner = braceBody(body, after);
777
+ if (inner === undefined)
778
+ continue;
779
+ paths.push(...leafPaths(inner.body, [...prefix, name]));
780
+ key.lastIndex = inner.end + 1;
781
+ } else {
782
+ paths.push([...prefix, name]);
783
+ }
784
+ }
785
+ return paths;
786
+ }
787
+ function schemaEnvNames(schema, iface, prefix) {
788
+ const at = schema.indexOf(`interface ${iface}`);
789
+ const body = at < 0 ? undefined : braceBody(schema, at);
790
+ return body === undefined ? [] : leafPaths(body.body).map((path) => prefix + path.map(envVarFor).join("_"));
791
+ }
792
+ function nuxtFindings(root, releases, model) {
793
+ const findings = [];
794
+ const dirs = [...new Set(releases.map((release) => release.buildContext).filter((context) => context !== undefined && context !== ""))].map((dir) => join3(root, dir)).filter((dir) => existsSync2(join3(dir, "nuxt.config.ts")));
795
+ for (const dir of dirs) {
796
+ const schemaPath = [join3(dir, ".nuxt/types/schema.d.ts"), join3(dir, ".nuxt/types/runtime-config.d.ts")].find((path) => existsSync2(path));
797
+ let allowed;
798
+ let level = "error";
799
+ let source;
800
+ if (schemaPath !== undefined) {
801
+ const schema = readFileSync2(schemaPath, "utf8");
802
+ allowed = new Set([
803
+ ...schemaEnvNames(schema, "SharedRuntimeConfig", "NUXT_"),
804
+ ...schemaEnvNames(schema, "SharedPublicRuntimeConfig", "NUXT_PUBLIC_")
805
+ ]);
806
+ source = `${basename2(dir)}/${schemaPath.slice(dir.length + 1)}`;
807
+ } else {
808
+ const config = readFileSync2(join3(dir, "nuxt.config.ts"), "utf8");
809
+ const at = config.indexOf("runtimeConfig:");
810
+ const block = at < 0 ? undefined : braceBody(config, at);
811
+ if (block === undefined)
812
+ continue;
813
+ allowed = new Set(leafPaths(block.body).map((path) => path[0] === "public" ? `NUXT_PUBLIC_${path.slice(1).map(envVarFor).join("_")}` : `NUXT_${path.map(envVarFor).join("_")}`));
814
+ level = "warn";
815
+ source = `${basename2(dir)}/nuxt.config.ts (run \`nuxt prepare\` in ${basename2(dir)} for the resolved config, modules included)`;
816
+ }
817
+ for (const [name, service] of Object.entries(model?.services ?? {})) {
818
+ for (const key of Object.keys(service.environment ?? {})) {
819
+ if (key.startsWith("NUXT_") && !allowed.has(key))
820
+ findings.push({ level, check: "nuxt", message: `service "${name}" sets ${key}, which matches no runtimeConfig key in ${source}` });
821
+ }
822
+ }
823
+ }
824
+ return findings;
825
+ }
826
+
827
+ // src/audit/run.ts
828
+ var CONFIG_FILE = "release.config.ts";
829
+ var DEFINE_CONFIG_IMPORT = /import\s*\{[^}]*\bdefineConfig\b[^}]*\}\s*from\s*['"]([^'"]+)['"]/;
830
+ function installed(specifier, root) {
831
+ try {
832
+ Bun.resolveSync(specifier, root);
833
+ return true;
834
+ } catch {
835
+ return false;
836
+ }
837
+ }
838
+ async function loadConfig(root) {
839
+ const specifier = DEFINE_CONFIG_IMPORT.exec(await Bun.file(join4(root, CONFIG_FILE)).text())?.[1];
840
+ if (specifier !== undefined && !installed(specifier, root)) {
841
+ Bun.plugin({
842
+ name: "release-stand-in",
843
+ setup(build) {
844
+ build.module(specifier, () => ({ exports: { defineConfig: (config) => config }, loader: "object" }));
845
+ }
846
+ });
847
+ }
848
+ const config = (await import(join4(root, CONFIG_FILE))).default;
849
+ if (config === undefined)
850
+ fail(`${CONFIG_FILE} has no default export`);
851
+ return config;
852
+ }
853
+ async function composeModels(options, base, overlays) {
854
+ const findings = [];
855
+ const load = async (files) => {
856
+ try {
857
+ return await options.loadCompose(options.root, files);
858
+ } catch (error) {
859
+ findings.push({ level: "error", check: "compose", message: `docker compose config failed for ${files.join(" + ")}: ${error instanceof Error ? error.message : String(error)}` });
860
+ return;
861
+ }
862
+ };
863
+ if (base === undefined)
864
+ return { model: undefined, findings };
865
+ const model = await load([base]);
866
+ for (const overlay of overlays)
867
+ await load([base, overlay]);
868
+ return { model, findings };
869
+ }
870
+ async function audit(config, options) {
871
+ const { root } = options;
872
+ const releases = config.releases ?? [];
873
+ const required = config.requiredServerEnv ?? [];
874
+ const { composeFiles, base, overlays } = composeLayout(root, config);
875
+ const compose = await composeModels(options, base, overlays);
876
+ const refs = envRefs(root, composeFiles);
877
+ const gated = gatedServices(releases);
878
+ const findings = [
879
+ ...syncFindings(root, config),
880
+ ...buildFindings(root, releases, options.env, options.home),
881
+ ...compose.findings,
882
+ ...envFindings(refs, required),
883
+ ...versionFindings(refs, releases),
884
+ ...imageFindings(config, releases, compose.model),
885
+ ...restartFindings(config, releases, compose.model, base),
886
+ ...postDeployFindings(releases, compose.model, base),
887
+ ...healthFindings(gated, compose.model),
888
+ ...routingFindings(config, gated, compose.model, base, overlays),
889
+ ...layoutFindings(root, base, compose.model),
890
+ ...nuxtFindings(root, releases, compose.model),
891
+ ...gitignoreFindings(root)
892
+ ];
893
+ return { root, composeFiles, findings };
894
+ }
895
+ var hasConfig = (root) => existsSync3(join4(root, CONFIG_FILE));
896
+
897
+ // src/commands/audit.ts
898
+ var usage = `stack audit [dir]
899
+
900
+ Cross-checks ${CONFIG_FILE} in dir (the current directory) against the compose files it syncs: sync files and build inputs exist, env variables are required or defaulted, versionEnv matches the compose interpolation, restart and post-deploy services exist, healthchecks, routing in overlays, bind mounts documented in the header, Nuxt runtimeConfig keys and .gitignore.
901
+ Needs docker for \`docker compose config\`. Exits 1 on errors, 0 otherwise, 2 when there is no ${CONFIG_FILE}.`;
902
+ var options = {
903
+ json: jsonOption("{ root, composeFiles, findings }")
904
+ };
905
+ async function audit2(args, overrides = {}) {
906
+ const parsed = parse(args, usage, options);
907
+ const root = resolve2(parsed.positionals[0] ?? ".");
908
+ if (!hasConfig(root)) {
909
+ console.error(`no ${CONFIG_FILE} in ${root}`);
910
+ return 2;
911
+ }
912
+ const result = await audit(await loadConfig(root), { root, loadCompose: dockerCompose, env: process6.env, home: homedir(), ...overrides });
913
+ if (parsed.values.json === true)
914
+ printJson(result);
915
+ else
916
+ console.log(render(result));
917
+ return errorsOf(result).length > 0 ? 1 : 0;
918
+ }
919
+
920
+ // src/port.ts
921
+ var MIN_PORT = 1024;
922
+ var MAX_PORT = 65535;
923
+ function stringToPort(name, min = MIN_PORT, max = MAX_PORT) {
924
+ let hash = 2166136261;
925
+ for (let i = 0;i < name.length; i++) {
926
+ hash ^= name.charCodeAt(i);
927
+ hash = hash * 16777619 >>> 0;
928
+ }
929
+ return min + hash % (max - min + 1);
930
+ }
931
+ function isListening(port) {
932
+ try {
933
+ Bun.listen({ hostname: "0.0.0.0", port, socket: { data: () => {
934
+ return;
935
+ } } }).stop(true);
936
+ return false;
937
+ } catch (error) {
938
+ return error.code === "EADDRINUSE";
939
+ }
940
+ }
941
+
942
+ // src/commands/port.ts
943
+ var usage2 = `stack port <name>
944
+
945
+ Prints the port a name always hashes to (FNV-1a, ${MIN_PORT}-${MAX_PORT} by default), so a service keeps the same port on every machine.
946
+ Says on stderr when something already listens on it; the exit code stays 0.`;
947
+ var options2 = {
948
+ min: { type: "string", description: `lowest port (${MIN_PORT})` },
949
+ max: { type: "string", description: `highest port (${MAX_PORT})` }
950
+ };
951
+ async function port(args) {
952
+ const parsed = parse(args, usage2, options2);
953
+ const [name] = parsed.positionals;
954
+ if (name === undefined)
955
+ fail("a name is needed");
956
+ const min = wholeNumber(parsed.values.min, "min", MIN_PORT);
957
+ const max = wholeNumber(parsed.values.max, "max", MAX_PORT, min);
958
+ if (max > MAX_PORT)
959
+ fail(`--max goes up to ${MAX_PORT}, not ${max}`);
960
+ const number = stringToPort(name, min, max);
961
+ console.log(number);
962
+ if (isListening(number))
963
+ console.error(`port ${number} is already in use on this machine`);
964
+ return 0;
965
+ }
966
+
967
+ // src/cli.ts
968
+ process7.exitCode = await runCli({
969
+ name: "stack",
970
+ version,
971
+ about: "a stable port per service name, and a compose release audit",
972
+ commands: {
973
+ port: { run: port, summary: "the port a name always hashes to, with a warning when something already listens on it" },
974
+ audit: { run: audit2, summary: "cross-check release.config.ts against its compose files" }
975
+ }
976
+ });
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@kaynooo/stack-tools",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "version": "0.1.2",
5
+ "description": "stack: a stable port per service name, and an audit of a compose release setup against its release.config.ts.",
6
+ "author": "Kaynooo <kaynooo@kevyn.fr>",
7
+ "license": "MIT",
8
+ "homepage": "https://git.kevyn.fr/kaynooo/agent-tools/src/branch/main/packages/stack#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://git.kevyn.fr/kaynooo/agent-tools.git",
12
+ "directory": "packages/stack"
13
+ },
14
+ "bugs": "https://git.kevyn.fr/kaynooo/agent-tools/issues",
15
+ "keywords": ["docker", "compose", "port", "release", "cli", "bun"],
16
+ "bin": {
17
+ "stack": "./dist/cli.js"
18
+ },
19
+ "files": ["dist"],
20
+ "engines": {
21
+ "bun": ">=1.4.3"
22
+ },
23
+ "publishConfig": {
24
+ "registry": "https://git.kevyn.fr/api/packages/kaynooo/npm/"
25
+ },
26
+ "scripts": {
27
+ "build": "$npm_execpath build src/cli.ts --target bun --outdir dist",
28
+ "stack": "$npm_execpath src/cli.ts"
29
+ },
30
+ "devDependencies": {
31
+ "@kaynooo/cli-kit": "workspace:*"
32
+ }
33
+ }