shiplane 0.0.0 → 0.1.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.
@@ -0,0 +1,2921 @@
1
+ import { a as releaseFlow, i as backendService, n as publishedPackage, r as mobileApp, t as webApp } from "./web-app.module-Bw-npC4Z.js";
2
+ import { C as changelogSection, D as tagName, E as releaseTags, O as expandPatterns, S as cameWithRelease, a as deployRunTitle, c as shipsFrom, d as changesetApps, f as packageBumps, h as unreleasedChangesets, i as minutesBudget, k as workspacePatterns, l as webShip, m as unreleasedApps, p as splitChangesets, r as deployEstimate, s as onlyVersionFiles, u as appBumps, v as CommandFailed, w as firstRelease, x as DEFAULT_TAG_FORMAT, y as releaseSource } from "./budget-C8_aayQk.js";
3
+ import { z } from "zod";
4
+ import { styleText } from "node:util";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { Document, LineCounter, isMap, isScalar, isSeq, parseDocument } from "yaml";
8
+ import { fileURLToPath } from "node:url";
9
+ import { createJiti } from "jiti";
10
+ import { execFile, spawn } from "node:child_process";
11
+ //#region src/adapters/files/node-files.adapter.ts
12
+ /** The repository on disk, under `root`. */
13
+ const nodeFiles = (root) => {
14
+ const at = (file) => path.join(root, file);
15
+ return {
16
+ exists: (file) => fs.existsSync(at(file)),
17
+ read: (file) => fs.existsSync(at(file)) ? fs.readFileSync(at(file), "utf8") : null,
18
+ write: (file, text) => {
19
+ fs.mkdirSync(path.dirname(at(file)), { recursive: true });
20
+ fs.writeFileSync(at(file), text);
21
+ },
22
+ remove: (file) => fs.rmSync(at(file), { force: true }),
23
+ list: (dir) => fs.existsSync(at(dir)) ? fs.readdirSync(at(dir)) : []
24
+ };
25
+ };
26
+ //#endregion
27
+ //#region src/modules/suggest.ts
28
+ const SUGGESTED = {
29
+ "server-hosting": {
30
+ kind: "backend-service",
31
+ factory: "backendService",
32
+ port: "serverHosting"
33
+ },
34
+ "static-hosting": {
35
+ kind: "web-app",
36
+ factory: "webApp",
37
+ port: "staticHosting"
38
+ },
39
+ "mobile-distribution": {
40
+ kind: "mobile-app",
41
+ factory: "mobileApp",
42
+ port: "mobileDistribution"
43
+ },
44
+ "package-registry": {
45
+ kind: "published-package",
46
+ factory: "publishedPackage",
47
+ port: "packageRegistry"
48
+ }
49
+ };
50
+ const suggestedModule = (adapter) => SUGGESTED[adapter.capability];
51
+ /** The module a provider makes under a name, as `init` composes it before the config exists. */
52
+ const moduleFor = (adapter, name) => {
53
+ switch (adapter.capability) {
54
+ case "server-hosting": return backendService({
55
+ name,
56
+ serverHosting: adapter
57
+ });
58
+ case "static-hosting": return webApp({
59
+ name,
60
+ staticHosting: adapter
61
+ });
62
+ case "mobile-distribution": return mobileApp({
63
+ name,
64
+ mobileDistribution: adapter
65
+ });
66
+ case "package-registry": return publishedPackage({
67
+ name,
68
+ packageRegistry: adapter
69
+ });
70
+ }
71
+ };
72
+ //#endregion
73
+ //#region src/application/config/problem.ts
74
+ const distance = (left, right) => {
75
+ const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
76
+ for (let row = 1; row <= left.length; row += 1) {
77
+ let diagonal = previous[0] ?? 0;
78
+ previous[0] = row;
79
+ for (let column = 1; column <= right.length; column += 1) {
80
+ const above = previous[column] ?? 0;
81
+ const cost = left[row - 1] === right[column - 1] ? 0 : 1;
82
+ previous[column] = Math.min(above + 1, (previous[column - 1] ?? 0) + 1, diagonal + cost);
83
+ diagonal = above;
84
+ }
85
+ }
86
+ return previous[right.length] ?? 0;
87
+ };
88
+ /** The candidate a typo most likely meant, when one is close enough to be worth naming. */
89
+ const didYouMean = (word, candidates) => {
90
+ const [best] = candidates.map((candidate) => ({
91
+ candidate,
92
+ cost: distance(word.toLowerCase(), candidate.toLowerCase())
93
+ })).sort((left, right) => left.cost - right.cost);
94
+ return best && best.cost <= Math.max(2, Math.floor(word.length / 3)) ? `did you mean "${best.candidate}"?` : void 0;
95
+ };
96
+ /** Top to bottom per file, problems without a line last. */
97
+ const sortProblems = (problems) => [...problems].sort((left, right) => left.file.localeCompare(right.file) || (left.line ?? Number.MAX_SAFE_INTEGER) - (right.line ?? Number.MAX_SAFE_INTEGER));
98
+ //#endregion
99
+ //#region src/application/config/unitSchema.ts
100
+ const definition = (schema) => schema.def;
101
+ const mapShape = (shape, map) => Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, map(value)]));
102
+ /**
103
+ * The same schema, refusing unknown keys at every depth. Read through `def.type` rather than
104
+ * `instanceof`: a config loads its own copy of zod.
105
+ */
106
+ const deepStrict = (schema) => {
107
+ const def = definition(schema);
108
+ const strict = () => {
109
+ switch (def.type) {
110
+ case "object": return z.strictObject(mapShape(def.shape ?? {}, deepStrict));
111
+ case "optional": return def.innerType ? deepStrict(def.innerType).optional() : schema;
112
+ case "nullable": return def.innerType ? deepStrict(def.innerType).nullable() : schema;
113
+ case "default": return def.innerType ? deepStrict(def.innerType).default(def.defaultValue) : schema;
114
+ case "union": return z.union((def.options ?? []).map(deepStrict));
115
+ case "record": return def.keyType && def.valueType ? z.record(def.keyType, deepStrict(def.valueType)) : schema;
116
+ case "array": return def.element ? z.array(deepStrict(def.element)) : schema;
117
+ default: return schema;
118
+ }
119
+ };
120
+ const result = strict();
121
+ const { description } = schema;
122
+ return description && result !== schema ? result.describe(description) : result;
123
+ };
124
+ /** The keys an object schema allows at a path, best effort, for "did you mean". */
125
+ const keysAt = (schema, at) => {
126
+ const def = definition(schema);
127
+ if (def.type === "optional" || def.type === "nullable" || def.type === "default") return def.innerType ? keysAt(def.innerType, at) : [];
128
+ if (def.type === "union") return (def.options ?? []).flatMap((option) => keysAt(option, at));
129
+ if (def.type === "record" && at.length > 0 && def.valueType) return keysAt(def.valueType, at.slice(1));
130
+ if (def.type !== "object") return [];
131
+ const [first, ...rest] = at;
132
+ if (first === void 0) return Object.keys(def.shape ?? {});
133
+ const child = def.shape?.[String(first)];
134
+ return child ? keysAt(child, rest) : [];
135
+ };
136
+ /** What a unit file naming this module may hold: `module`, then its adapter's settings. */
137
+ const unitSchema = (module) => z.strictObject({
138
+ module: z.literal(module.name).describe(`The module that ships this app, with ${module.provider}`),
139
+ ...mapShape(module.settings.shape, deepStrict)
140
+ });
141
+ /** The JSON Schema editors read for `shiplane.unit.yml`: the module an app names picks its keys. */
142
+ const unitJsonSchema = (modules) => z.toJSONSchema(z.union(modules.map(unitSchema)), {
143
+ io: "input",
144
+ unrepresentable: "any"
145
+ });
146
+ //#endregion
147
+ //#region src/domain/environment.ts
148
+ /** Where a unit runs, in promotion order: production ships what preview validated. */
149
+ const ENVIRONMENTS = ["preview", "production"];
150
+ //#endregion
151
+ //#region src/application/config/values.ts
152
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
153
+ /** A map keyed by exactly the environments: one of its values is picked per environment. */
154
+ const isPerEnvValue = (value) => isRecord(value) && Object.keys(value).length === ENVIRONMENTS.length && ENVIRONMENTS.every((environment) => environment in value);
155
+ /** `${units.<name>.<key>}`, where key may be dotted. */
156
+ const REFERENCE = /\$\{units\.([\w-]+)\.([\w.-]+)\}/g;
157
+ const referencesIn = (value, at = []) => {
158
+ if (typeof value === "string") return [...value.matchAll(REFERENCE)].map(([, unit = "", key = ""]) => ({
159
+ unit,
160
+ key,
161
+ at
162
+ }));
163
+ if (Array.isArray(value)) return value.flatMap((item, index) => referencesIn(item, [...at, String(index)]));
164
+ if (isRecord(value)) return Object.entries(value).flatMap(([key, item]) => referencesIn(item, [...at, key]));
165
+ return [];
166
+ };
167
+ const valueAt = (value, at) => at.reduce((current, key) => isRecord(current) ? current[key] : void 0, value);
168
+ //#endregion
169
+ //#region src/application/config/readUnitFile.ts
170
+ const UNIT_FILE = "shiplane.unit.yml";
171
+ const UNIT_FILES = [UNIT_FILE, "release.unit.yml"];
172
+ const locate = (doc, counter) => (at, key) => {
173
+ let node = doc.contents;
174
+ for (const segment of at) {
175
+ if (!isMap(node) && !isSeq(node)) return void 0;
176
+ node = node.get(segment, true);
177
+ }
178
+ if (key !== void 0 && isMap(node)) node = node.items.find((pair) => isScalar(pair.key) && pair.key.value === key)?.key;
179
+ const offset = node?.range?.[0];
180
+ return offset === void 0 ? void 0 : counter.linePos(offset).line;
181
+ };
182
+ const describeIssue = (issue, file, module, lineAt) => {
183
+ const at = issue.path;
184
+ if (issue.code === "unrecognized_keys") return issue.keys.map((key) => ({
185
+ file,
186
+ line: lineAt(at, key),
187
+ message: `unknown key "${[...at, key].join(".")}" for ${module.name}`,
188
+ hint: didYouMean(key, keysAt(module.settings, at))
189
+ }));
190
+ const name = at.join(".");
191
+ if (issue.code === "invalid_type" && issue.message.endsWith("received undefined")) return [{
192
+ file,
193
+ line: at.length > 1 ? lineAt(at.slice(0, -1)) : void 0,
194
+ message: `"${name}" is required`
195
+ }];
196
+ return [{
197
+ file,
198
+ line: lineAt(at),
199
+ message: `"${name}": ${issue.message}`
200
+ }];
201
+ };
202
+ const problem = (file, line, message, hint) => ({ problems: [{
203
+ file,
204
+ line,
205
+ message,
206
+ hint
207
+ }] });
208
+ /** A unit file checked against the adapter of the module it names, every problem with its line. */
209
+ const readUnitFile = (file, text, modules, features = []) => {
210
+ const counter = new LineCounter();
211
+ const doc = parseDocument(text, {
212
+ lineCounter: counter,
213
+ uniqueKeys: true,
214
+ prettyErrors: false
215
+ });
216
+ if (doc.errors.length > 0) return { problems: doc.errors.map((error) => ({
217
+ file,
218
+ line: counter.linePos(error.pos[0]).line,
219
+ message: error.message.split("\n")[0] ?? error.message
220
+ })) };
221
+ const lineAt = locate(doc, counter);
222
+ const data = doc.toJS();
223
+ const names = modules.map(({ name }) => name);
224
+ const oneOf = `one of: ${names.join(", ")}`;
225
+ if (isRecord(data) && "target" in data && !("module" in data)) return problem(file, lineAt(["target"]), "target: is now module: the module in shiplane.config.ts that ships this app", oneOf);
226
+ if (!isRecord(data) || typeof data.module !== "string") return problem(file, 1, "a unit file starts with module: the module that ships it", oneOf);
227
+ const named = data.module;
228
+ const module = modules.find(({ name }) => name === named);
229
+ if (features.includes(named)) return problem(file, lineAt(["module"]), `"${named}" ships no app: it runs on every ship`, oneOf);
230
+ if (!module) return problem(file, lineAt(["module"]), `no module named "${named}" in shiplane.config.ts`, didYouMean(named, names) ?? oneOf);
231
+ const parsed = unitSchema(module).safeParse(data);
232
+ if (!parsed.success) return { problems: parsed.error.issues.flatMap((issue) => describeIssue(issue, file, module, lineAt)) };
233
+ return {
234
+ unit: {
235
+ module: named,
236
+ options: Object.fromEntries(Object.entries(data).filter(([key]) => key !== "module")),
237
+ lineOf: (at) => lineAt(at)
238
+ },
239
+ problems: []
240
+ };
241
+ };
242
+ //#endregion
243
+ //#region src/application/releaseOrder.ts
244
+ /** `admin (reads api.url)`: an app, with the values of other apps it reads. */
245
+ const withReads = ({ name, options }) => {
246
+ const reads = [...new Set(referencesIn(options).filter(({ unit }) => unit !== name).map(({ unit, key }) => `${unit}.${key}`))];
247
+ return reads.length > 0 ? `${name} (reads ${reads.join(", ")})` : name;
248
+ };
249
+ /** `1 expo · Latest → 2 api → 3 admin (reads api.url)`: the apps numbered in release order. */
250
+ const releaseOrder = (units) => units.map((unit, index) => `${index + 1} ${withReads(unit)}${index === 0 ? " · Latest" : ""}`).join(" → ");
251
+ //#endregion
252
+ //#region src/application/say.ts
253
+ const paint = (style, text) => styleText(style, text);
254
+ /** A failure, said with what to run next; the caller returns false so nothing else runs. */
255
+ const fail = ({ output, progress }, title, detail, commands = []) => {
256
+ progress.say("worried", `${paint(["bold", "red"], `✗ ${title}:`)} ${detail}`);
257
+ commands.forEach((command) => output.line(` ${paint("cyan", command)}`));
258
+ };
259
+ /** Yes without asking under --yes; without a terminal, no. */
260
+ const confirm = async ({ prompter, options, output }, question, initial = false) => {
261
+ if (options.yes) return true;
262
+ if (!prompter.interactive) {
263
+ output.line(paint("yellow", "Not a terminal: pass --yes to run it."));
264
+ return false;
265
+ }
266
+ return prompter.confirm(question, initial);
267
+ };
268
+ /** `api`, `api and admin`, `api, admin and landing`. */
269
+ const listed = (names) => names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.slice(-1).join("")}`;
270
+ //#endregion
271
+ //#region src/domain/codeScope.ts
272
+ const NOT_SHIPPED = [
273
+ /(^|\/)(shiplane|release)\.unit\.yml$/,
274
+ /^\.changeset\//,
275
+ /^\.planning\//,
276
+ /^\.github\//,
277
+ /^\.claude\//,
278
+ /^docs\//,
279
+ /\.md$/
280
+ ];
281
+ /** A package's folder and the folders of every workspace package it uses, however deep. */
282
+ const codeFolders = (packageName, dependencies, folders) => {
283
+ const seen = new Set([packageName]);
284
+ const queue = [packageName];
285
+ for (const name of queue) for (const dependency of dependencies[name] ?? []) {
286
+ if (seen.has(dependency)) continue;
287
+ seen.add(dependency);
288
+ queue.push(dependency);
289
+ }
290
+ return [...seen].flatMap((name) => folders[name] ?? []);
291
+ };
292
+ /**
293
+ * The changed files that can reach what a unit ships: in its own code folders, or at the root
294
+ * outside every workspace folder, such as the lockfile. Another app's folder never does.
295
+ */
296
+ const changesReaching = (files, scope) => files.filter((file) => {
297
+ if (scope.versionFiles.has(file) || NOT_SHIPPED.some((pattern) => pattern.test(file))) return false;
298
+ const inside = (folder) => file.startsWith(`${folder}/`);
299
+ return scope.own.some(inside) || !scope.workspace.some(inside);
300
+ });
301
+ //#endregion
302
+ //#region src/application/config/optionsFor.ts
303
+ const resolve = (value, env, units) => {
304
+ const picked = isPerEnvValue(value) ? value[env] : value;
305
+ if (typeof picked === "string") return picked.replace(REFERENCE, (_match, name, key) => {
306
+ const other = units.find((unit) => unit.name === name);
307
+ const resolved = other ? resolve(valueAt(other.options, key.split(".")), env, units) : "";
308
+ return typeof resolved === "string" ? resolved : "";
309
+ });
310
+ if (Array.isArray(picked)) return picked.map((item) => resolve(item, env, units));
311
+ if (isRecord(picked)) return Object.fromEntries(Object.entries(picked).map(([key, item]) => [key, resolve(item, env, units)]));
312
+ return picked;
313
+ };
314
+ /** A unit's options for one environment: per-environment values picked, references filled in. */
315
+ const optionsFor = (unit, env, units) => {
316
+ const resolved = resolve(unit.options, env, units);
317
+ return isRecord(resolved) ? resolved : {};
318
+ };
319
+ //#endregion
320
+ //#region src/application/targets.ts
321
+ /** The module that ships an app: the one its unit file names. */
322
+ const moduleOf = ({ release }, unit) => release.modules.find(({ name }) => name === unit.module);
323
+ /** An app's settings for an environment, its module's defaults applied first. */
324
+ const resolvedOptions = (module, unit, environment, units) => {
325
+ const withDefaults = module.settings.parse(unit.options);
326
+ return optionsFor({
327
+ ...unit,
328
+ options: withDefaults
329
+ }, environment, units);
330
+ };
331
+ /** What a module's stages are told about one app's tag. */
332
+ const jobInput = (context, module, unit, { tag, environment, commit }) => ({
333
+ unit,
334
+ tag,
335
+ environment,
336
+ commit,
337
+ options: resolvedOptions(module, unit, environment, context.release.units)
338
+ });
339
+ /** Where a tag lands and the jobs that ship it, as its module says. */
340
+ const shipPlanOf = (context, module, input) => module.ship(decideContext(context), input);
341
+ /** Every file a release may move after a tag without changing what ships. */
342
+ const versionFiles = (context) => new Set(context.release.units.flatMap((unit) => moduleOf(context, unit)?.versionFiles?.(unit, context.release.units, context.open) ?? []));
343
+ /** A command as a person would type it, variables first, secrets by name only. */
344
+ const commandLine = ({ command, args, env, secrets }) => [
345
+ ...Object.entries(env ?? {}).map(([key, value]) => `${key}=${value}`),
346
+ command,
347
+ ...args,
348
+ ...(secrets ?? []).flatMap(({ flag, name }) => [flag, `${name}=$${name}`])
349
+ ].join(" ");
350
+ /** Runs a job's commands here in order, then records the deploy. Throws on the first failure. */
351
+ const runHere = async ({ shell, services, release, output }, job, { tag, environment }) => {
352
+ const secretArgs = (step) => (step.secrets ?? []).flatMap(({ flag, name }) => {
353
+ const value = shell.env(name);
354
+ if (value) return [flag, `${name}=${value}`];
355
+ output.line(` ! ${name} is not set: ${flag} left out`);
356
+ return [];
357
+ });
358
+ const run = (step) => shell.attach(step.command, [...step.args, ...secretArgs(step)], {
359
+ cwd: path.join(release.root, step.cwd ?? ""),
360
+ env: step.env
361
+ });
362
+ try {
363
+ for (const step of job.local) {
364
+ const status = await run(step);
365
+ if (status !== 0) throw new Error(`${step.command} exited with ${status}`);
366
+ }
367
+ } finally {
368
+ for (const step of job.cleanup ?? []) await run(step);
369
+ }
370
+ if (job.record) await services.codeHost.recordDeployment(tag, environment);
371
+ };
372
+ /** Dispatches the ship workflow on a ref for its units and returns at once: the runner ships them. */
373
+ const dispatchShip = async ({ services }, { ref, units }, environment) => services.ciPipeline.dispatch(services.ciPipeline.shipWorkflow, ref, {
374
+ units: units.join(" "),
375
+ environment
376
+ });
377
+ /** Which changed files can reach what a unit ships. */
378
+ const reaching = async (context, unit) => {
379
+ const { versioning } = context.services;
380
+ const [dependencies, folders] = await Promise.all([versioning.dependencies(), versioning.folders()]);
381
+ const scope = {
382
+ own: [unit.dir, ...codeFolders(unit.packageName, dependencies, folders)],
383
+ workspace: Object.values(folders),
384
+ versionFiles: versionFiles(context)
385
+ };
386
+ return (files) => changesReaching(files, scope);
387
+ };
388
+ /** What a module's per-app stages may read and run. */
389
+ const decideContext = (context) => ({
390
+ root: context.release.root,
391
+ shell: context.shell,
392
+ sourceControl: context.services.sourceControl,
393
+ codeHost: context.services.codeHost,
394
+ ciPipeline: context.services.ciPipeline,
395
+ units: context.release.units,
396
+ tagFormat: context.release.tagFormat,
397
+ versionFiles: versionFiles(context),
398
+ now: () => context.clock.now(),
399
+ open: context.open,
400
+ changedCode: async (unit, from, to) => {
401
+ const [files, filter] = await Promise.all([context.services.sourceControl.diffNames(from, to), reaching(context, unit)]);
402
+ return filter(files);
403
+ }
404
+ });
405
+ /** What a module may read once apps ship. */
406
+ const afterShipContext = (context) => ({
407
+ open: context.open,
408
+ tagFormat: context.release.tagFormat,
409
+ subjectsReaching: async (unit, from, to) => {
410
+ const [commits, filter] = await Promise.all([context.services.sourceControl.commitsBetween(from, to), reaching(context, unit)]);
411
+ return commits.filter(({ files }) => filter(files).length > 0).map(({ subject }) => subject);
412
+ }
413
+ });
414
+ /**
415
+ * What the person reads for an environment: a package registry has no staging, so when every unit
416
+ * is a published package, preview is where users install it — it reads "live".
417
+ */
418
+ const environmentLabel = (context, units, environment) => {
419
+ if (environment !== "preview") return environment;
420
+ const names = [...units];
421
+ return names.length > 0 && names.every((name) => {
422
+ const unit = context.release.units.find((candidate) => candidate.name === name);
423
+ return unit !== void 0 && moduleOf(context, unit)?.kind === "published-package";
424
+ }) ? "live" : environment;
425
+ };
426
+ //#endregion
427
+ //#region src/application/requirements.ts
428
+ /**
429
+ * Every tool and sign-in the flow, the features and the modules need, once each. With `apps`, only
430
+ * the modules shipping one of those apps count.
431
+ */
432
+ const requirementsOf = (release, apps) => {
433
+ const appsOf = (name) => release.units.filter(({ module, name: app }) => module === name && (!apps || apps.has(app)));
434
+ const required = [
435
+ ...[
436
+ release.flow.sourceControl,
437
+ release.flow.codeHost,
438
+ release.flow.ciPipeline,
439
+ release.flow.versioning
440
+ ].flatMap((adapter) => adapter.requirements?.() ?? []),
441
+ ...release.modules.flatMap((module) => {
442
+ const shipped = appsOf(module.name);
443
+ return apps && shipped.length === 0 ? [] : module.requirements?.(shipped) ?? [];
444
+ }),
445
+ ...release.features.flatMap((feature) => feature.requirements?.() ?? [])
446
+ ];
447
+ return required.filter((requirement, index) => required.findIndex(({ label }) => label === requirement.label) === index);
448
+ };
449
+ /** A requirement's check run from the root: its exit status, 127 when the tool is missing. */
450
+ const checkStatus = async (shell, root, { check }) => (await shell.capture(check.command, check.args, {
451
+ cwd: path.join(root, check.cwd ?? ""),
452
+ env: check.env
453
+ })).status;
454
+ /**
455
+ * Before a release writes anything: each sign-in its picked units need. A failing one offers its
456
+ * fix, then is checked again. False, with the commands to run, when one still fails.
457
+ */
458
+ const preflight = async (context, apps) => {
459
+ const { shell, prompter, options, release } = context;
460
+ const failing = [];
461
+ for (const requirement of requirementsOf(release, apps)) {
462
+ const status = await checkStatus(shell, release.root, requirement);
463
+ if (status === 0) continue;
464
+ const { fix } = requirement;
465
+ if ((fix !== void 0 && status !== 127 && prompter.interactive && !options.yes ? await prompter.confirm(`Run ${commandLine(fix)} now?`, true) : false) && fix) {
466
+ await shell.attach(fix.command, fix.args, {
467
+ cwd: path.join(release.root, fix.cwd ?? ""),
468
+ env: fix.env
469
+ });
470
+ if (await checkStatus(shell, release.root, requirement) === 0) continue;
471
+ }
472
+ failing.push(requirement);
473
+ }
474
+ if (failing.length === 0) return true;
475
+ fail(context, `Not signed in: ${failing.map(({ label }) => label).join(", ")}`, "nothing was written. Sign in, then run the release again.", [...failing.flatMap(({ fix }) => fix ? [commandLine(fix)] : []), "shiplane"]);
476
+ return false;
477
+ };
478
+ //#endregion
479
+ //#region src/application/setupFiles.ts
480
+ const CONFIG_FILE = "shiplane.config.ts";
481
+ const SCHEMA_FILE = "node_modules/.cache/shiplane/schema.json";
482
+ const VSCODE_SETTINGS = ".vscode/settings.json";
483
+ /** `cloudflare-pages` → `cloudflarePages`. */
484
+ const factoryName = (name) => name.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
485
+ /** `fly` serving servers → `flyServerHosting`, the factory an official adapter is imported by. */
486
+ const adapterFactory = ({ name, capability }) => `${factoryName(name)}${factoryName(`-${capability}`)}`;
487
+ const moduleCall = ({ factory, port, adapter, name }) => `${factory}({ ${name ? `name: "${name}", ` : ""}${port}: ${adapter}() })`;
488
+ /**
489
+ * The module an app ships with, given what the release already composes: the one holding this
490
+ * provider for that kind, else a new one under the kind's name, or the provider's when that is taken.
491
+ */
492
+ const placeModule = (adapter, modules, pkg = INSTALLED) => {
493
+ const from = adapter.name === "shell" ? pkg : pluginPackage(adapter.name);
494
+ const { kind, factory, port } = suggestedModule(adapter);
495
+ const held = modules.find((module) => module.kind === kind && module.provider === adapter.name);
496
+ if (held) return { name: held.name };
497
+ const taken = modules.some((module) => module.name === kind);
498
+ const name = taken ? `${kind}-${adapter.name}` : kind;
499
+ return {
500
+ name,
501
+ entry: {
502
+ factory,
503
+ port,
504
+ adapter: adapterFactory(adapter),
505
+ from,
506
+ ...taken ? { name } : {}
507
+ }
508
+ };
509
+ };
510
+ /** The name other repositories install the CLI under. */
511
+ const INSTALLED = "shiplane";
512
+ const NAMES$1 = /shiplane/;
513
+ /** Where a plugin is installed from. */
514
+ const pluginPackage = (plugin) => `@shiplane/${plugin}`;
515
+ /** What a written config imports the CLI as. */
516
+ const releasePackage = (files) => {
517
+ const manifest = JSON.parse(files.read("package.json") ?? "{}");
518
+ return "shiplane" in {
519
+ ...manifest.dependencies,
520
+ ...manifest.devDependencies
521
+ } ? "shiplane" : INSTALLED;
522
+ };
523
+ /** The flow init writes: git, GitHub, GitHub Actions and changesets, each from its plugin. */
524
+ const FLOW_PLUGINS = {
525
+ git: ["gitSourceControl"],
526
+ github: ["gitHubActionsCiPipeline", "gitHubCodeHost"],
527
+ changesets: ["changesetsVersioning"]
528
+ };
529
+ const importLine = (names, from) => `import { ${[...new Set(names)].sort().join(", ")} } from "${from}";`;
530
+ /** A root config with today's flow and these modules, in the order given. */
531
+ const renderConfig = (entries, pkg = INSTALLED) => {
532
+ const byPlugin = new Map(Object.entries(FLOW_PLUGINS).map(([plugin, names]) => [pluginPackage(plugin), [...names]]));
533
+ const own = [
534
+ "defineRelease",
535
+ "releaseFlow",
536
+ ...entries.map(({ factory }) => factory)
537
+ ];
538
+ entries.forEach(({ adapter, from }) => {
539
+ if (from === pkg) own.push(adapter);
540
+ else byPlugin.set(from, [...byPlugin.get(from) ?? [], adapter]);
541
+ });
542
+ return [
543
+ importLine(own, pkg),
544
+ ...[...byPlugin].sort(([a], [b]) => a.localeCompare(b)).map(([from, names]) => importLine(names, from)),
545
+ "",
546
+ "export default defineRelease({",
547
+ " flow: releaseFlow({",
548
+ " sourceControl: gitSourceControl(),",
549
+ " codeHost: gitHubCodeHost(),",
550
+ " ciPipeline: gitHubActionsCiPipeline(),",
551
+ " versioning: changesetsVersioning(),",
552
+ " }),",
553
+ " // What gets released, in this order. The first app is the repository's Latest release.",
554
+ " modules: [",
555
+ ...entries.map((entry) => ` ${moduleCall(entry)},`),
556
+ " ],",
557
+ "});",
558
+ ""
559
+ ].join("\n");
560
+ };
561
+ /** The index of the bracket closing the one at `open`, or -1. */
562
+ const closing = (text, open) => {
563
+ let depth = 0;
564
+ for (let index = open; index < text.length; index += 1) {
565
+ if (text[index] === "[") depth += 1;
566
+ if (text[index] === "]") depth -= 1;
567
+ if (depth === 0) return index;
568
+ }
569
+ return -1;
570
+ };
571
+ /** Adds a name to the CLI's import, under whichever name it has, or a new import when there is none. */
572
+ const withNamedImport = (config, name, pkg) => {
573
+ const match = new RegExp(`import \\{([^}]*)\\} from "(${NAMES$1.source})";`).exec(config);
574
+ if (!match) return `import { ${name} } from "${pkg}";\n${config}`;
575
+ const names = match[1]?.split(",").map((part) => part.trim()).filter(Boolean) ?? [];
576
+ if (names.includes(name)) return config;
577
+ const line = `import { ${[...names, name].sort().join(", ")} } from "${match[2] ?? pkg}";`;
578
+ return config.replace(match[0], line);
579
+ };
580
+ /** Adds a module and its imports to an existing config, or null when its shape is not ours. */
581
+ const addToConfig = (config, entry, pkg = INSTALLED) => {
582
+ const start = config.search(/modules:\s*\[/);
583
+ if (start < 0) return null;
584
+ const open = config.indexOf("[", start);
585
+ const close = closing(config, open);
586
+ if (close < 0) return null;
587
+ const call = moduleCall(entry);
588
+ const inner = config.slice(open + 1, close);
589
+ const trimmed = inner.trimEnd();
590
+ const tail = inner.slice(trimmed.length);
591
+ const comma = trimmed === "" || trimmed.endsWith(",") ? "" : ",";
592
+ const added = inner.includes("\n") ? `${trimmed}${comma}\n ${call},${tail}` : `${trimmed}${comma}${trimmed === "" ? "" : " "}${call}${tail}`;
593
+ const withCall = withNamedImport(`${config.slice(0, open + 1)}${added}${config.slice(close)}`, entry.factory, pkg);
594
+ if (entry.from === pkg) return withNamedImport(withCall, entry.adapter, pkg);
595
+ const importLine = `import { ${entry.adapter} } from "${entry.from}";`;
596
+ if (withCall.includes(importLine)) return withCall;
597
+ const last = [...withCall.matchAll(/^import [^;]*;$/gm)].at(-1);
598
+ const at = last?.index === void 0 ? 0 : last.index + last[0].length;
599
+ return `${withCall.slice(0, at)}${at === 0 ? "" : "\n"}${importLine}${at === 0 ? "\n" : ""}${withCall.slice(at)}`;
600
+ };
601
+ /** A unit file naming its module, with the settings init found, and where it found them. */
602
+ const renderUnit = (module, options, { reason, schemaLine }) => {
603
+ const doc = new Document({
604
+ module,
605
+ ...options
606
+ });
607
+ doc.commentBefore = [
608
+ ...schemaLine ? [` yaml-language-server: $schema=${schemaLine}`] : [],
609
+ ` Written by shiplane init. Every key: shiplane docs ${module}`,
610
+ ...reason ? [` Read from ${reason}`] : []
611
+ ].join("\n");
612
+ return doc.toString();
613
+ };
614
+ /** A schema's keys as dotted paths: a nested object lists each of its own keys, not itself. */
615
+ const flatten = (properties, required, prefix = "") => Object.entries(properties).flatMap(([name, property]) => property.properties ? flatten(property.properties, property.required ?? [], `${prefix}${name}.`) : [{
616
+ key: `${prefix}${name}`,
617
+ description: property.description ?? "",
618
+ default: property.default,
619
+ required: required.includes(name)
620
+ }]);
621
+ /** Every key a unit file takes, nested ones as `build.command`, for `shiplane docs`. */
622
+ const documentedKeys = (settings) => {
623
+ const schema = z.toJSONSchema(settings, {
624
+ io: "input",
625
+ unrepresentable: "any"
626
+ });
627
+ return flatten(schema.properties ?? {}, schema.required ?? []);
628
+ };
629
+ /** Each key a schema takes, with its description and default, from its JSON Schema. */
630
+ const settingsKeys = (settings) => {
631
+ const schema = z.toJSONSchema(settings, {
632
+ io: "input",
633
+ unrepresentable: "any"
634
+ });
635
+ return Object.entries(schema.properties ?? {}).map(([key, property]) => ({
636
+ key,
637
+ description: property.description ?? "",
638
+ default: property.default,
639
+ required: schema.required?.includes(key) ?? false
640
+ }));
641
+ };
642
+ /** A unit file with only its module set and every other key commented, described. */
643
+ const renderBlankUnit = (module, settings, schemaLine) => [
644
+ ...schemaLine ? [`# yaml-language-server: $schema=${schemaLine}`] : [],
645
+ `# Written by shiplane init --blank. Uncomment and fill what applies.`,
646
+ `module: ${module}`,
647
+ ...settingsKeys(settings).flatMap(({ key, description, default: fallback, required }) => [
648
+ "",
649
+ `# ${description}${required ? " (required)" : ""}`,
650
+ `# ${key}:${fallback === void 0 ? "" : ` ${JSON.stringify(fallback)}`}`
651
+ ]),
652
+ ""
653
+ ].join("\n");
654
+ /** The schema a unit file's editor reads, relative to that unit file. */
655
+ const schemaLineFor = (dir) => path.posix.relative(dir, "node_modules/.cache/shiplane/schema.json") || "node_modules/.cache/shiplane/schema.json";
656
+ /** The JSON Schema for every unit file: the module an app names picks the keys it takes. */
657
+ const schemaText = (modules) => `${JSON.stringify(unitJsonSchema(modules), null, 2)}\n`;
658
+ /**
659
+ * Writes the editor schema when it no longer matches the composed modules. It is generated, never
660
+ * committed: every command keeps it current. True when it wrote.
661
+ */
662
+ const refreshEditorSchema = (files, release) => {
663
+ const text = schemaText(release.modules);
664
+ if (files.read("node_modules/.cache/shiplane/schema.json") === text) return false;
665
+ files.write(SCHEMA_FILE, text);
666
+ return true;
667
+ };
668
+ /** Maps every unit file to the schema once, keeping a settings file's comments as they are. */
669
+ const withEditorSchema = (settings) => {
670
+ const entry = `"yaml.schemas": { "./${SCHEMA_FILE}": "**/${UNIT_FILE}" }`;
671
+ if (settings === null) return `{\n ${entry}\n}\n`;
672
+ if (settings.includes("\"yaml.schemas\"")) return null;
673
+ const open = settings.indexOf("{");
674
+ if (open < 0) return null;
675
+ return `${settings.slice(0, open + 1)}\n ${entry},${settings.slice(open + 1)}`;
676
+ };
677
+ const editorSettingsFile = VSCODE_SETTINGS;
678
+ /** A folder as adapters see it when recognising what ships from it. */
679
+ const folderView = (files, dir) => ({
680
+ dir,
681
+ name: path.posix.basename(dir),
682
+ files: files.list(dir),
683
+ has: (file) => files.exists(path.posix.join(dir, file)),
684
+ read: (file) => files.read(path.posix.join(dir, file))
685
+ });
686
+ /** The repository's short name: its package name without scope, else its folder's. */
687
+ const repositoryName = (files, root) => {
688
+ const parsed = z.object({ name: z.string() }).safeParse(JSON.parse(files.read("package.json") ?? "{}"));
689
+ return parsed.success ? parsed.data.name.replace(/^@[^/]+\//, "") : path.basename(root);
690
+ };
691
+ //#endregion
692
+ //#region src/application/doctor.ts
693
+ /**
694
+ * `shiplane doctor`: the config as written, the editor schema refreshed, the release order, a warning
695
+ * for each module no app names, then every tool and sign-in the flow, modules and features need, each
696
+ * failure with the command that fixes it, offered to run.
697
+ */
698
+ const doctor = async (context) => {
699
+ const { output, files, shell, prompter, root } = context;
700
+ output.line();
701
+ output.line(`${paint("cyan", "◆")} ${paint("bold", "shiplane doctor")}`);
702
+ const release = await context.load();
703
+ if (release.problems.length > 0) {
704
+ release.problems.forEach(({ file, line, message, hint }) => {
705
+ output.line(`${paint("red", "✗")} ${paint("bold", line === void 0 ? file : `${file}:${line}`)} ${message}`);
706
+ if (hint) output.line(` ${paint("dim", hint)}`);
707
+ });
708
+ return false;
709
+ }
710
+ refreshEditorSchema(files, release);
711
+ const appsOf = (name) => release.units.filter(({ module }) => module === name);
712
+ if (release.units.length > 0) output.line(`${paint("dim", "│")} Order ${paint("dim", releaseOrder(release.units))}`);
713
+ release.modules.filter((module) => appsOf(module.name).length === 0).forEach(({ name }) => output.line(`${paint("dim", "│")} ${paint("yellow", "!")} ${name} ${paint("dim", `no app names it: module: ${name} in a ${UNIT_FILE}`)}`));
714
+ (release.renames ?? []).forEach(({ from, to }) => output.line(`${paint("dim", "│")} ${paint("yellow", "!")} ${paint("dim", `rename ${from} to ${to}: the old name still works for now`)}`));
715
+ const unique = requirementsOf(release);
716
+ const failing = [];
717
+ const missing = /* @__PURE__ */ new Set();
718
+ for (const requirement of unique) {
719
+ const { check } = requirement;
720
+ const status = await checkStatus(shell, root, requirement);
721
+ if (status === 0) output.line(`${paint("dim", "│")} ${paint("green", "✓")} ${requirement.label}`);
722
+ else {
723
+ failing.push(requirement);
724
+ if (status === 127) missing.add(check.command);
725
+ const fix = status === 127 ? `not installed: ${check.command}` : requirement.fix ? `fix: ${commandLine(requirement.fix)}` : "not available here";
726
+ output.line(`${paint("dim", "│")} ${paint("red", "✗")} ${requirement.label} ${paint("dim", fix)}`);
727
+ }
728
+ }
729
+ for (const { fix } of failing) {
730
+ if (!fix || !prompter.interactive || missing.has(fix.command)) continue;
731
+ if (await prompter.confirm(`Run ${commandLine(fix)} now?`)) await shell.attach(fix.command, fix.args, {
732
+ cwd: path.join(root, fix.cwd ?? ""),
733
+ env: fix.env
734
+ });
735
+ }
736
+ output.line(`${paint("dim", "└")} Next: ${paint("cyan", failing.length > 0 ? "shiplane doctor" : "shiplane status")}`);
737
+ return failing.length === 0;
738
+ };
739
+ //#endregion
740
+ //#region src/application/initRelease.ts
741
+ const bar = paint("dim", "│");
742
+ /** Sets `key`, dotted, in a nested object. */
743
+ const setAt = (target, key, value) => {
744
+ const [head = "", ...rest] = key.split(".");
745
+ if (rest.length === 0) {
746
+ target[head] = value;
747
+ return;
748
+ }
749
+ const child = isRecord(target[head]) ? target[head] : {};
750
+ target[head] = child;
751
+ setAt(child, rest.join("."), value);
752
+ };
753
+ /** Each workspace folder with a manifest and no unit file yet, with what adapters recognise in it. */
754
+ const scanFolders = (context, adapters) => expandPatterns(context.root, workspacePatterns(context.root)).filter((dir) => dir !== "." && context.files.exists(path.posix.join(dir, "package.json"))).filter((dir) => !UNIT_FILES.some((name) => context.files.exists(path.posix.join(dir, name)))).map((dir) => {
755
+ const folder = folderView(context.files, dir);
756
+ const detections = adapters.flatMap((adapter) => {
757
+ const detection = adapter.detect?.(folder);
758
+ return detection ? [{
759
+ adapter,
760
+ detection
761
+ }] : [];
762
+ });
763
+ return {
764
+ folder,
765
+ guess: [
766
+ "found",
767
+ "likely",
768
+ "possible"
769
+ ].map((certainty) => detections.find(({ detection }) => detection.certainty === certainty)).find(Boolean) ?? null
770
+ };
771
+ });
772
+ /** The options a placed folder needs that its folder did not say, asked or taken as suggested. */
773
+ const askOptions = async (context, folder, adapter, found, yes) => {
774
+ const options = structuredClone(found);
775
+ const repository = repositoryName(context.files, context.root);
776
+ for (const question of adapter.questions?.(folder, options, repository) ?? []) {
777
+ const answer = yes ? question.initial ?? null : await context.prompter.text(`${folder.dir} · ${question.message}`, question.initial);
778
+ if (answer !== null && answer !== "") setAt(options, question.key, answer);
779
+ }
780
+ return options;
781
+ };
782
+ const candidateLine = ({ folder, guess }, width) => {
783
+ const target = guess?.detection.certainty === "found" ? paint("green", guess.adapter.name) : paint("yellow", "?");
784
+ return `${folder.dir.padEnd(width)}${target.padEnd(18)}${paint("dim", guess?.detection.reason ?? "")}`;
785
+ };
786
+ /** Whether the person writes, after seeing the list, the diff if asked. */
787
+ const review = async (context, writes, yes) => {
788
+ const { output, prompter } = context;
789
+ output.line(`${paint("cyan", "◆")} ${paint("bold", "Write these files?")}`);
790
+ writes.forEach(({ file, created }) => output.line(`${bar} ${created ? paint("green", "+") : paint("yellow", "~")} ${file}`));
791
+ if (yes) return true;
792
+ for (;;) {
793
+ const answer = await prompter.select("Write these files?", [
794
+ {
795
+ value: "write",
796
+ label: "Write"
797
+ },
798
+ {
799
+ value: "diff",
800
+ label: "Show the files"
801
+ },
802
+ {
803
+ value: "cancel",
804
+ label: "Cancel, write nothing"
805
+ }
806
+ ], "write");
807
+ if (answer !== "diff") return answer === "write";
808
+ writes.forEach(({ file, text }) => {
809
+ output.line();
810
+ output.line(paint("bold", file));
811
+ text.split("\n").forEach((line) => output.line(` ${line}`));
812
+ });
813
+ }
814
+ };
815
+ /**
816
+ * `shiplane init`: finds every workspace folder, guesses how each ships from what it holds, asks only
817
+ * what it cannot tell, shows every file, writes them, then runs doctor. Run again, it offers the
818
+ * folders added since and never rewrites a unit file. `--yes` takes every guess, `--blank` writes
819
+ * commented templates.
820
+ */
821
+ const initRelease = async (context, { yes, blank }) => {
822
+ const { output, prompter, files } = context;
823
+ const existing = files.exists("shiplane.config.ts") ? await context.load() : null;
824
+ const adapters = context.adapters;
825
+ const candidates = scanFolders(context, adapters);
826
+ output.line(`${paint("dim", "┌")} ${paint("bold", "shiplane init")}`);
827
+ output.line(bar);
828
+ output.line(`${paint("green", "◇")} Workspace ${paint("dim", workspacePatterns(context.root).join(", "))}`);
829
+ output.line(bar);
830
+ if (existing) {
831
+ output.line(`${paint("cyan", "◆")} ${paint("bold", "Since the last init")}`);
832
+ candidates.filter(({ guess }) => guess).forEach(({ folder, guess }) => output.line(`${bar} ${paint("green", "+")} ${folder.dir.padEnd(14)}${paint("dim", `new folder, ${guess?.detection.reason ?? ""}`)}`));
833
+ output.line(`${bar} ${paint("dim", "=")} ${`${existing.units.length} folders`.padEnd(14)}${paint("dim", "unchanged, your edits kept")}`);
834
+ output.line(bar);
835
+ }
836
+ const placeable = candidates.filter(({ guess }) => guess !== null);
837
+ const width = Math.max(14, ...placeable.map(({ folder }) => folder.dir.length)) + 2;
838
+ placeable.forEach((candidate) => output.line(`${bar} ${candidateLine(candidate, width)}`));
839
+ const unplaced = candidates.length - placeable.length;
840
+ if (unplaced > 0) {
841
+ const folders = `${unplaced} folder${unplaced === 1 ? "" : "s"}`;
842
+ output.line(`${bar} ${paint("dim", `◻ ${folders} with nothing to ship them, versioned only (shiplane add <folder> ships one)`)}`);
843
+ }
844
+ output.line(bar);
845
+ const offered = placeable;
846
+ const pickedDirs = yes ? offered.map(({ folder }) => folder.dir) : await prompter.multiselect("Which folders ship somewhere?", offered.map(({ folder, guess }) => ({
847
+ value: folder.dir,
848
+ label: folder.dir,
849
+ hint: guess ? `${guess.adapter.name} · ${guess.detection.reason}` : ""
850
+ })), offered.map(({ folder }) => folder.dir));
851
+ if (pickedDirs === null) {
852
+ output.line(paint("dim", "Nothing written."));
853
+ return true;
854
+ }
855
+ const placed = [];
856
+ for (const candidate of candidates.filter(({ folder }) => pickedDirs.includes(folder.dir))) {
857
+ const { folder, guess } = candidate;
858
+ const name = guess?.detection.certainty === "found" || yes ? guess?.adapter.name ?? "skip" : await prompter.select(`How does ${folder.dir} ship?`, [...adapters.map((adapter) => ({
859
+ value: adapter.name,
860
+ label: adapter.name,
861
+ hint: adapter.name === guess?.adapter.name ? `${guess.detection.reason} (recommended)` : ""
862
+ })), {
863
+ value: "skip",
864
+ label: "skip",
865
+ hint: "versioned, never shipped"
866
+ }], guess?.adapter.name);
867
+ const adapter = adapters.find((candidateAdapter) => candidateAdapter.name === name);
868
+ if (!adapter) continue;
869
+ const found = guess?.adapter === adapter ? guess.detection.options : {};
870
+ const options = blank ? {} : await askOptions(context, folder, adapter, found, yes);
871
+ placed.push({
872
+ folder,
873
+ adapter,
874
+ options,
875
+ reason: guess?.adapter === adapter ? guess.detection.reason : void 0
876
+ });
877
+ }
878
+ const extras = [...files.exists(".vscode") ? [{
879
+ value: "editor",
880
+ label: "editor autocompletion",
881
+ hint: editorSettingsFile
882
+ }] : []];
883
+ const editor = ((yes ? extras.map(({ value }) => value) : extras.length === 0 ? [] : await prompter.multiselect("Also set up", extras, extras.map(({ value }) => value))) ?? []).includes("editor");
884
+ const modules = [...existing?.modules ?? []];
885
+ const entries = [];
886
+ const pkg = releasePackage(files);
887
+ const named = placed.map((entry) => {
888
+ const { name, entry: added } = placeModule(entry.adapter, modules, pkg);
889
+ if (added) {
890
+ entries.push(added);
891
+ modules.push(moduleFor(entry.adapter, name));
892
+ }
893
+ return {
894
+ ...entry,
895
+ module: name
896
+ };
897
+ });
898
+ const writes = [];
899
+ if (!existing) writes.push({
900
+ file: CONFIG_FILE,
901
+ text: renderConfig(entries, pkg),
902
+ created: true
903
+ });
904
+ else {
905
+ let config = files.read("shiplane.config.ts") ?? "";
906
+ for (const entry of entries) config = addToConfig(config, entry, pkg) ?? config;
907
+ if (config !== files.read("shiplane.config.ts")) writes.push({
908
+ file: CONFIG_FILE,
909
+ text: config,
910
+ created: false
911
+ });
912
+ }
913
+ named.forEach(({ folder, adapter, module, options, reason }) => {
914
+ const schemaLine = editor ? void 0 : schemaLineFor(folder.dir);
915
+ writes.push({
916
+ file: path.posix.join(folder.dir, UNIT_FILE),
917
+ text: blank ? renderBlankUnit(module, adapter.settings, schemaLine) : renderUnit(module, options, {
918
+ reason,
919
+ schemaLine
920
+ }),
921
+ created: true
922
+ });
923
+ });
924
+ writes.push({
925
+ file: SCHEMA_FILE,
926
+ text: schemaText(modules),
927
+ created: !files.exists(SCHEMA_FILE)
928
+ });
929
+ if (editor) {
930
+ const current = files.read(editorSettingsFile);
931
+ const settings = withEditorSchema(current);
932
+ if (current?.includes(`./node_modules/.cache/shiplane/schema.json`)) {} else if (settings) writes.push({
933
+ file: editorSettingsFile,
934
+ text: settings,
935
+ created: !files.exists(editorSettingsFile)
936
+ });
937
+ else output.line(`${bar} ${paint("dim", `${editorSettingsFile} already maps yaml.schemas: add ./${SCHEMA_FILE} for **/${UNIT_FILE}`)}`);
938
+ }
939
+ if (!await review(context, writes, yes)) {
940
+ output.line(paint("dim", "Nothing written."));
941
+ return true;
942
+ }
943
+ writes.forEach(({ file, text }) => files.write(file, text));
944
+ output.line(`${paint("green", "◇")} Wrote ${writes.length} file${writes.length === 1 ? "" : "s"}`);
945
+ return doctor(context);
946
+ };
947
+ //#endregion
948
+ //#region src/application/addUnit.ts
949
+ /** `shiplane add <folder>`: init's questions for one folder, its unit file written. */
950
+ const addUnit = async (context, dir) => {
951
+ const { output, prompter, files } = context;
952
+ const folderDir = path.posix.normalize(dir).replace(/\/$/, "");
953
+ const candidate = scanFolders(context, context.adapters).find(({ folder }) => folder.dir === folderDir);
954
+ if (!candidate) {
955
+ output.line(`${paint("red", "✗")} ${folderDir} is not a workspace folder without a ${UNIT_FILE}`);
956
+ return false;
957
+ }
958
+ const { folder, guess } = candidate;
959
+ const name = guess?.detection.certainty === "found" ? guess.adapter.name : await prompter.select(`How does ${folder.dir} ship?`, context.adapters.map((adapter) => ({
960
+ value: adapter.name,
961
+ label: adapter.name,
962
+ hint: adapter.name === guess?.adapter.name ? `${guess.detection.reason} (recommended)` : ""
963
+ })), guess?.adapter.name);
964
+ const adapter = context.adapters.find((offered) => offered.name === name);
965
+ if (!adapter) return false;
966
+ const options = await askOptions(context, folder, adapter, guess?.adapter === adapter ? guess.detection.options : {}, false);
967
+ const file = path.posix.join(folder.dir, UNIT_FILE);
968
+ if (!await prompter.confirm(`Write ${file}?`)) {
969
+ output.line(paint("dim", "Nothing written."));
970
+ return true;
971
+ }
972
+ const release = await context.load();
973
+ const pkg = releasePackage(files);
974
+ const placed = placeModule(adapter, release.modules, pkg);
975
+ files.write(file, renderUnit(placed.name, options, { reason: guess?.detection.reason }));
976
+ if (placed.entry) {
977
+ const config = addToConfig(files.read("shiplane.config.ts") ?? "", placed.entry, pkg);
978
+ if (config) files.write(CONFIG_FILE, config);
979
+ else output.line(`${paint("yellow", "!")} add ${moduleCall(placed.entry)} to the modules in ${CONFIG_FILE}`);
980
+ }
981
+ const modules = placed.entry ? [...release.modules, moduleFor(adapter, placed.name)] : release.modules;
982
+ files.write(SCHEMA_FILE, schemaText(modules));
983
+ output.line(`${paint("green", "◇")} Wrote ${file}`);
984
+ return true;
985
+ };
986
+ /** `shiplane remove <unit>`: its unit file goes; changesets still version it. */
987
+ const removeUnit = async (context, name) => {
988
+ const { output, prompter, files } = context;
989
+ const unit = (await context.load()).units.find((candidate) => candidate.name === name);
990
+ if (!unit) {
991
+ output.line(`${paint("red", "✗")} no unit named "${name}"`);
992
+ return false;
993
+ }
994
+ if (!await prompter.confirm(`Stop shipping ${name}? It stays versioned.`)) return true;
995
+ files.remove(unit.file);
996
+ output.line(`${paint("green", "◇")} Removed ${unit.file}`);
997
+ return true;
998
+ };
999
+ //#endregion
1000
+ //#region src/adapters/manifest/package-json-manifest.adapter.ts
1001
+ const PackageSchema = z.object({
1002
+ name: z.string(),
1003
+ version: z.string()
1004
+ });
1005
+ const packageJsonManifest = { read: (root, dir) => {
1006
+ const file = path.join(root, dir, "package.json");
1007
+ if (!fs.existsSync(file)) return null;
1008
+ const parsed = PackageSchema.safeParse(JSON.parse(fs.readFileSync(file, "utf8")));
1009
+ return parsed.success ? parsed.data : null;
1010
+ } };
1011
+ //#endregion
1012
+ //#region src/application/config/loadRelease.ts
1013
+ const EXTENSIONS = [
1014
+ "ts",
1015
+ "mts",
1016
+ "js",
1017
+ "mjs"
1018
+ ];
1019
+ /** The config's names, the one from before shiplane last: still read, listed to rename. */
1020
+ const CONFIG_FILES = [...EXTENSIONS.map((extension) => `shiplane.config.${extension}`), ...EXTENSIONS.map((extension) => `release.config.${extension}`)];
1021
+ const renameOf = (file) => /(^|\/)release\.(config|unit)\./.test(file) ? {
1022
+ from: file,
1023
+ to: file.replace(/(^|\/)release\./, "$1shiplane.")
1024
+ } : null;
1025
+ const findConfig = (root) => CONFIG_FILES.map((file) => path.join(root, file)).find((file) => fs.existsSync(file));
1026
+ const NAMES = ["shiplane"];
1027
+ const resolves = (specifier) => {
1028
+ try {
1029
+ return fileURLToPath(import.meta.resolve(specifier));
1030
+ } catch {
1031
+ return null;
1032
+ }
1033
+ };
1034
+ const selfAliases = () => {
1035
+ const own = NAMES.find((name) => resolves(name) !== null);
1036
+ if (!own) return {};
1037
+ return Object.fromEntries([
1038
+ "",
1039
+ "/plugin",
1040
+ "/testing"
1041
+ ].flatMap((sub) => {
1042
+ const target = resolves(`${own}${sub}`);
1043
+ return target ? NAMES.map((name) => [`${name}${sub}`, target]) : [];
1044
+ }));
1045
+ };
1046
+ /** A port no flow fills yet: a release that never loaded has nothing to run on. */
1047
+ const unset = (port) => ({
1048
+ name: "unset",
1049
+ create: () => {
1050
+ throw new Error(`no ${port} adapter: shiplane.config.ts sets none`);
1051
+ }
1052
+ });
1053
+ /** The flow of a release that did not load: every port unset. */
1054
+ const unsetFlow = () => releaseFlow({
1055
+ sourceControl: unset("sourceControl"),
1056
+ codeHost: unset("codeHost"),
1057
+ ciPipeline: unset("ciPipeline"),
1058
+ versioning: unset("versioning")
1059
+ });
1060
+ const FLOW_MISSING = [
1061
+ "flow is missing: give it one, such as",
1062
+ "flow: releaseFlow({ sourceControl: gitSourceControl(), codeHost: gitHubCodeHost(),",
1063
+ "ciPipeline: gitHubActionsCiPipeline(), versioning: changesetsVersioning() }),",
1064
+ "from the shiplane-git, shiplane-github and shiplane-changesets plugins"
1065
+ ].join(" ");
1066
+ const typed = (value, type) => isRecord(value) && value.type === type && typeof value.name === "string";
1067
+ const isFlow = (value) => isRecord(value) && value.type === "flow";
1068
+ const isModule = (value) => typed(value, "module");
1069
+ const isFeature = (value) => typed(value, "feature");
1070
+ const listOf = (value, key, is, example) => {
1071
+ if (value === void 0) return [];
1072
+ if (!Array.isArray(value)) throw new Error(`${key} is not a list, such as ${key}: [${example}]`);
1073
+ return value.map((item, index) => {
1074
+ if (!is(item)) throw new Error(`${key}[${index}] is not one of its ${key}, such as ${example}`);
1075
+ return item;
1076
+ });
1077
+ };
1078
+ const LEFTOVERS = {
1079
+ plugins: "plugins is gone: defineRelease takes flow, modules and features, such as modules: [backendService({ serverHosting: flyServerHosting() })]",
1080
+ latest: "latest is gone: the first app of the first module is the Latest release"
1081
+ };
1082
+ /** The modules, their names unique and their adapters' settings free of `module`. */
1083
+ const checkModules = (modules, features) => {
1084
+ const names = [...modules, ...features].map(({ name }) => name);
1085
+ names.forEach((name, index) => {
1086
+ if (names.indexOf(name) !== index) throw new Error(`two modules are named "${name}": give one its own, such as { name: "${name}-2", ... }`);
1087
+ });
1088
+ const clash = modules.find(({ settings }) => "module" in settings.shape);
1089
+ if (clash) throw new Error(`"module" is reserved for the unit file's module, yet ${clash.name}'s adapter takes it`);
1090
+ };
1091
+ const tagFormatOf = (tag) => {
1092
+ if (tag === void 0) return DEFAULT_TAG_FORMAT;
1093
+ if (typeof tag !== "string" || !tag.includes("{version}")) throw new Error("tag must name the version, such as tag: \"v{version}\"");
1094
+ return tag;
1095
+ };
1096
+ const releasesCommitsOf = (choice) => {
1097
+ if (choice === void 0 || choice === "ignore") return false;
1098
+ if (choice === "release") return true;
1099
+ throw new Error("commitsWithoutChangeset is \"release\" or \"ignore\"");
1100
+ };
1101
+ const readConfig = async (file, aliases) => {
1102
+ const loaded = await createJiti(import.meta.url, {
1103
+ alias: aliases,
1104
+ moduleCache: false,
1105
+ fsCache: false
1106
+ }).import(file, { default: true });
1107
+ if (!isRecord(loaded)) throw new Error("its default export is not defineRelease({ modules })");
1108
+ for (const [key, message] of Object.entries(LEFTOVERS)) if (key in loaded) throw new Error(message);
1109
+ if (loaded.flow === void 0) throw new Error(FLOW_MISSING);
1110
+ if (!isFlow(loaded.flow)) throw new Error("flow is not a release flow, such as flow: releaseFlow({ ... })");
1111
+ const modules = listOf(loaded.modules, "modules", isModule, "webApp({ ... })");
1112
+ const features = listOf(loaded.features, "features", isFeature, "releaseComments({ ... })");
1113
+ checkModules(modules, features);
1114
+ const units = Array.isArray(loaded.units) ? loaded.units.filter((unit) => typeof unit === "string") : void 0;
1115
+ const display = isRecord(loaded.display) ? loaded.display : {};
1116
+ const flag = (value) => typeof value === "boolean" ? value : void 0;
1117
+ return {
1118
+ flow: loaded.flow,
1119
+ modules,
1120
+ features,
1121
+ units,
1122
+ display: {
1123
+ verbose: flag(display.verbose),
1124
+ mascot: flag(display.mascot)
1125
+ },
1126
+ tagFormat: tagFormatOf(loaded.tag),
1127
+ releasesCommits: releasesCommitsOf(loaded.commitsWithoutChangeset)
1128
+ };
1129
+ };
1130
+ /** Apps in release order: by module as the config lists them, then by name. */
1131
+ const inReleaseOrder = (read, modules) => {
1132
+ const rank = (unit) => modules.findIndex(({ name }) => name === unit.module);
1133
+ return [...read].sort((left, right) => rank(left.unit) - rank(right.unit) || left.unit.name.localeCompare(right.unit.name));
1134
+ };
1135
+ const referenceProblems = ({ unit, file }, ordered) => referencesIn(unit.options).flatMap(({ unit: name, key, at }) => {
1136
+ const other = ordered.find((candidate) => candidate.unit.name === name)?.unit;
1137
+ const line = file.lineOf(at);
1138
+ if (!other) return [{
1139
+ file: unit.file,
1140
+ line,
1141
+ message: `"${name}" has no ${UNIT_FILE} to read from`
1142
+ }];
1143
+ if (valueAt(other.options, key.split(".")) === void 0) return [{
1144
+ file: unit.file,
1145
+ line,
1146
+ message: `"${name}" has no "${key}" in ${other.file}`
1147
+ }];
1148
+ const position = (target) => ordered.findIndex((candidate) => candidate.unit === target);
1149
+ if (other !== unit && position(other) > position(unit)) return [{
1150
+ file: unit.file,
1151
+ line,
1152
+ message: `"${unit.name}" reads ${name}.${key}, which is released after it`,
1153
+ hint: other.module === unit.module ? `${unit.name} and ${name} share ${unit.module}: give ${name} a module of its own, listed first` : `move ${other.module} before ${unit.module} in the modules of shiplane.config.ts`
1154
+ }];
1155
+ return [];
1156
+ });
1157
+ /**
1158
+ * The release as written: what `shiplane.config.ts` composes, and one app per folder that holds a
1159
+ * `shiplane.unit.yml`, in release order. Every problem is collected, never thrown.
1160
+ */
1161
+ const loadRelease = async (root, options = {}) => {
1162
+ const empty = (problems) => ({
1163
+ root,
1164
+ flow: unsetFlow(),
1165
+ tagFormat: DEFAULT_TAG_FORMAT,
1166
+ modules: [],
1167
+ features: [],
1168
+ units: [],
1169
+ problems
1170
+ });
1171
+ const configFile = findConfig(root);
1172
+ if (!configFile) return empty([{
1173
+ file: "shiplane.config.ts",
1174
+ message: "No shiplane.config.ts in this repository",
1175
+ hint: "shiplane init writes it, with a shiplane.unit.yml next to each app"
1176
+ }]);
1177
+ let config;
1178
+ try {
1179
+ config = await readConfig(configFile, options.aliases ?? selfAliases());
1180
+ } catch (error) {
1181
+ const reason = error instanceof Error ? error.message : String(error);
1182
+ return empty([{
1183
+ file: path.basename(configFile),
1184
+ message: `it did not load: ${reason.split("\n")[0]}`
1185
+ }]);
1186
+ }
1187
+ const manifests = options.manifests ?? packageJsonManifest;
1188
+ const problems = [];
1189
+ const features = config.features.map(({ name }) => name);
1190
+ const ordered = inReleaseOrder(expandPatterns(root, config.units ?? workspacePatterns(root)).flatMap((dir) => {
1191
+ const relative = UNIT_FILES.map((name) => path.posix.join(dir, name)).find((file) => fs.existsSync(path.join(root, file)));
1192
+ if (!relative) return [];
1193
+ const result = readUnitFile(relative, fs.readFileSync(path.join(root, relative), "utf8"), config.modules, features);
1194
+ problems.push(...result.problems);
1195
+ const manifest = manifests.read(root, dir);
1196
+ if (!manifest) problems.push({
1197
+ file: relative,
1198
+ message: "no package.json next to it to read its name and version"
1199
+ });
1200
+ if (!result.unit || !manifest) return [];
1201
+ return [{
1202
+ unit: {
1203
+ name: dir === "." ? manifest.name.replace(/^@[^/]+\//, "") : path.posix.basename(dir),
1204
+ dir,
1205
+ file: relative,
1206
+ packageName: manifest.name,
1207
+ version: manifest.version,
1208
+ module: result.unit.module,
1209
+ options: result.unit.options,
1210
+ after: []
1211
+ },
1212
+ file: result.unit
1213
+ }];
1214
+ }), config.modules);
1215
+ ordered.forEach((entry, index) => {
1216
+ const twin = ordered.findIndex(({ unit }) => unit.name === entry.unit.name);
1217
+ if (twin !== index) problems.push({
1218
+ file: entry.unit.file,
1219
+ message: `two folders are both named "${entry.unit.name}"`,
1220
+ hint: `rename one of ${ordered[twin]?.unit.dir} and ${entry.unit.dir}`
1221
+ });
1222
+ problems.push(...referenceProblems(entry, ordered));
1223
+ entry.unit.after = [...new Set(referencesIn(entry.unit.options).map(({ unit }) => unit))].filter((name) => name !== entry.unit.name && ordered.some(({ unit }) => unit.name === name));
1224
+ });
1225
+ return {
1226
+ root,
1227
+ flow: config.flow,
1228
+ modules: config.modules,
1229
+ features: config.features,
1230
+ units: ordered.map(({ unit }) => unit),
1231
+ problems: sortProblems(problems),
1232
+ display: config.display,
1233
+ renames: [path.basename(configFile), ...ordered.map(({ unit }) => unit.file)].flatMap((file) => renameOf(file) ?? []),
1234
+ tagFormat: config.tagFormat,
1235
+ releasesCommits: config.releasesCommits
1236
+ };
1237
+ };
1238
+ //#endregion
1239
+ //#region src/application/docsFor.ts
1240
+ /**
1241
+ * `shiplane docs <module or adapter>`: every key a unit file takes, described, with its default. A
1242
+ * module name reads the release config; an adapter name, the official adapters and those composed.
1243
+ */
1244
+ const docsFor = async (context, name) => {
1245
+ const { output } = context;
1246
+ const release = await context.load();
1247
+ const module = release.modules.find((candidate) => candidate.name === name);
1248
+ const adapters = [...context.adapters, ...release.modules.map(({ provider, settings }) => ({
1249
+ name: provider,
1250
+ settings
1251
+ }))];
1252
+ const adapter = adapters.find((candidate) => candidate.name === name);
1253
+ const found = module ? {
1254
+ title: `module: ${module.name} ${paint("dim", `with ${module.provider}`)}`,
1255
+ settings: module.settings
1256
+ } : adapter && {
1257
+ title: `${adapter.name} ${paint("dim", "adapter")}`,
1258
+ settings: adapter.settings
1259
+ };
1260
+ if (!found) {
1261
+ const known = [...new Set([...release.modules.map((candidate) => candidate.name), ...adapters.map((candidate) => candidate.name)])];
1262
+ output.line(`${paint("red", "✗")} no module or adapter "${name}": ${known.join(", ")}`);
1263
+ return false;
1264
+ }
1265
+ const keys = documentedKeys(found.settings);
1266
+ const width = Math.max(8, ...keys.map(({ key }) => key.length)) + 2;
1267
+ output.line();
1268
+ output.line(` ${paint("bold", found.title)}`);
1269
+ output.line();
1270
+ keys.forEach(({ key, description, default: fallback, required }) => {
1271
+ const note = required ? paint("yellow", "required") : fallback === void 0 ? "optional" : `default: ${typeof fallback === "string" ? fallback : JSON.stringify(fallback)}`;
1272
+ output.line(` ${key.padEnd(width)}${description}`);
1273
+ output.line(` ${" ".repeat(width)}${paint("dim", note)}`);
1274
+ });
1275
+ output.line();
1276
+ return true;
1277
+ };
1278
+ //#endregion
1279
+ //#region src/application/newAdapter.ts
1280
+ const adapterFile = (name, factory, pkg) => `import { defineServerHosting, z } from "${pkg}";
1281
+
1282
+ /** Hosts a server on ${name}. Replace the command with the one that deploys it. */
1283
+ export const ${factory} = () =>
1284
+ defineServerHosting({
1285
+ name: "${name}",
1286
+ settings: z.object({
1287
+ service: z.string().describe("What to deploy"),
1288
+ }),
1289
+ describe: ({ options }) => \`\${options.service} on ${name}\`,
1290
+ jobs: ({ tag, options }) => [
1291
+ {
1292
+ label: \`deploy \${tag} to \${options.service}\`,
1293
+ local: [{ command: "echo", args: ["deploy", options.service] }],
1294
+ },
1295
+ ],
1296
+ });
1297
+ `;
1298
+ const testFile = (name, factory, pkg) => `import { serverHostingContract, serverHostingFake } from "${pkg}/testing";
1299
+
1300
+ import { ${factory} } from "./${name}";
1301
+
1302
+ // The contract every server host passes, run on this adapter and on the Fake tests use in its place.
1303
+ serverHostingContract([
1304
+ { adapter: ${factory}(), settings: { service: "web-preview" } },
1305
+ { adapter: serverHostingFake(), settings: { service: "web-preview" } },
1306
+ ]);
1307
+ `;
1308
+ /**
1309
+ * `shiplane adapter new <name>`: a server hosting adapter, the port's contract suite run on it and on
1310
+ * its Fake, and a module for it in the root config.
1311
+ */
1312
+ const newAdapter = async (context, name) => {
1313
+ const { output, files } = context;
1314
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
1315
+ output.line(`${paint("red", "✗")} an adapter name is lowercase words joined by dashes, like my-host`);
1316
+ return false;
1317
+ }
1318
+ const factory = `${factoryName(name)}ServerHosting`;
1319
+ const pkg = releasePackage(files);
1320
+ const file = `release/adapters/${name}.ts`;
1321
+ if (files.exists(file)) {
1322
+ output.line(`${paint("red", "✗")} ${file} already exists`);
1323
+ return false;
1324
+ }
1325
+ const config = addToConfig(files.read("shiplane.config.ts") ?? "", {
1326
+ factory: "backendService",
1327
+ port: "serverHosting",
1328
+ adapter: factory,
1329
+ name,
1330
+ from: `./release/adapters/${name}`
1331
+ }, pkg);
1332
+ if (!config) {
1333
+ output.line(`${paint("red", "✗")} ${CONFIG_FILE} has no modules list to add it to: run shiplane init first`);
1334
+ return false;
1335
+ }
1336
+ files.write(file, adapterFile(name, factory, pkg));
1337
+ files.write(`release/adapters/${name}.test.ts`, testFile(name, factory, pkg));
1338
+ files.write(CONFIG_FILE, config);
1339
+ output.line(`${paint("green", "◇")} Wrote ${file}, its contract test, and a ${name} module in ${CONFIG_FILE}`);
1340
+ output.line(`${paint("dim", "└")} Next: point an app at it with ${paint("cyan", `module: ${name}`)}`);
1341
+ return Promise.resolve(true);
1342
+ };
1343
+ //#endregion
1344
+ //#region src/domain/releasePr.ts
1345
+ /**
1346
+ * Where `pnpm shiplane` picks up, from what main and GitHub hold right now. A merged release is
1347
+ * tagged and shipped before the next one is opened.
1348
+ */
1349
+ const nextStep = ({ pending, releasePrs, untagged, unreleased }) => {
1350
+ if (releasePrs.length > 0) return {
1351
+ step: "wait-merge",
1352
+ prs: releasePrs
1353
+ };
1354
+ if ((pending > 0 || unreleased > 0) && untagged === 0) return { step: "release-pr" };
1355
+ return { step: "ship" };
1356
+ };
1357
+ const RELEASE_BRANCH_PREFIX = "shiplane/release-";
1358
+ const twoDigits = (value) => String(value).padStart(2, "0");
1359
+ const releaseBranchName = (now) => `${RELEASE_BRANCH_PREFIX}${now.getFullYear()}-${twoDigits(now.getMonth() + 1)}-${twoDigits(now.getDate())}-${twoDigits(now.getHours())}${twoDigits(now.getMinutes())}`;
1360
+ const sentence = (items) => items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
1361
+ const MAX_LINE = 100;
1362
+ /** One app's release commit: `chore(api): release v0.0.4`. */
1363
+ const releaseCommitTitle = ({ app, to }) => `chore(${app}): release v${to}`;
1364
+ /** Conventional and short: `chore(api): release v0.0.4`, or `chore(release): ...` for several apps. */
1365
+ const releaseTitle = (bumps) => {
1366
+ const [first, ...others] = bumps;
1367
+ if (!first) return "chore(release): package changelogs";
1368
+ if (others.length === 0) return releaseCommitTitle(first);
1369
+ const named = `chore(release): ${sentence(bumps.map(({ app, to }) => `${app} v${to}`))}`;
1370
+ return named.length <= MAX_LINE ? named : `chore(release): ${bumps.length} apps`;
1371
+ };
1372
+ /** A bullet wrapped to commitlint's 100-character body lines, continued under its text. */
1373
+ const bullet = (text) => text.split(" ").reduce((lines, word) => {
1374
+ const last = lines.at(-1);
1375
+ if (last !== void 0 && `${last} ${word}`.length <= MAX_LINE) return [...lines.slice(0, -1), `${last} ${word}`];
1376
+ return [...lines, `${last === void 0 ? "-" : " "} ${word}`];
1377
+ }, []).join("\n");
1378
+ /** The release commit's body: each app's version, then what its users get. */
1379
+ const releaseCommitBody = (bumps) => bumps.map(({ app, to, notes, movedWith }) => {
1380
+ const lines = notes.length > 0 ? notes : movedWith.length > 0 ? [`Moves with ${movedWith.join(", ")}.`] : [];
1381
+ return [`${app} ${to}`, ...lines.map(bullet)].join("\n");
1382
+ }).join("\n\n");
1383
+ /** The release PR's body; `onMerge` says what happens to each unit once it is merged. */
1384
+ const releasePrBody = (bumps, onMerge) => {
1385
+ const appWidth = Math.max(3, ...bumps.map(({ app }) => app.length));
1386
+ const versionWidth = Math.max(7, ...bumps.map(({ from, to }) => `${from} → ${to}`.length));
1387
+ const row = (cells) => `| ${cells.join(" | ")} |`;
1388
+ const table = [
1389
+ row([
1390
+ "App".padEnd(appWidth),
1391
+ "Version".padEnd(versionWidth),
1392
+ "On merge"
1393
+ ]),
1394
+ row([
1395
+ "-".repeat(appWidth),
1396
+ "-".repeat(versionWidth),
1397
+ "--------"
1398
+ ]),
1399
+ ...bumps.map((bump) => row([
1400
+ bump.app.padEnd(appWidth),
1401
+ `${bump.from} → ${bump.to}`.padEnd(versionWidth),
1402
+ onMerge(bump)
1403
+ ]))
1404
+ ];
1405
+ const notes = bumps.flatMap(({ app, to, notes: lines }) => lines.length > 0 ? [
1406
+ "",
1407
+ `### ${app} ${to}`,
1408
+ "",
1409
+ ...lines.map((line) => `- ${line}`)
1410
+ ] : []);
1411
+ return [
1412
+ "## 🎯 What & why",
1413
+ "",
1414
+ "Versions the changesets merged since the last release. Squash and merge it by hand: `pnpm shiplane`, still running or run again, tags and ships to preview once it is merged.",
1415
+ "",
1416
+ ...bumps.length > 0 ? table : ["Internal packages only: changelogs, nothing ships."],
1417
+ ...notes,
1418
+ "",
1419
+ "## ✅ Testing",
1420
+ "",
1421
+ "Versions, changelogs and version files only. No UI change."
1422
+ ].join("\n");
1423
+ };
1424
+ const MERGE_BUTTON = [
1425
+ {
1426
+ value: "--merge",
1427
+ label: "Create a merge commit",
1428
+ hint: "every commit, joined by a merge commit"
1429
+ },
1430
+ {
1431
+ value: "--squash",
1432
+ label: "Squash and merge",
1433
+ hint: "the commits combined into one"
1434
+ },
1435
+ {
1436
+ value: "--rebase",
1437
+ label: "Rebase and merge",
1438
+ hint: "every commit, rebased onto main"
1439
+ }
1440
+ ];
1441
+ /** The methods as GitHub's merge button lists them, preselected as the pull request page does. */
1442
+ const mergeChoices = ({ allowed, preselected }) => {
1443
+ const choices = MERGE_BUTTON.filter(({ value }) => allowed.includes(value));
1444
+ return {
1445
+ choices,
1446
+ initial: preselected && allowed.includes(preselected) ? preselected : choices[0]?.value
1447
+ };
1448
+ };
1449
+ const WAIT_KEYS = {
1450
+ d: "diff",
1451
+ m: "merge",
1452
+ o: "open"
1453
+ };
1454
+ /** What a key does while the release waits for its pull request to merge. */
1455
+ const waitKey = (name) => name && WAIT_KEYS[name] || null;
1456
+ //#endregion
1457
+ //#region src/application/steps.ts
1458
+ const MAX_OUTPUT_LINES = 40;
1459
+ const reasonOf$1 = (error) => error instanceof Error ? error.message : String(error);
1460
+ /** What the failed command printed, so the person reads why without running it again. */
1461
+ const printOutput = ({ output }, error) => {
1462
+ if (!(error instanceof CommandFailed) || !error.output) return;
1463
+ const lines = error.output.split("\n");
1464
+ const shown = lines.slice(-MAX_OUTPUT_LINES);
1465
+ if (shown.length < lines.length) output.line(paint("dim", ` … ${lines.length - shown.length} earlier lines`));
1466
+ shown.forEach((line) => output.line(paint("dim", ` │ ${line}`)));
1467
+ };
1468
+ /** Takes back the steps that ran, newest first; one that cannot be undone never stops the rest. */
1469
+ const cancel = async (context, ran) => {
1470
+ const undos = ran.flatMap(({ undo }) => undo ? [undo] : []).reverse();
1471
+ const kept = ran.flatMap((step) => step.kept ? [step.kept] : []);
1472
+ if (undos.length === 0 && kept.length === 0) return;
1473
+ const left = [];
1474
+ for (const undo of undos) try {
1475
+ await context.progress.during(`undo: ${undo.label}`, "working", undo.run);
1476
+ } catch (error) {
1477
+ left.push(undo);
1478
+ context.progress.say("worried", `${paint("red", "✗")} undo ${undo.label}: ${reasonOf$1(error)}`);
1479
+ }
1480
+ if (left.length === 0 && kept.length === 0) {
1481
+ context.progress.say("resting", paint("dim", "Cancelled: everything this run did is undone."));
1482
+ return;
1483
+ }
1484
+ const commands = [...new Set([...left, ...kept].flatMap(({ byHand }) => byHand()))];
1485
+ const these = commands.length > 1 ? "these" : "this";
1486
+ const ask = kept.length === 0 ? "run these to finish the cleanup:" : `run ${these} to finish:`;
1487
+ fail(context, "Cancelled, not all of it", [...kept.map(({ label }) => label), ask].join("; "), commands);
1488
+ };
1489
+ /**
1490
+ * Runs steps in order, each shown with its place in the run. At the first failure it says why,
1491
+ * with the command's own output, and undoes the steps that ran.
1492
+ */
1493
+ const runSteps = async (context, steps) => {
1494
+ for (const [index, step] of steps.entries()) try {
1495
+ await context.progress.during(step.label, "working", step.run, {
1496
+ index,
1497
+ total: steps.length
1498
+ });
1499
+ } catch (error) {
1500
+ fail(context, `${step.label} failed`, `${reasonOf$1(error)}, the steps after it did not run.`);
1501
+ printOutput(context, error);
1502
+ await cancel(context, steps.slice(0, index));
1503
+ return false;
1504
+ }
1505
+ return true;
1506
+ };
1507
+ /** A branch from main; undone by dropping the changes made on it and the branch itself. */
1508
+ const branchStep = ({ services: { sourceControl: source } }, branch) => {
1509
+ let untracked = /* @__PURE__ */ new Set();
1510
+ return {
1511
+ label: `branch ${branch} from main`,
1512
+ run: async () => {
1513
+ untracked = new Set(await source.changedFiles());
1514
+ await source.createBranch(branch);
1515
+ },
1516
+ undo: {
1517
+ label: `delete ${branch}`,
1518
+ run: async () => {
1519
+ const created = (await source.changedFiles()).filter((file) => !untracked.has(file));
1520
+ await source.discard(created);
1521
+ await source.switchTo("main");
1522
+ await source.deleteBranch(branch);
1523
+ },
1524
+ byHand: () => [
1525
+ "git reset --hard",
1526
+ "git switch main",
1527
+ `git branch -D ${branch}`
1528
+ ]
1529
+ }
1530
+ };
1531
+ };
1532
+ const pushStep = ({ services: { sourceControl: source } }, branch) => ({
1533
+ label: `push ${branch}`,
1534
+ run: () => source.push(branch),
1535
+ undo: {
1536
+ label: `delete ${branch} on origin`,
1537
+ run: () => source.deleteRemoteBranch(branch),
1538
+ byHand: () => [`git push origin --delete ${branch}`]
1539
+ }
1540
+ });
1541
+ /** Opens a pull request; undone by closing it, with a comment saying why. */
1542
+ const openPrStep = ({ services: { codeHost: host } }, label, open) => {
1543
+ let opened = null;
1544
+ return {
1545
+ label,
1546
+ run: async () => {
1547
+ opened = await open();
1548
+ },
1549
+ undo: {
1550
+ label: "close the pull request",
1551
+ run: async () => {
1552
+ if (opened) await host.closePr(opened, "The release stopped part way, so it closed this.");
1553
+ },
1554
+ byHand: () => opened ? [`gh pr close ${opened.number}`] : []
1555
+ }
1556
+ };
1557
+ };
1558
+ //#endregion
1559
+ //#region src/application/openReleasePr.ts
1560
+ const plural$1 = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
1561
+ /** What happens to a unit once the release PR merges: its module ships the version to preview. */
1562
+ const shipsOnMerge = (context, { contributions, companions }) => (bump) => {
1563
+ const contributed = contributions[bump.app]?.onMerge;
1564
+ if (contributed) return contributed;
1565
+ const unit = context.release.units.find(({ name }) => name === bump.app);
1566
+ const along = companions.find(({ app }) => app === bump.app);
1567
+ const reason = along ? ` (not picked: ${along.why})` : bump.movedWith.length > 0 ? ` (moved with ${bump.movedWith.join(", ")})` : "";
1568
+ return `${environmentLabel(context, [bump.app], "preview") === "live" ? "Ship live" : "Ship to preview"} with ${(unit && moduleOf(context, unit)?.provider) ?? "its target"}${reason}`;
1569
+ };
1570
+ /** Units going out unpicked, each with the package that takes it along. */
1571
+ const printCompanions = ({ output, release }, { companions, split }) => {
1572
+ if (companions.length === 0) return;
1573
+ const names = companions.map(({ app }) => app);
1574
+ const verb = names.length === 1 ? "is not picked but ships too" : "are not picked but ship too";
1575
+ output.line(` ${paint(["bold", "yellow"], "!")} ${paint("bold", `${listed(names)} ${verb}:`)}`);
1576
+ companions.forEach(({ app, version, why }) => {
1577
+ const packageName = release.units.find(({ name }) => name === app)?.packageName;
1578
+ const waiting = split.waits.filter(({ releases }) => releases.some(({ name }) => name === packageName)).length;
1579
+ const own = waiting > 0 ? ` · picking it ships its ${plural$1(waiting, "changeset")} too` : "";
1580
+ output.line(` ${app.padEnd(11)}${version.padEnd(20)}${paint("dim", `${why}${own}`)}`);
1581
+ });
1582
+ output.line();
1583
+ };
1584
+ /** The table a person reads before anything is written: each unit, its move, what ships. */
1585
+ const printSummary = (context, prepared) => {
1586
+ const { output, release } = context;
1587
+ const { bumps, packages, pending, held, unreleased, contributions, companions } = prepared;
1588
+ const dot = paint("dim", "·");
1589
+ const stays = held.filter((app) => !bumps.some((bump) => bump.app === app));
1590
+ const heldLabel = stays.length > 0 ? ` ${dot} ${stays.join(", ")} held` : "";
1591
+ const where = environmentLabel(context, bumps.map(({ app }) => app), "preview");
1592
+ output.line();
1593
+ output.line(` ${paint("bold", "Release")} ${dot} ${where} ${dot} ${plural$1(pending, "changeset")}${heldLabel}`);
1594
+ output.line();
1595
+ const width = Math.max(13, ...release.units.map(({ name }) => name.length)) + 2;
1596
+ output.line(paint("dim", ` ${"Unit".padEnd(width)}${"Version".padEnd(20)}${where === "live" ? "Ships live" : "Ships to preview"}`));
1597
+ release.units.forEach((unit) => {
1598
+ const bump = bumps.find(({ app }) => app === unit.name);
1599
+ const version = bump ? `${bump.from} → ${bump.to}` : unit.version;
1600
+ const left = unreleased.find(({ app }) => app === unit.name);
1601
+ const ships = (() => {
1602
+ if (held.includes(unit.name) && !bump) return paint("yellow", "⏸ held, its changesets stay pending");
1603
+ if (left && !bump) return paint("yellow", `! ${plural$1(left.commits.length, "commit")} since ${left.version}, no changeset: not in this release`);
1604
+ const contributed = contributions[unit.name]?.summary;
1605
+ if (contributed && contributed.length > 0) return contributed.join(`\n ${" ".repeat(width + 20)}`);
1606
+ if (!bump) return paint("dim", "– nothing changed");
1607
+ const along = companions.some(({ app }) => app === unit.name) ? paint("yellow", " not picked, goes along") : "";
1608
+ return `${paint("green", "↑ ship")} ${paint("dim", moduleOf(context, unit)?.provider ?? "")}${along}`;
1609
+ })();
1610
+ output.line(` ${unit.name.padEnd(width)}${version.padEnd(20)}${ships}`);
1611
+ });
1612
+ if (packages > 0) output.line(` ${"packages".padEnd(width)}${`${packages} bumped`.padEnd(20)}${paint("dim", "changelogs only, nothing published")}`);
1613
+ output.line();
1614
+ printCompanions(context, prepared);
1615
+ };
1616
+ /**
1617
+ * Versions what `prepared` covers on one branch from main, opens its PR, and goes back to main.
1618
+ * Null, with what to do, when it must not run.
1619
+ */
1620
+ const openReleasePr = async (context, prepared) => {
1621
+ const { output, services, clock } = context;
1622
+ printSummary(context, prepared);
1623
+ const blocked = Object.values(prepared.contributions).find((entry) => entry.blocked)?.blocked;
1624
+ if (blocked) {
1625
+ fail(context, blocked.title, blocked.detail, blocked.commands);
1626
+ return null;
1627
+ }
1628
+ const source = releaseSource("build", "preview", await services.sourceControl.position());
1629
+ if (!source.allowed) {
1630
+ fail(context, source.why === "not-main" ? "Not from main" : "main is behind origin", "a release versions what is merged.", [
1631
+ "git switch main",
1632
+ "git pull",
1633
+ "shiplane"
1634
+ ]);
1635
+ return null;
1636
+ }
1637
+ if (!await services.sourceControl.isClean()) {
1638
+ fail(context, "Uncommitted changes", "commit or stash them first, the release PR commits every change.");
1639
+ return null;
1640
+ }
1641
+ const planned = [
1642
+ "Open the release PR, then wait for you to squash merge it",
1643
+ "Tag each version and publish its release notes",
1644
+ ...Object.values(prepared.contributions).flatMap(({ step }) => step ? [step] : [])
1645
+ ];
1646
+ output.line(paint("dim", " Steps"));
1647
+ planned.forEach((step, index) => output.line(` ${index + 1}. ${step}`));
1648
+ output.line();
1649
+ if (!await confirm(context, `Release these ${environmentLabel(context, prepared.bumps.map(({ app }) => app), "preview") === "live" ? "live" : "to preview"}?`, true)) {
1650
+ output.line(paint("dim", "Nothing ran."));
1651
+ return null;
1652
+ }
1653
+ const branch = releaseBranchName(clock.now());
1654
+ const title = releaseTitle(prepared.bumps);
1655
+ const prs = [];
1656
+ return await runSteps(context, [
1657
+ branchStep(context, branch),
1658
+ {
1659
+ label: "versions and changelogs",
1660
+ run: () => services.versioning.apply(prepared.added, prepared.split.waits)
1661
+ },
1662
+ ...Object.values(prepared.contributions).flatMap(({ writes }) => writes),
1663
+ {
1664
+ label: `commit "${title}"`,
1665
+ run: async () => services.sourceControl.commit(await services.sourceControl.changedFiles(), title, releaseCommitBody(prepared.bumps) || void 0)
1666
+ },
1667
+ pushStep(context, branch),
1668
+ openPrStep(context, "open the release pull request", async () => {
1669
+ const pr = await services.codeHost.createPr({
1670
+ base: "main",
1671
+ head: branch,
1672
+ title,
1673
+ body: releasePrBody(prepared.bumps, shipsOnMerge(context, prepared)),
1674
+ label: "type: chore"
1675
+ });
1676
+ prs.push(pr);
1677
+ return pr;
1678
+ }),
1679
+ {
1680
+ label: "back to main",
1681
+ run: () => services.sourceControl.switchTo("main")
1682
+ }
1683
+ ]) ? prs : null;
1684
+ };
1685
+ //#endregion
1686
+ //#region src/domain/scope.ts
1687
+ const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
1688
+ const previewChoice = ({ version, changesets, commits, tagged, versioned, firstRelease, onChannel, decidedBy, releaseOnly }) => {
1689
+ const later = decidedBy ? ` · ${decidedBy.platform} decides ${decidedBy.choice} once picked` : "";
1690
+ if (changesets > 0) return {
1691
+ pending: true,
1692
+ hint: `${plural(changesets, "changeset")}${later}`
1693
+ };
1694
+ if (commits > 0) return {
1695
+ pending: true,
1696
+ hint: `${plural(commits, "commit")} since ${version}, changelog from its commits${later}`
1697
+ };
1698
+ if (!tagged) {
1699
+ if (versioned) return {
1700
+ pending: true,
1701
+ hint: `${version} versioned, not tagged yet${later}`
1702
+ };
1703
+ return firstRelease ? {
1704
+ pending: true,
1705
+ hint: `${version} first release${later}`
1706
+ } : {
1707
+ pending: false,
1708
+ hint: "nothing new"
1709
+ };
1710
+ }
1711
+ if (releaseOnly) return {
1712
+ pending: false,
1713
+ hint: `${version} released, nothing deploys it`
1714
+ };
1715
+ if (decidedBy) return {
1716
+ pending: false,
1717
+ hint: `${version} released, nothing new (${decidedBy.check} shows its builds)`
1718
+ };
1719
+ return onChannel ? {
1720
+ pending: false,
1721
+ hint: `${version} is on preview, nothing new`
1722
+ } : {
1723
+ pending: true,
1724
+ hint: `${version} released, not on preview yet`
1725
+ };
1726
+ };
1727
+ const productionChoice = ({ version, tagged, onChannel, onPreview, decidedBy, releaseOnly }) => {
1728
+ if (!tagged) return {
1729
+ pending: false,
1730
+ hint: "not released yet"
1731
+ };
1732
+ if (releaseOnly) return {
1733
+ pending: false,
1734
+ hint: `${version} released, nothing deploys it`
1735
+ };
1736
+ if (decidedBy) return {
1737
+ pending: true,
1738
+ hint: `${version} released, ${decidedBy.platform} decides once picked`
1739
+ };
1740
+ if (onChannel) return {
1741
+ pending: false,
1742
+ hint: `${version} is on production, nothing new`
1743
+ };
1744
+ return onPreview ? {
1745
+ pending: true,
1746
+ hint: `${version} is on preview, promotes it`
1747
+ } : {
1748
+ pending: false,
1749
+ hint: `${version} is not on preview yet: release it there first`
1750
+ };
1751
+ };
1752
+ /** The first question: which units have something to release here, and why not the rest. */
1753
+ const scopeChoices = (apps, channel) => apps.map((info) => ({
1754
+ app: info.app,
1755
+ ...channel === "production" ? productionChoice(info) : previewChoice(info)
1756
+ }));
1757
+ //#endregion
1758
+ //#region src/application/readScope.ts
1759
+ const MANIFEST = "package.json";
1760
+ const unitRefs = (units) => units.map(({ name, packageName }) => ({
1761
+ name,
1762
+ packageName
1763
+ }));
1764
+ /** The units the pending changesets name. */
1765
+ const namedUnits = async ({ release, services }) => new Set((await services.versioning.pending()).flatMap(({ text }) => changesetApps(text, unitRefs(release.units))));
1766
+ /** Units whose folder moved since their current version, that no changeset or bump ships. */
1767
+ const findUnreleased = async ({ release, services: { sourceControl: source } }, named) => {
1768
+ if (!release.releasesCommits) return [];
1769
+ return unreleasedApps((await Promise.all(release.units.map(async ({ name, dir, version }) => {
1770
+ const since = await source.tagCommit(tagName(name, version, release.tagFormat)) ?? (await source.versionCommit(dir, "package.json", version))?.sha;
1771
+ if (!since) return [];
1772
+ return [{
1773
+ app: name,
1774
+ version,
1775
+ commits: await source.subjectsSince(since, dir, UNIT_FILES)
1776
+ }];
1777
+ }))).flat(), named);
1778
+ };
1779
+ /** A tag's deploy on an environment, from every record the host keeps. */
1780
+ const deployedOn = (history, tag, environment) => {
1781
+ const states = history.filter(({ title }) => title === deployRunTitle(tag, environment)).map(({ state }) => state);
1782
+ if (states.includes("done")) return "done";
1783
+ return states.includes("running") ? "running" : "none";
1784
+ };
1785
+ /**
1786
+ * Each unit as the first question sees it: git for what is new, the host's deploy records for what
1787
+ * each environment runs (offline, nothing counts as deployed).
1788
+ */
1789
+ const readScope = async (context, environment) => {
1790
+ const { release, services } = context;
1791
+ const pending = await services.versioning.pending();
1792
+ const refs = unitRefs(release.units);
1793
+ const named = pending.map(({ text }) => changesetApps(text, refs));
1794
+ const unreleased = await findUnreleased(context, new Set(named.flat()));
1795
+ const [deployed, tags] = await Promise.all([services.codeHost.deployments().catch(() => []), services.sourceControl.tags()]);
1796
+ return Promise.all(release.units.map(async (unit) => {
1797
+ const tag = tagName(unit.name, unit.version, context.release.tagFormat);
1798
+ const target = moduleOf(context, unit);
1799
+ const decidedBy = target?.decidedBy;
1800
+ const commit = await services.sourceControl.versionCommit(unit.dir, MANIFEST, unit.version);
1801
+ const tagged = await services.sourceControl.tagCommit(tag) !== null;
1802
+ const live = async (on) => {
1803
+ if (!target?.live || !tagged) return deployedOn(deployed, tag, on) === "done";
1804
+ const { head } = await services.sourceControl.position();
1805
+ const input = jobInput(context, target, unit, {
1806
+ tag,
1807
+ environment: on,
1808
+ commit: head
1809
+ });
1810
+ return target.live(decideContext(context), input).catch(() => false);
1811
+ };
1812
+ return {
1813
+ app: unit.name,
1814
+ version: unit.version,
1815
+ changesets: named.filter((apps) => apps.includes(unit.name)).length,
1816
+ commits: unreleased.find((entry) => entry.app === unit.name)?.commits.length ?? 0,
1817
+ tagged,
1818
+ versioned: commit !== null && cameWithRelease({
1819
+ app: unit.name,
1820
+ version: unit.version,
1821
+ commit
1822
+ }),
1823
+ firstRelease: !tagged && commit !== null && firstRelease(unit.name, unit.version, tags, context.release.tagFormat),
1824
+ onChannel: await live(environment),
1825
+ onPreview: await live("preview"),
1826
+ ...decidedBy ? { decidedBy } : {},
1827
+ ...target?.releaseOnly ? { releaseOnly: true } : {}
1828
+ };
1829
+ }));
1830
+ };
1831
+ //#endregion
1832
+ //#region src/application/pickScope.ts
1833
+ /** Every unit with something to release here: what --yes and a run without a terminal cover. */
1834
+ const defaultScope = (info, environment) => new Set(scopeChoices(info, environment).filter(({ pending }) => pending).map(({ app }) => app));
1835
+ /**
1836
+ * The first question: which units this run covers. Every unit is listed; those with nothing to
1837
+ * release are greyed out with why. Null when cancelled or when nothing is pending.
1838
+ */
1839
+ const pickScope = async (context, environment) => {
1840
+ const { output, prompter, options, progress } = context;
1841
+ const info = await progress.during("Reading what changed: changesets, commits, tags and GitHub deployments", "thinking", () => readScope(context, environment));
1842
+ const choices = scopeChoices(info, environment);
1843
+ if (!choices.some(({ pending }) => pending)) {
1844
+ output.line();
1845
+ choices.forEach(({ app, hint }) => output.line(` ${paint("dim", `${app.padEnd(15)}${hint}`)}`));
1846
+ output.line();
1847
+ progress.say("resting", `${paint("bold", `Nothing to release to ${environment}.`)} ${paint("dim", environment === "preview" ? "Queue a change first:" : "Release to preview first:")}`);
1848
+ output.line(` ${paint("cyan", environment === "preview" ? "pnpm changeset" : "shiplane")}`);
1849
+ output.line();
1850
+ return null;
1851
+ }
1852
+ if (options.yes || !prompter.interactive) return {
1853
+ scope: defaultScope(info, environment),
1854
+ info
1855
+ };
1856
+ const picked = await prompter.multiselect(`What do you want to release to ${environment}? Greyed units have nothing to release.`, choices.map(({ app, pending, hint }) => ({
1857
+ value: app,
1858
+ label: app,
1859
+ hint,
1860
+ disabled: !pending
1861
+ })), choices.filter(({ pending }) => pending).map(({ app }) => app));
1862
+ return picked ? {
1863
+ scope: new Set(picked),
1864
+ info
1865
+ } : null;
1866
+ };
1867
+ //#endregion
1868
+ //#region src/application/followUps.ts
1869
+ const reasonOf = (error) => error instanceof Error ? error.message : String(error);
1870
+ /** What every feature asks for once these apps ship, in order. One that cannot read is said, then skipped. */
1871
+ const followUpsOf = async (context, shipped) => {
1872
+ const all = [];
1873
+ if (shipped.length === 0) return all;
1874
+ for (const feature of context.release.features) try {
1875
+ const asked = await context.progress.during(`${feature.name}: reading what to follow up`, "thinking", () => feature.afterShip(afterShipContext(context), shipped));
1876
+ all.push(...asked);
1877
+ } catch (error) {
1878
+ context.output.line(` ${paint("yellow", "!")} ${feature.name} ${paint("dim", `could not read: ${reasonOf(error)}`)}`);
1879
+ }
1880
+ return all;
1881
+ };
1882
+ /** Runs what the features ask for once units shipped. A failure is said and never fails the release. */
1883
+ const runFollowUps = async (context, shipped) => {
1884
+ for (const { label, run } of await followUpsOf(context, shipped)) try {
1885
+ await run();
1886
+ context.output.line(` ${paint("green", "✓")} ${label}`);
1887
+ } catch (error) {
1888
+ context.output.line(` ${paint("yellow", "!")} ${label} ${paint("dim", reasonOf(error))}`);
1889
+ }
1890
+ };
1891
+ /** What the features would do once these units ship, run nothing. */
1892
+ const planFollowUps = async (context, shipped) => {
1893
+ const all = await followUpsOf(context, shipped);
1894
+ if (all.length === 0) return;
1895
+ context.output.line();
1896
+ context.output.line(` ${paint("bold", "Then")} ${paint("dim", "once shipped")}`);
1897
+ all.forEach(({ label }) => context.output.line(` ${label}`));
1898
+ };
1899
+ //#endregion
1900
+ //#region src/application/planShips.ts
1901
+ /**
1902
+ * `shiplane plan`: every command shipping the current tags would run, both ways, in release order,
1903
+ * then what the features would do. It runs nothing and asks nothing; it reads git, and the code host
1904
+ * for features.
1905
+ */
1906
+ const planShips = async (context, environment) => {
1907
+ const { release, services, output } = context;
1908
+ const { head } = await services.sourceControl.position();
1909
+ output.line();
1910
+ output.line(` ${paint("bold", "Plan")} ${paint("dim", "·")} ${environment} ${paint("dim", "· nothing runs")}`);
1911
+ output.line(` ${paint("bold", "Order")} ${releaseOrder(release.units)}`);
1912
+ const shipped = [];
1913
+ for (const unit of release.units) {
1914
+ const module = moduleOf(context, unit);
1915
+ if (!module) continue;
1916
+ const tag = tagName(unit.name, unit.version, context.release.tagFormat);
1917
+ const tagged = await services.sourceControl.tagCommit(tag) !== null;
1918
+ if (tagged && !module.releaseOnly) shipped.push({
1919
+ unit,
1920
+ tag,
1921
+ environment
1922
+ });
1923
+ const plan = shipPlanOf(context, module, jobInput(context, module, unit, {
1924
+ tag,
1925
+ environment,
1926
+ commit: head
1927
+ }));
1928
+ output.line();
1929
+ output.line(` ${paint("bold", tag)} → ${plan.where}${tagged ? "" : paint("yellow", " (not tagged yet: release first)")}`);
1930
+ plan.jobs.forEach((job) => {
1931
+ output.line(` ${paint("dim", "this machine")}`);
1932
+ job.local.forEach((command) => output.line(` ${commandLine(command)}`));
1933
+ if (job.record) output.line(` ${paint("dim", `then record ${tag} on ${environment} in GitHub Deployments`)}`);
1934
+ if (job.ci) {
1935
+ const workflow = services.ciPipeline.shipWorkflow;
1936
+ output.line(` ${paint("dim", "GitHub Actions")}`);
1937
+ output.line(` gh workflow run ${workflow} --ref ${job.ci.ref} -f units=${unit.name} -f environment=${environment}`);
1938
+ }
1939
+ });
1940
+ }
1941
+ await planFollowUps(context, shipped);
1942
+ output.line();
1943
+ };
1944
+ //#endregion
1945
+ //#region src/domain/companions.ts
1946
+ /** The shortest chain of moving packages from `from` to one a changeset names, breadth first. */
1947
+ const chainTo = (from, dependencies, moving, named) => {
1948
+ const seen = /* @__PURE__ */ new Set();
1949
+ let paths = [[from]];
1950
+ while (paths.length > 0) {
1951
+ const next = [];
1952
+ for (const path of paths) {
1953
+ const last = path[path.length - 1] ?? from;
1954
+ for (const dependency of dependencies[last] ?? []) {
1955
+ if (!moving.has(dependency) || seen.has(dependency)) continue;
1956
+ seen.add(dependency);
1957
+ const chain = [...path, dependency];
1958
+ if (named.has(dependency)) return chain.slice(1);
1959
+ next.push(chain);
1960
+ }
1961
+ }
1962
+ paths = next;
1963
+ }
1964
+ return [];
1965
+ };
1966
+ /**
1967
+ * Preview: the units a release moves that the person did not pick. changesets moves a unit whenever
1968
+ * a workspace package it uses moves, so it cannot stay behind; this says through which package.
1969
+ */
1970
+ const draggedUnits = (plan, dependencies, units, scope) => {
1971
+ const moving = new Set(plan.releases.map(({ name }) => name));
1972
+ const named = new Set(plan.releases.filter(({ changesets }) => changesets.length > 0).map(({ name }) => name));
1973
+ const picked = units.filter(({ name }) => scope.has(name));
1974
+ return units.flatMap(({ name: app, packageName }) => {
1975
+ const release = plan.releases.find(({ name }) => name === packageName);
1976
+ if (scope.has(app) || !release) return [];
1977
+ const chain = chainTo(packageName, dependencies, moving, named);
1978
+ const source = chain[chain.length - 1];
1979
+ const movers = picked.filter((unit) => plan.changesets.some(({ releases }) => releases.some(({ name }) => name === source) && releases.some(({ name }) => name === unit.packageName))).map(({ name }) => name);
1980
+ const whose = movers.length > 0 ? `${movers.join(", ")}'s changes move` : "this release moves";
1981
+ return [{
1982
+ app,
1983
+ version: release.newVersion,
1984
+ with: movers,
1985
+ why: chain.length > 0 ? `uses ${chain.join(" → ")}, which ${whose}` : "moves with this release"
1986
+ }];
1987
+ });
1988
+ };
1989
+ const OWN_CHANGE = /^- ([0-9a-f]{7,40}): /gm;
1990
+ const DEPENDENCY_CHANGES = /^- Updated dependencies \[([^\]]+)\]/gm;
1991
+ /** The changes a version carries: its own, and those a package it uses moved for. */
1992
+ const changeIds = (notes) => new Set([...[...notes.matchAll(OWN_CHANGE)].flatMap(([, id]) => id ? [id] : []), ...[...notes.matchAll(DEPENDENCY_CHANGES)].flatMap(([, ids]) => (ids ?? "").split(",").map((id) => id.trim()))]);
1993
+ /** A change's first line in these notes, with an ellipsis when it goes on. */
1994
+ const summaryOf = (notes, id) => {
1995
+ const lines = notes.split("\n");
1996
+ const index = lines.findIndex((line) => line.startsWith(`- ${id}: `));
1997
+ const first = lines[index]?.slice(`- ${id}: `.length).trim();
1998
+ if (index < 0 || !first) return null;
1999
+ return /^ {2}\S/.test(lines[index + 1] ?? "") ? `${first}…` : first;
2000
+ };
2001
+ /** The packages listed under the `Updated dependencies` line that names this change. */
2002
+ const packagesMovedFor = (notes, id) => {
2003
+ const lines = notes.split("\n");
2004
+ const start = lines.findIndex((line) => line.startsWith("- Updated dependencies [") && line.includes(id));
2005
+ if (start < 0) return [];
2006
+ const listed = lines.slice(start + 1);
2007
+ const end = listed.findIndex((line) => !/^ {2}- \S+@/.test(line));
2008
+ return (end < 0 ? listed : listed.slice(0, end)).map((line) => line.trim().slice(2).replace(/@[^@]*$/, ""));
2009
+ };
2010
+ /** Why two versions went out together: the change they share, or the package both moved for. */
2011
+ const sharedReason = (partner, other, id) => {
2012
+ const summary = summaryOf(partner.notes, id) ?? summaryOf(other.notes, id);
2013
+ if (summary) return ` for: ${summary}`;
2014
+ const theirs = new Set(packagesMovedFor(partner.notes, id));
2015
+ const both = packagesMovedFor(other.notes, id).filter((name) => theirs.has(name));
2016
+ return both.length > 0 ? `: both use ${both.join(", ")}, which moved` : "";
2017
+ };
2018
+ /**
2019
+ * Production: the units preview runs with the picked ones that are not picked. Two versions went to
2020
+ * preview together when their notes share a change, their own or one a package they use moved for.
2021
+ */
2022
+ const releasedTogether = (picked, others) => others.flatMap((other) => {
2023
+ const ids = changeIds(other.notes);
2024
+ const partners = picked.flatMap((partner) => {
2025
+ const shared = [...changeIds(partner.notes)].find((id) => ids.has(id));
2026
+ return shared ? [{
2027
+ partner,
2028
+ shared
2029
+ }] : [];
2030
+ });
2031
+ const [first] = partners;
2032
+ if (!first) return [];
2033
+ const names = partners.map(({ partner }) => `${partner.app} ${partner.version}`).join(", ");
2034
+ return [{
2035
+ app: other.app,
2036
+ version: other.version,
2037
+ with: partners.map(({ partner }) => partner.app),
2038
+ why: `went to preview with ${names}${sharedReason(first.partner, other, first.shared)}`
2039
+ }];
2040
+ });
2041
+ //#endregion
2042
+ //#region src/application/prepareRelease.ts
2043
+ const NOTHING_HELD = {
2044
+ ships: [],
2045
+ waits: []
2046
+ };
2047
+ /** The person's answer to a plugin's choice; the suggestion without a terminal or with --yes. */
2048
+ const choose = async ({ prompter, options }, choice) => {
2049
+ if (!choice) return null;
2050
+ if (options.yes || !prompter.interactive) return choice.suggested;
2051
+ return prompter.select(choice.question, choice.options, choice.suggested);
2052
+ };
2053
+ /** What each picked unit's plugin adds, given the unit's bump so far. One at a time: it may ask. */
2054
+ const contributionsOf = async (context, scope, bumps) => {
2055
+ const { head } = await context.services.sourceControl.position();
2056
+ const contributions = {};
2057
+ for (const unit of context.release.units.filter(({ name }) => scope.has(name))) {
2058
+ const module = moduleOf(context, unit);
2059
+ const version = module?.version?.bind(module);
2060
+ if (!module || !version) continue;
2061
+ const input = jobInput(context, module, unit, {
2062
+ tag: tagName(unit.name, unit.version, context.release.tagFormat),
2063
+ environment: "preview",
2064
+ commit: head
2065
+ });
2066
+ const bump = bumps.find(({ app }) => app === unit.name);
2067
+ const contribute = (chosen) => version(decideContext(context), {
2068
+ ...input,
2069
+ bump,
2070
+ chosen
2071
+ });
2072
+ const suggested = await contribute();
2073
+ const chosen = await choose(context, suggested.choice);
2074
+ contributions[unit.name] = chosen && chosen !== suggested.choice?.suggested ? await contribute(chosen) : suggested;
2075
+ }
2076
+ return contributions;
2077
+ };
2078
+ /** What a release PR covering `scope` would version, computed without writing anything. */
2079
+ const prepareRelease = async (context, scope) => {
2080
+ const { release, services } = context;
2081
+ const refs = unitRefs(release.units);
2082
+ const [dependencies, named, base, pendingFiles] = await Promise.all([
2083
+ services.versioning.dependencies(),
2084
+ namedUnits(context),
2085
+ services.versioning.plan([], []),
2086
+ services.versioning.pending()
2087
+ ]);
2088
+ const baseBumps = appBumps(base, dependencies, refs);
2089
+ const unreleased = await findUnreleased(context, new Set([...named, ...baseBumps.map(({ app }) => app)]));
2090
+ const held = [...named].filter((app) => !scope.has(app));
2091
+ const adopted = unreleased.filter(({ app }) => scope.has(app)).flatMap(({ app, version, commits }) => {
2092
+ const ref = refs.find(({ name }) => name === app);
2093
+ return ref ? unreleasedChangesets(ref, version, commits) : [];
2094
+ });
2095
+ const split = held.length > 0 ? splitChangesets(base.changesets, held, refs) : NOTHING_HELD;
2096
+ const picked = held.length > 0 || adopted.length > 0 ? await services.versioning.plan(adopted, split.waits) : base;
2097
+ const contributions = await contributionsOf(context, scope, appBumps(picked, dependencies, refs));
2098
+ const contributed = Object.values(contributions).flatMap(({ added }) => added);
2099
+ const added = [...adopted, ...contributed];
2100
+ const plan = contributed.length > 0 ? await services.versioning.plan(added, split.waits) : picked;
2101
+ return {
2102
+ pending: (held.length > 0 ? split.ships.length : pendingFiles.length) + added.length,
2103
+ held,
2104
+ unreleased: unreleased.filter(({ app }) => !scope.has(app)),
2105
+ split,
2106
+ bumps: appBumps(plan, dependencies, refs),
2107
+ companions: draggedUnits(plan, dependencies, refs, scope),
2108
+ packages: packageBumps(plan, refs),
2109
+ added,
2110
+ shipped: plan.changesets,
2111
+ contributions
2112
+ };
2113
+ };
2114
+ //#endregion
2115
+ //#region src/application/askPath.ts
2116
+ const PATH_LABEL = {
2117
+ github: "GitHub Actions",
2118
+ local: "this machine"
2119
+ };
2120
+ /** The minutes block above the question: status, what is left, this release shaded in, the pace. */
2121
+ const showMinutes = ({ output, clock }, budget, estimate) => {
2122
+ const drawn = minutesBudget(budget, clock.now(), 30, estimate.total);
2123
+ output.line();
2124
+ output.line(` ${paint("bold", drawn.title)} ${paint(["bold", drawn.tone], drawn.status)}`);
2125
+ output.line(` ${paint(drawn.tone, drawn.bar)} ${paint(["bold", drawn.tone], drawn.amount)}`);
2126
+ if (drawn.after) {
2127
+ output.line(` ${drawn.after}`);
2128
+ const each = estimate.lines.map(({ app, minutes, measured }) => `${app} ~${minutes} ${measured ? "(its last runs)" : "(typical, no run yet)"}`);
2129
+ output.line(` ${paint("dim", ` ${each.join(" · ")}`)}`);
2130
+ }
2131
+ output.line(` ${paint("dim", drawn.pace)}`);
2132
+ output.line();
2133
+ };
2134
+ /**
2135
+ * How each unit ships, asked one by one with this month's Actions minutes shown once: GitHub Actions
2136
+ * or this machine, in the order given. Null when cancelled or without a terminal to ask.
2137
+ */
2138
+ const askPaths = async (context, environment, shipments) => {
2139
+ const { services, prompter, clock } = context;
2140
+ const measured = Object.fromEntries(await Promise.all(shipments.map(async ({ item, workflows }) => [item.app, (await Promise.all(workflows.map((workflow) => services.ciPipeline.measuredMinutes(workflow)))).flat()])));
2141
+ const typical = Object.fromEntries(shipments.flatMap(({ item, typicalMinutes }) => typicalMinutes === void 0 ? [] : [[item.app, typicalMinutes]]));
2142
+ const estimate = deployEstimate(shipments.map(({ item }) => item), measured, typical);
2143
+ const budget = await services.ciPipeline.minutes();
2144
+ if (budget) showMinutes(context, budget, estimate);
2145
+ if (!prompter.interactive) {
2146
+ fail(context, "Not a terminal", "say how to ship.", ["shiplane ship --via github", "shiplane ship --via local"]);
2147
+ return null;
2148
+ }
2149
+ const low = budget !== null && minutesBudget(budget, clock.now(), 30, estimate.total).tone === "red";
2150
+ const paths = [];
2151
+ for (const { item } of shipments) {
2152
+ const minutes = estimate.lines.find(({ app }) => app === item.app)?.minutes;
2153
+ const path = await prompter.select(`How should ${item.tag} ship to ${environment}?`, [{
2154
+ value: "github",
2155
+ label: PATH_LABEL.github,
2156
+ hint: budget ? `runs on GitHub from its tag, about ${minutes} of ${budget.left.toLocaleString("en-US")} minutes left` : "its workflow runs on GitHub, from its tag"
2157
+ }, {
2158
+ value: "local",
2159
+ label: PATH_LABEL.local,
2160
+ hint: "the same commands, run here: no Actions minutes"
2161
+ }], low ? "local" : "github");
2162
+ if (!path) return null;
2163
+ paths.push(path);
2164
+ }
2165
+ return paths;
2166
+ };
2167
+ //#endregion
2168
+ //#region src/application/waitForMerge.ts
2169
+ const POLL_MS = 15e3;
2170
+ const KEYS = [
2171
+ "d",
2172
+ "m",
2173
+ "o"
2174
+ ];
2175
+ /** Merges the pull request with the method the person picks. GitHub refuses approving your own PR. */
2176
+ const mergeHere = async (context, pr) => {
2177
+ const { choices, initial } = mergeChoices(await context.services.codeHost.mergeMethods());
2178
+ if (choices.length === 0) {
2179
+ fail(context, "No merge method", "the repository allows none: merge it on GitHub.");
2180
+ return;
2181
+ }
2182
+ const method = await context.prompter.select(`Merge #${pr.number} into main?`, [...choices, {
2183
+ value: "no",
2184
+ label: "Not now"
2185
+ }], initial);
2186
+ if (!method || method === "no") {
2187
+ context.output.line(paint("dim", " Not merged."));
2188
+ return;
2189
+ }
2190
+ await context.services.codeHost.merge(pr, method);
2191
+ };
2192
+ const ACTIONS = {
2193
+ diff: (context, pr) => context.services.codeHost.showDiff(pr),
2194
+ merge: mergeHere,
2195
+ open: (context, pr) => context.services.codeHost.openInBrowser(pr)
2196
+ };
2197
+ /**
2198
+ * True once merged, false when closed without a merge. It polls the host; in a terminal the person
2199
+ * can also read the diff (d), merge from here (m) or open it in the browser (o).
2200
+ */
2201
+ const waitForMerge = async (context, pr) => {
2202
+ const { output, prompter, services } = context;
2203
+ output.line(` ${paint("green", "✓")} Release PR ${paint("cyan", pr.url)}`);
2204
+ output.line(paint("dim", " Review and merge it here or on GitHub; this carries on by itself once merged."));
2205
+ if (prompter.interactive) output.line(` ${paint("cyan", "d")} ${paint("dim", "see the diff")} ${paint("cyan", "m")} ${paint("dim", "merge it from here")} ${paint("cyan", "o")} ${paint("dim", "open it on GitHub")} ${paint("cyan", "Ctrl-C")} ${paint("dim", "stop, release picks up here")}`);
2206
+ output.line();
2207
+ for (;;) {
2208
+ const state = await services.codeHost.prState(pr).catch(() => "OPEN");
2209
+ if (state !== "OPEN") return state === "MERGED";
2210
+ const action = waitKey(await prompter.waitForKey(`Waiting for #${pr.number} to merge`, POLL_MS, prompter.interactive ? KEYS : []) ?? void 0);
2211
+ if (action) await ACTIONS[action](context, pr);
2212
+ }
2213
+ };
2214
+ //#endregion
2215
+ //#region src/application/pullRequestFirst.ts
2216
+ /**
2217
+ * A small PR a plugin needs merged before it ships, such as production's version moving: branch,
2218
+ * write, commit, push, open, back to main, wait for the merge, pull. `declined` when the person
2219
+ * said no.
2220
+ */
2221
+ const pullRequestFirst = async (context, request) => {
2222
+ const { output, services } = context;
2223
+ if (!await confirm(context, request.question)) {
2224
+ output.line(paint("dim", " Not now."));
2225
+ return "declined";
2226
+ }
2227
+ const created = {};
2228
+ const opened = await runSteps(context, [
2229
+ branchStep(context, request.branch),
2230
+ {
2231
+ label: `commit "${request.title}"`,
2232
+ run: async () => {
2233
+ await request.write();
2234
+ for (const changeset of request.changesets) await services.versioning.write(changeset);
2235
+ await services.sourceControl.commit(await services.sourceControl.changedFiles(), request.title);
2236
+ }
2237
+ },
2238
+ pushStep(context, request.branch),
2239
+ openPrStep(context, "open the pull request", async () => {
2240
+ created.pr = await services.codeHost.createPr({
2241
+ base: "main",
2242
+ head: request.branch,
2243
+ title: request.title,
2244
+ body: request.body,
2245
+ label: "type: chore"
2246
+ });
2247
+ return created.pr;
2248
+ }),
2249
+ {
2250
+ label: "back to main",
2251
+ run: () => services.sourceControl.switchTo("main")
2252
+ }
2253
+ ]);
2254
+ const { pr } = created;
2255
+ if (!opened || !pr) return "failed";
2256
+ output.line();
2257
+ if (!await waitForMerge(context, pr)) {
2258
+ fail(context, `#${pr.number} was closed without a merge`, "nothing shipped.", ["shiplane"]);
2259
+ return "failed";
2260
+ }
2261
+ return await runSteps(context, [{
2262
+ label: "pull main",
2263
+ run: () => services.sourceControl.pull()
2264
+ }]) ? "merged" : "failed";
2265
+ };
2266
+ //#endregion
2267
+ //#region src/application/ship.ts
2268
+ /** Builds and submits run on their own platform: a build asks only when a workflow can start it. */
2269
+ const choosesPath = ({ kind, jobs }) => kind === "update" || kind === "deploy" || kind === "build" && jobs.every(({ ci }) => ci);
2270
+ const WEB_STATUS = {
2271
+ deploying: "deploying already",
2272
+ shipped: "already there",
2273
+ "not-on-preview": "not on preview yet: ship it there first"
2274
+ };
2275
+ /** A web unit decides from GitHub Deployments, which a ship records once it rolled out. */
2276
+ const webDecision = (context, module, input, history) => {
2277
+ const { jobs } = shipPlanOf(context, module, input);
2278
+ const ship = webShip({
2279
+ environment: input.environment,
2280
+ run: deployedOn(history, input.tag, input.environment),
2281
+ onPreview: deployedOn(history, input.tag, "preview") === "done"
2282
+ });
2283
+ return ship === "deploy" ? {
2284
+ action: "ship",
2285
+ kind: "deploy",
2286
+ jobs
2287
+ } : {
2288
+ action: "none",
2289
+ status: WEB_STATUS[ship]
2290
+ };
2291
+ };
2292
+ /** Where a choice stands, then the person's pick: its jobs ship, or nothing does and it is held. */
2293
+ const chosen = async (context, choice) => {
2294
+ const { output, prompter } = context;
2295
+ output.line();
2296
+ choice.lines.forEach((line) => output.line(` ${line}`));
2297
+ output.line();
2298
+ const value = prompter.interactive ? await prompter.select(choice.question, choice.options.map(({ value, label, hint, disabled }) => ({
2299
+ value,
2300
+ label,
2301
+ hint,
2302
+ disabled
2303
+ })), choice.suggested) : null;
2304
+ const jobs = choice.options.find((option) => option.value === value)?.jobs ?? [];
2305
+ return jobs.length > 0 ? {
2306
+ action: "ship",
2307
+ kind: "update",
2308
+ jobs
2309
+ } : {
2310
+ action: "none",
2311
+ status: choice.held
2312
+ };
2313
+ };
2314
+ /**
2315
+ * What every picked unit needs on the environment, in dispatch order, said as it goes. A module may
2316
+ * first need a small PR merged (a version moving): it opens, merges, and the module decides again.
2317
+ * Null when one of them refused.
2318
+ */
2319
+ const decideAll = async (context, environment, scope) => {
2320
+ const { release, services, output } = context;
2321
+ const recorded = await services.codeHost.deployments().catch(() => []);
2322
+ const ready = [];
2323
+ for (const unit of release.units) {
2324
+ const module = moduleOf(context, unit);
2325
+ if (scope && !scope.has(unit.name) || !module) continue;
2326
+ const tag = tagName(unit.name, unit.version, context.release.tagFormat);
2327
+ if (!module.decide && !await services.sourceControl.tagCommit(tag)) continue;
2328
+ const decide = async () => {
2329
+ const { head } = await services.sourceControl.position();
2330
+ const input = jobInput(context, module, unit, {
2331
+ tag,
2332
+ environment,
2333
+ commit: head
2334
+ });
2335
+ return {
2336
+ input,
2337
+ decision: module.decide ? await module.decide(decideContext(context), input) : webDecision(context, module, input, recorded)
2338
+ };
2339
+ };
2340
+ let { input, decision } = await context.progress.during(`Checking what ${tag} needs on ${environment}`, "thinking", decide);
2341
+ while (decision.action === "pull-request") {
2342
+ const merged = await pullRequestFirst(context, decision);
2343
+ if (merged === "failed") return null;
2344
+ if (merged === "declined") {
2345
+ decision = {
2346
+ action: "none",
2347
+ status: "left for later"
2348
+ };
2349
+ break;
2350
+ }
2351
+ ({input, decision} = await decide());
2352
+ }
2353
+ if (decision.action === "choose") decision = await chosen(context, decision);
2354
+ if (decision.action === "fail") {
2355
+ fail(context, decision.title, decision.detail, decision.commands);
2356
+ return null;
2357
+ }
2358
+ if (decision.action === "none") {
2359
+ output.line(` ${paint("dim", "·")} ${tag} ${paint("dim", decision.status)}`);
2360
+ continue;
2361
+ }
2362
+ ready.push({
2363
+ unit,
2364
+ module,
2365
+ input,
2366
+ kind: decision.kind,
2367
+ jobs: decision.jobs,
2368
+ decided: module.decide !== void 0,
2369
+ notLocal: decision.notLocal ?? null
2370
+ });
2371
+ }
2372
+ return ready;
2373
+ };
2374
+ /** Why a path cannot ship a unit, or null when it can. */
2375
+ const blockedOn = async (context, path, { input, jobs, decided, notLocal }) => {
2376
+ const { services } = context;
2377
+ if (path === "github") {
2378
+ const workflow = services.ciPipeline.shipWorkflow;
2379
+ for (const { ci } of jobs) {
2380
+ if (!ci) return "only ships from this machine";
2381
+ const file = `.github/workflows/${workflow}`;
2382
+ if (await services.sourceControl.fileAt(ci.ref, file) !== null) continue;
2383
+ return ci.ref !== "main" && await services.sourceControl.fileAt("main", file) !== null ? `predates ${workflow}` : `no ${workflow}`;
2384
+ }
2385
+ return null;
2386
+ }
2387
+ if (decided) return notLocal;
2388
+ return shipsFrom(path, { sinceTagOnlyVersionFiles: onlyVersionFiles(await services.sourceControl.diffNames(input.tag, "HEAD"), versionFiles(context)) }) ? null : "main moved past it";
2389
+ };
2390
+ const OTHER_PATH = {
2391
+ github: "local",
2392
+ local: "github"
2393
+ };
2394
+ /** What to do instead, when the path a person forced cannot ship a unit. */
2395
+ const INSTEAD = {
2396
+ github: "ship it from this machine",
2397
+ local: "this machine builds its checkout, ship it through GitHub Actions"
2398
+ };
2399
+ const TAKES = {
2400
+ github: "ships through GitHub Actions",
2401
+ local: "ships from this machine"
2402
+ };
2403
+ /**
2404
+ * The way a unit ships: the forced one when it can, the only one left when the other cannot, or
2405
+ * asked. Said whenever it is not asked.
2406
+ */
2407
+ const routeOf = async (context, entry, forced) => {
2408
+ const say = (mark, why) => context.output.line(` ${mark} ${entry.input.tag} ${paint("dim", why)}`);
2409
+ if (forced) {
2410
+ const why = await blockedOn(context, forced, entry);
2411
+ if (!why) return forced;
2412
+ say(paint("yellow", "!"), `${why}: ${INSTEAD[forced]}`);
2413
+ return "skip";
2414
+ }
2415
+ const github = await blockedOn(context, "github", entry);
2416
+ const local = await blockedOn(context, "local", entry);
2417
+ if (github && local) {
2418
+ say(paint("red", "✗"), `${github}, and ${local}: nothing can ship it`);
2419
+ return "stuck";
2420
+ }
2421
+ const blocked = github ? "github" : local ? "local" : null;
2422
+ if (!blocked) return "ask";
2423
+ say(paint("dim", "·"), `${github ?? local}: ${TAKES[OTHER_PATH[blocked]]}`);
2424
+ return OTHER_PATH[blocked];
2425
+ };
2426
+ const shipmentOf = (shipWorkflow) => ({ unit, module, input, jobs }) => ({
2427
+ item: {
2428
+ app: unit.name,
2429
+ tag: input.tag,
2430
+ kind: "deploy"
2431
+ },
2432
+ workflows: jobs.some(({ ci }) => ci) ? [shipWorkflow] : [],
2433
+ typicalMinutes: module.typicalMinutes
2434
+ });
2435
+ /**
2436
+ * The ship workflow's runs: one per ref, each naming its units. A tag on main's commit runs from
2437
+ * main, so a release whose tags all sit there costs one run.
2438
+ */
2439
+ const shipRuns = async ({ services }, entries) => {
2440
+ const { originMain } = await services.sourceControl.position();
2441
+ const runs = /* @__PURE__ */ new Map();
2442
+ for (const { unit, jobs } of entries) for (const { ci } of jobs) {
2443
+ if (!ci) continue;
2444
+ const ref = (ci.ref === "main" ? originMain : await services.sourceControl.tagCommit(ci.ref)) === originMain ? "main" : ci.ref;
2445
+ const units = runs.get(ref) ?? [];
2446
+ if (!units.includes(unit.name)) runs.set(ref, [...units, unit.name]);
2447
+ }
2448
+ return [...runs.entries()].map(([ref, units]) => ({
2449
+ ref,
2450
+ units
2451
+ }));
2452
+ };
2453
+ /** `Ship a through GitHub Actions`, or each tag with its way when they differ. */
2454
+ const shipQuestion = (going, paths, environment, context) => {
2455
+ const label = environmentLabel(context, going.map(({ unit }) => unit.name), environment);
2456
+ const used = [...new Set(going.flatMap((entry) => paths.get(entry) ?? []))];
2457
+ const [only] = used;
2458
+ const names = going.map((entry) => {
2459
+ const path = paths.get(entry);
2460
+ return used.length > 1 && path ? `${entry.input.tag} (${PATH_LABEL[path]})` : entry.input.tag;
2461
+ }).join(", ");
2462
+ const how = used.length === 1 && only ? ` through ${PATH_LABEL[only]}` : "";
2463
+ return `Ship ${names} ${label === "live" ? "live" : `to ${label}`}${how}?`;
2464
+ };
2465
+ /**
2466
+ * Ships every picked unit its environment does not run yet, and returns once each one is
2467
+ * triggered: EAS builds and workflows go on on their own, a Fly deploy from here once rolled out.
2468
+ * Production asks for its name first. False on a failure.
2469
+ */
2470
+ const shipTo = async (context, environment, { scope, via }) => {
2471
+ const { output, prompter, options, services } = context;
2472
+ if (environment === "production" && !options.ci) {
2473
+ if (options.yes) {
2474
+ fail(context, "No --yes on production", "every production step asks a person.", ["shiplane ship --channel production"]);
2475
+ return false;
2476
+ }
2477
+ if (!await prompter.typed("Type \"production\" to start:", "production")) {
2478
+ output.line(paint("dim", "Nothing ran."));
2479
+ return false;
2480
+ }
2481
+ }
2482
+ const ready = await decideAll(context, environment, scope);
2483
+ if (!ready) return false;
2484
+ if (ready.length === 0) {
2485
+ context.progress.say("resting", paint("dim", `Nothing to ship to ${environment}.`));
2486
+ return true;
2487
+ }
2488
+ const forced = options.ci ? "local" : via;
2489
+ const paths = /* @__PURE__ */ new Map();
2490
+ const unanswered = [];
2491
+ let stuck = false;
2492
+ for (const entry of ready.filter(choosesPath)) {
2493
+ const route = await routeOf(context, entry, forced);
2494
+ if (route === "ask") unanswered.push(entry);
2495
+ else if (route === "stuck") stuck = true;
2496
+ else if (route !== "skip") paths.set(entry, route);
2497
+ }
2498
+ if (unanswered.length > 0) {
2499
+ const answers = await askPaths(context, environment, unanswered.map(shipmentOf(services.ciPipeline.shipWorkflow)));
2500
+ if (!answers) {
2501
+ output.line(paint("dim", " Nothing shipped."));
2502
+ return prompter.interactive;
2503
+ }
2504
+ unanswered.forEach((entry, index) => {
2505
+ const answer = answers[index];
2506
+ if (answer) paths.set(entry, answer);
2507
+ });
2508
+ }
2509
+ const going = ready.filter((entry) => !choosesPath(entry) || paths.has(entry));
2510
+ if (going.length === 0) return !stuck;
2511
+ if (going.some((entry) => paths.get(entry) === "local") && !await services.sourceControl.isClean()) {
2512
+ fail(context, "Uncommitted changes", "this machine ships its checkout: commit or stash them first.");
2513
+ return false;
2514
+ }
2515
+ if (!await confirm(context, shipQuestion(going, paths, environment, context), environment === "preview")) {
2516
+ if (environment === "preview" && prompter.interactive && await prompter.confirm("Ship to production instead?")) return shipTo(context, "production", {
2517
+ scope,
2518
+ via
2519
+ });
2520
+ context.progress.say("resting", paint("dim", "Nothing shipped."));
2521
+ return true;
2522
+ }
2523
+ const jobs = going.filter((entry) => paths.get(entry) !== "github").flatMap((entry) => entry.jobs.map((job) => ({
2524
+ entry,
2525
+ job
2526
+ })));
2527
+ const runs = await shipRuns(context, going.filter((entry) => paths.get(entry) === "github"));
2528
+ const total = jobs.length + runs.length;
2529
+ for (const [index, { entry, job }] of jobs.entries()) try {
2530
+ await context.progress.during(job.label, "working", () => runHere(context, job, entry.input), {
2531
+ index,
2532
+ total
2533
+ });
2534
+ } catch (error) {
2535
+ const reason = error instanceof Error ? error.message : String(error);
2536
+ fail(context, `${job.label} failed`, `${reason}, nothing after it ran.`);
2537
+ return false;
2538
+ }
2539
+ const workflow = services.ciPipeline.shipWorkflow;
2540
+ for (const [index, run] of runs.entries()) {
2541
+ const label = `ship ${run.units.join(", ")} from ${run.ref} (${workflow})`;
2542
+ try {
2543
+ await context.progress.during(label, "working", () => dispatchShip(context, run, environment), {
2544
+ index: jobs.length + index,
2545
+ total
2546
+ });
2547
+ } catch (error) {
2548
+ const reason = error instanceof Error ? error.message : String(error);
2549
+ fail(context, `${label} failed`, `${reason}, nothing after it ran.`);
2550
+ return false;
2551
+ }
2552
+ }
2553
+ const names = going.map(({ input }) => input.tag).join(", ");
2554
+ output.line();
2555
+ context.progress.say("happy", `${paint(["bold", "green"], "✓ Triggered.")} ${paint("dim", `${names}, shipping to ${environment} on their own.`)}`);
2556
+ await runFollowUps(context, going.map(({ unit, input }) => ({
2557
+ unit,
2558
+ tag: input.tag,
2559
+ environment
2560
+ })));
2561
+ if (runs.length > 0) output.line(` ${paint("cyan", "gh run list --limit 5")}`);
2562
+ output.line(` ${paint("cyan", `shiplane status --channel ${environment}`)}`);
2563
+ output.line();
2564
+ return !stuck;
2565
+ };
2566
+ //#endregion
2567
+ //#region src/application/promote.ts
2568
+ const STAGES$1 = ["What to promote", "Ship"];
2569
+ /** Each unit's version on preview with its notes, read from its tag. */
2570
+ const releasedVersions = async ({ release, services }, apps) => Promise.all(release.units.filter(({ name }) => apps.includes(name)).map(async ({ name, dir, version }) => {
2571
+ return {
2572
+ app: name,
2573
+ version,
2574
+ notes: changelogSection(await services.sourceControl.fileAt(tagName(name, version, release.tagFormat), services.versioning.changelogFile(dir)) ?? "", version)
2575
+ };
2576
+ }));
2577
+ /**
2578
+ * Which units production gets: the person's pick, plus what preview only ever ran with it when they
2579
+ * accept. Offered ticked with why, never added silently. Null when cancelled.
2580
+ */
2581
+ const pickPromotion = async (context) => {
2582
+ const { output } = context;
2583
+ const picked = await pickScope(context, "production");
2584
+ if (!picked || picked.scope.size === 0) return null;
2585
+ const left = scopeChoices(picked.info, "production").filter(({ app, pending }) => pending && !picked.scope.has(app)).map(({ app }) => app);
2586
+ if (left.length === 0) return picked.scope;
2587
+ const companions = await context.progress.during("Reading the notes of what preview runs, to see what went there together", "thinking", async () => releasedTogether(await releasedVersions(context, [...picked.scope]), await releasedVersions(context, left)));
2588
+ if (companions.length === 0) return picked.scope;
2589
+ const names = companions.map(({ app }) => app);
2590
+ const partners = [...new Set(companions.flatMap(({ with: partner }) => partner))];
2591
+ output.line();
2592
+ output.line(` ${paint(["bold", "yellow"], "!")} ${paint("bold", `Preview runs ${listed(names)} with what you picked:`)}`);
2593
+ companions.forEach(({ app, version, why }) => output.line(` ${app.padEnd(11)}${version.padEnd(10)}${paint("dim", why)}`));
2594
+ output.line();
2595
+ const versions = companions.map(({ app, version }) => `${app} ${version}`);
2596
+ const them = companions.length === 1 ? "it" : "them";
2597
+ if (await confirm(context, `Promote ${listed(versions)} too? Preview has only run ${them} with ${listed(partners)}.`, true)) return new Set([...picked.scope, ...names]);
2598
+ const promoted = picked.info.filter(({ app }) => partners.includes(app)).map(({ app, version }) => `${app} ${version}`);
2599
+ output.line(paint("dim", ` ${listed(names)} ${companions.length === 1 ? "stays" : "stay"} on preview: production runs ${listed(promoted)} next to the ${listed(names)} it has.`));
2600
+ return picked.scope;
2601
+ };
2602
+ /** How each picked unit does on preview, said; when one looks unwell, asks before going on. */
2603
+ const previewLooksWell = async (context, scope) => {
2604
+ const { output, release, services } = context;
2605
+ const { head } = await services.sourceControl.position();
2606
+ const healths = (await context.progress.during("Reading how preview runs what you picked", "thinking", () => Promise.all(release.units.filter(({ name }) => scope.has(name)).map(async (unit) => {
2607
+ const module = moduleOf(context, unit);
2608
+ if (!module?.health) return [];
2609
+ const tag = tagName(unit.name, unit.version, context.release.tagFormat);
2610
+ const input = jobInput(context, module, unit, {
2611
+ tag,
2612
+ environment: "preview",
2613
+ commit: head
2614
+ });
2615
+ const health = await module.health(decideContext(context), input).catch(() => null);
2616
+ return health ? [{
2617
+ tag,
2618
+ ...health
2619
+ }] : [];
2620
+ })))).flat();
2621
+ if (healths.length === 0) return true;
2622
+ output.line();
2623
+ healths.forEach(({ tag, ok, summary }) => output.line(` ${ok ? paint("green", "✓") : paint(["bold", "yellow"], "!")} ${tag.padEnd(18)}${paint("dim", summary)}`));
2624
+ output.line();
2625
+ const unwell = healths.filter(({ ok }) => !ok);
2626
+ if (unwell.length === 0) return true;
2627
+ return confirm(context, `Promote anyway? ${unwell.map(({ tag, why }) => `${tag}: ${why ?? "looks unwell"}`).join("; ")}.`, false);
2628
+ };
2629
+ /** Production, from what preview runs: every unit picked, its name typed, each step asked. */
2630
+ const promote = async (context, via) => {
2631
+ context.progress.stage(STAGES$1, 0);
2632
+ const scope = await pickPromotion(context);
2633
+ if (!scope) return true;
2634
+ if (!await previewLooksWell(context, scope)) {
2635
+ context.output.line(paint("dim", " Nothing promoted."));
2636
+ return true;
2637
+ }
2638
+ context.progress.stage(STAGES$1, 1);
2639
+ return shipTo(context, "production", {
2640
+ scope,
2641
+ via
2642
+ });
2643
+ };
2644
+ //#endregion
2645
+ //#region src/application/tagRelease.ts
2646
+ /** The tags and release notes still missing for the versions merged release PRs brought. */
2647
+ const missingTags = async (context) => {
2648
+ const { release, services } = context;
2649
+ const [tags, notes, named] = await Promise.all([
2650
+ services.sourceControl.tags(),
2651
+ services.codeHost.releasedTags().catch(() => /* @__PURE__ */ new Set()),
2652
+ namedUnits(context)
2653
+ ]);
2654
+ return releaseTags((await Promise.all(release.units.map(async ({ name, dir, version }) => {
2655
+ const commit = await services.sourceControl.versionCommit(dir, MANIFEST, version);
2656
+ const first = !named.has(name) && firstRelease(name, version, tags, release.tagFormat);
2657
+ return commit ? [{
2658
+ app: name,
2659
+ version,
2660
+ commit,
2661
+ first
2662
+ }] : [];
2663
+ }))).flat(), tags, notes, release.tagFormat);
2664
+ };
2665
+ const notesFor = async ({ release, services }, tag) => {
2666
+ const unit = release.units.find(({ name }) => name === tag.app);
2667
+ return changelogSection((unit ? await services.sourceControl.fileAt(tag.sha, services.versioning.changelogFile(unit.dir)) : null) ?? "", tag.version);
2668
+ };
2669
+ /** Tags each version on the commit that brought it, pushes the tags, publishes their notes. */
2670
+ const tagRelease = async (context, tags) => {
2671
+ if (tags.length === 0) return true;
2672
+ const { output, release, services } = context;
2673
+ const names = tags.map(({ tag }) => tag).join(", ");
2674
+ output.line(` ${paint("bold", "Tags and release notes")} ${paint("dim", names)}`);
2675
+ if (!await confirm(context, `Tag ${names} and publish their release notes?`, true)) {
2676
+ output.line(paint("dim", "Nothing ran."));
2677
+ return false;
2678
+ }
2679
+ const created = tags.filter(({ needsTag }) => needsTag);
2680
+ return runSteps(context, [
2681
+ ...created.map((tag) => ({
2682
+ label: `tag ${tag.tag} on ${tag.sha.slice(0, 7)}`,
2683
+ run: async () => services.sourceControl.tag(tag.tag, tag.sha, `${tag.tag}\n\n${await notesFor(context, tag)}`),
2684
+ undo: {
2685
+ label: `delete the tag ${tag.tag} here`,
2686
+ run: () => services.sourceControl.deleteTag(tag.tag),
2687
+ byHand: () => [`git tag --delete ${tag.tag}`]
2688
+ }
2689
+ })),
2690
+ ...created.length > 0 ? [{
2691
+ label: "push the tags",
2692
+ run: () => services.sourceControl.pushTags(created.map(({ tag }) => tag)),
2693
+ kept: {
2694
+ label: `${created.map(({ tag }) => tag).join(", ")} ${created.length > 1 ? "stay" : "stays"} on origin`,
2695
+ byHand: () => ["shiplane tag"]
2696
+ }
2697
+ }] : [],
2698
+ ...tags.filter(({ needsNotes }) => needsNotes).map((tag) => ({
2699
+ label: `release notes for ${tag.tag}`,
2700
+ run: async () => services.codeHost.createRelease(tag.tag, await notesFor(context, tag), tag.app === release.units[0]?.name)
2701
+ }))
2702
+ ]);
2703
+ };
2704
+ //#endregion
2705
+ //#region src/application/releaseToPreview.ts
2706
+ const STAGES = [
2707
+ "What to release",
2708
+ "Versions",
2709
+ "Release PR",
2710
+ "Merge",
2711
+ "Tags",
2712
+ "Ship"
2713
+ ];
2714
+ /**
2715
+ * `release` on preview: the release PR, the wait for its merge, the tags, then the ship. It reads where things
2716
+ * stand first, so a run stopped anywhere picks up where it left off. False when something failed.
2717
+ */
2718
+ const releaseToPreview = async (context) => {
2719
+ const { output, services, progress } = context;
2720
+ const stage = (name) => progress.stage(STAGES, STAGES.indexOf(name));
2721
+ stage("What to release");
2722
+ const picked = await pickScope(context, "preview");
2723
+ if (!picked || picked.scope.size === 0) {
2724
+ progress.say("resting", paint("dim", "Nothing ran."));
2725
+ return true;
2726
+ }
2727
+ if (!await preflight(context, picked.scope)) return false;
2728
+ const covered = picked.info.filter(({ app }) => picked.scope.has(app));
2729
+ const [releasePrs, missing] = await progress.during("Looking for an open release PR and versions not tagged yet", "thinking", () => Promise.all([services.codeHost.openPrsFrom(RELEASE_BRANCH_PREFIX), missingTags(context)]));
2730
+ const step = nextStep({
2731
+ pending: covered.reduce((sum, { changesets }) => sum + changesets, 0),
2732
+ releasePrs,
2733
+ untagged: missing.length,
2734
+ unreleased: covered.filter(({ changesets, commits }) => changesets === 0 && commits > 0).length
2735
+ });
2736
+ let prs = [];
2737
+ let current = context;
2738
+ if (step.step === "release-pr") {
2739
+ stage("Versions");
2740
+ const prepared = await progress.during("Planning each app's version with changesets, and what its target ships", "thinking", () => prepareRelease(context, picked.scope));
2741
+ if (prepared.bumps.length === 0 && prepared.packages === 0) {
2742
+ printSummary(context, prepared);
2743
+ output.line(paint("dim", " Nothing to version for these units: the others wait for a later release."));
2744
+ return true;
2745
+ }
2746
+ stage("Release PR");
2747
+ const opened = await openReleasePr(context, prepared);
2748
+ if (!opened) return false;
2749
+ prs = opened;
2750
+ } else if (step.step === "wait-merge") prs = step.prs;
2751
+ if (prs.length > 0) stage("Merge");
2752
+ for (const pr of prs) {
2753
+ output.line();
2754
+ if (!await waitForMerge(context, pr)) {
2755
+ fail(context, `#${pr.number} was closed without a merge`, "nothing shipped.", ["shiplane"]);
2756
+ return false;
2757
+ }
2758
+ progress.say("happy", `${paint("green", "✓")} Release PR #${pr.number} merged`);
2759
+ }
2760
+ if (prs.length > 0) {
2761
+ if (!await runSteps(context, [{
2762
+ label: "switch to main",
2763
+ run: () => services.sourceControl.switchTo("main")
2764
+ }, {
2765
+ label: "pull main",
2766
+ run: () => services.sourceControl.pull()
2767
+ }])) return false;
2768
+ current = {
2769
+ ...context,
2770
+ release: await context.load()
2771
+ };
2772
+ }
2773
+ const tags = prs.length > 0 ? await missingTags(current) : missing;
2774
+ if (tags.length > 0) stage("Tags");
2775
+ if (!await tagRelease(current, tags)) return false;
2776
+ stage("Ship");
2777
+ return shipTo(current, "preview", { scope: new Set([...picked.scope, ...tags.map(({ app }) => app)]) });
2778
+ };
2779
+ //#endregion
2780
+ //#region src/adapters/terminal/live-line.ts
2781
+ const CLEAR = "\r\x1B[2K";
2782
+ const TICK_MS = 140;
2783
+ /**
2784
+ * The one line the release redraws in place: the mascot and what runs. Anything else printed goes
2785
+ * above it, and a prompt or a child process holds it so the terminal is theirs meanwhile.
2786
+ */
2787
+ var LiveLine = class {
2788
+ render = null;
2789
+ timer = null;
2790
+ tick = 0;
2791
+ held = 0;
2792
+ get busy() {
2793
+ return this.render !== null;
2794
+ }
2795
+ show(render, animate) {
2796
+ this.render = render;
2797
+ this.tick = 0;
2798
+ this.draw();
2799
+ if (animate) this.timer = setInterval(() => {
2800
+ this.tick += 1;
2801
+ this.draw();
2802
+ }, TICK_MS);
2803
+ }
2804
+ clear() {
2805
+ if (this.timer) clearInterval(this.timer);
2806
+ this.timer = null;
2807
+ if (this.render && this.held === 0) process.stdout.write(CLEAR);
2808
+ this.render = null;
2809
+ }
2810
+ /** Prints a line above the live one. */
2811
+ above(text) {
2812
+ if (this.render && this.held === 0) process.stdout.write(CLEAR);
2813
+ process.stdout.write(`${text}\n`);
2814
+ this.draw();
2815
+ }
2816
+ /** Gives the terminal to `work`, a prompt or a child process, then draws the live line again. */
2817
+ async hold(work) {
2818
+ if (this.render && this.held === 0) process.stdout.write(CLEAR);
2819
+ this.held += 1;
2820
+ try {
2821
+ return await work();
2822
+ } finally {
2823
+ this.held -= 1;
2824
+ this.draw();
2825
+ }
2826
+ }
2827
+ draw() {
2828
+ if (this.render && this.held === 0) process.stdout.write(`${CLEAR}${this.render(this.tick)}`);
2829
+ }
2830
+ };
2831
+ const liveLine = new LiveLine();
2832
+ //#endregion
2833
+ //#region src/adapters/shell/system-shell.adapter.ts
2834
+ const MAX_BUFFER = 256 * 1024 * 1024;
2835
+ const environment = (options) => ({
2836
+ ...process.env,
2837
+ ...options.env
2838
+ });
2839
+ const systemShell = {
2840
+ capture: (command, args, options = {}) => new Promise((resolve) => {
2841
+ const child = execFile(command, [...args], {
2842
+ cwd: options.cwd,
2843
+ env: environment(options),
2844
+ maxBuffer: MAX_BUFFER
2845
+ }, (error, stdout, stderr) => {
2846
+ const code = error?.code;
2847
+ resolve({
2848
+ status: !error ? 0 : typeof code === "number" ? code : code === "ENOENT" ? 127 : 1,
2849
+ stdout,
2850
+ stderr
2851
+ });
2852
+ });
2853
+ if (options.input !== void 0) child.stdin?.end(options.input);
2854
+ }),
2855
+ attach: (command, args, options = {}) => liveLine.hold(() => new Promise((resolve) => {
2856
+ const child = spawn(command, [...args], {
2857
+ cwd: options.cwd,
2858
+ env: environment(options),
2859
+ stdio: options.input === void 0 ? "inherit" : [
2860
+ "pipe",
2861
+ "inherit",
2862
+ "inherit"
2863
+ ]
2864
+ });
2865
+ if (options.input !== void 0) child.stdin?.end(options.input);
2866
+ child.on("error", () => resolve(127));
2867
+ child.on("close", (code) => resolve(code ?? 1));
2868
+ })),
2869
+ env: (name) => process.env[name]
2870
+ };
2871
+ //#endregion
2872
+ //#region src/application/readStatus.ts
2873
+ /** Where every unit stands on an environment, and the step a release takes next. Reads only. */
2874
+ const readStatus = async (context, environment) => {
2875
+ const info = await readScope(context, environment);
2876
+ const choices = scopeChoices(info, environment);
2877
+ const [releasePrs, untagged] = await Promise.all([context.services.codeHost.openPrsFrom(RELEASE_BRANCH_PREFIX).catch(() => []), missingTags(context)]);
2878
+ const { head } = await context.services.sourceControl.position();
2879
+ const live = async (name) => {
2880
+ const unit = context.release.units.find((candidate) => candidate.name === name);
2881
+ const module = unit && moduleOf(context, unit);
2882
+ if (!unit || !module?.inspect) return {};
2883
+ const input = jobInput(context, module, unit, {
2884
+ tag: tagName(unit.name, unit.version, context.release.tagFormat),
2885
+ environment,
2886
+ commit: head
2887
+ });
2888
+ return { live: await module.inspect(decideContext(context), input).catch((error) => ({ error: error instanceof Error ? error.message : String(error) })) };
2889
+ };
2890
+ return {
2891
+ environment,
2892
+ units: await Promise.all(info.map(async (entry) => {
2893
+ const choice = choices.find(({ app }) => app === entry.app);
2894
+ const unit = context.release.units.find(({ name }) => name === entry.app);
2895
+ return {
2896
+ unit: entry.app,
2897
+ target: (unit && moduleOf(context, unit)?.provider) ?? "",
2898
+ version: entry.version,
2899
+ tag: tagName(entry.app, entry.version, context.release.tagFormat),
2900
+ tagged: entry.tagged,
2901
+ changesets: entry.changesets,
2902
+ commits: entry.commits,
2903
+ pending: choice?.pending ?? false,
2904
+ hint: choice?.hint ?? "",
2905
+ ...await live(entry.app)
2906
+ };
2907
+ })),
2908
+ releasePrs,
2909
+ untagged,
2910
+ next: nextStep({
2911
+ pending: info.reduce((sum, { changesets }) => sum + changesets, 0),
2912
+ releasePrs,
2913
+ untagged: untagged.length,
2914
+ unreleased: info.filter(({ changesets, commits }) => changesets === 0 && commits > 0).length
2915
+ })
2916
+ };
2917
+ };
2918
+ //#endregion
2919
+ export { ENVIRONMENTS as C, optionsFor as S, nodeFiles as T, addUnit as _, missingTags as a, doctor as b, shipTo as c, pickScope as d, openReleasePr as f, loadRelease as g, findConfig as h, releaseToPreview as i, prepareRelease as l, docsFor as m, systemShell as n, tagRelease as o, newAdapter as p, liveLine as r, promote as s, readStatus as t, planShips as u, removeUnit as v, keysAt as w, refreshEditorSchema as x, initRelease as y };
2920
+
2921
+ //# sourceMappingURL=readStatus-D5YVR5ZC.js.map