shiplane 0.5.2 → 0.6.0-fix-shiplane-ship-node-cache.3dccda9
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.
- package/README.md +1 -1
- package/dist/cli.js +157 -312
- package/dist/cli.js.map +1 -1
- package/dist/{readStatus-DypM0faL.js → compose-BTQXZqHM.js} +2758 -1448
- package/dist/compose-BTQXZqHM.js.map +1 -0
- package/dist/{budget-BTnKtGF6.js → display-CfV4G1TR.js} +155 -52
- package/dist/display-CfV4G1TR.js.map +1 -0
- package/dist/{static-hosting.port-B5i6W7eD.d.ts → index-B1Rd22nM.d.ts} +482 -21
- package/dist/index.d.ts +2 -3
- package/dist/index.js +3 -4
- package/dist/{issues-TcWtMTv5.js → issues-DCRpXUBW.js} +1 -1
- package/dist/{issues-TcWtMTv5.js.map → issues-DCRpXUBW.js.map} +1 -1
- package/dist/memory.d.ts +1 -1
- package/dist/memory.js +1 -1
- package/dist/{package-registry.fake-BLBdd7IQ.d.ts → package-registry.fake-CjoePEzE.d.ts} +53 -6
- package/dist/{package-registry.fake-CN6M1-Gi.js → package-registry.fake-ykiSBd8M.js} +58 -6
- package/dist/package-registry.fake-ykiSBd8M.js.map +1 -0
- package/dist/plugin-D-JQhwVd.d.ts +118 -0
- package/dist/plugin.d.ts +3 -23
- package/dist/plugin.js +84 -7
- package/dist/plugin.js.map +1 -0
- package/dist/shell-server-hosting.adapter-CvOcC6Wh.js +369 -0
- package/dist/shell-server-hosting.adapter-CvOcC6Wh.js.map +1 -0
- package/dist/{src-DO7WyrfV.js → src-8BbKTQBb.js} +2 -2
- package/dist/src-8BbKTQBb.js.map +1 -0
- package/dist/testing.d.ts +103 -18
- package/dist/testing.js +235 -22
- package/dist/testing.js.map +1 -1
- package/package.json +2 -1
- package/dist/budget-BTnKtGF6.js.map +0 -1
- package/dist/display-IqkJ6uCw.js +0 -96
- package/dist/display-IqkJ6uCw.js.map +0 -1
- package/dist/index-C_urG4yY.d.ts +0 -252
- package/dist/package-registry.fake-CN6M1-Gi.js.map +0 -1
- package/dist/readStatus-DypM0faL.js.map +0 -1
- package/dist/shell-server-hosting.adapter-C7_5MWrl.js +0 -50
- package/dist/shell-server-hosting.adapter-C7_5MWrl.js.map +0 -1
- package/dist/src-DO7WyrfV.js.map +0 -1
- package/dist/web-app.module-BB1fY1Kd.js +0 -125
- package/dist/web-app.module-BB1fY1Kd.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compose-BTQXZqHM.js","names":["envVarNames","confirm","NAMES","configWrites","confirm","confirm","confirm","confirm","STAGES","confirm","sleep"],"sources":["../src/adapters/files/node-files.adapter.ts","../src/modules/suggest.ts","../src/application/config/problem.ts","../src/application/config/unitSchema.ts","../src/domain/environment.ts","../src/application/config/values.ts","../src/application/config/readUnitFile.ts","../src/application/say.ts","../src/application/callerWorkflow.ts","../src/application/releaseOrder.ts","../src/domain/codeScope.ts","../src/application/config/optionsFor.ts","../src/application/targets.ts","../src/application/unattended.ts","../src/application/checkEnvBeforeDeploy.ts","../src/application/reportEnvToCheck.ts","../src/application/requirements.ts","../src/application/manifest.ts","../src/application/setupFiles.ts","../src/application/doctor.ts","../src/application/initRelease.ts","../src/application/addUnit.ts","../src/domain/words.ts","../src/application/readScope.ts","../src/application/steps.ts","../src/application/branchPublish.ts","../src/domain/releasePr.ts","../src/domain/versionChoice.ts","../src/domain/companions.ts","../src/application/prepareRelease.ts","../src/application/chooseVersion.ts","../src/application/openReleasePr.ts","../src/domain/scope.ts","../src/application/pickScope.ts","../src/domain/prepare.ts","../src/domain/shipRoute.ts","../src/application/askPath.ts","../src/application/followUps.ts","../src/application/mapLimit.ts","../src/application/waitForMerge.ts","../src/application/pullRequestFirst.ts","../src/application/tagRelease.ts","../src/application/readStatus.ts","../src/application/shipSteps.ts","../src/application/ship.ts","../src/application/releaseToPreview.ts","../src/application/branchRelease.ts","../src/application/docsFor.ts","../src/application/newAdapter.ts","../src/application/planShips.ts","../src/application/promote.ts","../src/application/customAdapter.ts","../src/application/rehearse.ts","../src/application/setup.ts","../src/adapters/manifest/package-json-manifest.adapter.ts","../src/adapters/terminal/live-line.ts","../src/adapters/shell/system-shell.adapter.ts","../src/adapters/terminal/terminal-progress.adapter.ts","../src/adapters/terminal/terminal.adapter.ts","../src/application/config/loadRelease.ts","../src/cli/installed.ts","../src/cli/plugins.ts","../src/cli/compose.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { Files } from \"../../ports/files.port\";\n\n/** The repository on disk, under `root`. */\nexport const nodeFiles = (root: string): Files => {\n const at = (file: string) => path.join(root, file);\n return {\n exists: (file) => fs.existsSync(at(file)),\n read: (file) => (fs.existsSync(at(file)) ? fs.readFileSync(at(file), \"utf8\") : null),\n write: (file, text) => {\n fs.mkdirSync(path.dirname(at(file)), { recursive: true });\n fs.writeFileSync(at(file), text);\n },\n append: (file, text) => {\n const at = path.resolve(root, file);\n fs.mkdirSync(path.dirname(at), { recursive: true });\n fs.appendFileSync(at, text);\n },\n remove: (file) => fs.rmSync(at(file), { force: true }),\n list: (dir) => (fs.existsSync(at(dir)) ? fs.readdirSync(at(dir)) : []),\n folders: (dir) =>\n fs.existsSync(at(dir))\n ? fs\n .readdirSync(at(dir), { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n : [],\n };\n};\n","import type { DeliveryAdapter } from \"../ports/adapter.port\";\nimport type { MobileDistributionPort } from \"../ports/mobile-distribution.port\";\nimport type { PackageRegistryPort } from \"../ports/package-registry.port\";\nimport type { ServerHostingPort } from \"../ports/server-hosting.port\";\nimport type { StaticHostingPort } from \"../ports/static-hosting.port\";\nimport type { ReleaseModule } from \"./module\";\nimport { backendService } from \"./backend-service/backend-service.module\";\nimport { mobileApp } from \"./mobile-app/mobile-app.module\";\nimport { publishedPackage } from \"./published-package/published-package.module\";\nimport { webApp } from \"./web-app/web-app.module\";\n\n/** An adapter of any delivery port, as `setup` offers them. */\nexport type AnyDeliveryAdapter =\n | DeliveryAdapter<ServerHostingPort>\n | DeliveryAdapter<StaticHostingPort>\n | DeliveryAdapter<MobileDistributionPort>\n | DeliveryAdapter<PackageRegistryPort>;\n\n/** The module a provider suggests: its kind, the factory a config calls, the port it fills. */\nexport interface Suggested {\n kind: string;\n factory: string;\n port: string;\n}\n\nconst SUGGESTED: Record<AnyDeliveryAdapter[\"capability\"], Suggested> = {\n \"server-hosting\": { kind: \"backend-service\", factory: \"backendService\", port: \"serverHosting\" },\n \"static-hosting\": { kind: \"web-app\", factory: \"webApp\", port: \"staticHosting\" },\n \"mobile-distribution\": {\n kind: \"mobile-app\",\n factory: \"mobileApp\",\n port: \"mobileDistribution\",\n },\n \"package-registry\": {\n kind: \"published-package\",\n factory: \"publishedPackage\",\n port: \"packageRegistry\",\n },\n};\n\nexport const suggestedModule = (adapter: AnyDeliveryAdapter): Suggested =>\n SUGGESTED[adapter.capability];\n\ntype Capability = AnyDeliveryAdapter[\"capability\"];\n\ntype MakesModule<K extends Capability> = (\n adapter: Extract<AnyDeliveryAdapter, { capability: K }>,\n name: string,\n) => ReleaseModule;\n\nconst MODULE_FOR = {\n \"server-hosting\": (adapter, name) => backendService({ name, serverHosting: adapter }),\n \"static-hosting\": (adapter, name) => webApp({ name, staticHosting: adapter }),\n \"mobile-distribution\": (adapter, name) => mobileApp({ name, mobileDistribution: adapter }),\n \"package-registry\": (adapter, name) => publishedPackage({ name, packageRegistry: adapter }),\n} satisfies { [K in Capability]: MakesModule<K> };\n\nconst makes: { [K in Capability]: MakesModule<K> } = MODULE_FOR;\n\n/** The module a provider makes under a name, as `setup` composes it before the config exists. */\nexport const moduleFor = <K extends Capability>(\n adapter: Extract<AnyDeliveryAdapter, { capability: K }>,\n name: string,\n): ReleaseModule => {\n const make: MakesModule<K> = makes[adapter.capability];\n return make(adapter, name);\n};\n","/** Something wrong in the config, said where a person can fix it. */\nexport interface ConfigProblem {\n /** Relative to the repository root. */\n file: string;\n line?: number;\n message: string;\n hint?: string;\n}\n\nconst distance = (left: string, right: string): number => {\n const previous = Array.from({ length: right.length + 1 }, (_, index) => index);\n for (let row = 1; row <= left.length; row += 1) {\n let diagonal = previous[0] ?? 0;\n previous[0] = row;\n for (let column = 1; column <= right.length; column += 1) {\n const above = previous[column] ?? 0;\n const cost = left[row - 1] === right[column - 1] ? 0 : 1;\n previous[column] = Math.min(above + 1, (previous[column - 1] ?? 0) + 1, diagonal + cost);\n diagonal = above;\n }\n }\n return previous[right.length] ?? 0;\n};\n\n/** The candidate a typo most likely meant, when one is close enough to be worth naming. */\nexport const didYouMean = (word: string, candidates: readonly string[]): string | undefined => {\n const [best] = candidates\n .map((candidate) => ({\n candidate,\n cost: distance(word.toLowerCase(), candidate.toLowerCase()),\n }))\n .sort((left, right) => left.cost - right.cost);\n return best && best.cost <= Math.max(2, Math.floor(word.length / 3))\n ? `did you mean \"${best.candidate}\"?`\n : undefined;\n};\n\n/** Top to bottom per file, problems without a line last. */\nexport const sortProblems = (problems: ConfigProblem[]) =>\n [...problems].sort(\n (left, right) =>\n left.file.localeCompare(right.file) ||\n (left.line ?? Number.MAX_SAFE_INTEGER) - (right.line ?? Number.MAX_SAFE_INTEGER),\n );\n","import { z } from \"zod\";\n\nimport type { Environment } from \"../../domain/environment\";\nimport type { ReleaseModule } from \"../../modules/module\";\nimport { ENV_VAR_NAME } from \"../../domain/checkEnvBeforeDeploy\";\n\ninterface Inspectable {\n def: {\n type: string;\n innerType?: z.ZodType;\n defaultValue?: unknown;\n keyType?: z.ZodType;\n valueType?: z.ZodType;\n element?: z.ZodType;\n options?: z.ZodType[];\n shape?: Record<string, z.ZodType>;\n };\n description?: string;\n}\n\n// A config loads its own copy of zod, so a schema is read by its shape, never by its class.\nconst inspect = (schema: z.ZodType): Inspectable => schema;\n\nconst definition = (schema: z.ZodType) => inspect(schema).def;\n\nconst mapShape = (shape: Record<string, z.ZodType>, map: (schema: z.ZodType) => z.ZodType) =>\n Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, map(value)]));\n\n/**\n * The same schema, refusing unknown keys at every depth. Read through `def.type` rather than\n * `instanceof`: a config loads its own copy of zod.\n */\nexport const deepStrict = (schema: z.ZodType): z.ZodType => {\n const def = definition(schema);\n const strict = (): z.ZodType => {\n switch (def.type) {\n case \"object\":\n return z.strictObject(mapShape(def.shape ?? {}, deepStrict));\n case \"optional\":\n return def.innerType ? deepStrict(def.innerType).optional() : schema;\n case \"nullable\":\n return def.innerType ? deepStrict(def.innerType).nullable() : schema;\n case \"default\":\n return def.innerType ? deepStrict(def.innerType).default(def.defaultValue) : schema;\n case \"union\":\n return z.union((def.options ?? []).map(deepStrict));\n case \"record\":\n return def.keyType && def.valueType\n ? z.record(def.keyType as z.ZodString, deepStrict(def.valueType))\n : schema;\n case \"array\":\n return def.element ? z.array(deepStrict(def.element)) : schema;\n default:\n return schema;\n }\n };\n const result = strict();\n const { description } = inspect(schema);\n return description && result !== schema ? result.describe(description) : result;\n};\n\n/** The keys an object schema allows at a path, best effort, for \"did you mean\". */\nexport const keysAt = (schema: z.ZodType, at: readonly PropertyKey[]): string[] => {\n const def = definition(schema);\n if (def.type === \"optional\" || def.type === \"nullable\" || def.type === \"default\") {\n return def.innerType ? keysAt(def.innerType, at) : [];\n }\n if (def.type === \"union\") return (def.options ?? []).flatMap((option) => keysAt(option, at));\n if (def.type === \"record\" && at.length > 0 && def.valueType) {\n return keysAt(def.valueType, at.slice(1));\n }\n if (def.type !== \"object\") return [];\n const [first, ...rest] = at;\n if (first === undefined) return Object.keys(def.shape ?? {});\n const child = def.shape?.[String(first)];\n return child ? keysAt(child, rest) : [];\n};\n\nconst envVarNames = z\n .array(z.string().regex(ENV_VAR_NAME, \"an env var name is UPPER_SNAKE, like SENTRY_DSN\"))\n .describe(\"Env var names, one per line\");\n\nconst onlyOn = (environment: Environment) =>\n envVarNames.optional().describe(`Checked on ${environment} only, on top of all`);\n\nconst environmentLists = {\n preview: onlyOn(\"preview\"),\n production: onlyOn(\"production\"),\n} satisfies Record<Environment, z.ZodOptional<typeof envVarNames>>;\n\n/** One list for every environment, or `all` plus a list per environment. */\nexport const checkEnvBeforeDeploySchema = z\n .union([\n envVarNames,\n z.strictObject({\n all: envVarNames.optional().describe(\"Checked on every environment, current and future\"),\n ...environmentLists,\n }),\n ])\n .describe(\n \"Before each deploy, shiplane checks these env var names are set on the platform; you set the values\",\n );\n\n/** What a unit file naming this module may hold: `module`, then its adapter's settings. */\nexport const unitSchema = (module: ReleaseModule) =>\n z.strictObject({\n module: z\n .literal(module.name)\n .describe(`The module that ships this app, with ${module.provider}`),\n buildCommand: z\n .string()\n .optional()\n .describe('How to build this app, when its package.json has no \"build\" script'),\n checkEnvBeforeDeploy: checkEnvBeforeDeploySchema.optional(),\n ...mapShape(module.settings.shape, deepStrict),\n });\n\n/** The JSON Schema editors read for `shiplane.unit.yml`: the module an app names picks its keys. */\nexport const unitJsonSchema = (modules: readonly ReleaseModule[]) =>\n z.toJSONSchema(z.union(modules.map(unitSchema)), { io: \"input\", unrepresentable: \"any\" });\n","/** Where a unit runs, in promotion order: production ships what preview validated. */\nexport const ENVIRONMENTS = [\"preview\", \"production\"] as const;\n\nexport type Environment = (typeof ENVIRONMENTS)[number];\n","import type { Environment } from \"../../domain/environment\";\nimport { ENVIRONMENTS } from \"../../domain/environment\";\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** A map keyed by exactly the environments: one of its values is picked per environment. */\nexport const isPerEnvValue = (value: unknown): value is Record<Environment, unknown> =>\n isRecord(value) &&\n Object.keys(value).length === ENVIRONMENTS.length &&\n ENVIRONMENTS.every((environment) => environment in value);\n\n/** `${units.<name>.<key>}`, where key may be dotted. */\nexport const REFERENCE = /\\$\\{units\\.([\\w-]+)\\.([\\w.-]+)\\}/g;\n\nexport interface Reference {\n unit: string;\n key: string;\n /** Where it is written in the unit file. */\n at: string[];\n}\n\nexport const referencesIn = (value: unknown, at: string[] = []): Reference[] => {\n if (typeof value === \"string\") {\n return [...value.matchAll(REFERENCE)].map(([, unit = \"\", key = \"\"]) => ({ unit, key, at }));\n }\n if (Array.isArray(value)) {\n return value.flatMap((item, index) => referencesIn(item, [...at, String(index)]));\n }\n if (isRecord(value)) {\n return Object.entries(value).flatMap(([key, item]) => referencesIn(item, [...at, key]));\n }\n return [];\n};\n\nexport const valueAt = (value: unknown, at: readonly string[]): unknown =>\n at.reduce<unknown>((current, key) => (isRecord(current) ? current[key] : undefined), value);\n","import type { Document } from \"yaml\";\nimport type { z } from \"zod\";\nimport { isMap, isScalar, isSeq, LineCounter, parseDocument } from \"yaml\";\n\nimport type { EnvVarName } from \"../../domain/checkEnvBeforeDeploy\";\nimport type { Environment } from \"../../domain/environment\";\nimport type { ReleaseModule } from \"../../modules/module\";\nimport type { ConfigProblem } from \"./problem\";\nimport { EnvToCheck, isEnvVarName } from \"../../domain/checkEnvBeforeDeploy\";\nimport { didYouMean } from \"./problem\";\nimport { checkEnvBeforeDeploySchema, keysAt, unitSchema } from \"./unitSchema\";\nimport { isRecord } from \"./values\";\n\nexport const UNIT_FILE = \"shiplane.unit.yml\";\n/** The name unit files had before shiplane: still read, listed to rename. */\nexport const LEGACY_UNIT_FILE = \"release.unit.yml\";\nexport const UNIT_FILES = [UNIT_FILE, LEGACY_UNIT_FILE];\n\nexport interface UnitFile {\n /** The module that ships it. */\n module: string;\n /** Its `buildCommand:`, when it says one. */\n buildCommand?: string;\n /** Its `checkEnvBeforeDeploy:`, when it lists one. */\n checkEnvBeforeDeploy?: EnvToCheck;\n options: Record<string, unknown>;\n /** The line a key path sits on, for problems found after reading. */\n lineOf: (at: readonly string[]) => number | undefined;\n}\n\nconst locate =\n (doc: Document, counter: LineCounter) =>\n (at: readonly PropertyKey[], key?: string): number | undefined => {\n let node: unknown = doc.contents;\n for (const segment of at) {\n if (!isMap(node) && !isSeq(node)) return undefined;\n node = node.get(segment, true);\n }\n if (key !== undefined && isMap(node)) {\n node = node.items.find((pair) => isScalar(pair.key) && pair.key.value === key)?.key;\n }\n const offset = (node as { range?: number[] } | undefined)?.range?.[0];\n return offset === undefined ? undefined : counter.linePos(offset).line;\n };\n\n/** Of a union's branches, the one written in the right shape: its problems are inside, not the shape. */\nconst closestBranch = (branches: readonly (readonly z.core.$ZodIssue[])[]) =>\n branches.find((issues) =>\n issues.every(({ code, path }) => !(code === \"invalid_type\" && path.length === 0)),\n );\n\nconst describeIssue = (\n issue: z.core.$ZodIssue,\n file: string,\n module: ReleaseModule,\n lineAt: ReturnType<typeof locate>,\n): ConfigProblem[] => {\n const at = issue.path;\n if (issue.code === \"invalid_union\") {\n const branch = closestBranch(issue.errors);\n if (branch) {\n return branch.flatMap((inner) =>\n describeIssue({ ...inner, path: [...at, ...inner.path] }, file, module, lineAt),\n );\n }\n }\n if (issue.code === \"unrecognized_keys\") {\n return issue.keys.map((key) => ({\n file,\n line: lineAt(at, key),\n message: `unknown key \"${[...at, key].join(\".\")}\" for ${module.name}`,\n hint: didYouMean(key, keysAt(module.settings, at)),\n }));\n }\n const name = at.join(\".\");\n if (issue.code === \"invalid_type\" && issue.message.endsWith(\"received undefined\")) {\n // A missing key has no line of its own: its parent map's, unless that is the whole file.\n const line = at.length > 1 ? lineAt(at.slice(0, -1)) : undefined;\n return [{ file, line, message: `\"${name}\" is required` }];\n }\n return [{ file, line: lineAt(at), message: `\"${name}\": ${issue.message}` }];\n};\n\nconst CORE_KEYS = new Set([\"module\", \"buildCommand\", \"checkEnvBeforeDeploy\"]);\n\nconst envVarNames = (list: readonly string[] = []) => list.filter(isEnvVarName);\n\nconst envToCheck = (written: z.infer<typeof checkEnvBeforeDeploySchema>) =>\n new EnvToCheck(\n Array.isArray(written)\n ? envVarNames(written)\n : {\n all: envVarNames(written.all),\n ...({\n preview: envVarNames(written.preview),\n production: envVarNames(written.production),\n } satisfies Record<Environment, EnvVarName[]>),\n },\n );\n\nconst problem = (file: string, line: number | undefined, message: string, hint: string) => ({\n problems: [{ file, line, message, hint }],\n});\n\n/** A unit file checked against the adapter of the module it names, every problem with its line. */\nexport const readUnitFile = (\n file: string,\n text: string,\n modules: readonly ReleaseModule[],\n features: readonly string[] = [],\n): { unit?: UnitFile; problems: ConfigProblem[] } => {\n const counter = new LineCounter();\n const doc = parseDocument(text, { lineCounter: counter, uniqueKeys: true, prettyErrors: false });\n if (doc.errors.length > 0) {\n return {\n problems: doc.errors.map((error) => ({\n file,\n line: counter.linePos(error.pos[0]).line,\n message: error.message.split(\"\\n\")[0] ?? error.message,\n })),\n };\n }\n const lineAt = locate(doc, counter);\n const data: unknown = doc.toJS();\n const names = modules.map(({ name }) => name);\n const oneOf = `one of: ${names.join(\", \")}`;\n if (isRecord(data) && \"target\" in data && !(\"module\" in data)) {\n return problem(\n file,\n lineAt([\"target\"]),\n \"target: is now module: the module in shiplane.config.ts that ships this app\",\n oneOf,\n );\n }\n if (!isRecord(data) || typeof data.module !== \"string\") {\n return problem(file, 1, \"a unit file starts with module: the module that ships it\", oneOf);\n }\n const named = data.module;\n const module = modules.find(({ name }) => name === named);\n if (features.includes(named)) {\n return problem(\n file,\n lineAt([\"module\"]),\n `\"${named}\" ships no app: it runs on every ship`,\n oneOf,\n );\n }\n if (!module) {\n return problem(\n file,\n lineAt([\"module\"]),\n `no module named \"${named}\" in shiplane.config.ts`,\n didYouMean(named, names) ?? oneOf,\n );\n }\n const parsed = unitSchema(module).safeParse(data);\n if (!parsed.success) {\n return {\n problems: parsed.error.issues.flatMap((issue) => describeIssue(issue, file, module, lineAt)),\n };\n }\n const options = Object.fromEntries(Object.entries(data).filter(([key]) => !CORE_KEYS.has(key)));\n const buildCommand = typeof data.buildCommand === \"string\" ? data.buildCommand : undefined;\n const written = parsed.data.checkEnvBeforeDeploy;\n return {\n unit: {\n module: named,\n ...(buildCommand ? { buildCommand } : {}),\n ...(written ? { checkEnvBeforeDeploy: envToCheck(written) } : {}),\n options,\n lineOf: (at) => lineAt(at),\n },\n problems: [],\n };\n};\n","import { styleText } from \"node:util\";\n\nimport type { ReleaseContext } from \"./context\";\n\ntype Style = Parameters<typeof styleText>[0];\n\nexport const paint = (style: Style, text: string) => styleText(style, text);\n\n/** What a failure says, whatever was thrown. */\nexport const reasonOf = (error: unknown) =>\n error instanceof Error ? error.message : String(error);\n\n/** A failure, said with what to run next; the caller returns false so nothing else runs. */\nexport const fail = (\n { output, progress }: ReleaseContext,\n title: string,\n detail: string,\n commands: string[] = [],\n) => {\n progress.say(\"worried\", `${paint([\"bold\", \"red\"], `✗ ${title}:`)} ${detail}`);\n commands.forEach((command) => output.line(` ${paint(\"cyan\", command)}`));\n};\n\n/** Yes without asking under --yes; without a terminal, no. */\nexport const confirm = async (\n { prompter, options, output }: ReleaseContext,\n question: string,\n initial = false,\n) => {\n if (options.yes) return true;\n if (!prompter.interactive) {\n output.line(paint(\"yellow\", \"Not a terminal: pass --yes to run it.\"));\n return false;\n }\n return prompter.confirm(question, initial);\n};\n\n/** `api`, `api and admin`, `api, admin and landing`. */\nexport const listed = (names: readonly string[]) =>\n names.length < 2\n ? names.join(\"\")\n : `${names.slice(0, -1).join(\", \")} and ${names.slice(-1).join(\"\")}`;\n\n/** The keys a screen offers, each the same way: `d see the diff o open it on GitHub`. */\nexport const keyHints = (hints: readonly { key: string; label: string }[]) =>\n hints.map(({ key, label }) => `${paint(\"cyan\", key)} ${paint(\"dim\", label)}`).join(\" \");\n","import path from \"node:path\";\n\nimport type { CallerWorkflow } from \"../ports/ci-pipeline.port\";\nimport type { Release } from \"./config/loadRelease\";\nimport type { SetupContext } from \"./setupContext\";\nimport { paint, reasonOf } from \"./say\";\n\n/** What a workflow calling shiplane's own holds in its `uses:` line. */\nconst CALLS = \"/.github/workflows/shiplane-ship.yml@\";\nconst USES = /^([ \\t]*)uses:[ \\t]*\\S*\\/\\.github\\/workflows\\/shiplane-ship\\.yml@.*$/m;\nconst PINNED = /shiplane-ship\\.yml@\\S+[ \\t]+#[ \\t]*shiplane@(\\S+)/;\n\n/** The workflow a repository ships from, as its CI pipeline writes it; null when it writes none. */\nconst callerOf = ({ version, root, shell }: SetupContext, release: Release) => {\n const ci = release.flow.ciPipeline.create({ root, shell });\n const file = ci.workflowFile?.(ci.shipWorkflow);\n const make = ci.callerWorkflow;\n if (!version || !file || !make) return null;\n return { file, name: path.posix.basename(file), version, make: () => make(version) };\n};\n\n/** The made workflow, or null once why it could not be made is said. */\nconst madeOrSaid = async (\n { output }: SetupContext,\n make: () => Promise<CallerWorkflow | { error: string }>,\n bar: string,\n) => {\n const made = await make().catch((error: unknown) => ({ error: reasonOf(error) }));\n if (!(\"error\" in made)) return made;\n output.line(`${bar}${paint(\"yellow\", \"!\")} ${paint(\"dim\", made.error)}`);\n return null;\n};\n\n/** What setup writes for the caller workflow: nothing when one is there, or none can be made. */\nexport const callerWrite = async (context: SetupContext, release: Release) => {\n const caller = callerOf(context, release);\n if (!caller || context.files.exists(caller.file)) return null;\n const made = await madeOrSaid(context, caller.make, \" \");\n return made ? { file: made.file, text: made.content, created: true } : null;\n};\n\n/** `text` with its `uses:` line pinned as `content`'s is, everything else as the person wrote it. */\nconst repinned = (text: string, content: string) => {\n const uses = USES.exec(content)?.[0].trim() ?? \"\";\n return text.replace(USES, (_line, indent: string) => `${indent}${uses}`);\n};\n\n/** What is wrong with the caller workflow, its fix, and whether that fix may overwrite a person's. */\nconst problemOf = (file: string, name: string, version: string, text: string | null) => {\n if (text === null) {\n return { said: `${name} missing`, ask: `Write ${file}?`, fix: (content: string) => content };\n }\n if (!text.includes(CALLS)) {\n return {\n said: `${name} does not call shiplane-ship.yml`,\n ask: `Replace ${file} with one that calls shiplane-ship.yml? Your workflow is lost.`,\n fix: (content: string) => content,\n overwrites: true,\n };\n }\n const pinned = PINNED.exec(text)?.[1];\n if (pinned === version) return null;\n return {\n said: `${name} pins ${pinned ? `shiplane@${pinned}` : \"no shiplane version\"}, installed ${version}`,\n ask: `Re-pin ${file} to shiplane@${version}?`,\n fix: (content: string) => repinned(text, content),\n };\n};\n\n/**\n * Doctor's check of the caller workflow, on a laptop only: there, pinned to the shiplane installed,\n * each problem said with its fix offered. Replacing a person's own workflow is asked, never assumed.\n */\nexport const checkCallerWorkflow = async (\n context: SetupContext,\n release: Release,\n { yes }: { yes: boolean },\n): Promise<boolean> => {\n const { shell, files, output, prompter } = context;\n if (shell.env(\"GITHUB_ACTIONS\") === \"true\" || shell.env(\"CI\") === \"true\") return true;\n const caller = callerOf(context, release);\n if (!caller) return true;\n const { file, name, version } = caller;\n const bar = `${paint(\"dim\", \"│\")} `;\n const problem = problemOf(file, name, version, files.read(file));\n if (!problem) {\n output.line(`${bar}${paint(\"green\", \"✓\")} ${name} ${paint(\"dim\", `shiplane@${version}`)}`);\n return true;\n }\n output.line(`${bar}${paint(\"red\", \"✗\")} ${problem.said}`);\n const agreed = problem.overwrites\n ? !yes && prompter.interactive && (await prompter.confirm(problem.ask, false))\n : yes || (prompter.interactive && (await prompter.confirm(problem.ask, true)));\n if (!agreed) return false;\n const made = await madeOrSaid(context, caller.make, bar);\n if (!made) return false;\n const created = !files.exists(file);\n files.write(file, problem.fix(made.content));\n output.line(`${bar}${created ? paint(\"green\", \"+\") : paint(\"yellow\", \"~\")} ${file}`);\n return true;\n};\n\n/** The Renovate preset that keeps the caller workflow's pin, commit and comment, current. */\nexport const SHIPLANE_RENOVATE_PRESET = \"github>arnaud-zg/js-packages//renovate/shiplane\";\n\n/** Where Renovate looks for its config, in its order; JSON5 ones setup leaves to the person. */\nconst RENOVATE_CONFIGS = [\n \"renovate.json\",\n \"renovate.json5\",\n \".github/renovate.json\",\n \".github/renovate.json5\",\n \".gitlab/renovate.json\",\n \".gitlab/renovate.json5\",\n \".renovaterc\",\n \".renovaterc.json\",\n \".renovaterc.json5\",\n];\n\ntype RenovateConfig = Record<string, unknown> & { extends?: unknown };\n\n/** The config a JSON text holds, or null when it is not JSON. */\nconst jsonObject = (text: string) => {\n try {\n return JSON.parse(text) as RenovateConfig | null;\n } catch {\n return null;\n }\n};\n\n/** The repository's Renovate config: its file, its text, its JSON when setup may edit it. */\nconst renovateConfigOf = ({ files }: SetupContext) => {\n const file = RENOVATE_CONFIGS.find((name) => files.exists(name));\n const text = files.read(file ?? \"package.json\") ?? \"\";\n if (file) return { file, text, config: file.endsWith(\".json5\") ? null : jsonObject(text) };\n return jsonObject(text)?.renovate === undefined\n ? null\n : { file: \"package.json\", text, config: null };\n};\n\n/**\n * Renovate's part once ship.yml calls shiplane-ship.yml (`shipText`, else as on disk): the write\n * adding the preset to a JSON config's `extends`, else null once what to do is said. A config is\n * never created, and one setup cannot safely edit is named, never touched.\n */\nexport const renovateWrite = (context: SetupContext, release: Release, shipText?: string) => {\n const caller = callerOf(context, release);\n const text = shipText ?? (caller ? context.files.read(caller.file) : null);\n if (!text?.includes(CALLS)) return null;\n const found = renovateConfigOf(context);\n const entry = `\"${SHIPLANE_RENOVATE_PRESET}\"`;\n if (!found) {\n context.output.line(\n ` ${paint(\"dim\", `shiplane doctor keeps the ship.yml pin current; on Renovate, add ${entry} to extends`)}`,\n );\n return null;\n }\n const { file, config } = found;\n if (found.text.includes(entry)) return null;\n if (!config) {\n context.output.line(\n ` ${paint(\"yellow\", \"!\")} ${file}: add ${entry} to extends to keep the ship.yml pin current`,\n );\n return null;\n }\n const presets = Array.isArray(config.extends) ? (config.extends as unknown[]) : [];\n const extended = { ...config, extends: [...presets, SHIPLANE_RENOVATE_PRESET] };\n return {\n file,\n text: `${JSON.stringify(extended, null, 2)}\\n`,\n created: false,\n reason: \"Renovate keeps the ship.yml pin current\",\n };\n};\n","import type { ReleaseUnit } from \"../domain/unit\";\nimport { referencesIn } from \"./config/values\";\n\n/** `admin (reads api.url)`: an app, with the values of other apps it reads. */\nconst withReads = ({ name, options }: ReleaseUnit) => {\n const reads = [\n ...new Set(\n referencesIn(options)\n .filter(({ unit }) => unit !== name)\n .map(({ unit, key }) => `${unit}.${key}`),\n ),\n ];\n return reads.length > 0 ? `${name} (reads ${reads.join(\", \")})` : name;\n};\n\n/** `1 expo · Latest → 2 api → 3 admin (reads api.url)`: the apps numbered in release order. */\nexport const releaseOrder = (units: readonly ReleaseUnit[]) =>\n units\n .map((unit, index) => `${index + 1} ${withReads(unit)}${index === 0 ? \" · Latest\" : \"\"}`)\n .join(\" → \");\n","/** Where a unit's code comes from, to tell which changed files can reach what it ships. */\nexport interface CodeScope {\n /** Its own folder and those of the workspace packages it uses. */\n own: readonly string[];\n /** Every workspace package's folder. */\n workspace: readonly string[];\n versionFiles: ReadonlySet<string>;\n}\n\n// Notes, docs, CI and release config: they change how a release is made or read, never what it ships.\nconst NOT_SHIPPED = [\n /(^|\\/)(shiplane|release)\\.unit\\.yml$/,\n /^\\.changeset\\//,\n /^\\.planning\\//,\n /^\\.github\\//,\n /^\\.claude\\//,\n /^docs\\//,\n /\\.md$/,\n];\n\n/** A package's folder and the folders of every workspace package it uses, however deep. */\nexport const codeFolders = (\n packageName: string,\n dependencies: Record<string, string[]>,\n folders: Record<string, string>,\n): string[] => {\n const seen = new Set<string>([packageName]);\n const queue = [packageName];\n for (const name of queue) {\n for (const dependency of dependencies[name] ?? []) {\n if (seen.has(dependency)) continue;\n seen.add(dependency);\n queue.push(dependency);\n }\n }\n return [...seen].flatMap((name) => folders[name] ?? []);\n};\n\n/**\n * The changed files that can reach what a unit ships: in its own code folders, or at the root\n * outside every workspace folder, such as the lockfile. Another app's folder never does.\n */\nexport const changesReaching = (files: readonly string[], scope: CodeScope): string[] =>\n files.filter((file) => {\n if (scope.versionFiles.has(file) || NOT_SHIPPED.some((pattern) => pattern.test(file))) {\n return false;\n }\n const inside = (folder: string) => file.startsWith(`${folder}/`);\n return scope.own.some(inside) || !scope.workspace.some(inside);\n });\n","import type { Environment } from \"../../domain/environment\";\nimport type { ReleaseUnit } from \"../../domain/unit\";\nimport { isPerEnvValue, isRecord, REFERENCE, valueAt } from \"./values\";\n\nconst resolve = (value: unknown, env: Environment, units: readonly ReleaseUnit[]): unknown => {\n const picked = isPerEnvValue(value) ? value[env] : value;\n if (typeof picked === \"string\") {\n return picked.replace(REFERENCE, (_match, name: string, key: string) => {\n const other = units.find((unit) => unit.name === name);\n const resolved = other ? resolve(valueAt(other.options, key.split(\".\")), env, units) : \"\";\n return typeof resolved === \"string\" ? resolved : \"\";\n });\n }\n if (Array.isArray(picked)) return picked.map((item) => resolve(item, env, units));\n if (isRecord(picked)) {\n return Object.fromEntries(\n Object.entries(picked).map(([key, item]) => [key, resolve(item, env, units)]),\n );\n }\n return picked;\n};\n\n/** A unit's options for one environment: per-environment values picked, references filled in. */\nexport const optionsFor = (\n unit: ReleaseUnit,\n env: Environment,\n units: readonly ReleaseUnit[],\n): Record<string, unknown> => {\n const resolved = resolve(unit.options, env, units);\n return isRecord(resolved) ? resolved : {};\n};\n","import os from \"node:os\";\nimport path from \"node:path\";\n\nimport type { Environment } from \"../domain/environment\";\nimport type { ReleaseUnit } from \"../domain/unit\";\nimport type { AfterShipContext, AppInput, ReleaseModule } from \"../modules/module\";\nimport type { Command, DecideContext, Job } from \"../ports/delivery.port\";\nimport type { ReleaseContext } from \"./context\";\nimport { changesReaching, codeFolders } from \"../domain/codeScope\";\nimport { tagName } from \"../domain/tags\";\nimport { optionsFor } from \"./config/optionsFor\";\nimport { reasonOf } from \"./say\";\n\n/** The module that ships an app: the one its unit file names. */\nexport const moduleOf = ({ release }: ReleaseContext, unit: ReleaseUnit) =>\n release.modules.find(({ name }) => name === unit.module);\n\n/** An app's settings for an environment, its module's defaults applied first. */\nexport const resolvedOptions = (\n module: ReleaseModule,\n unit: ReleaseUnit,\n environment: Environment,\n units: readonly ReleaseUnit[],\n): Record<string, unknown> => {\n const withDefaults = module.settings.parse(unit.options);\n return optionsFor({ ...unit, options: withDefaults }, environment, units);\n};\n\n/** Where this checkout stands: the commit it is on and the branch releases start from. */\nexport interface Checkout {\n commit: string;\n defaultBranch: string;\n}\n\n/** The commit this machine is on and the default branch, read once for every unit a run looks at. */\nexport const checkout = async ({ services }: ReleaseContext): Promise<Checkout> => {\n const [{ head }, defaultBranch] = await Promise.all([\n services.sourceControl.position(),\n services.sourceControl.defaultBranch(),\n ]);\n return { commit: head, defaultBranch };\n};\n\n/** What a module's stages are told about one app's tag. */\nexport const jobInput = (\n context: ReleaseContext,\n module: ReleaseModule,\n unit: ReleaseUnit,\n { tag, environment, commit, defaultBranch }: { tag: string; environment: Environment } & Checkout,\n): AppInput => ({\n unit,\n tag,\n environment,\n commit,\n defaultBranch,\n options: resolvedOptions(module, unit, environment, context.release.units),\n});\n\n/** The module that ships a unit and the tag it ships, or null when no module claims it. */\nexport const unitTag = (context: ReleaseContext, unit: ReleaseUnit) => {\n const module = moduleOf(context, unit);\n if (!module) return null;\n return { module, tag: tagName(unit.name, unit.version, context.release.tagFormat) };\n};\n\n/** One unit aimed at an environment at a commit: its module, its tag, and what its stages are told. */\nexport const unitTarget = (\n context: ReleaseContext,\n { unit, environment, ...at }: { unit: ReleaseUnit; environment: Environment } & Checkout,\n) => {\n const found = unitTag(context, unit);\n if (!found) return null;\n const input = jobInput(context, found.module, unit, { tag: found.tag, environment, ...at });\n return { ...found, input };\n};\n\n/** Where a tag lands and the jobs that ship it, as its module says. */\nexport const shipPlanOf = (context: ReleaseContext, module: ReleaseModule, input: AppInput) =>\n module.ship(decideContext(context), input);\n\n/** Every file a release may move after a tag without changing what ships. */\nexport const versionFiles = (context: ReleaseContext) =>\n new Set(\n context.release.units.flatMap(\n (unit) =>\n moduleOf(context, unit)?.versionFiles?.(unit, context.release.units, context.open) ?? [],\n ),\n );\n\n/** A command as a person would type it, variables first, secrets by name only. */\nexport const commandLine = ({ command, args, env, secrets }: Command) =>\n [\n ...Object.entries(env ?? {}).map(([key, value]) => `${key}=${value}`),\n command,\n ...args,\n ...(secrets ?? []).flatMap(({ flag, name }) => [flag, `${name}=$${name}`]),\n ].join(\" \");\n\n/** Runs a job's commands in a checkout in order. Throws on the first failure. */\nconst runIn = async ({ shell, output }: ReleaseContext, job: Job, root: string) => {\n const secretArgs = (step: Command) =>\n (step.secrets ?? []).flatMap(({ flag, name }) => {\n const value = shell.env(name);\n if (value) return [flag, `${name}=${value}`];\n output.line(` ! ${name} is not set: ${flag} left out`);\n return [];\n });\n const run = (step: Command) =>\n shell.attach(step.command, [...step.args, ...secretArgs(step)], {\n cwd: path.join(root, step.cwd ?? \"\"),\n env: step.env,\n });\n try {\n for (const step of job.local) {\n const status = await run(step);\n if (status !== 0) throw new Error(`${step.command} exited with ${status}`);\n }\n } finally {\n for (const step of job.cleanup ?? []) await run(step);\n }\n};\n\nconst SIGNALS = [\"SIGINT\", \"SIGTERM\"] as const;\n\n/**\n * Runs a job from a worktree detached at its tag: installed, given the checkout's ignored `.env*`\n * files at the root and in each folder a command runs in, and always removed after, also when it\n * was half made or the run is interrupted. A removal that fails is said, never in place of the\n * run's own failure.\n */\nconst runFromTag = async (context: ReleaseContext, job: Job, tag: string) => {\n const { shell, release, services, clock, output } = context;\n const dir = path.join(\n os.tmpdir(),\n `shiplane-${tag.replace(/[^\\w.-]/g, \"-\")}-${clock.now().getTime()}`,\n );\n const folders = [...new Set(job.local.flatMap(({ cwd }) => (cwd ? [cwd] : [])))];\n let removing: Promise<void> | null = null;\n const remove = () => {\n removing ??= services.sourceControl.removeWorktree(dir).catch((error: unknown) => {\n const reason = reasonOf(error);\n output.line(` ! could not remove the worktree ${dir}: ${reason}`);\n output.line(` git worktree remove --force ${dir}`);\n });\n return removing;\n };\n // Interrupted, the worktree goes first, then the signal does what it would have.\n const onSignal = (signal: NodeJS.Signals) => {\n detach();\n void remove().finally(() => process.kill(process.pid, signal));\n };\n const detach = () => SIGNALS.forEach((signal) => process.off(signal, onSignal));\n SIGNALS.forEach((signal) => process.once(signal, onSignal));\n try {\n await services.sourceControl.addWorktree(dir, tag);\n const envFiles = await services.sourceControl.ignoredFiles([\n \".env*\",\n ...folders.map((folder) => path.posix.join(folder, \".env*\")),\n ]);\n for (const file of envFiles) {\n const { status, stderr } = await shell.capture(\"cp\", [\n path.join(release.root, file),\n path.join(dir, file),\n ]);\n if (status !== 0) throw new Error(`copying ${file} failed: ${stderr.trim()}`);\n }\n const installed = await shell.attach(\"pnpm\", [\"install\", \"--frozen-lockfile\"], { cwd: dir });\n if (installed !== 0) throw new Error(`pnpm install exited with ${installed}`);\n await runIn(context, job, dir);\n } finally {\n detach();\n await remove();\n }\n};\n\n/**\n * Runs a job's commands here in order, from its tag when it names one, then records the deploy.\n * Throws on the first failure.\n */\nexport const runHere = async (\n context: ReleaseContext,\n job: Job,\n { tag, environment }: { tag: string; environment: Environment },\n) => {\n await (job.from ? runFromTag(context, job, job.from) : runIn(context, job, context.release.root));\n if (job.record) await context.services.codeHost.recordDeployment(tag, environment);\n};\n\n/** Dispatches the ship workflow on a ref for its units and returns at once: the runner ships them. */\nexport const dispatchShip = async (\n { services }: ReleaseContext,\n { ref, units }: { ref: string; units: readonly string[] },\n environment: Environment,\n) =>\n services.ciPipeline.dispatch(services.ciPipeline.shipWorkflow, ref, {\n units: units.join(\" \"),\n environment,\n });\n\n/** Which changed files can reach what a unit ships. */\nconst reaching = async (context: ReleaseContext, unit: ReleaseUnit) => {\n const { versioning } = context.services;\n const [dependencies, folders] = await Promise.all([\n versioning.dependencies(),\n versioning.folders(),\n ]);\n const scope = {\n own: [unit.dir, ...codeFolders(unit.packageName, dependencies, folders)],\n workspace: Object.values(folders),\n versionFiles: versionFiles(context),\n };\n return (files: readonly string[]) => changesReaching(files, scope);\n};\n\n/** What a module's per-app stages may read and run. */\nexport const decideContext = (context: ReleaseContext): DecideContext => ({\n root: context.release.root,\n shell: context.shell,\n sourceControl: context.services.sourceControl,\n codeHost: context.services.codeHost,\n ciPipeline: context.services.ciPipeline,\n units: context.release.units,\n tagFormat: context.release.tagFormat,\n versionFiles: versionFiles(context),\n now: () => context.clock.now(),\n open: context.open,\n changedCode: async (unit, from, to) => {\n const [files, filter] = await Promise.all([\n context.services.sourceControl.diffNames(from, to),\n reaching(context, unit),\n ]);\n return filter(files);\n },\n});\n\n/** What a module may read once apps ship. */\nexport const afterShipContext = (context: ReleaseContext): AfterShipContext => ({\n open: context.open,\n tagFormat: context.release.tagFormat,\n subjectsReaching: async (unit, from, to) => {\n const [commits, filter] = await Promise.all([\n context.services.sourceControl.commitsBetween(from, to),\n reaching(context, unit),\n ]);\n return commits.filter(({ files }) => filter(files).length > 0).map(({ subject }) => subject);\n },\n});\n\n/** A package registry has no staging and nothing deploys a release-only unit: no environment. */\nexport const hasNoEnvironment = ({ kind, releaseOnly }: ReleaseModule) =>\n kind === \"published-package\" || releaseOnly === true;\n\n/**\n * What the person reads for an environment: when no unit has one, preview is where users get them,\n * so it reads \"live\". Naming no unit asks about the whole repository.\n */\nexport const environmentLabel = (\n context: ReleaseContext,\n units: Iterable<string>,\n environment: string,\n) => {\n if (environment !== \"preview\") return environment;\n const named = [...units];\n const names = named.length > 0 ? named : context.release.units.map(({ name }) => name);\n const noneHasOne =\n names.length > 0 &&\n names.every((name) => {\n const unit = context.release.units.find((candidate) => candidate.name === name);\n const module = unit && moduleOf(context, unit);\n return module !== undefined && hasNoEnvironment(module);\n });\n return noneHasOne ? \"live\" : environment;\n};\n\n/** Where a sentence sends units: \"to preview\", or \"live\" when none of them has an environment. */\nexport const destination = (\n context: ReleaseContext,\n units: Iterable<string>,\n environment: string,\n) => {\n const label = environmentLabel(context, units, environment);\n return label === \"live\" ? label : `to ${label}`;\n};\n","import type { Prompter } from \"../ports/terminal.port\";\n\n/** Nobody answers: --yes takes every suggestion, and without a terminal there is nobody to ask. */\nexport const unattended = ({\n prompter,\n options,\n}: {\n prompter: Pick<Prompter, \"interactive\">;\n options: { yes: boolean };\n}) => options.yes || !prompter.interactive;\n","import type { EnvToCheck, EnvVarName } from \"../domain/checkEnvBeforeDeploy\";\nimport type { Environment } from \"../domain/environment\";\nimport type { ReleaseUnit } from \"../domain/unit\";\nimport type { PlatformEnvPort } from \"../ports/platform-env.port\";\nimport type { Shell } from \"../ports/shell.port\";\nimport type { Release } from \"./config/loadRelease\";\nimport type { ReleaseContext } from \"./context\";\nimport { findUnset } from \"../domain/checkEnvBeforeDeploy\";\nimport { paint, reasonOf } from \"./say\";\nimport { resolvedOptions } from \"./targets\";\nimport { unattended } from \"./unattended\";\n\nexport const STEP = \"Check env before deploy\";\nconst SET_THEM = \"Are they set now?\";\nconst READ_AGAIN = \"Read the platform again?\";\n\nexport type Checked = { unit: ReleaseUnit; toCheck: EnvToCheck };\n\n/** The units that list env to check, each with its list. */\nexport const listing = (units: readonly ReleaseUnit[]): Checked[] =>\n units.flatMap((unit) =>\n unit.checkEnvBeforeDeploy ? [{ unit, toCheck: unit.checkEnvBeforeDeploy }] : [],\n );\n\ntype WithoutOptions<Input> = Omit<Input, \"options\">;\n\n/** A unit's platform env, its settings for each environment filled in. */\nexport interface UnitPlatformEnv {\n listNames: (\n input: WithoutOptions<Parameters<PlatformEnvPort[\"listNames\"]>[0]>,\n ) => Promise<ReadonlySet<EnvVarName>>;\n setCommand: (input: WithoutOptions<Parameters<PlatformEnvPort[\"setCommand\"]>[0]>) => string;\n}\n\n/** The unit's platform env, or the provider that cannot list names. */\nexport const platformEnvOf = (\n { release, shell }: { release: Release; shell: Shell },\n unit: ReleaseUnit,\n): UnitPlatformEnv | { cannotList: string } => {\n const module = release.modules.find(({ name }) => name === unit.module);\n if (!module?.env) return { cannotList: module?.provider ?? unit.module };\n const port = module.env({ root: release.root, shell });\n const options = (environment: Environment) =>\n resolvedOptions(module, unit, environment, release.units);\n return {\n listNames: (input) => port.listNames({ ...input, options: options(input.environment) }),\n setCommand: (input) => port.setCommand({ ...input, options: options(input.environment) }),\n };\n};\n\nconst line = ({ output }: ReleaseContext, mark: string, text: string) =>\n output.line(`${mark} ${paint(\"bold\", STEP)} ${text}`);\n\n/** The names the platform holds, or null when the person stops, or CI cannot read it. */\nconst readNames = async (\n context: ReleaseContext,\n port: UnitPlatformEnv,\n input: { unit: ReleaseUnit; environment: Environment },\n): Promise<ReadonlySet<EnvVarName> | null> => {\n try {\n return await port.listNames(input);\n } catch (error) {\n const reason = reasonOf(error);\n line(context, paint(\"red\", \"✗\"), `${input.unit.name} on ${input.environment}: ${reason}`);\n const retry = !unattended(context) && (await context.prompter.confirm(READ_AGAIN, true));\n return retry ? readNames(context, port, input) : null;\n }\n};\n\n/** One unit on one environment: true once every listed name is on its platform. */\nconst checkUnit = async (\n context: ReleaseContext,\n port: UnitPlatformEnv,\n { unit, toCheck }: Checked,\n environment: Environment,\n): Promise<boolean> => {\n const expected = toCheck.for(environment);\n const where = `${unit.name} on ${environment}`;\n const setOnPlatform = await readNames(context, port, { unit, environment });\n if (!setOnPlatform) return false;\n const unset = findUnset({ expected, setOnPlatform });\n if (unset.isEmpty()) {\n line(context, paint(\"green\", \"✓\"), `${where}: ${expected.size} of ${expected.size} set`);\n return true;\n }\n const { output } = context;\n const command = port.setCommand({ unit, environment, names: unset.names() });\n line(\n context,\n paint(\"yellow\", \"!\"),\n `${where}: ${unset.names().length} unset env vars, the deploy waits`,\n );\n unset.names().forEach((name) => output.line(` ${name}`));\n if (unattended(context)) {\n output.line(` ${paint(\"dim\", \"Nothing was written. Set them, then run again:\")}`);\n output.line(` ${command}`);\n return false;\n }\n output.line(\n ` ${paint(\"dim\", \"You set these values; shiplane never does. Run, with your values:\")}`,\n );\n output.line(` ${command}`);\n if (!(await context.prompter.confirm(SET_THEM, true))) return false;\n return checkUnit(context, port, { unit, toCheck }, environment);\n};\n\n/**\n * Before a deploy: each unit that lists env to check has every name on its platform. A person sets\n * the values; shiplane only reads names. False when a name is still unset and nothing should ship.\n */\nexport const checkEnvBeforeDeploy = async (\n context: ReleaseContext,\n { environment, units }: { environment: Environment; units: readonly ReleaseUnit[] },\n): Promise<boolean> => {\n for (const entry of listing(units)) {\n const port = platformEnvOf(context, entry.unit);\n if (\"cannotList\" in port) {\n line(\n context,\n paint(\"yellow\", \"!\"),\n `${entry.unit.name}: can't check env on ${port.cannotList}, the deploy goes on`,\n );\n continue;\n }\n if (!(await checkUnit(context, port, entry, environment))) return false;\n }\n return true;\n};\n","import type { Environment } from \"../domain/environment\";\nimport type { Shell } from \"../ports/shell.port\";\nimport type { Output } from \"../ports/terminal.port\";\nimport type { Checked, UnitPlatformEnv } from \"./checkEnvBeforeDeploy\";\nimport type { Release } from \"./config/loadRelease\";\nimport { findUnset } from \"../domain/checkEnvBeforeDeploy\";\nimport { ENVIRONMENTS } from \"../domain/environment\";\nimport { listing, platformEnvOf, STEP } from \"./checkEnvBeforeDeploy\";\nimport { paint, reasonOf } from \"./say\";\n\nconst doctorLine = (output: Output, mark: string, text: string) =>\n output.line(`${paint(\"dim\", \"│\")} ${mark} ${text}`);\n\n/** One unit on one environment, for doctor: true when every listed name is on its platform. */\nconst reportUnit = async (\n output: Output,\n port: UnitPlatformEnv,\n { unit, toCheck }: Checked,\n environment: Environment,\n): Promise<boolean> => {\n const expected = toCheck.for(environment);\n const where = `${unit.name} on ${environment}`;\n const setOnPlatform = await port.listNames({ unit, environment }).catch((error: unknown) => {\n const reason = reasonOf(error);\n doctorLine(output, paint(\"red\", \"✗\"), `${where}: ${reason}`);\n return null;\n });\n if (!setOnPlatform) return false;\n const unset = findUnset({ expected, setOnPlatform });\n if (unset.isEmpty()) {\n doctorLine(output, paint(\"green\", \"✓\"), `${where}: ${expected.size} of ${expected.size} set`);\n return true;\n }\n const names = unset.names();\n doctorLine(\n output,\n paint(\"red\", \"✗\"),\n `${where}: ${names.length} unset env vars: ${names.join(\", \")}`,\n );\n output.line(\n `${paint(\"dim\", \"│\")} ${paint(\"dim\", `you set them: ${port.setCommand({ unit, environment, names })}`)}`,\n );\n return false;\n};\n\n/**\n * `doctor`'s env section: each unit that lists env to check, on every environment. Prints nothing\n * when no unit lists any. False when a name is unset or a platform cannot be read.\n */\nexport const reportEnvToCheck = async ({\n release,\n shell,\n output,\n}: {\n release: Release;\n shell: Shell;\n output: Output;\n}): Promise<boolean> => {\n const checked = listing(release.units);\n if (checked.length === 0) return true;\n doctorLine(output, \"\", paint(\"bold\", STEP));\n let allSet = true;\n for (const entry of checked) {\n entry.toCheck\n .listedTwice()\n .forEach((name) =>\n doctorLine(\n output,\n paint(\"yellow\", \"!\"),\n `${entry.unit.name}: ${name} is in all and listed again`,\n ),\n );\n const port = platformEnvOf({ release, shell }, entry.unit);\n if (\"cannotList\" in port) {\n doctorLine(\n output,\n paint(\"yellow\", \"!\"),\n `${entry.unit.name}: can't check env on ${port.cannotList}`,\n );\n continue;\n }\n for (const environment of ENVIRONMENTS) {\n allSet = (await reportUnit(output, port, entry, environment)) && allSet;\n }\n }\n return allSet;\n};\n","import path from \"node:path\";\n\nimport type { Requirement } from \"../ports/delivery.port\";\nimport type { Shell } from \"../ports/shell.port\";\nimport type { Release } from \"./config/loadRelease\";\nimport type { ReleaseContext } from \"./context\";\nimport { fail } from \"./say\";\nimport { commandLine } from \"./targets\";\nimport { unattended } from \"./unattended\";\n\n/**\n * Every tool and sign-in the flow, the features and the modules need, once each. With `apps`, only\n * the modules shipping one of those apps count.\n */\nexport const requirementsOf = (release: Release, apps?: ReadonlySet<string>): Requirement[] => {\n const required: Requirement[] = [\n ...[\n release.flow.sourceControl,\n release.flow.codeHost,\n release.flow.ciPipeline,\n release.flow.versioning,\n ].flatMap((adapter) => adapter.requirements?.() ?? []),\n ...modulesRequire(release, apps),\n ...release.features.flatMap((feature) => feature.requirements?.() ?? []),\n ];\n return onceEach(required);\n};\n\n/** The sign-ins only the modules shipping those apps need, once each. */\nexport const signInsOf = (release: Release, apps: ReadonlySet<string>): Requirement[] =>\n onceEach(modulesRequire(release, apps));\n\nconst modulesRequire = (release: Release, apps?: ReadonlySet<string>) =>\n release.modules.flatMap((module) => {\n const shipped = release.units.filter(\n ({ module: name, name: app }) => name === module.name && (!apps || apps.has(app)),\n );\n return apps && shipped.length === 0 ? [] : (module.requirements?.(shipped) ?? []);\n });\n\nconst onceEach = (required: Requirement[]) => {\n const seen = new Set<string>();\n return required.filter(({ label }) => !seen.has(label) && Boolean(seen.add(label)));\n};\n\n/** A requirement's check run from the root: its exit status, 127 when the tool is missing. */\nexport const checkStatus = async (shell: Shell, root: string, { check }: Requirement) =>\n (\n await shell.capture(check.command, check.args, {\n cwd: path.join(root, check.cwd ?? \"\"),\n env: check.env,\n })\n ).status;\n\n/**\n * Before a release writes anything: each sign-in its picked units need. A failing one offers its\n * fix, then is checked again. False, with the commands to run, when one still fails.\n */\nexport const preflight = (context: ReleaseContext, apps: ReadonlySet<string>) =>\n signIn(context, {\n requirements: requirementsOf(context.release, apps),\n again: \"run the release again\",\n });\n\n/** Each requirement checked; a failing one offers its fix. False, with the commands, when one still fails. */\nexport const signIn = async (\n context: ReleaseContext,\n { requirements, again }: { requirements: readonly Requirement[]; again: string },\n): Promise<boolean> => {\n const { shell, prompter, release } = context;\n const failing: Requirement[] = [];\n for (const requirement of requirements) {\n const status = await checkStatus(shell, release.root, requirement);\n if (status === 0) continue;\n const { fix } = requirement;\n const offered =\n fix !== undefined && status !== 127 && !unattended(context)\n ? await prompter.confirm(`Run ${commandLine(fix)} now?`, true)\n : false;\n if (offered && fix) {\n await shell.attach(fix.command, fix.args, {\n cwd: path.join(release.root, fix.cwd ?? \"\"),\n env: fix.env,\n });\n if ((await checkStatus(shell, release.root, requirement)) === 0) continue;\n }\n failing.push(requirement);\n }\n if (failing.length === 0) return true;\n fail(\n context,\n `Not signed in: ${failing.map(({ label }) => label).join(\", \")}`,\n `nothing was written. Sign in, then ${again}.`,\n [...failing.flatMap(({ fix }) => (fix ? [commandLine(fix)] : [])), \"shiplane\"],\n );\n return false;\n};\n","import path from \"node:path\";\nimport { z } from \"zod\";\n\nimport type { Files } from \"../ports/files.port\";\n\nconst Strings = z.record(z.string(), z.string());\n\n// A field npm would not write reads as absent, as a missing one does.\nconst lenient = <Schema extends z.ZodType>(schema: Schema) => schema.optional().catch(undefined);\n\nconst Fields = z.object({\n name: lenient(z.string()),\n version: lenient(z.string()),\n scripts: lenient(Strings),\n dependencies: lenient(Strings),\n devDependencies: lenient(Strings),\n});\n\n/** A package.json: the fields shiplane reads, every other one kept as written, in its order. */\nexport const PackageJsonSchema = z\n .record(z.string(), z.unknown())\n .transform((json) => ({ ...json, ...Fields.parse(json) }));\n\nexport type PackageJson = z.infer<typeof PackageJsonSchema>;\n\n/** A folder's package.json, or null when it has none or holds no object. */\nexport const readManifest = ({\n files,\n dir,\n}: {\n files: Pick<Files, \"read\">;\n dir: string;\n}): PackageJson | null => {\n const text = files.read(path.posix.join(dir, \"package.json\"));\n if (text === null) return null;\n return PackageJsonSchema.safeParse(JSON.parse(text)).data ?? null;\n};\n","import path from \"node:path\";\nimport { Document } from \"yaml\";\nimport { z } from \"zod\";\n\nimport type { ReleaseModule } from \"../modules/module\";\nimport type { AnyDeliveryAdapter } from \"../modules/suggest\";\nimport type { FolderView } from \"../ports/delivery.port\";\nimport type { Files } from \"../ports/files.port\";\nimport type { Release } from \"./config/loadRelease\";\nimport { suggestedModule } from \"../modules/suggest\";\nimport { UNIT_FILE } from \"./config/readUnitFile\";\nimport { unitJsonSchema } from \"./config/unitSchema\";\nimport { readManifest } from \"./manifest\";\n\nexport const CONFIG_FILE = \"shiplane.config.ts\";\n// Generated for the editor, never edited or committed: kept out of the repository's own folders.\nexport const SCHEMA_FILE = \"node_modules/.cache/shiplane/schema.json\";\nconst VSCODE_SETTINGS = \".vscode/settings.json\";\n\n/** `cloudflare-pages` → `cloudflarePages`. */\nexport const factoryName = (name: string) =>\n name.replace(/-([a-z])/g, (_match, letter: string) => letter.toUpperCase());\n\n/** `fly` serving servers → `flyServerHosting`, the factory an official adapter is imported by. */\nexport const adapterFactory = ({ name, capability }: AnyDeliveryAdapter) =>\n `${factoryName(name)}${factoryName(`-${capability}`)}`;\n\n/** A module as a config writes it: its factory, its name when not its kind, its adapter. */\nexport interface ModuleEntry {\n /** `webApp`. */\n factory: string;\n /** The port it fills: `staticHosting`. */\n port: string;\n /** The adapter's factory: `cloudflarePagesStaticHosting`. */\n adapter: string;\n /** Set when another module already holds the kind's name. */\n name?: string;\n /** Where the adapter's factory is imported from. */\n from: string;\n}\n\nexport const moduleCall = ({ factory, port, adapter, name }: ModuleEntry) =>\n `${factory}({ ${name ? `name: \"${name}\", ` : \"\"}${port}: ${adapter}() })`;\n\n/**\n * The module an app ships with, given what the release already composes: the one holding this\n * provider for that kind, else a new one under the kind's name, or the provider's when that is taken.\n */\nexport const placeModule = (\n adapter: AnyDeliveryAdapter,\n modules: readonly ReleaseModule[],\n pkg: string = INSTALLED,\n): { name: string; entry?: ModuleEntry } => {\n // A plugin is `<cli>-<provider>`; the shell adapter is built into the CLI itself.\n const from = adapter.name === \"shell\" ? pkg : pluginPackage(adapter.name);\n const { kind, factory, port } = suggestedModule(adapter);\n const held = modules.find((module) => module.kind === kind && module.provider === adapter.name);\n if (held) return { name: held.name };\n const taken = modules.some((module) => module.name === kind);\n const name = taken ? `${kind}-${adapter.name}` : kind;\n return {\n name,\n entry: {\n factory,\n port,\n adapter: adapterFactory(adapter),\n from,\n ...(taken ? { name } : {}),\n },\n };\n};\n\n/** The name other repositories install the CLI under. */\nconst INSTALLED = \"shiplane\";\nconst NAMES = /shiplane/;\n\n/** Where a plugin is installed from. */\nexport const pluginPackage = (plugin: string) => `@shiplane/${plugin}`;\n\n/** What a written config imports the CLI as. */\nexport const releasePackage = (files: Files) => {\n const manifest = readManifest({ files, dir: \".\" });\n const deps = { ...manifest?.dependencies, ...manifest?.devDependencies };\n return \"shiplane\" in deps ? \"shiplane\" : INSTALLED;\n};\n\nconst importLine = (names: Iterable<string>, from: string) =>\n `import { ${[...new Set(names)].sort().join(\", \")} } from \"${from}\";`;\n\n/** Which adapter fills a flow port in the config: its factory and where it is imported from. */\nexport interface FlowChoice {\n factory: string;\n from: string;\n}\n\nexport type FlowPort = \"sourceControl\" | \"codeHost\" | \"ciPipeline\" | \"versioning\";\n\nexport const FLOW_PORTS: readonly FlowPort[] = [\n \"sourceControl\",\n \"codeHost\",\n \"ciPipeline\",\n \"versioning\",\n];\n\n/** The flow setup writes when nothing else is chosen: git, GitHub, GitHub Actions, changesets. */\nexport const DEFAULT_FLOW: Record<FlowPort, FlowChoice> = {\n sourceControl: { factory: \"gitSourceControl\", from: pluginPackage(\"git\") },\n codeHost: { factory: \"gitHubCodeHost\", from: pluginPackage(\"github\") },\n ciPipeline: { factory: \"gitHubActionsCiPipeline\", from: pluginPackage(\"github\") },\n versioning: { factory: \"changesetsVersioning\", from: pluginPackage(\"changesets\") },\n};\n\n/** Versioning from commits: same plugin, and setup offers it when no changesets config exists. */\nexport const COMMITS_VERSIONING: FlowChoice = {\n factory: \"commitsVersioning\",\n from: pluginPackage(\"changesets\"),\n};\n\n/** Both ways of versioning run on changesets. Private packages, such as plugins, version too. */\nexport const CHANGESETS_CONFIG = `${JSON.stringify(\n {\n changelog: \"@changesets/cli/changelog\",\n commit: false,\n fixed: [],\n linked: [],\n access: \"restricted\",\n baseBranch: \"main\",\n updateInternalDependencies: \"patch\",\n ignore: [],\n privatePackages: { version: true, tag: false },\n },\n null,\n 2,\n)}\\n`;\n\nexport const CHANGESETS_CLI = { name: \"@changesets/cli\", version: \"^3.0.1\" };\n\n/** A root config with this flow (today's by default) and these modules, in the order given. */\nexport const renderConfig = (\n entries: readonly ModuleEntry[],\n pkg: string = INSTALLED,\n flow: Record<FlowPort, FlowChoice> = DEFAULT_FLOW,\n units?: readonly string[],\n) => {\n const byPlugin = new Map<string, string[]>();\n const add = (from: string, name: string) =>\n byPlugin.set(from, [...(byPlugin.get(from) ?? []), name]);\n FLOW_PORTS.forEach((port) => add(flow[port].from, flow[port].factory));\n const own = [\"defineRelease\", \"releaseFlow\", ...entries.map(({ factory }) => factory)];\n entries.forEach(({ adapter, from }) => {\n if (from === pkg) own.push(adapter);\n else add(from, adapter);\n });\n const local = (from: string) => from.startsWith(\".\");\n return [\n importLine(own, pkg),\n ...[...byPlugin]\n .filter(([from]) => !local(from))\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([from, names]) => importLine(names, from)),\n ...[...byPlugin]\n .filter(([from]) => local(from))\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([from, names]) => importLine(names, from)),\n \"\",\n \"export default defineRelease({\",\n \" flow: releaseFlow({\",\n ...FLOW_PORTS.map((port) => ` ${port}: ${flow[port].factory}(),`),\n \" }),\",\n ...(units ? [` units: [${units.map((unit) => JSON.stringify(unit)).join(\", \")}],`] : []),\n \" // What gets released, in this order. The first app is the repository's Latest release.\",\n \" modules: [\",\n ...entries.map((entry) => ` ${moduleCall(entry)},`),\n \" ],\",\n \"});\",\n \"\",\n ].join(\"\\n\");\n};\n\n/** The index of the bracket closing the one at `open`, or -1. */\nconst closing = (text: string, open: number) => {\n let depth = 0;\n for (let index = open; index < text.length; index += 1) {\n if (text[index] === \"[\") depth += 1;\n if (text[index] === \"]\") depth -= 1;\n if (depth === 0) return index;\n }\n return -1;\n};\n\n/** Adds a name to the CLI's import, under whichever name it has, or a new import when there is none. */\nconst withNamedImport = (config: string, name: string, pkg: string) => {\n const match = new RegExp(`import \\\\{([^}]*)\\\\} from \"(${NAMES.source})\";`).exec(config);\n if (!match) return `import { ${name} } from \"${pkg}\";\\n${config}`;\n const names =\n match[1]\n ?.split(\",\")\n .map((part) => part.trim())\n .filter(Boolean) ?? [];\n if (names.includes(name)) return config;\n const line = `import { ${[...names, name].sort().join(\", \")} } from \"${match[2] ?? pkg}\";`;\n return config.replace(match[0], line);\n};\n\n/** Adds a module and its imports to an existing config, or null when its shape is not ours. */\nexport const addToConfig = (\n config: string,\n entry: ModuleEntry,\n pkg: string = INSTALLED,\n): string | null => {\n const start = config.search(/modules:\\s*\\[/);\n if (start < 0) return null;\n const open = config.indexOf(\"[\", start);\n const close = closing(config, open);\n if (close < 0) return null;\n const call = moduleCall(entry);\n const inner = config.slice(open + 1, close);\n const trimmed = inner.trimEnd();\n const tail = inner.slice(trimmed.length);\n const comma = trimmed === \"\" || trimmed.endsWith(\",\") ? \"\" : \",\";\n const added = inner.includes(\"\\n\")\n ? `${trimmed}${comma}\\n ${call},${tail}`\n : `${trimmed}${comma}${trimmed === \"\" ? \"\" : \" \"}${call}${tail}`;\n const withCall = withNamedImport(\n `${config.slice(0, open + 1)}${added}${config.slice(close)}`,\n entry.factory,\n pkg,\n );\n // The built-in shell adapter joins the CLI's own import.\n if (entry.from === pkg) {\n return withNamedImport(withCall, entry.adapter, pkg);\n }\n const importLine = `import { ${entry.adapter} } from \"${entry.from}\";`;\n if (withCall.includes(importLine)) return withCall;\n const imports = [...withCall.matchAll(/^import [^;]*;$/gm)];\n const last = imports.at(-1);\n const at = last?.index === undefined ? 0 : last.index + last[0].length;\n return `${withCall.slice(0, at)}${at === 0 ? \"\" : \"\\n\"}${importLine}${at === 0 ? \"\\n\" : \"\"}${withCall.slice(at)}`;\n};\n\n/** A unit file naming its module, with the settings setup found, and where it found them. */\nexport const renderUnit = (\n module: string,\n options: Record<string, unknown>,\n { reason, schemaLine }: { reason?: string; schemaLine?: string },\n) => {\n const doc = new Document({ module, ...options });\n doc.commentBefore = [\n ...(schemaLine ? [` yaml-language-server: $schema=${schemaLine}`] : []),\n ` Written by shiplane init. Every key: shiplane docs ${module}`,\n ...(reason ? [` Read from ${reason}`] : []),\n ].join(\"\\n\");\n return doc.toString();\n};\n\ninterface JsonProperty {\n description?: string;\n default?: unknown;\n properties?: Record<string, JsonProperty>;\n required?: string[];\n}\n\ninterface DocumentedKey {\n key: string;\n description: string;\n default: unknown;\n required: boolean;\n}\n\n/** A schema's keys as dotted paths: a nested object lists each of its own keys, not itself. */\nconst flatten = (\n properties: Record<string, JsonProperty>,\n required: readonly string[],\n prefix = \"\",\n): DocumentedKey[] =>\n Object.entries(properties).flatMap(([name, property]) =>\n property.properties\n ? flatten(property.properties, property.required ?? [], `${prefix}${name}.`)\n : [\n {\n key: `${prefix}${name}`,\n description: property.description ?? \"\",\n default: property.default,\n required: required.includes(name),\n },\n ],\n );\n\n/** Every key a unit file takes, nested ones as `build.command`, for `shiplane docs`. */\nexport const documentedKeys = (settings: z.ZodObject): DocumentedKey[] => {\n const schema = z.toJSONSchema(settings, { io: \"input\", unrepresentable: \"any\" }) as JsonProperty;\n return flatten(schema.properties ?? {}, schema.required ?? []);\n};\n\n/** Each key a schema takes, with its description and default, from its JSON Schema. */\nexport const settingsKeys = (settings: z.ZodObject) => {\n const schema = z.toJSONSchema(settings, { io: \"input\", unrepresentable: \"any\" }) as {\n properties?: Record<string, JsonProperty>;\n required?: string[];\n };\n return Object.entries(schema.properties ?? {}).map(([key, property]) => ({\n key,\n description: property.description ?? \"\",\n default: property.default,\n required: schema.required?.includes(key) ?? false,\n }));\n};\n\n/** A unit file with only its module set and every other key commented, described. */\nexport const renderBlankUnit = (module: string, settings: z.ZodObject, schemaLine?: string) =>\n [\n ...(schemaLine ? [`# yaml-language-server: $schema=${schemaLine}`] : []),\n `# Written by shiplane init --blank. Uncomment and fill what applies.`,\n `module: ${module}`,\n ...settingsKeys(settings).flatMap(({ key, description, default: fallback, required }) => [\n \"\",\n `# ${description}${required ? \" (required)\" : \"\"}`,\n `# ${key}:${fallback === undefined ? \"\" : ` ${JSON.stringify(fallback)}`}`,\n ]),\n \"\",\n ].join(\"\\n\");\n\n/** The schema a unit file's editor reads, relative to that unit file. */\nexport const schemaLineFor = (dir: string) => path.posix.relative(dir, SCHEMA_FILE) || SCHEMA_FILE;\n\n/** The JSON Schema for every unit file: the module an app names picks the keys it takes. */\nexport const schemaText = (modules: readonly ReleaseModule[]) =>\n `${JSON.stringify(unitJsonSchema(modules), null, 2)}\\n`;\n\n/**\n * Writes the editor schema when it no longer matches the composed modules. It is generated, never\n * committed: every command keeps it current. True when it wrote.\n */\nexport const refreshEditorSchema = (files: Files, release: Release) => {\n const text = schemaText(release.modules);\n if (files.read(SCHEMA_FILE) === text) return false;\n files.write(SCHEMA_FILE, text);\n return true;\n};\n\n/** Maps every unit file to the schema once, keeping a settings file's comments as they are. */\nexport const withEditorSchema = (settings: string | null): string | null => {\n const entry = `\"yaml.schemas\": { \"./${SCHEMA_FILE}\": \"**/${UNIT_FILE}\" }`;\n if (settings === null) return `{\\n ${entry}\\n}\\n`;\n if (settings.includes('\"yaml.schemas\"')) return null;\n const open = settings.indexOf(\"{\");\n if (open < 0) return null;\n return `${settings.slice(0, open + 1)}\\n ${entry},${settings.slice(open + 1)}`;\n};\n\nexport const editorSettingsFile = VSCODE_SETTINGS;\n\n/** A folder as adapters see it when recognising what ships from it. */\nexport const folderView = (files: Files, dir: string): FolderView => ({\n dir,\n name: path.posix.basename(dir),\n files: files.list(dir),\n has: (file) => files.exists(path.posix.join(dir, file)),\n read: (file) => files.read(path.posix.join(dir, file)),\n});\n\n/** The repository's short name: its package name without scope, else its folder's. */\nexport const repositoryName = (files: Files, root: string) => {\n const name = readManifest({ files, dir: \".\" })?.name;\n return name === undefined ? path.basename(root) : name.replace(/^@[^/]+\\//, \"\");\n};\n","import path from \"node:path\";\n\nimport type { Requirement } from \"../ports/delivery.port\";\nimport type { SetupContext } from \"./setupContext\";\nimport { checkCallerWorkflow } from \"./callerWorkflow\";\nimport { UNIT_FILE } from \"./config/readUnitFile\";\nimport { releaseOrder } from \"./releaseOrder\";\nimport { reportEnvToCheck } from \"./reportEnvToCheck\";\nimport { checkStatus, requirementsOf } from \"./requirements\";\nimport { paint } from \"./say\";\nimport { refreshEditorSchema } from \"./setupFiles\";\nimport { commandLine } from \"./targets\";\n\n/**\n * `shiplane doctor`: the config as written, the editor schema refreshed, the release order, a warning\n * for each module no app names, then every tool and sign-in the flow, modules and features need, each\n * failure with the command that fixes it, offered to run, and the workflow that ships on CI.\n */\nexport const doctor = async (\n context: SetupContext,\n { yes }: { yes: boolean } = { yes: false },\n): Promise<boolean> => {\n const { output, files, shell, prompter, root } = context;\n output.line();\n output.line(`${paint(\"cyan\", \"◆\")} ${paint(\"bold\", \"shiplane doctor\")}`);\n const release = await context.load();\n if (release.problems.length > 0) {\n release.problems.forEach(({ file, line, message, hint }) => {\n output.line(\n `${paint(\"red\", \"✗\")} ${paint(\"bold\", line === undefined ? file : `${file}:${line}`)} ${message}`,\n );\n if (hint) output.line(` ${paint(\"dim\", hint)}`);\n });\n return false;\n }\n refreshEditorSchema(files, release);\n const appsOf = (name: string) => release.units.filter(({ module }) => module === name);\n if (release.units.length > 0) {\n output.line(`${paint(\"dim\", \"│\")} Order ${paint(\"dim\", releaseOrder(release.units))}`);\n }\n release.modules\n .filter((module) => appsOf(module.name).length === 0)\n .forEach(({ name }) =>\n output.line(\n `${paint(\"dim\", \"│\")} ${paint(\"yellow\", \"!\")} ${name} ${paint(\"dim\", `no app names it: module: ${name} in a ${UNIT_FILE}`)}`,\n ),\n );\n (release.renames ?? []).forEach(({ from, to }) =>\n output.line(\n `${paint(\"dim\", \"│\")} ${paint(\"yellow\", \"!\")} ${paint(\"dim\", `rename ${from} to ${to}: the old name still works for now`)}`,\n ),\n );\n const unique = requirementsOf(release);\n const failing: Requirement[] = [];\n const missing = new Set<string>();\n for (const requirement of unique) {\n const { check } = requirement;\n const status = await checkStatus(shell, root, requirement);\n if (status === 0) {\n output.line(`${paint(\"dim\", \"│\")} ${paint(\"green\", \"✓\")} ${requirement.label}`);\n continue;\n }\n failing.push(requirement);\n if (status === 127) missing.add(check.command);\n const fix =\n status === 127\n ? `not installed: ${check.command}`\n : requirement.fix\n ? `fix: ${commandLine(requirement.fix)}`\n : \"not available here\";\n output.line(\n `${paint(\"dim\", \"│\")} ${paint(\"red\", \"✗\")} ${requirement.label} ${paint(\"dim\", fix)}`,\n );\n }\n for (const { fix } of failing) {\n if (!fix || !prompter.interactive || missing.has(fix.command)) continue;\n if (await prompter.confirm(`Run ${commandLine(fix)} now?`)) {\n await shell.attach(fix.command, fix.args, {\n cwd: path.join(root, fix.cwd ?? \"\"),\n env: fix.env,\n });\n }\n }\n const shipsOnCi = await checkCallerWorkflow(context, release, { yes });\n const envSet = await reportEnvToCheck({ release, shell, output });\n const passed = failing.length === 0 && shipsOnCi && envSet;\n output.line(\n `${paint(\"dim\", \"└\")} Next: ${paint(\"cyan\", passed ? \"shiplane status\" : \"shiplane doctor\")}`,\n );\n return passed;\n};\n","import path from \"node:path\";\n\nimport type { ReleaseModule } from \"../modules/module\";\nimport type { AnyDeliveryAdapter } from \"../modules/suggest\";\nimport type { Detection, FolderView } from \"../ports/delivery.port\";\nimport type { SetupContext } from \"./setupContext\";\nimport type { ModuleEntry } from \"./setupFiles\";\nimport { moduleFor } from \"../modules/suggest\";\nimport { UNIT_FILE, UNIT_FILES } from \"./config/readUnitFile\";\nimport { isRecord } from \"./config/values\";\nimport { expandPatterns, workspacePatterns } from \"./config/workspaceFolders\";\nimport { doctor } from \"./doctor\";\nimport { paint } from \"./say\";\nimport {\n addToConfig,\n CONFIG_FILE,\n editorSettingsFile,\n folderView,\n placeModule,\n releasePackage,\n renderBlankUnit,\n renderConfig,\n renderUnit,\n repositoryName,\n SCHEMA_FILE,\n schemaLineFor,\n schemaText,\n withEditorSchema,\n} from \"./setupFiles\";\n\ninterface Candidate {\n folder: FolderView;\n /** The adapter that recognised it best: found, then likely, then possible. */\n guess: { adapter: AnyDeliveryAdapter; detection: Detection } | null;\n}\n\ninterface Placed {\n folder: FolderView;\n adapter: AnyDeliveryAdapter;\n options: Record<string, unknown>;\n reason?: string;\n}\n\ninterface Write {\n file: string;\n text: string;\n created: boolean;\n}\n\nconst bar = paint(\"dim\", \"│\");\n\n/** Sets `key`, dotted, in a nested object. */\nconst setAt = (target: Record<string, unknown>, key: string, value: unknown) => {\n const [head = \"\", ...rest] = key.split(\".\");\n if (rest.length === 0) {\n target[head] = value;\n return;\n }\n const child = isRecord(target[head]) ? target[head] : {};\n target[head] = child;\n setAt(child, rest.join(\".\"), value);\n};\n\n/** Each workspace folder with a manifest and no unit file yet, with what adapters recognise in it. */\nexport const scanFolders = (\n context: SetupContext,\n adapters: readonly AnyDeliveryAdapter[],\n): Candidate[] =>\n expandPatterns(context.root, workspacePatterns(context.root))\n .filter((dir) => dir !== \".\" && context.files.exists(path.posix.join(dir, \"package.json\")))\n .filter((dir) => !UNIT_FILES.some((name) => context.files.exists(path.posix.join(dir, name))))\n .map((dir) => {\n const folder = folderView(context.files, dir);\n const detections = adapters.flatMap((adapter) => {\n const detection = adapter.detect?.(folder);\n return detection ? [{ adapter, detection }] : [];\n });\n const strongest = ([\"found\", \"likely\", \"possible\"] as const)\n .map((certainty) => detections.find(({ detection }) => detection.certainty === certainty))\n .find(Boolean);\n const guess = strongest ?? null;\n return { folder, guess };\n });\n\n/** The options a placed folder needs that its folder did not say, asked or taken as suggested. */\nexport const askOptions = async (\n context: SetupContext,\n folder: FolderView,\n adapter: AnyDeliveryAdapter,\n found: Record<string, unknown>,\n yes: boolean,\n) => {\n const options = structuredClone(found);\n const repository = repositoryName(context.files, context.root);\n for (const question of adapter.questions?.(folder, options, repository) ?? []) {\n const answer = yes\n ? (question.initial ?? null)\n : await context.prompter.text(`${folder.dir} · ${question.message}`, question.initial);\n if (answer !== null && answer !== \"\") setAt(options, question.key, answer);\n }\n return options;\n};\n\nconst candidateLine = ({ folder, guess }: Candidate, width: number) => {\n const target =\n guess?.detection.certainty === \"found\"\n ? paint(\"green\", guess.adapter.name)\n : paint(\"yellow\", \"?\");\n return `${folder.dir.padEnd(width)}${target.padEnd(18)}${paint(\"dim\", guess?.detection.reason ?? \"\")}`;\n};\n\n/** Whether the person writes, after seeing the list, the diff if asked. */\nconst review = async (context: SetupContext, writes: Write[], yes: boolean) => {\n const { output, prompter } = context;\n output.line(`${paint(\"cyan\", \"◆\")} ${paint(\"bold\", \"Write these files?\")}`);\n writes.forEach(({ file, created }) =>\n output.line(`${bar} ${created ? paint(\"green\", \"+\") : paint(\"yellow\", \"~\")} ${file}`),\n );\n if (yes) return true;\n for (;;) {\n const answer = await prompter.select(\n \"Write these files?\",\n [\n { value: \"write\", label: \"Write\" },\n { value: \"diff\", label: \"Show the files\" },\n { value: \"cancel\", label: \"Cancel, write nothing\" },\n ],\n \"write\",\n );\n if (answer !== \"diff\") return answer === \"write\";\n writes.forEach(({ file, text }) => {\n output.line();\n output.line(paint(\"bold\", file));\n text.split(\"\\n\").forEach((line) => output.line(` ${line}`));\n });\n }\n};\n\n/** The config: written whole the first time, else each new module added to the one there. */\nconst configWrites = (\n { files }: SetupContext,\n { existing, entries, pkg }: { existing: boolean; entries: readonly ModuleEntry[]; pkg: string },\n): Write[] => {\n if (!existing) return [{ file: CONFIG_FILE, text: renderConfig(entries, pkg), created: true }];\n const before = files.read(CONFIG_FILE) ?? \"\";\n const config = entries.reduce((text, entry) => addToConfig(text, entry, pkg) ?? text, before);\n if (config === files.read(CONFIG_FILE)) return [];\n return [{ file: CONFIG_FILE, text: config, created: false }];\n};\n\n/** The editor's settings mapping unit files to the schema, unless an earlier init mapped them. */\nconst editorWrites = ({ files, output }: SetupContext): Write[] => {\n const current = files.read(editorSettingsFile);\n if (current?.includes(`./${SCHEMA_FILE}`)) return [];\n const settings = withEditorSchema(current);\n if (settings) {\n return [\n { file: editorSettingsFile, text: settings, created: !files.exists(editorSettingsFile) },\n ];\n }\n output.line(\n `${bar} ${paint(\"dim\", `${editorSettingsFile} already maps yaml.schemas: add ./${SCHEMA_FILE} for **/${UNIT_FILE}`)}`,\n );\n return [];\n};\n\n/**\n * `shiplane init`: finds every workspace folder, guesses how each ships from what it holds, asks only\n * what it cannot tell, shows every file, writes them, then runs doctor. Run again, it offers the\n * folders added since and never rewrites a unit file. `--yes` takes every guess, `--blank` writes\n * commented templates.\n */\nexport const initRelease = async (\n context: SetupContext,\n { yes, blank }: { yes: boolean; blank: boolean },\n): Promise<boolean> => {\n const { output, prompter, files } = context;\n const existing = files.exists(CONFIG_FILE) ? await context.load() : null;\n const adapters = context.adapters;\n const candidates = scanFolders(context, adapters);\n output.line(`${paint(\"dim\", \"┌\")} ${paint(\"bold\", \"shiplane init\")}`);\n output.line(bar);\n output.line(\n `${paint(\"green\", \"◇\")} Workspace ${paint(\"dim\", workspacePatterns(context.root).join(\", \"))}`,\n );\n output.line(bar);\n if (existing) {\n output.line(`${paint(\"cyan\", \"◆\")} ${paint(\"bold\", \"Since the last init\")}`);\n candidates\n .filter(({ guess }) => guess)\n .forEach(({ folder, guess }) =>\n output.line(\n `${bar} ${paint(\"green\", \"+\")} ${folder.dir.padEnd(14)}${paint(\"dim\", `new folder, ${guess?.detection.reason ?? \"\"}`)}`,\n ),\n );\n output.line(\n `${bar} ${paint(\"dim\", \"=\")} ${`${existing.units.length} folders`.padEnd(14)}${paint(\"dim\", \"unchanged, your edits kept\")}`,\n );\n output.line(bar);\n }\n const placeable = candidates.filter(({ guess }) => guess !== null);\n const width = Math.max(14, ...placeable.map(({ folder }) => folder.dir.length)) + 2;\n placeable.forEach((candidate) => output.line(`${bar} ${candidateLine(candidate, width)}`));\n const unplaced = candidates.length - placeable.length;\n if (unplaced > 0) {\n const folders = `${unplaced} folder${unplaced === 1 ? \"\" : \"s\"}`;\n output.line(\n `${bar} ${paint(\"dim\", `◻ ${folders} with nothing to ship them, versioned only (shiplane add <folder> ships one)`)}`,\n );\n }\n output.line(bar);\n const offered = placeable;\n const pickedDirs = yes\n ? offered.map(({ folder }) => folder.dir)\n : await prompter.multiselect(\n \"Which folders ship somewhere?\",\n offered.map(({ folder, guess }) => ({\n value: folder.dir,\n label: folder.dir,\n hint: guess ? `${guess.adapter.name} · ${guess.detection.reason}` : \"\",\n })),\n offered.map(({ folder }) => folder.dir),\n );\n if (pickedDirs === null) {\n output.line(paint(\"dim\", \"Nothing written.\"));\n return true;\n }\n const placed: Placed[] = [];\n for (const candidate of candidates.filter(({ folder }) => pickedDirs.includes(folder.dir))) {\n const { folder, guess } = candidate;\n const sure = guess?.detection.certainty === \"found\";\n const name =\n sure || yes\n ? (guess?.adapter.name ?? \"skip\")\n : await prompter.select(\n `How does ${folder.dir} ship?`,\n [\n ...adapters.map((adapter) => ({\n value: adapter.name,\n label: adapter.name,\n hint:\n adapter.name === guess?.adapter.name\n ? `${guess.detection.reason} (recommended)`\n : \"\",\n })),\n { value: \"skip\", label: \"skip\", hint: \"versioned, never shipped\" },\n ],\n guess?.adapter.name,\n );\n const adapter = adapters.find((candidateAdapter) => candidateAdapter.name === name);\n if (!adapter) continue;\n const found = guess?.adapter === adapter ? guess.detection.options : {};\n const options = blank ? {} : await askOptions(context, folder, adapter, found, yes);\n placed.push({\n folder,\n adapter,\n options,\n reason: guess?.adapter === adapter ? guess.detection.reason : undefined,\n });\n }\n const extras = [\n ...(files.exists(\".vscode\")\n ? [{ value: \"editor\", label: \"editor autocompletion\", hint: editorSettingsFile }]\n : []),\n ];\n const chosen = yes\n ? extras.map(({ value }) => value)\n : extras.length === 0\n ? []\n : await prompter.multiselect(\n \"Also set up\",\n extras,\n extras.map(({ value }) => value),\n );\n const editor = (chosen ?? []).includes(\"editor\");\n const modules: ReleaseModule[] = [...(existing?.modules ?? [])];\n const entries: ModuleEntry[] = [];\n const pkg = releasePackage(files);\n const named = placed.map((entry) => {\n const { name, entry: added } = placeModule(entry.adapter, modules, pkg);\n if (added) {\n entries.push(added);\n modules.push(moduleFor(entry.adapter, name));\n }\n return { ...entry, module: name };\n });\n const writes: Write[] = configWrites(context, { existing: existing !== null, entries, pkg });\n named.forEach(({ folder, adapter, module, options, reason }) => {\n const schemaLine = editor ? undefined : schemaLineFor(folder.dir);\n writes.push({\n file: path.posix.join(folder.dir, UNIT_FILE),\n text: blank\n ? renderBlankUnit(module, adapter.settings, schemaLine)\n : renderUnit(module, options, { reason, schemaLine }),\n created: true,\n });\n });\n writes.push({\n file: SCHEMA_FILE,\n text: schemaText(modules),\n created: !files.exists(SCHEMA_FILE),\n });\n if (editor) writes.push(...editorWrites(context));\n if (!(await review(context, writes, yes))) {\n output.line(paint(\"dim\", \"Nothing written.\"));\n return true;\n }\n writes.forEach(({ file, text }) => files.write(file, text));\n output.line(\n `${paint(\"green\", \"◇\")} Wrote ${writes.length} file${writes.length === 1 ? \"\" : \"s\"}`,\n );\n return doctor(context);\n};\n","import path from \"node:path\";\n\nimport type { SetupContext } from \"./setupContext\";\nimport type { ModuleEntry } from \"./setupFiles\";\nimport { moduleFor } from \"../modules/suggest\";\nimport { UNIT_FILE } from \"./config/readUnitFile\";\nimport { askOptions, scanFolders } from \"./initRelease\";\nimport { paint } from \"./say\";\nimport {\n addToConfig,\n CONFIG_FILE,\n moduleCall,\n placeModule,\n releasePackage,\n renderUnit,\n SCHEMA_FILE,\n schemaText,\n} from \"./setupFiles\";\n\n/** A new module joins the config's modules, or the person is told where to add it. */\nconst addModule = (\n { files, output }: SetupContext,\n { entry, pkg }: { entry: ModuleEntry; pkg: string },\n) => {\n const config = addToConfig(files.read(CONFIG_FILE) ?? \"\", entry, pkg);\n if (config) {\n files.write(CONFIG_FILE, config);\n return;\n }\n output.line(`${paint(\"yellow\", \"!\")} add ${moduleCall(entry)} to the modules in ${CONFIG_FILE}`);\n};\n\n/** `shiplane add <folder>`: init's questions for one folder, its unit file written. */\nexport const addUnit = async (context: SetupContext, dir: string): Promise<boolean> => {\n const { output, prompter, files } = context;\n const folderDir = path.posix.normalize(dir).replace(/\\/$/, \"\");\n const candidate = scanFolders(context, context.adapters).find(\n ({ folder }) => folder.dir === folderDir,\n );\n if (!candidate) {\n output.line(\n `${paint(\"red\", \"✗\")} ${folderDir} is not a workspace folder without a ${UNIT_FILE}`,\n );\n return false;\n }\n const { folder, guess } = candidate;\n const name =\n guess?.detection.certainty === \"found\"\n ? guess.adapter.name\n : await prompter.select(\n `How does ${folder.dir} ship?`,\n context.adapters.map((adapter) => ({\n value: adapter.name,\n label: adapter.name,\n hint:\n adapter.name === guess?.adapter.name ? `${guess.detection.reason} (recommended)` : \"\",\n })),\n guess?.adapter.name,\n );\n const adapter = context.adapters.find((offered) => offered.name === name);\n if (!adapter) return false;\n const found = guess?.adapter === adapter ? guess.detection.options : {};\n const options = await askOptions(context, folder, adapter, found, false);\n const file = path.posix.join(folder.dir, UNIT_FILE);\n if (!(await prompter.confirm(`Write ${file}?`))) {\n output.line(paint(\"dim\", \"Nothing written.\"));\n return true;\n }\n const release = await context.load();\n const pkg = releasePackage(files);\n const placed = placeModule(adapter, release.modules, pkg);\n files.write(file, renderUnit(placed.name, options, { reason: guess?.detection.reason }));\n if (placed.entry) addModule(context, { entry: placed.entry, pkg });\n const modules = placed.entry\n ? [...release.modules, moduleFor(adapter, placed.name)]\n : release.modules;\n files.write(SCHEMA_FILE, schemaText(modules));\n output.line(`${paint(\"green\", \"◇\")} Wrote ${file}`);\n return true;\n};\n\n/** `shiplane remove <unit>`: its unit file goes; changesets still version it. */\nexport const removeUnit = async (context: SetupContext, name: string): Promise<boolean> => {\n const { output, prompter, files } = context;\n const unit = (await context.load()).units.find((candidate) => candidate.name === name);\n if (!unit) {\n output.line(`${paint(\"red\", \"✗\")} no unit named \"${name}\"`);\n return false;\n }\n if (!(await prompter.confirm(`Stop shipping ${name}? It stays versioned.`))) return true;\n files.remove(unit.file);\n output.line(`${paint(\"green\", \"◇\")} Removed ${unit.file}`);\n return true;\n};\n","/** `1 version`, `3 versions`. */\nexport const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n","import type { UnitRef } from \"../domain/changes\";\nimport type { Environment } from \"../domain/environment\";\nimport type { ScopeInfo } from \"../domain/scope\";\nimport type { ReleaseUnit } from \"../domain/unit\";\nimport type { Deploy } from \"../ports/code-host.port\";\nimport type { ReleaseContext } from \"./context\";\nimport { changesetApps } from \"../domain/changes\";\nimport { deployRunTitle } from \"../domain/deploys\";\nimport { cameWithRelease, firstRelease, tagName } from \"../domain/tags\";\nimport { checkout, decideContext, hasNoEnvironment, jobInput, moduleOf } from \"./targets\";\n\nexport const MANIFEST = \"package.json\";\n\nexport const unitRefs = (units: readonly ReleaseUnit[]): UnitRef[] =>\n units.map(({ name, packageName }) => ({ name, packageName }));\n\n/** The units the pending changesets name. */\nexport const namedUnits = async ({ release, services }: ReleaseContext) =>\n new Set(\n (await services.versioning.pending()).flatMap(({ text }) =>\n changesetApps(text, unitRefs(release.units)),\n ),\n );\n\n/** A tag's deploy on an environment, from every record the host keeps. */\nexport const deployedOn = (history: readonly Deploy[], tag: string, environment: Environment) => {\n const states = history\n .filter(({ title }) => title === deployRunTitle(tag, environment))\n .map(({ state }) => state);\n if (states.includes(\"done\")) return \"done\";\n return states.includes(\"running\") ? \"running\" : \"none\";\n};\n\n/**\n * Each unit as the first question sees it: git for what is new, the host's deploy records for what\n * each environment runs (offline, nothing counts as deployed).\n */\nexport const readScope = async (\n context: ReleaseContext,\n environment: Environment,\n): Promise<ScopeInfo[]> => {\n const { release, services } = context;\n const pending = await services.versioning.pending();\n const refs = unitRefs(release.units);\n const named = pending.map(({ text }) => changesetApps(text, refs));\n const [deployed, tags] = await Promise.all([\n services.codeHost.deployments().catch(() => []),\n services.sourceControl.tags(),\n ]);\n return Promise.all(\n release.units.map(async (unit) => {\n const tag = tagName(unit.name, unit.version, context.release.tagFormat);\n const target = moduleOf(context, unit);\n const decidedBy = target?.decidedBy;\n const commit = await services.sourceControl.versionCommit(unit.dir, MANIFEST, unit.version);\n const tagged = (await services.sourceControl.tagCommit(tag)) !== null;\n // A module that reads its platform (a registry) says what runs; else deploy records do.\n const live = async (on: Environment) => {\n if (!target?.live || !tagged) return deployedOn(deployed, tag, on) === \"done\";\n const at = await checkout(context);\n const input = jobInput(context, target, unit, { tag, environment: on, ...at });\n return target.live(decideContext(context), input).catch(() => false);\n };\n return {\n app: unit.name,\n version: unit.version,\n changesets: named.filter((apps) => apps.includes(unit.name)).length,\n tagged,\n versioned:\n commit !== null && cameWithRelease({ app: unit.name, version: unit.version, commit }),\n firstRelease:\n !tagged &&\n commit !== null &&\n firstRelease(unit.name, unit.version, tags, context.release.tagFormat),\n onChannel: await live(environment),\n onPreview: await live(\"preview\"),\n ...(decidedBy ? { decidedBy } : {}),\n ...(target?.releaseOnly ? { releaseOnly: true } : {}),\n ...(target && hasNoEnvironment(target) ? { noEnvironment: true } : {}),\n };\n }),\n );\n};\n","import type { OpenPr } from \"../domain/releasePr\";\nimport type { ReleaseContext } from \"./context\";\nimport { CommandFailed } from \"../ports/shell.port\";\nimport { fail, paint, reasonOf } from \"./say\";\n\n/** How a step takes back what it did, and what a person runs when that fails too. */\nexport interface Undo {\n label: string;\n run: () => Promise<void>;\n byHand: () => string[];\n}\n\n/** What a step leaves in place on purpose when a later one fails, and what finishes the job. */\nexport interface Kept {\n label: string;\n byHand: () => string[];\n}\n\n/** One labelled thing a release does; the label is what a dry run or a failure shows. */\nexport interface Step {\n label: string;\n run: () => Promise<void>;\n /** Run when a later step fails, so a stopped release leaves nothing half done. */\n undo?: Undo;\n /** What stays when a later step fails, said instead of claiming all was undone. */\n kept?: Kept;\n}\n\nconst MAX_OUTPUT_LINES = 40;\n\n/** What the failed command printed, so the person reads why without running it again. */\nconst printOutput = ({ output }: ReleaseContext, error: unknown) => {\n if (!(error instanceof CommandFailed) || !error.output) return;\n const lines = error.output.split(\"\\n\");\n const shown = lines.slice(-MAX_OUTPUT_LINES);\n if (shown.length < lines.length) {\n output.line(paint(\"dim\", ` … ${lines.length - shown.length} earlier lines`));\n }\n shown.forEach((line) => output.line(paint(\"dim\", ` │ ${line}`)));\n};\n\n/** Takes back the steps that ran, newest first; one that cannot be undone never stops the rest. */\nconst cancel = async (context: ReleaseContext, ran: readonly Step[]) => {\n const undos = ran.flatMap(({ undo }) => (undo ? [undo] : [])).reverse();\n const kept = ran.flatMap((step) => (step.kept ? [step.kept] : []));\n if (undos.length === 0 && kept.length === 0) return;\n const left: Undo[] = [];\n for (const undo of undos) {\n try {\n await context.progress.during(`undo: ${undo.label}`, \"working\", undo.run);\n } catch (error) {\n left.push(undo);\n context.progress.say(\n \"worried\",\n `${paint(\"red\", \"✗\")} undo ${undo.label}: ${reasonOf(error)}`,\n );\n }\n }\n if (left.length === 0 && kept.length === 0) {\n context.progress.say(\"resting\", paint(\"dim\", \"Cancelled: everything this run did is undone.\"));\n return;\n }\n const commands = [...new Set([...left, ...kept].flatMap(({ byHand }) => byHand()))];\n const these = commands.length > 1 ? \"these\" : \"this\";\n const ask = kept.length === 0 ? \"run these to finish the cleanup:\" : `run ${these} to finish:`;\n fail(\n context,\n \"Cancelled, not all of it\",\n [...kept.map(({ label }) => label), ask].join(\"; \"),\n commands,\n );\n};\n\n/**\n * Runs steps in order, each shown with its place in the run. At the first failure it says why,\n * with the command's own output, and undoes the steps that ran.\n */\nexport const runSteps = async (context: ReleaseContext, steps: readonly Step[]) => {\n for (const [index, step] of steps.entries()) {\n try {\n await context.progress.during(step.label, \"working\", step.run, {\n index,\n total: steps.length,\n });\n } catch (error) {\n fail(context, `${step.label} failed`, `${reasonOf(error)}, the steps after it did not run.`);\n printOutput(context, error);\n await cancel(context, steps.slice(0, index));\n return false;\n }\n }\n return true;\n};\n\n/** A branch from the default one; undone by dropping the changes made on it and the branch itself. */\nexport const branchStep = (\n { services: { sourceControl: source } }: ReleaseContext,\n { branch, from }: { branch: string; from: string },\n): Step => {\n let untracked = new Set<string>();\n return {\n label: `branch ${branch} from ${from}`,\n run: async () => {\n untracked = new Set(await source.changedFiles());\n await source.createBranch(branch);\n },\n undo: {\n label: `delete ${branch}`,\n run: async () => {\n const created = (await source.changedFiles()).filter((file) => !untracked.has(file));\n await source.discard(created);\n await source.switchTo(from);\n await source.deleteBranch(branch);\n },\n byHand: () => [\"git reset --hard\", `git switch ${from}`, `git branch -D ${branch}`],\n },\n };\n};\n\nexport const pushStep = (\n { services: { sourceControl: source } }: ReleaseContext,\n branch: string,\n): Step => ({\n label: `push ${branch}`,\n run: () => source.push(branch),\n undo: {\n label: `delete ${branch} on origin`,\n run: () => source.deleteRemoteBranch(branch),\n byHand: () => [`git push origin --delete ${branch}`],\n },\n});\n\n/** Opens a pull request; undone by closing it, with a comment saying why. */\nexport const openPrStep = (\n { services: { codeHost: host } }: ReleaseContext,\n label: string,\n open: () => Promise<OpenPr>,\n): Step => {\n let opened: OpenPr | null = null;\n return {\n label,\n run: async () => {\n opened = await open();\n },\n undo: {\n label: \"close the pull request\",\n run: async () => {\n if (opened) await host.closePr(opened, \"The release stopped part way, so it closed this.\");\n },\n byHand: () => (opened ? [`gh pr close ${opened.number}`] : []),\n },\n };\n};\n","import path from \"node:path\";\n\nimport type { BranchPublished } from \"../domain/branchRelease\";\nimport type { OpenPr } from \"../domain/releasePr\";\nimport type { Channel } from \"../domain/testChannel\";\nimport type { ReleaseUnit } from \"../domain/unit\";\nimport type { Files } from \"../ports/files.port\";\nimport type { ReleaseContext } from \"./context\";\nimport type { PackageJson } from \"./manifest\";\nimport type { Step } from \"./steps\";\nimport {\n BRANCH_COMMENT_MARKER,\n branchComment,\n installLine,\n repositoryOfPr,\n} from \"../domain/branchRelease\";\nimport { isNumbered, nextNumber, testTag, testVersion } from \"../domain/testChannel\";\nimport { readManifest } from \"./manifest\";\nimport { MANIFEST } from \"./readScope\";\nimport { signIn, signInsOf } from \"./requirements\";\nimport { paint, reasonOf } from \"./say\";\nimport { runSteps } from \"./steps\";\nimport { decideContext, moduleOf, runHere, shipPlanOf, unitTarget } from \"./targets\";\n\n/** Where this checkout stands, as a branch release reads it. */\nexport interface Here {\n branch: string;\n head: string;\n defaultBranch: string;\n /** Where origin's default branch stands, fetched as the position was read. */\n originMain: string;\n}\n\n/** One unit a branch release publishes, at its branch version. */\ninterface Candidate {\n unit: ReleaseUnit;\n version: string;\n}\n\n/** What a test release publishes, on which channel and npm tag, and the pending units it cannot test yet. */\nexport interface BranchPlan {\n channel: Channel;\n tag: string;\n publish: Candidate[];\n others: string[];\n}\n\nconst REGISTRY = \"package-registry\";\n\nconst isRegistry = (context: ReleaseContext, unit: ReleaseUnit) =>\n moduleOf(context, unit)?.capability === REGISTRY;\n\n/**\n * The units a test version covers: what the pending changesets release, each at the version the\n * next release gives it, so a test version always sorts above the last release. The same on every\n * branch: a changeset says what is meant to ship, a diff only what moved.\n */\nconst pendingUnits = async (\n context: ReleaseContext,\n): Promise<{ unit: ReleaseUnit; base: string }[]> => {\n const { releases } = await context.services.versioning.plan([], []);\n return context.release.units.flatMap((unit) => {\n const next = releases.find(({ name }) => name === unit.packageName)?.newVersion;\n return next ? [{ unit, base: next }] : [];\n });\n};\n\n/** The versions the unit's registry holds, to number a channel's next one. */\nconst publishedVersionsOf = async (context: ReleaseContext, unit: ReleaseUnit, here: Here) => {\n const target = unitTarget(context, {\n unit,\n environment: \"preview\",\n commit: here.head,\n defaultBranch: here.defaultBranch,\n });\n const read = target?.module.publishedVersions;\n if (!target || !read) throw new Error(`${unit.name}'s registry cannot list its versions`);\n return read(decideContext(context), target.input);\n};\n\n/**\n * The units this test version covers, at test versions on the channel: npm packages publish, the\n * other units are not available as test releases yet. A numbered channel reads each package's published versions for its next number.\n */\nexport const planBranch = async (\n context: ReleaseContext,\n { here, channel }: { here: Here; channel: Channel },\n): Promise<BranchPlan> => {\n const changed = await pendingUnits(context);\n const publish = await Promise.all(\n changed\n .filter(({ unit }) => isRegistry(context, unit))\n .map(async ({ unit, base }) => ({\n unit,\n version: testVersion({\n next: base,\n channel,\n branch: here.branch,\n sha: here.head,\n n: isNumbered(channel)\n ? nextNumber({\n published: await publishedVersionsOf(context, unit, here),\n next: base,\n channel,\n })\n : 0,\n }),\n })),\n );\n return {\n channel,\n tag: testTag(channel, here.branch),\n publish,\n others: changed.filter(({ unit }) => !isRegistry(context, unit)).map(({ unit }) => unit.name),\n };\n};\n\nconst manifestFile = ({ unit }: Candidate) => path.posix.join(unit.dir, MANIFEST);\n\nconst writeVersion = (files: Files, candidate: Candidate) => {\n const manifest = readManifest({ files, dir: candidate.unit.dir });\n if (!manifest) return;\n const versioned = { ...manifest, version: candidate.version };\n files.write(manifestFile(candidate), `${JSON.stringify(versioned, null, 2)}\\n`);\n};\n\n/** The step that writes each branch version into its package.json, for npm to publish. */\nconst versionStep = ({ files }: ReleaseContext, publish: readonly Candidate[]): Step => ({\n label: `set ${publish.map(({ unit, version }) => `${unit.name} ${version}`).join(\", \")}`,\n run: () => Promise.resolve(publish.forEach((candidate) => writeVersion(files, candidate))),\n});\n\n/** One package as the branch release publishes it: its name on the registry and its steps. */\ninterface Publishing {\n published: BranchPublished;\n steps: Step[];\n}\n\nconst NPM_REGISTRY = /^https?:\\/\\/registry\\.npmjs\\.(org|com)\\/?$/;\n\n/** Whether npm publishes the package to its public registry: no `publishConfig.registry` elsewhere. */\nconst publishesToNpmjs = (manifest: PackageJson | null) => {\n const config = manifest && \"publishConfig\" in manifest ? manifest.publishConfig : undefined;\n const registry =\n typeof config === \"object\" && config !== null && \"registry\" in config\n ? config.registry\n : undefined;\n return typeof registry !== \"string\" || NPM_REGISTRY.test(registry);\n};\n\n/** One unit at its branch version, as its registry publishes it under the branch's tag. */\nconst publishingOf = (\n context: ReleaseContext,\n { candidate, here, tag }: { candidate: Candidate; here: Here; tag: string },\n): Publishing[] => {\n const unit = { ...candidate.unit, version: candidate.version };\n const target = unitTarget(context, {\n unit,\n environment: \"preview\",\n commit: here.head,\n defaultBranch: here.defaultBranch,\n });\n if (!target) return [];\n const input = { ...target.input, distTag: tag };\n const name = target.module.publishedName?.(decideContext(context), input) ?? unit.packageName;\n const onNpmjs = publishesToNpmjs(readManifest({ files: context.files, dir: unit.dir }));\n const steps = shipPlanOf(context, target.module, input).jobs.map((job) => ({\n label: job.label,\n run: () => runHere(context, job, { tag: target.tag, environment: \"preview\" }),\n }));\n return [{ published: { name, version: candidate.version, tag, onNpmjs }, steps }];\n};\n\n/**\n * Writes the branch versions, publishes each package, then always puts every package.json back as\n * it was: nothing is committed, tagged or versioned. False when a step failed.\n */\nconst publishAll = async (\n context: ReleaseContext,\n { plan, publishing }: { plan: BranchPlan; publishing: readonly Publishing[] },\n) => {\n const originals = plan.publish\n .map(manifestFile)\n .map((file) => ({ file, text: context.files.read(file) }));\n const steps = [versionStep(context, plan.publish), ...publishing.flatMap(({ steps }) => steps)];\n try {\n return await runSteps(context, steps);\n } finally {\n originals.forEach(({ file, text }) => text !== null && context.files.write(file, text));\n }\n};\n\n/** Rows padded to their widest cell, two spaces apart. */\nconst padded = (rows: readonly string[][]) => {\n const widths = (rows[0] ?? []).map((_, column) =>\n Math.max(...rows.map((row) => (row[column] ?? \"\").length)),\n );\n return rows.map((row) =>\n row\n .map((cell, column) => cell.padEnd(widths[column] ?? 0))\n .join(\" \")\n .trimEnd(),\n );\n};\n\n/** What a dry run shows: each package at the version it would take, and the npm tag; true. */\nexport const printPlan = ({ output, progress }: ReleaseContext, plan: BranchPlan) => {\n progress.say(\"resting\", `Would publish on ${plan.channel}, npm tag ${plan.tag} (dry run)`);\n const [header = \"\", ...rows] = padded([\n [\"Package\", \"Version\", \"Install\"],\n ...plan.publish.map(({ unit, version }) => [\n unit.packageName,\n version,\n `npm i ${unit.packageName}@${plan.tag}`,\n ]),\n ]);\n output.line(paint(\"dim\", ` ${header}`));\n rows.forEach((row) => output.line(` ${row}`));\n output.line(paint(\"dim\", \" Nothing published.\"));\n return true;\n};\n\nconst printPublished = ({ output, progress }: ReleaseContext, published: BranchPublished[]) => {\n const [first] = published;\n progress.say(\"happy\", `${paint(\"green\", \"✓\")} Published under npm tag ${first?.tag ?? \"\"}`);\n const [header = \"\", ...rows] = padded([\n [\"Package\", \"Version\", \"Install\"],\n ...published.map((entry) => [entry.name, entry.version, installLine(entry)]),\n ]);\n output.line(paint(\"dim\", ` ${header}`));\n rows.forEach((row) => output.line(` ${row}`));\n};\n\n/**\n * The pull request's comment, from the config's template, edited each run; none without a pull\n * request. A failure is said, never undoes the publish.\n */\nconst commentOn = async (\n { services, output, release }: ReleaseContext,\n {\n pr,\n here,\n published,\n others,\n channel,\n }: {\n pr: OpenPr | null;\n here: Here;\n published: BranchPublished[];\n others: readonly string[];\n channel: Channel;\n },\n) => {\n if (!pr) return;\n const body = branchComment({\n sha: here.head,\n branch: here.branch,\n repository: repositoryOfPr(pr.url),\n published,\n others,\n channel,\n ...(release.testComment === undefined ? {} : { template: release.testComment }),\n });\n await services.codeHost\n .upsertComment({ on: pr, marker: BRANCH_COMMENT_MARKER, body })\n .then(() => output.line(paint(\"dim\", ` The install lines are on #${pr.number} too.`)))\n .catch((error: unknown) =>\n output.line(\n ` ${paint(\"yellow\", \"!\")} could not comment on #${pr.number}: ${reasonOf(error)}`,\n ),\n );\n};\n\n/** A test version ready to go: where it runs, its pull request if any, and what it publishes. */\nexport interface BranchRun {\n here: Here;\n pr: OpenPr | null;\n plan: BranchPlan;\n}\n\n/** Publishes the test version, prints its install lines and keeps them on the pull request, if any. */\nexport const publishBranch = async (context: ReleaseContext, run: BranchRun) => {\n // An expired npm token fails the publish as a 404: check the sign-in before writing a version.\n const signedIn = await signIn(context, {\n requirements: signInsOf(\n context.release,\n new Set(run.plan.publish.map(({ unit }) => unit.name)),\n ),\n again: \"run shiplane again\",\n });\n if (!signedIn) return false;\n const publishing = run.plan.publish.flatMap((candidate) =>\n publishingOf(context, { candidate, here: run.here, tag: run.plan.tag }),\n );\n if (!(await publishAll(context, { plan: run.plan, publishing }))) return false;\n const published = publishing.map((entry) => entry.published);\n printPublished(context, published);\n await commentOn(context, {\n pr: run.pr,\n here: run.here,\n published,\n others: run.plan.others,\n channel: run.plan.channel,\n });\n return true;\n};\n","import type { AppBump } from \"./changes\";\n\nexport interface OpenPr {\n number: number;\n url: string;\n /** The commit the PR's branch stands on, when the host says: main moving past it makes the PR stale. */\n head?: string;\n}\n\n/** Whether a release PR merges from the terminal, or waits for someone else to approve it. */\nexport type Approval = \"none\" | \"required\";\n\nexport type MergeMethod = \"--squash\" | \"--merge\" | \"--rebase\";\n\n/** What the pull request page offers: the methods the repository allows, and the one it preselects. */\nexport interface MergeMethods {\n allowed: MergeMethod[];\n preselected: MergeMethod | null;\n}\n\nexport type ReleaseStep =\n { step: \"wait-merge\"; prs: OpenPr[] } | { step: \"release-pr\" } | { step: \"ship\" };\n\n/**\n * Where `pnpm shiplane` picks up, from what main and GitHub hold right now. A merged release is\n * tagged and shipped before the next one is opened.\n */\nexport const nextStep = ({\n pending,\n releasePrs,\n untagged,\n}: {\n pending: number;\n /** The open release PR, if any; older releases may have left one per app. */\n releasePrs: OpenPr[];\n /** Versions a merged release moved that have no tag or release notes yet. */\n untagged: number;\n}): ReleaseStep => {\n if (releasePrs.length > 0) return { step: \"wait-merge\", prs: releasePrs };\n if (pending > 0 && untagged === 0) return { step: \"release-pr\" };\n return { step: \"ship\" };\n};\n\n// The tool's own name: a branch a person names chore/release-notes is never taken for one.\nexport const RELEASE_BRANCH_PREFIX = \"shiplane/release-\";\n\nexport const twoDigits = (value: number) => String(value).padStart(2, \"0\");\n\nexport const releaseBranchName = (now: Date) =>\n `${RELEASE_BRANCH_PREFIX}${now.getFullYear()}-${twoDigits(now.getMonth() + 1)}-${twoDigits(now.getDate())}-${twoDigits(now.getHours())}${twoDigits(now.getMinutes())}`;\n\nconst sentence = (items: string[]) =>\n items.length < 2 ? items.join(\"\") : `${items.slice(0, -1).join(\", \")} and ${items.at(-1)}`;\n\nconst MAX_LINE = 100;\n\n/** One app's release commit: `chore(api): release v0.0.4`. */\nexport const releaseCommitTitle = ({ app, to }: AppBump) => `chore(${app}): release v${to}`;\n\n// commitlint caps a header at 100; a squash merge appends \" (#12345)\", so a title keeps 9 spare.\nexport const MAX_TITLE = MAX_LINE - \" (#12345)\".length;\n\nconst counted = (count: number, word: string) => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** Each app's module kind, so a title calls services services and packages plugins. */\nexport type KindOf = (app: string) => string | undefined;\n\n/** What a title calls a unit of each module kind; several kinds at once are apps. */\nconst NOUN: Record<string, string> = {\n \"published-package\": \"package\",\n \"backend-service\": \"service\",\n \"web-app\": \"web app\",\n \"mobile-app\": \"mobile app\",\n \"internal-tool\": \"tool\",\n};\n\n/**\n * The apps, gathered into families in their own order: a root moving with its `root-*` apps\n * (`shiplane`, `shiplane-npm`) is one family; any other app is a family of one.\n */\nexport const releaseFamilies = (bumps: AppBump[]): AppBump[][] => {\n const roots = bumps.filter(\n ({ app }) => !bumps.some((other) => other.app !== app && app.startsWith(`${other.app}-`)),\n );\n return roots.map((root) =>\n bumps.filter(({ app }) => app === root.app || app.startsWith(`${root.app}-`)),\n );\n};\n\n/** One family as a title names it: `api v0.0.4`, `shiplane and 7 plugins v0.1.0`, `api v0.3.0 and 2 more services`. */\nconst familyLabel = ([root, ...members]: AppBump[], kindOf: KindOf) => {\n if (!root) return \"\";\n // One member is clearer named than counted: `api v0.3.0, api-worker v0.3.0`.\n if (members.length < 2)\n return [root, ...members].map(({ app, to }) => `${app} v${to}`).join(\", \");\n const kinds = new Set([root, ...members].map(({ app }) => kindOf(app)));\n const [kind] = kinds;\n const noun = (kinds.size === 1 && kind && NOUN[kind]) || \"app\";\n // A package's siblings extend it: plugins. Siblings of anything else are more of it.\n const rest =\n noun === \"package\"\n ? counted(members.length, \"plugin\")\n : `${members.length} more ${counted(members.length, noun).replace(/^\\d+ /, \"\")}`;\n return members.every(({ to }) => to === root.to)\n ? `${root.app} and ${rest} v${root.to}`\n : `${root.app} v${root.to} and ${rest}`;\n};\n\n/**\n * The release PRs a release opens, all from main at once: one per app, a family counting as one.\n * Apps `linked` (one changeset naming both, or one moving with the other) share a PR, so no two\n * PRs ever touch the same file.\n */\nexport const releasePrGroups = (\n bumps: AppBump[],\n linked: readonly (readonly string[])[],\n): AppBump[][] => {\n const groups = releaseFamilies(bumps).map((family) => new Set(family.map(({ app }) => app)));\n const merged = linked.reduce((current, apps) => {\n const touched = current.filter((group) => apps.some((app) => group.has(app)));\n if (touched.length < 2) return current;\n const union = new Set(touched.flatMap((group) => [...group]));\n return [...current.filter((group) => !touched.includes(group)), union];\n }, groups);\n // Kept in the release's own order, by each group's first app.\n const order = (group: Set<string>) => bumps.findIndex(({ app }) => group.has(app));\n return merged\n .sort((left, right) => order(left) - order(right))\n .map((group) => bumps.filter(({ app }) => group.has(app)));\n};\n\n/** Whether a title still fits once a squash merge appends its PR number. */\nexport const titleFits = (title: string) => title.length <= MAX_TITLE;\n\n/**\n * Conventional, and naming every app it brings, never a bare count: `chore(api): release v0.0.4`,\n * `chore(release): api v0.0.2 and admin v0.1.0`, or, when listing each one is too long, families\n * by their root: `chore(release): shiplane and 7 plugins v0.1.0, landing v1.2.0 and expo v2.1.0`.\n * One release is one PR: a title too long even then stays whole, see `titleFits`.\n */\nexport const releaseTitle = (bumps: AppBump[], kindOf: KindOf = () => undefined) => {\n const [first, ...others] = bumps;\n if (!first) return \"chore(release): package changelogs\";\n if (others.length === 0) return releaseCommitTitle(first);\n // One family is one app's release: `chore(shiplane): release v0.1.0`, its plugins in the body.\n const families = releaseFamilies(bumps);\n const [only] = families;\n if (families.length === 1 && only?.[0]) return releaseCommitTitle(only[0]);\n const every = `chore(release): ${sentence(bumps.map(({ app, to }) => `${app} v${to}`))}`;\n if (titleFits(every)) return every;\n // Families first: their own \"and\" never runs into the list's last one.\n families.sort((left, right) => Number(right.length > 1) - Number(left.length > 1));\n const labels = families.map((family) => familyLabel(family, kindOf));\n // Two families end the list: commas alone keep \"a and 2 more and b and 7 plugins\" from happening.\n const list = labels.at(-1)?.includes(\" and \") ? labels.join(\", \") : sentence(labels);\n return `chore(release): ${list}`;\n};\n\n/** A bullet wrapped to commitlint's 100-character body lines, continued under its text. */\nconst bullet = (text: string) =>\n text\n .split(\" \")\n .reduce<string[]>((lines, word) => {\n const last = lines.at(-1);\n if (last !== undefined && `${last} ${word}`.length <= MAX_LINE) {\n return [...lines.slice(0, -1), `${last} ${word}`];\n }\n return [...lines, `${last === undefined ? \"-\" : \" \"} ${word}`];\n }, [])\n .join(\"\\n\");\n\n/** The release commit's body: each app's version, then what its users get. */\nexport const releaseCommitBody = (bumps: AppBump[]) =>\n bumps\n .map(({ app, to, notes, movedWith }) => {\n const lines =\n notes.length > 0\n ? notes\n : movedWith.length > 0\n ? [`Moves with ${movedWith.join(\", \")}.`]\n : [];\n return [`${app} ${to}`, ...lines.map(bullet)].join(\"\\n\");\n })\n .join(\"\\n\\n\");\n\n/**\n * The release PR's body; `onMerge` says what happens to each unit once it is merged, `where` where\n * the run ships them, such as \"to preview\".\n */\nexport const releasePrBody = (\n bumps: AppBump[],\n onMerge: (bump: AppBump) => string,\n where: string,\n) => {\n const appWidth = Math.max(3, ...bumps.map(({ app }) => app.length));\n const versionWidth = Math.max(7, ...bumps.map(({ from, to }) => `${from} → ${to}`.length));\n const row = (cells: string[]) => `| ${cells.join(\" | \")} |`;\n const table = [\n row([\"App\".padEnd(appWidth), \"Version\".padEnd(versionWidth), \"On merge\"]),\n row([\"-\".repeat(appWidth), \"-\".repeat(versionWidth), \"--------\"]),\n ...bumps.map((bump) =>\n row([\n bump.app.padEnd(appWidth),\n `${bump.from} → ${bump.to}`.padEnd(versionWidth),\n onMerge(bump),\n ]),\n ),\n ];\n const notes = bumps.flatMap(({ app, to, notes: lines }) =>\n lines.length > 0 ? [\"\", `### ${app} ${to}`, \"\", ...lines.map((line) => `- ${line}`)] : [],\n );\n return [\n \"## 🎯 What & why\",\n \"\",\n `Versions the changesets merged since the last release. Squash and merge it by hand: \\`pnpm shiplane\\`, still running or run again, tags and ships ${where} once it is merged.`,\n \"\",\n ...(bumps.length > 0 ? table : [\"Internal packages only: changelogs, nothing ships.\"]),\n ...notes,\n \"\",\n \"## ✅ Testing\",\n \"\",\n \"Versions, changelogs and version files only. No UI change.\",\n ].join(\"\\n\");\n};\n\nconst MERGE_BUTTON: { value: MergeMethod; label: string; hint: string }[] = [\n {\n value: \"--merge\",\n label: \"Create a merge commit\",\n hint: \"every commit, joined by a merge commit\",\n },\n { value: \"--squash\", label: \"Squash and merge\", hint: \"the commits combined into one\" },\n { value: \"--rebase\", label: \"Rebase and merge\", hint: \"every commit, rebased onto main\" },\n];\n\n/** The methods as GitHub's merge button lists them, preselected as the pull request page does. */\nexport const mergeChoices = ({ allowed, preselected }: MergeMethods) => {\n const choices = MERGE_BUTTON.filter(({ value }) => allowed.includes(value));\n const initial = preselected && allowed.includes(preselected) ? preselected : choices[0]?.value;\n return { choices, initial };\n};\n\nexport type WaitAction = \"diff\" | \"merge\" | \"open\";\n\nconst WAIT_KEYS: Record<string, WaitAction> = { d: \"diff\", m: \"merge\", o: \"open\" };\n\n/** What a key does while the release waits for its pull request to merge. */\nexport const waitKey = (name: string | undefined): WaitAction | null =>\n (name && WAIT_KEYS[name]) || null;\n","import type { AppBump, BumpLevel, PlannedChangeset } from \"./changes\";\nimport { nextVersion } from \"./versions\";\n\n/** Biggest first: up the list is a bigger version, down a smaller one. */\nexport const LEVELS: readonly BumpLevel[] = [\"major\", \"minor\", \"patch\"];\n\nconst PLAIN_VERSION = /^\\d+\\.\\d+\\.\\d+$/;\n\nexport interface VersionChoices {\n /** The level versioning computed. */\n computed: BumpLevel;\n /** The version each level leads to. */\n versions: Record<BumpLevel, string>;\n}\n\n/** A version a person chose over the computed one. */\nexport interface ForcedVersion {\n /** Nothing in the release ships above it. */\n level: BumpLevel;\n /** Moves the release up to that level, and carries why into its notes. */\n changeset: PlannedChangeset;\n}\n\n/**\n * The versions a release can go to, when everything it moves lands on one version: a single unit\n * or a fixed group. Null when units move apart, or on a version no bump explains, a prerelease.\n */\nexport const versionChoices = (bumps: readonly AppBump[]): VersionChoices | null => {\n const [first] = bumps;\n if (!first || !PLAIN_VERSION.test(first.from)) return null;\n if (bumps.some(({ from, to }) => from !== first.from || to !== first.to)) return null;\n const { from, to } = first;\n const versions = {\n major: nextVersion(from, \"major\"),\n minor: nextVersion(from, \"minor\"),\n patch: nextVersion(from, \"patch\"),\n };\n const computed = LEVELS.find((level) => versions[level] === to);\n return computed ? { computed, versions } : null;\n};\n\n/** The person's choice, as what the release adds: `packages` are all those it moves. */\nexport const forcedVersion = (\n { computed, versions }: VersionChoices,\n level: BumpLevel,\n reason: string,\n packages: readonly string[],\n): ForcedVersion => ({\n level,\n changeset: {\n id: `forced-${versions[level]}`,\n releases: packages.map((name) => ({ name, type: level })),\n summary: `Version forced to ${versions[level]} instead of ${versions[computed]}: ${reason}`,\n },\n});\n","import type { StatusPlan, UnitRef } from \"./changes\";\n\n/** A unit that goes out with the picked ones without being picked, and why. */\nexport interface Companion {\n /** The unit's name. */\n app: string;\n version: string;\n /** The picked units it goes with. */\n with: string[];\n /** Why, as a person reads it. */\n why: string;\n}\n\n/** The shortest chain of moving packages from `from` to one a changeset names, breadth first. */\nconst chainTo = (\n from: string,\n dependencies: Record<string, string[]>,\n moving: ReadonlySet<string>,\n named: ReadonlySet<string>,\n): string[] => {\n const seen = new Set<string>();\n let paths = [[from]];\n while (paths.length > 0) {\n const next: string[][] = [];\n for (const path of paths) {\n const last = path[path.length - 1] ?? from;\n for (const dependency of dependencies[last] ?? []) {\n if (!moving.has(dependency) || seen.has(dependency)) continue;\n seen.add(dependency);\n const chain = [...path, dependency];\n if (named.has(dependency)) return chain.slice(1);\n next.push(chain);\n }\n }\n paths = next;\n }\n return [];\n};\n\n/**\n * Preview: the units a release moves that the person did not pick. changesets moves a unit whenever\n * a workspace package it uses moves, so it cannot stay behind; this says through which package.\n */\nexport const draggedUnits = (\n plan: StatusPlan,\n dependencies: Record<string, string[]>,\n units: readonly UnitRef[],\n scope: ReadonlySet<string>,\n): Companion[] => {\n const moving = new Set(plan.releases.map(({ name }) => name));\n const named = new Set(\n plan.releases.filter(({ changesets }) => changesets.length > 0).map(({ name }) => name),\n );\n const picked = units.filter(({ name }) => scope.has(name));\n return units.flatMap(({ name: app, packageName }) => {\n const release = plan.releases.find(({ name }) => name === packageName);\n if (scope.has(app) || !release) return [];\n const chain = chainTo(packageName, dependencies, moving, named);\n const source = chain[chain.length - 1];\n const movers = picked\n .filter((unit) =>\n plan.changesets.some(\n ({ releases }) =>\n releases.some(({ name }) => name === source) &&\n releases.some(({ name }) => name === unit.packageName),\n ),\n )\n .map(({ name }) => name);\n const whose = movers.length > 0 ? `${movers.join(\", \")}'s changes move` : \"this release moves\";\n return [\n {\n app,\n version: release.newVersion,\n with: movers,\n why:\n chain.length > 0\n ? `uses ${chain.join(\" → \")}, which ${whose}`\n : \"moves with this release\",\n },\n ];\n });\n};\n\n/** A unit's version on preview with its release notes. */\nexport interface Released {\n app: string;\n version: string;\n notes: string;\n}\n\nconst OWN_CHANGE = /^- ([0-9a-f]{7,40}): /gm;\nconst DEPENDENCY_CHANGES = /^- Updated dependencies \\[([^\\]]+)\\]/gm;\n\n/** The changes a version carries: its own, and those a package it uses moved for. */\nconst changeIds = (notes: string) =>\n new Set([\n ...[...notes.matchAll(OWN_CHANGE)].flatMap(([, id]) => (id ? [id] : [])),\n ...[...notes.matchAll(DEPENDENCY_CHANGES)].flatMap(([, ids]) =>\n (ids ?? \"\").split(\",\").map((id) => id.trim()),\n ),\n ]);\n\n/** A change's first line in these notes, with an ellipsis when it goes on. */\nconst summaryOf = (notes: string, id: string) => {\n const lines = notes.split(\"\\n\");\n const index = lines.findIndex((line) => line.startsWith(`- ${id}: `));\n const first = lines[index]?.slice(`- ${id}: `.length).trim();\n if (index < 0 || !first) return null;\n const goesOn = /^ {2}\\S/.test(lines[index + 1] ?? \"\");\n return goesOn ? `${first}…` : first;\n};\n\n/** The packages listed under the `Updated dependencies` line that names this change. */\nconst packagesMovedFor = (notes: string, id: string) => {\n const lines = notes.split(\"\\n\");\n const start = lines.findIndex(\n (line) => line.startsWith(\"- Updated dependencies [\") && line.includes(id),\n );\n if (start < 0) return [];\n const listed = lines.slice(start + 1);\n const end = listed.findIndex((line) => !/^ {2}- \\S+@/.test(line));\n return (end < 0 ? listed : listed.slice(0, end)).map((line) =>\n line\n .trim()\n .slice(2)\n .replace(/@[^@]*$/, \"\"),\n );\n};\n\n/** Why two versions went out together: the change they share, or the package both moved for. */\nconst sharedReason = (partner: Released, other: Released, id: string) => {\n const summary = summaryOf(partner.notes, id) ?? summaryOf(other.notes, id);\n if (summary) return ` for: ${summary}`;\n const theirs = new Set(packagesMovedFor(partner.notes, id));\n const both = packagesMovedFor(other.notes, id).filter((name) => theirs.has(name));\n return both.length > 0 ? `: both use ${both.join(\", \")}, which moved` : \"\";\n};\n\n/**\n * Production: the units preview runs with the picked ones that are not picked. Two versions went to\n * preview together when their notes share a change, their own or one a package they use moved for.\n */\nexport const releasedTogether = (picked: Released[], others: Released[]): Companion[] =>\n others.flatMap((other) => {\n const ids = changeIds(other.notes);\n const partners = picked.flatMap((partner) => {\n const shared = [...changeIds(partner.notes)].find((id) => ids.has(id));\n return shared ? [{ partner, shared }] : [];\n });\n const [first] = partners;\n if (!first) return [];\n const names = partners.map(({ partner }) => `${partner.app} ${partner.version}`).join(\", \");\n return [\n {\n app: other.app,\n version: other.version,\n with: partners.map(({ partner }) => partner.app),\n why: `went to preview with ${names}${sharedReason(first.partner, other, first.shared)}`,\n },\n ];\n });\n","import type { AppBump, PlannedChangeset } from \"../domain/changes\";\nimport type { Companion } from \"../domain/companions\";\nimport type { ForcedVersion } from \"../domain/versionChoice\";\nimport type { VersionChoice, VersionContribution } from \"../ports/delivery.port\";\nimport type { ReleaseContext } from \"./context\";\nimport { appBumps, packageBumps, splitChangesets } from \"../domain/changes\";\nimport { draggedUnits } from \"../domain/companions\";\nimport { namedUnits, unitRefs } from \"./readScope\";\nimport { checkout, decideContext, unitTarget } from \"./targets\";\nimport { unattended } from \"./unattended\";\n\nexport type Split = ReturnType<typeof splitChangesets>;\n\nconst NOTHING_HELD: Split = { ships: [], waits: [] };\n\nexport interface Prepared {\n /** The units the person picked. */\n scope: ReadonlySet<string>;\n /** The version the person chose over the computed one, when they did. */\n forced?: ForcedVersion;\n /** Changesets this release ships, the ones it writes included. */\n pending: number;\n /** Units the person left out: their changesets stay pending. */\n held: string[];\n split: Split;\n bumps: AppBump[];\n /** Units the person did not pick that move anyway, with the package that drags each. */\n companions: Companion[];\n /** Internal packages moved along: changelogs only. */\n packages: number;\n /** Changesets the release writes itself. */\n added: PlannedChangeset[];\n /** Every changeset the release versions, with the lines it ships. */\n shipped: PlannedChangeset[];\n /** What plugins add to the release PR, by unit: an EAS app's build or update. */\n contributions: Record<string, VersionContribution>;\n}\n\n/** The person's answer to a plugin's choice; the suggestion without a terminal or with --yes. */\nconst choose = async (context: ReleaseContext, choice: VersionChoice | undefined) => {\n if (!choice) return null;\n if (unattended(context)) return choice.suggested;\n return context.prompter.select(choice.question, choice.options, choice.suggested);\n};\n\n/** What each picked unit's plugin adds, given the unit's bump so far. One at a time: it may ask. */\nconst contributionsOf = async (\n context: ReleaseContext,\n scope: ReadonlySet<string>,\n bumps: readonly AppBump[],\n known: Readonly<Record<string, VersionContribution>> = {},\n) => {\n const at = await checkout(context);\n const contributions: Record<string, VersionContribution> = {};\n for (const unit of context.release.units.filter(({ name }) => scope.has(name))) {\n // Already answered for the whole release: one release PR of several never asks twice.\n const answered = known[unit.name];\n if (answered) {\n contributions[unit.name] = answered;\n continue;\n }\n const target = unitTarget(context, { unit, environment: \"preview\", ...at });\n const version = target?.module.version?.bind(target.module);\n if (!target || !version) continue;\n const { input } = target;\n const bump = bumps.find(({ app }) => app === unit.name);\n const contribute = (chosen?: string) =>\n version(decideContext(context), { ...input, bump, chosen });\n const suggested = await contribute();\n const chosen = await choose(context, suggested.choice);\n contributions[unit.name] =\n chosen && chosen !== suggested.choice?.suggested ? await contribute(chosen) : suggested;\n }\n return contributions;\n};\n\n/** What a release PR covering `scope` would version, computed without writing anything. */\nexport const prepareRelease = async (\n context: ReleaseContext,\n scope: ReadonlySet<string>,\n known: Readonly<Record<string, VersionContribution>> = {},\n forced?: ForcedVersion,\n): Promise<Prepared> => {\n const { release, services } = context;\n const refs = unitRefs(release.units);\n const [dependencies, named, base, pendingFiles] = await Promise.all([\n services.versioning.dependencies(),\n namedUnits(context),\n services.versioning.plan([], []),\n services.versioning.pending(),\n ]);\n const held = [...named].filter((app) => !scope.has(app));\n const split = held.length > 0 ? splitChangesets(base.changesets, held, refs) : NOTHING_HELD;\n const own = forced ? [forced.changeset] : [];\n const ceiling = forced?.level;\n const picked =\n held.length > 0 || forced ? await services.versioning.plan(own, split.waits, ceiling) : base;\n const contributions = await contributionsOf(\n context,\n scope,\n appBumps(picked, dependencies, refs),\n known,\n );\n const added = [\n ...own,\n ...Object.values(contributions).flatMap((contribution) => contribution.added),\n ];\n const plan =\n added.length > own.length\n ? await services.versioning.plan(added, split.waits, ceiling)\n : picked;\n return {\n scope,\n forced,\n pending: (held.length > 0 ? split.ships.length : pendingFiles.length) + added.length,\n held,\n split,\n bumps: appBumps(plan, dependencies, refs),\n companions: draggedUnits(plan, dependencies, refs, scope),\n packages: packageBumps(plan, refs),\n added,\n shipped: plan.changesets,\n contributions,\n };\n};\n","import type { BumpLevel } from \"../domain/changes\";\nimport type { VersionChoices } from \"../domain/versionChoice\";\nimport type { ReleaseContext } from \"./context\";\nimport type { Prepared } from \"./prepareRelease\";\nimport { forcedVersion, LEVELS, versionChoices } from \"../domain/versionChoice\";\nimport { prepareRelease } from \"./prepareRelease\";\nimport { confirm, fail, paint } from \"./say\";\nimport { unattended } from \"./unattended\";\n\n/** The release again at `level`, or null with why when versioning cannot land there. */\nconst forceVersion = async (\n context: ReleaseContext,\n prepared: Prepared,\n choices: VersionChoices,\n level: BumpLevel,\n reason: string,\n) => {\n const packages = prepared.bumps.flatMap(({ app }) =>\n context.release.units.filter(({ name }) => name === app).map((unit) => unit.packageName),\n );\n const forced = await prepareRelease(\n context,\n prepared.scope,\n {},\n forcedVersion(choices, level, reason, packages),\n );\n const version = choices.versions[level];\n const elsewhere = forced.bumps.find(({ to }) => to !== version);\n if (elsewhere) {\n fail(context, `Can't force ${version}`, `${elsewhere.app} would go to ${elsewhere.to}.`);\n return null;\n }\n context.output.line(\n ` ${paint([\"bold\", \"yellow\"], \"!\")} ${version} instead of ${choices.versions[choices.computed]}: ${reason}`,\n );\n return forced;\n};\n\n/**\n * The release to open: as computed, or at the version the person chose instead with why. Null when\n * they cancel. A plain yes when no one version covers the release, under --yes or with no terminal.\n */\nexport const chooseVersion = async (\n context: ReleaseContext,\n prepared: Prepared,\n where: string,\n): Promise<Prepared | null> => {\n const { prompter } = context;\n const choices = versionChoices(prepared.bumps);\n if (!choices || unattended(context)) {\n return (await confirm(context, `Release these ${where}?`, true)) ? prepared : null;\n }\n const { computed, versions } = choices;\n const picks = LEVELS.map((level) => ({\n value: level,\n label: `${versions[level]} ${level}${level === computed ? \", computed\" : \"\"}`,\n }));\n for (;;) {\n const level = await prompter.select(`Release these ${where} as (Esc cancels)`, picks, computed);\n if (!level) return null;\n if (level === computed) return prepared;\n const reason = await prompter.text(\n `Why ${versions[level]}? Tell users what changed, in one line.`,\n );\n // Esc or an empty line goes back to the versions.\n if (reason?.trim()) return forceVersion(context, prepared, choices, level, reason.trim());\n }\n};\n","import type { AppBump } from \"../domain/changes\";\nimport type { KindOf, OpenPr } from \"../domain/releasePr\";\nimport type { ReleaseContext } from \"./context\";\nimport type { Prepared } from \"./prepareRelease\";\nimport { releaseSource } from \"../domain/governance\";\nimport {\n releaseBranchName,\n releaseCommitBody,\n releasePrBody,\n releasePrGroups,\n releaseTitle,\n titleFits,\n} from \"../domain/releasePr\";\nimport { plural } from \"../domain/words\";\nimport { chooseVersion } from \"./chooseVersion\";\nimport { prepareRelease } from \"./prepareRelease\";\nimport { fail, listed, paint } from \"./say\";\nimport { branchStep, openPrStep, pushStep, runSteps } from \"./steps\";\nimport { destination, environmentLabel, moduleOf } from \"./targets\";\n\n/** What happens to a unit once the release PR merges: its module ships the version. */\nconst shipsOnMerge =\n (context: ReleaseContext, { contributions, companions }: Prepared) =>\n (bump: AppBump) => {\n const contributed = contributions[bump.app]?.onMerge;\n if (contributed) return contributed;\n const unit = context.release.units.find(({ name }) => name === bump.app);\n const along = companions.find(({ app }) => app === bump.app);\n const reason = along\n ? ` (not picked: ${along.why})`\n : bump.movedWith.length > 0\n ? ` (moved with ${bump.movedWith.join(\", \")})`\n : \"\";\n return `Ship ${destination(context, [bump.app], \"preview\")} with ${(unit && moduleOf(context, unit)?.provider) ?? \"its target\"}${reason}`;\n };\n\n/** Where a release sends what it moves. */\nconst whereTo = (context: ReleaseContext, { bumps }: Prepared) =>\n destination(\n context,\n bumps.map(({ app }) => app),\n \"preview\",\n );\n\n/** Units going out unpicked, each with the package that takes it along. */\nconst printCompanions = ({ output, release }: ReleaseContext, { companions, split }: Prepared) => {\n if (companions.length === 0) return;\n const names = companions.map(({ app }) => app);\n const verb = names.length === 1 ? \"is not picked but ships too\" : \"are not picked but ship too\";\n output.line(` ${paint([\"bold\", \"yellow\"], \"!\")} ${paint(\"bold\", `${listed(names)} ${verb}:`)}`);\n companions.forEach(({ app, version, why }) => {\n const packageName = release.units.find(({ name }) => name === app)?.packageName;\n const waiting = split.waits.filter(({ releases }) =>\n releases.some(({ name }) => name === packageName),\n ).length;\n const own = waiting > 0 ? ` · picking it ships its ${plural(waiting, \"changeset\")} too` : \"\";\n output.line(` ${app.padEnd(11)}${version.padEnd(20)}${paint(\"dim\", `${why}${own}`)}`);\n });\n output.line();\n};\n\n/** The table a person reads before anything is written: each unit, its move, what ships. */\nexport const printSummary = (context: ReleaseContext, prepared: Prepared) => {\n const { output, release } = context;\n const { bumps, packages, pending, held, contributions, companions } = prepared;\n const dot = paint(\"dim\", \"·\");\n const stays = held.filter((app) => !bumps.some((bump) => bump.app === app));\n const heldLabel = stays.length > 0 ? ` ${dot} ${stays.join(\", \")} held` : \"\";\n const moving = bumps.map(({ app }) => app);\n output.line();\n output.line(\n ` ${paint(\"bold\", \"Release\")} ${dot} ${environmentLabel(context, moving, \"preview\")} ${dot} ${plural(pending, \"changeset\")}${heldLabel}`,\n );\n output.line();\n // The unit column fits the longest name, as status does.\n const width = Math.max(13, ...release.units.map(({ name }) => name.length)) + 2;\n output.line(\n paint(\n \"dim\",\n ` ${\"Unit\".padEnd(width)}${\"Version\".padEnd(20)}Ships ${destination(context, moving, \"preview\")}`,\n ),\n );\n release.units.forEach((unit) => {\n const bump = bumps.find(({ app }) => app === unit.name);\n const version = bump ? `${bump.from} → ${bump.to}` : unit.version;\n const ships = (() => {\n if (held.includes(unit.name) && !bump)\n return paint(\"yellow\", \"⏸ held, its changesets stay pending\");\n const contributed = contributions[unit.name]?.summary;\n if (contributed && contributed.length > 0)\n return contributed.join(`\\n ${\" \".repeat(width + 20)}`);\n if (!bump) return paint(\"dim\", \"– nothing changed\");\n const along = companions.some(({ app }) => app === unit.name)\n ? paint(\"yellow\", \" not picked, goes along\")\n : \"\";\n return `${paint(\"green\", \"↑ ship\")} ${paint(\"dim\", moduleOf(context, unit)?.provider ?? \"\")}${along}`;\n })();\n output.line(` ${unit.name.padEnd(width)}${version.padEnd(20)}${ships}`);\n });\n if (packages > 0) {\n output.line(\n ` ${\"packages\".padEnd(width)}${`${packages} bumped`.padEnd(20)}${paint(\"dim\", \"changelogs only, nothing published\")}`,\n );\n }\n output.line();\n printCompanions(context, prepared);\n};\n\n/** Says what a plugin refuses in `prepared`; true when something does. */\nconst refused = (context: ReleaseContext, { contributions }: Prepared) => {\n const blocked = Object.values(contributions).find((entry) => entry.blocked)?.blocked;\n if (blocked) fail(context, blocked.title, blocked.detail, blocked.commands);\n return Boolean(blocked);\n};\n\n/**\n * Versions what `prepared` covers on one branch from the default branch, opens its PR, and goes\n * back to it.\n * Null, with what to do, when it must not run.\n */\nexport const openReleasePr = async (\n context: ReleaseContext,\n prepared: Prepared,\n /** Release PRs this one takes the place of, named at the top of its description. */\n replaces: readonly OpenPr[] = [],\n): Promise<OpenPr[] | null> => {\n const { output, services, clock } = context;\n printSummary(context, prepared);\n if (refused(context, prepared)) return null;\n const defaultBranch = await services.sourceControl.defaultBranch();\n const source = releaseSource(\"build\", \"preview\", await services.sourceControl.position(), {\n defaultBranch,\n });\n if (!source.allowed) {\n fail(\n context,\n source.why === \"not-main\" ? `Not from ${defaultBranch}` : `${defaultBranch} is behind origin`,\n \"a release versions what is merged.\",\n [`git switch ${defaultBranch}`, \"git pull\", \"shiplane\"],\n );\n return null;\n }\n if (!(await services.sourceControl.isClean())) {\n fail(\n context,\n \"Uncommitted changes\",\n \"commit or stash them first, the release PR commits every change.\",\n );\n return null;\n }\n const kindOf: KindOf = (app) => {\n const unit = context.release.units.find(({ name }) => name === app);\n return unit && moduleOf(context, unit)?.kind;\n };\n const groups = prGroupsOf(context, prepared);\n const titles = groups.map((group) => releaseTitle(group, kindOf));\n const planned = [\n groups.length > 1\n ? `Open ${groups.length} release PRs from main, one per app, then wait for you to squash merge each:\\n${titles\n .map((title) => ` ${title}`)\n .join(\"\\n\")}`\n : \"Open the release PR, then wait for you to squash merge it\",\n \"Tag each version and publish its release notes\",\n ...Object.values(prepared.contributions).flatMap(({ step }) => (step ? [step] : [])),\n ];\n output.line(paint(\"dim\", \" Steps\"));\n planned.forEach((step, index) => output.line(` ${index + 1}. ${step}`));\n output.line();\n const chosen = await chooseVersion(context, prepared, whereTo(context, prepared));\n if (!chosen) {\n output.line(paint(\"dim\", \"Nothing ran.\"));\n return null;\n }\n // A forced version can change what a plugin decides, and what its changeset ties together.\n if (refused(context, chosen)) return null;\n const opening = prGroupsOf(context, chosen);\n const now = clock.now();\n const prs: OpenPr[] = [];\n for (const group of opening) {\n const apps = new Set(group.map(({ app }) => app));\n const scoped =\n opening.length > 1 ? await prepareRelease(context, apps, chosen.contributions) : chosen;\n const [first] = group;\n const branch = `${releaseBranchName(now)}${opening.length > 1 && first ? `-${first.app}` : \"\"}`;\n const pr = await openOne(context, scoped, { kindOf, branch, from: defaultBranch, replaces });\n if (!pr) {\n if (prs.length > 0) {\n output.line(\n paint(\n \"dim\",\n ` ${listed(prs.map(({ number }) => `#${number}`))} stay open: merge them, then run shiplane for the rest.`,\n ),\n );\n }\n return null;\n }\n prs.push(pr);\n }\n return prs;\n};\n\n/**\n * The apps each release PR takes: one PR per app, a family as one. Apps one changeset names or\n * one moving with the other share a PR. A release moving internal packages stays one PR: their\n * changelog lines have no app to go with.\n */\nconst prGroupsOf = ({ release }: ReleaseContext, prepared: Prepared) => {\n if (prepared.packages > 0) return [prepared.bumps];\n const appOf = (packageName: string) =>\n release.units.find((unit) => unit.packageName === packageName)?.name;\n const linked = [\n ...prepared.shipped.map(({ releases }) => releases.map(({ name }) => appOf(name) ?? name)),\n ...prepared.bumps.map(({ app, movedWith }) => [\n app,\n ...movedWith.map((name) => appOf(name) ?? name),\n ]),\n ];\n return releasePrGroups(prepared.bumps, linked);\n};\n\n/** The line a release PR opens with when it takes the place of release PRs main moved past. */\nconst replacedLine = (replaces: readonly OpenPr[]) =>\n replaces.length === 0\n ? \"\"\n : `Replaces ${listed(replaces.map(({ number }) => `#${number}`))}, which went out of date when main moved.\\n\\n`;\n\n/** Versions `prepared` on `branch` from the default branch, opens its PR, and goes back to it. */\nconst openOne = async (\n context: ReleaseContext,\n prepared: Prepared,\n {\n kindOf,\n branch,\n from,\n replaces,\n }: { kindOf: KindOf; branch: string; from: string; replaces: readonly OpenPr[] },\n): Promise<OpenPr | null> => {\n const { services } = context;\n const title = releaseTitle(prepared.bumps, kindOf);\n // A title naming more apps than a header holds skips the commit hooks (commitlint's 100\n // characters) for this commit only.\n const skipHooks = !titleFits(title);\n const created: { pr?: OpenPr } = {};\n const done = await runSteps(context, [\n branchStep(context, { branch, from }),\n {\n label: \"versions and changelogs\",\n run: () =>\n services.versioning.apply(prepared.added, prepared.split.waits, prepared.forced?.level),\n },\n ...Object.values(prepared.contributions).flatMap(({ writes }) => writes),\n {\n label: `commit \"${title}\"`,\n run: async () =>\n services.sourceControl.commit(\n await services.sourceControl.changedFiles(),\n title,\n releaseCommitBody(prepared.bumps) || undefined,\n { skipHooks },\n ),\n },\n pushStep(context, branch),\n openPrStep(context, \"open the release pull request\", async () => {\n created.pr = await services.codeHost.createPr({\n base: from,\n head: branch,\n title,\n body:\n replacedLine(replaces) +\n releasePrBody(\n prepared.bumps,\n shipsOnMerge(context, prepared),\n whereTo(context, prepared),\n ),\n label: \"type: chore\",\n });\n return created.pr;\n }),\n { label: `back to ${from}`, run: () => services.sourceControl.switchTo(from) },\n ]);\n return done && created.pr ? created.pr : null;\n};\n","import type { Environment } from \"./environment\";\nimport { plural } from \"./words\";\n\n/** A unit whose live state its own platform knows, not GitHub Deployments: EAS for a mobile app. */\nexport interface DecidedBy {\n /** Who decides, as a person reads it: \"EAS\". */\n platform: string;\n /** What it decides between: \"build or update\". */\n choice: string;\n /** The command that shows its state: \"shiplane status\". */\n check: string;\n}\n\nexport interface ScopeInfo {\n /** The unit's name. */\n app: string;\n version: string;\n /** Pending changesets naming it. */\n changesets: number;\n /** Its current version has a release tag. */\n tagged: boolean;\n /** A merged release PR brought its current version: untagged, that release is unfinished. */\n versioned: boolean;\n /** No version of it was ever tagged, and a commit brought its version: its first release. */\n firstRelease?: boolean;\n /** GitHub Deployments record that version on the channel being released. */\n onChannel: boolean;\n /** ...and on preview, which production promotes from. */\n onPreview: boolean;\n decidedBy?: DecidedBy;\n /** Nothing deploys it: once tagged, every environment has it. */\n releaseOnly?: boolean;\n /** It has no environment to be on, such as a package: a person reads it as live or not. */\n noEnvironment?: boolean;\n}\n\nexport interface ScopeChoice {\n app: string;\n /** Something to release: offered and ticked. Otherwise shown greyed, with why. */\n pending: boolean;\n hint: string;\n}\n\nconst previewChoice = ({\n version,\n changesets,\n tagged,\n versioned,\n firstRelease,\n onChannel,\n decidedBy,\n releaseOnly,\n noEnvironment,\n}: ScopeInfo) => {\n const later = decidedBy ? ` · ${decidedBy.platform} decides ${decidedBy.choice} once picked` : \"\";\n if (changesets > 0) return { pending: true, hint: `${plural(changesets, \"changeset\")}${later}` };\n if (!tagged) {\n if (versioned) return { pending: true, hint: `${version} versioned, not tagged yet${later}` };\n return firstRelease\n ? { pending: true, hint: `${version} first release${later}` }\n : { pending: false, hint: \"nothing new\" };\n }\n if (releaseOnly) return { pending: false, hint: `${version} released, nothing deploys it` };\n // Its builds and updates live on its platform, not in GitHub Deployments: the check reads them.\n if (decidedBy) {\n return onChannel\n ? {\n pending: false,\n hint: `${version} released, nothing new (${decidedBy.check} shows its builds)`,\n }\n : { pending: true, hint: `${version} tagged, never reached preview: retry` };\n }\n const where = noEnvironment ? \"live\" : \"on preview\";\n return onChannel\n ? { pending: false, hint: `${version} is ${where}, nothing new` }\n : { pending: true, hint: `${version} released, not ${where} yet` };\n};\n\nconst productionChoice = ({\n version,\n tagged,\n onChannel,\n onPreview,\n decidedBy,\n releaseOnly,\n}: ScopeInfo) => {\n if (!tagged) return { pending: false, hint: \"not released yet\" };\n if (releaseOnly) return { pending: false, hint: `${version} released, nothing deploys it` };\n if (decidedBy) {\n return {\n pending: true,\n hint: `${version} released, ${decidedBy.platform} decides once picked`,\n };\n }\n if (onChannel) return { pending: false, hint: `${version} is on production, nothing new` };\n return onPreview\n ? { pending: true, hint: `${version} is on preview, promotes it` }\n : { pending: false, hint: `${version} is not on preview yet: release it there first` };\n};\n\n/** The first question: which units have something to release here, and why not the rest. */\nexport const scopeChoices = (apps: ScopeInfo[], channel: Environment): ScopeChoice[] =>\n apps.map((info) => ({\n app: info.app,\n ...(channel === \"production\" ? productionChoice(info) : previewChoice(info)),\n }));\n","import type { Environment } from \"../domain/environment\";\nimport type { ScopeInfo } from \"../domain/scope\";\nimport type { ReleaseContext } from \"./context\";\nimport { scopeChoices } from \"../domain/scope\";\nimport { readScope } from \"./readScope\";\nimport { paint } from \"./say\";\nimport { destination } from \"./targets\";\nimport { unattended } from \"./unattended\";\n\n/** Every unit with something to release here: what --yes and a run without a terminal cover. */\nexport const defaultScope = (info: ScopeInfo[], environment: Environment) =>\n new Set(\n scopeChoices(info, environment)\n .filter(({ pending }) => pending)\n .map(({ app }) => app),\n );\n\n/**\n * The first question: which units this run covers. Every unit is listed; those with nothing to\n * release are greyed out with why. Null when cancelled or when nothing is pending.\n */\nexport const pickScope = async (\n context: ReleaseContext,\n environment: Environment,\n): Promise<{ scope: Set<string>; info: ScopeInfo[] } | null> => {\n const { output, prompter, progress } = context;\n const info = await progress.during(\n \"Reading what changed: changesets, tags and GitHub deployments\",\n \"thinking\",\n () => readScope(context, environment),\n );\n const choices = scopeChoices(info, environment);\n const where = destination(\n context,\n info.map(({ app }) => app),\n environment,\n );\n if (!choices.some(({ pending }) => pending)) {\n output.line();\n choices.forEach(({ app, hint }) =>\n output.line(` ${paint(\"dim\", `${app.padEnd(15)}${hint}`)}`),\n );\n output.line();\n // Nothing promotes a release-only unit: only a new change moves it.\n const queue = environment === \"preview\" || info.every(({ releaseOnly }) => releaseOnly);\n progress.say(\n \"resting\",\n `${paint(\"bold\", `Nothing to release ${where}.`)} ${paint(\"dim\", queue ? \"Queue a change first:\" : \"Release to preview first:\")}`,\n );\n output.line(\n ` ${paint(\"cyan\", queue ? context.services.versioning.nextChange : \"shiplane\")}`,\n );\n output.line();\n return null;\n }\n if (unattended(context)) return { scope: defaultScope(info, environment), info };\n const picked = await prompter.multiselect(\n `What do you want to release ${where}? Greyed units have nothing to release.`,\n choices.map(({ app, pending, hint }) => ({ value: app, label: app, hint, disabled: !pending })),\n choices.filter(({ pending }) => pending).map(({ app }) => app),\n );\n return picked ? { scope: new Set(picked), info } : null;\n};\n","import { z } from \"zod\";\n\n/** What a `prepare` command may name, filled per unit. */\nconst PLACEHOLDERS = [\"unit\", \"dir\"];\n\n/** A `prepare` command: text naming only `{unit}` and `{dir}`. */\nexport const PrepareSchema = z\n .string({ error: 'prepare is a shell command, such as \"pnpm --filter {unit} build\"' })\n .superRefine((text, context) => {\n for (const [, name = \"\"] of text.matchAll(/\\{([^}]*)\\}/g)) {\n if (!PLACEHOLDERS.includes(name)) {\n context.addIssue({ code: \"custom\", message: `unknown placeholder {${name}} in prepare` });\n }\n }\n });\n\n/** The command a unit prepares with: `{unit}` its name, `{dir}` its folder from the root. */\nexport const prepareLine = (template: string, { name, dir }: { name: string; dir: string }) =>\n template.replaceAll(\"{unit}\", name).replaceAll(\"{dir}\", dir);\n","import type { DeployPath } from \"./deploys\";\n\n/**\n * Builds and submits run on their own platform: they ask only when a workflow can start them too.\n */\nexport const choosesPath = ({\n kind,\n jobs,\n}: {\n kind: string;\n jobs: readonly { ci?: object | null }[];\n}) =>\n kind === \"update\" ||\n kind === \"deploy\" ||\n ((kind === \"build\" || kind === \"submit\") && jobs.every(({ ci }) => ci));\n\n/** On a CI runner, dispatching another workflow would pay for two: this runner ships. */\nexport const forcedPath = ({ ci, via }: { ci: boolean; via: DeployPath | undefined }) =>\n ci ? (\"local\" as const) : via;\n\nexport const OTHER_PATH: Record<DeployPath, DeployPath> = { ci: \"local\", local: \"ci\" };\n\n/** How a unit goes, from why each path cannot ship it (null when it can). */\nexport type RouteChoice =\n { route: \"ask\" } | { route: \"stuck\" } | { route: DeployPath; blocked: string };\n\n/** Both paths open asks; one blocked takes the other; both blocked, nothing can ship it. */\nexport const routeChoice = ({\n ci,\n local,\n}: {\n ci: string | null;\n local: string | null;\n}): RouteChoice => {\n if (ci && local) return { route: \"stuck\" };\n if (ci) return { route: OTHER_PATH.ci, blocked: ci };\n if (local) return { route: OTHER_PATH.local, blocked: local };\n return { route: \"ask\" };\n};\n\n/** One job a workflow ships: its unit, the ref it runs on, and the commit that ref tags. */\nexport interface WorkflowJob {\n unit: string;\n ref: string;\n /** Null for a ref shipped as it moves, such as main. */\n commit: string | null;\n}\n\n/**\n * The ship workflow's runs: one per commit, each naming its units, so tags on one commit cost one\n * run. A run goes on the first unit's tag, never on main: a runner checks out its ref when it\n * starts, and main may have moved by then. Only a job that ships main on purpose runs from main.\n */\nexport const shipRuns = (jobs: readonly WorkflowJob[]) => {\n const runs = new Map<string, { ref: string; units: string[] }>();\n for (const { unit, ref, commit } of jobs) {\n const key = commit === null ? `ref:${ref}` : `commit:${commit}`;\n const run = runs.get(key) ?? { ref, units: [] };\n if (!run.units.includes(unit)) run.units.push(unit);\n runs.set(key, run);\n }\n return [...runs.values()];\n};\n","import type { ActionsMinutes } from \"../domain/budget\";\nimport type { DeployPath, ShipItem } from \"../domain/deploys\";\nimport type { Environment } from \"../domain/environment\";\nimport type { CiPipelinePort } from \"../ports/ci-pipeline.port\";\nimport type { ReleaseContext } from \"./context\";\nimport { deployEstimate, minutesBudget } from \"../domain/budget\";\nimport { fail, paint } from \"./say\";\n\nexport interface Shipment {\n item: ShipItem;\n /** The workflow its jobs dispatch on the CI pipeline, if any. */\n workflows: string[];\n typicalMinutes: number | undefined;\n}\n\n/** What a person calls the CI pipeline: its own label, else `CI`. */\nexport const ciLabel = (ci: CiPipelinePort) => ci.label ?? \"CI\";\n\n/** A way to ship, as a person reads it: the pipeline's label, or this machine. */\nexport const pathLabel = (ci: CiPipelinePort, path: DeployPath) =>\n path === \"ci\" ? ciLabel(ci) : \"this machine\";\n\n/** The minutes block above the question: status, what is left, this release shaded in, the pace. */\nconst showMinutes = (\n { output, clock, services }: ReleaseContext,\n budget: ActionsMinutes,\n estimate: ReturnType<typeof deployEstimate>,\n) => {\n const label = ciLabel(services.ciPipeline);\n const drawn = minutesBudget(budget, clock.now(), 30, estimate.total, label);\n output.line();\n output.line(` ${paint(\"bold\", drawn.title)} ${paint([\"bold\", drawn.tone], drawn.status)}`);\n output.line(` ${paint(drawn.tone, drawn.bar)} ${paint([\"bold\", drawn.tone], drawn.amount)}`);\n if (drawn.after) {\n output.line(` ${drawn.after}`);\n const each = estimate.lines.map(\n ({ app, minutes, measured }) =>\n `${app} ~${minutes} ${measured ? \"(its last runs)\" : \"(typical, no run yet)\"}`,\n );\n output.line(` ${paint(\"dim\", ` ${each.join(\" · \")}`)}`);\n }\n output.line(` ${paint(\"dim\", drawn.pace)}`);\n output.line();\n};\n\n/**\n * How each unit ships, asked one by one with this month's Actions minutes shown once: GitHub Actions\n * or this machine, in the order given. Null when cancelled or without a terminal to ask.\n */\nexport const askPaths = async (\n context: ReleaseContext,\n environment: Environment,\n shipments: readonly Shipment[],\n): Promise<DeployPath[] | null> => {\n const { services, prompter, clock } = context;\n const measured = Object.fromEntries(\n await Promise.all(\n shipments.map(async ({ item, workflows }) => [\n item.app,\n (\n await Promise.all(\n workflows.map((workflow) => services.ciPipeline.measuredMinutes(workflow)),\n )\n ).flat(),\n ]),\n ),\n );\n const typical = Object.fromEntries(\n shipments.flatMap(({ item, typicalMinutes }) =>\n typicalMinutes === undefined ? [] : [[item.app, typicalMinutes]],\n ),\n );\n const estimate = deployEstimate(\n shipments.map(({ item }) => item),\n measured,\n typical,\n );\n const budget = await services.ciPipeline.minutes();\n if (budget) showMinutes(context, budget, estimate);\n if (!prompter.interactive) {\n fail(context, \"Not a terminal\", \"say how to ship.\", [\n \"shiplane ship --via ci\",\n \"shiplane ship --via local\",\n ]);\n return null;\n }\n const low =\n budget !== null && minutesBudget(budget, clock.now(), 30, estimate.total).tone === \"red\";\n const paths: DeployPath[] = [];\n for (const { item } of shipments) {\n const minutes = estimate.lines.find(({ app }) => app === item.app)?.minutes;\n const path = await prompter.select<DeployPath>(\n `How should ${item.tag} ship to ${environment}?`,\n [\n {\n value: \"ci\",\n label: pathLabel(services.ciPipeline, \"ci\"),\n hint: budget\n ? `runs on ${ciLabel(services.ciPipeline)} from its tag, about ${minutes} of ${budget.left.toLocaleString(\"en-US\")} minutes left`\n : `its workflow runs on ${ciLabel(services.ciPipeline)}, from its tag`,\n },\n {\n value: \"local\",\n label: pathLabel(services.ciPipeline, \"local\"),\n hint: \"the same commands, run here: no Actions minutes\",\n },\n ],\n low ? \"local\" : \"ci\",\n );\n if (!path) return null;\n paths.push(path);\n }\n return paths;\n};\n","import type { FollowUp, Shipped } from \"../modules/module\";\nimport type { ReleaseContext } from \"./context\";\nimport { paint, reasonOf } from \"./say\";\nimport { afterShipContext } from \"./targets\";\n\n/** What every feature asks for once these apps ship, in order. One that cannot read is said, then skipped. */\nconst followUpsOf = async (context: ReleaseContext, shipped: readonly Shipped[]) => {\n const all: FollowUp[] = [];\n if (shipped.length === 0) return all;\n for (const feature of context.release.features) {\n try {\n const asked = await context.progress.during(\n `${feature.name}: reading what to follow up`,\n \"thinking\",\n () => feature.afterShip(afterShipContext(context), shipped),\n );\n all.push(...asked);\n } catch (error) {\n context.output.line(\n ` ${paint(\"yellow\", \"!\")} ${feature.name} ${paint(\"dim\", `could not read: ${reasonOf(error)}`)}`,\n );\n }\n }\n return all;\n};\n\n/** Runs what the features ask for once units shipped. A failure is said and never fails the release. */\nexport const runFollowUps = async (context: ReleaseContext, shipped: readonly Shipped[]) => {\n for (const { label, run } of await followUpsOf(context, shipped)) {\n try {\n await run();\n context.output.line(` ${paint(\"green\", \"✓\")} ${label}`);\n } catch (error) {\n context.output.line(` ${paint(\"yellow\", \"!\")} ${label} ${paint(\"dim\", reasonOf(error))}`);\n }\n }\n};\n\n/** What the features would do once these units ship, run nothing. */\nexport const planFollowUps = async (context: ReleaseContext, shipped: readonly Shipped[]) => {\n const all = await followUpsOf(context, shipped);\n if (all.length === 0) return;\n context.output.line();\n context.output.line(` ${paint(\"bold\", \"Then\")} ${paint(\"dim\", \"once shipped\")}`);\n all.forEach(({ label }) => context.output.line(` ${label}`));\n};\n","/** Runs `work` on every item, at most `limit` at once; results in input order, rejects like Promise.all. */\nexport const mapLimit = async <Item, Result>(\n items: readonly Item[],\n limit: number,\n work: (item: Item, index: number) => Promise<Result>,\n): Promise<Result[]> => {\n const results = new Array<Result>(items.length);\n const queue = items.entries();\n const worker = async () => {\n for (const [index, item] of queue) results[index] = await work(item, index);\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return results;\n};\n","import type { MergeMethod, OpenPr, WaitAction } from \"../domain/releasePr\";\nimport type { ReleaseContext } from \"./context\";\nimport { mergeChoices, waitKey } from \"../domain/releasePr\";\nimport { fail, keyHints, paint } from \"./say\";\n\nconst POLL_MS = 15_000;\n\n/** How a wait for the release PR ends: merged, closed on the host, or left to a later run. */\nexport type WaitOutcome = \"merged\" | \"closed\" | \"left\";\n\n/** Merges the pull request with the method the person picks. GitHub refuses approving your own PR. */\nconst mergeHere = async (context: ReleaseContext, pr: OpenPr) => {\n const { choices, initial } = mergeChoices(await context.services.codeHost.mergeMethods());\n if (choices.length === 0) {\n fail(context, \"No merge method\", \"the repository allows none: merge it on GitHub.\");\n return;\n }\n const method = await context.prompter.select<MergeMethod | \"no\">(\n `Merge #${pr.number} into main?`,\n [...choices, { value: \"no\", label: \"Not now\" }],\n initial,\n );\n if (!method || method === \"no\") {\n context.output.line(paint(\"dim\", \" Not merged.\"));\n return;\n }\n await context.services.codeHost.merge(pr, method);\n};\n\nconst ACTIONS: Record<WaitAction, (context: ReleaseContext, pr: OpenPr) => Promise<void>> = {\n diff: (context, pr) => context.services.codeHost.showDiff(pr),\n merge: mergeHere,\n open: (context, pr) => context.services.codeHost.openInBrowser(pr),\n};\n\n/** The keys a wait offers. Someone else approves a release that requires it: no merge from here. */\nconst hintsFor = (approvalRequired: boolean) => [\n { key: \"d\", label: \"see the diff\" },\n ...(approvalRequired ? [] : [{ key: \"m\", label: \"merge it from here\" }]),\n { key: \"o\", label: \"open it on GitHub\" },\n { key: \"Ctrl-C\", label: \"leave, continue later\" },\n];\n\n/** What the wait is for: someone's approval, or a merge from here or GitHub. */\nconst sayWaiting = (\n { output }: ReleaseContext,\n { pr, approvalRequired }: { pr: OpenPr; approvalRequired: boolean },\n) => {\n if (!approvalRequired) {\n output.line(\n paint(\n \"dim\",\n \" Review and merge it here or on GitHub; this carries on by itself once merged.\",\n ),\n );\n return;\n }\n output.line(` Waiting for approval on #${pr.number}. This can take a while.`);\n output.line(paint(\"dim\", \" It's safe to leave: run shiplane later and it picks up here.\"));\n};\n\n/**\n * Polls the host until the PR merges or closes; in a terminal the person can also read the diff\n * (d), merge from here (m, unless approval is required) or open it in the browser (o). Without a\n * terminal, a release waiting on someone's approval is left for a later run instead.\n */\nexport const waitForMerge = async (context: ReleaseContext, pr: OpenPr): Promise<WaitOutcome> => {\n const { output, prompter, services } = context;\n const approvalRequired = context.release.flow.approval === \"required\";\n output.line(` ${paint(\"green\", \"✓\")} Release PR ${paint(\"cyan\", pr.url)}`);\n sayWaiting(context, { pr, approvalRequired });\n if (approvalRequired && !prompter.interactive) {\n const state = await services.codeHost.prState(pr).catch(() => \"OPEN\" as const);\n if (state === \"OPEN\") return \"left\";\n return state === \"MERGED\" ? \"merged\" : \"closed\";\n }\n const hints = hintsFor(approvalRequired);\n if (prompter.interactive) {\n output.line();\n output.line(` ${keyHints(hints)}`);\n }\n output.line();\n const keys = prompter.interactive\n ? hints.map(({ key }) => key).filter((key) => key.length === 1)\n : [];\n for (;;) {\n const state = await services.codeHost.prState(pr).catch(() => \"OPEN\" as const);\n if (state !== \"OPEN\") return state === \"MERGED\" ? \"merged\" : \"closed\";\n const key = await prompter.waitForKey(\n approvalRequired\n ? `Waiting for #${pr.number} to be approved and merged`\n : `Waiting for #${pr.number} to merge`,\n POLL_MS,\n keys,\n );\n const action = key && keys.includes(key) ? waitKey(key) : null;\n if (action) await ACTIONS[action](context, pr);\n }\n};\n","import type { OpenPr } from \"../domain/releasePr\";\nimport type { Decision } from \"../ports/delivery.port\";\nimport type { ReleaseContext } from \"./context\";\nimport { confirm, fail, paint } from \"./say\";\nimport { branchStep, openPrStep, pushStep, runSteps } from \"./steps\";\nimport { waitForMerge } from \"./waitForMerge\";\n\ntype PullRequest = Extract<Decision, { action: \"pull-request\" }>;\n\n/**\n * A small PR a plugin needs merged before it ships, such as production's version moving: branch,\n * write, commit, push, open, back to main, wait for the merge, pull. `declined` when the person\n * said no, or the PR was left waiting for approval.\n */\nexport const pullRequestFirst = async (\n context: ReleaseContext,\n request: PullRequest,\n): Promise<\"merged\" | \"declined\" | \"failed\"> => {\n const { output, services } = context;\n if (!(await confirm(context, request.question))) {\n output.line(paint(\"dim\", \" Not now.\"));\n return \"declined\";\n }\n const created: { pr?: OpenPr } = {};\n const from = await services.sourceControl.defaultBranch();\n const opened = await runSteps(context, [\n branchStep(context, { branch: request.branch, from }),\n {\n label: `commit \"${request.title}\"`,\n run: async () => {\n await request.write();\n for (const changeset of request.changesets) await services.versioning.write(changeset);\n await services.sourceControl.commit(\n await services.sourceControl.changedFiles(),\n request.title,\n );\n },\n },\n pushStep(context, request.branch),\n openPrStep(context, \"open the pull request\", async () => {\n created.pr = await services.codeHost.createPr({\n base: from,\n head: request.branch,\n title: request.title,\n body: request.body,\n label: \"type: chore\",\n });\n return created.pr;\n }),\n { label: `back to ${from}`, run: () => services.sourceControl.switchTo(from) },\n ]);\n const { pr } = created;\n if (!opened || !pr) return \"failed\";\n output.line();\n const outcome = await waitForMerge(context, pr);\n if (outcome === \"closed\") {\n fail(context, `#${pr.number} was closed without a merge`, \"nothing shipped.\", [\"shiplane\"]);\n return \"failed\";\n }\n if (outcome === \"left\") {\n output.line(paint(\"dim\", ` Left #${pr.number} waiting. Run shiplane once it's merged.`));\n return \"declined\";\n }\n const pulled = await runSteps(context, [\n { label: `pull ${from}`, run: () => services.sourceControl.pull() },\n ]);\n return pulled ? \"merged\" : \"failed\";\n};\n","import type { ReleaseTag, TagCandidate } from \"../domain/tags\";\nimport type { ReleaseContext } from \"./context\";\nimport type { Step } from \"./steps\";\nimport { changelogSection, firstRelease, previousTag, releaseTags } from \"../domain/tags\";\nimport { MANIFEST, namedUnits } from \"./readScope\";\nimport { confirm, paint } from \"./say\";\nimport { runSteps } from \"./steps\";\n\n/** The tags and release notes still missing for the versions merged release PRs brought. */\nexport const missingTags = async (context: ReleaseContext): Promise<ReleaseTag[]> => {\n const { release, services } = context;\n const [tags, notes, named] = await Promise.all([\n services.sourceControl.tags(),\n services.codeHost.releasedTags().catch(() => new Set<string>()),\n namedUnits(context),\n ]);\n const candidates = await Promise.all(\n release.units.map(async ({ name, dir, version }): Promise<TagCandidate[]> => {\n const commit = await services.sourceControl.versionCommit(dir, MANIFEST, version);\n // A unit a changeset names releases through its release PR, never as it stands.\n const first = !named.has(name) && firstRelease(name, version, tags, release.tagFormat);\n return commit ? [{ app: name, version, commit, first }] : [];\n }),\n );\n return releaseTags(candidates.flat(), tags, notes, release.tagFormat);\n};\n\nconst notesFor = async ({ release, services }: ReleaseContext, tag: ReleaseTag) => {\n const unit = release.units.find(({ name }) => name === tag.app);\n const changelog = unit\n ? await services.sourceControl.fileAt(tag.sha, services.versioning.changelogFile(unit.dir))\n : null;\n return changelogSection(changelog ?? \"\", tag.version);\n};\n\n/** Tags each version on the commit that brought it, pushes the tags, publishes their notes. */\nexport const tagRelease = async (context: ReleaseContext, tags: readonly ReleaseTag[]) => {\n if (tags.length === 0) return true;\n const { output, release, services } = context;\n const names = tags.map(({ tag }) => tag).join(\", \");\n output.line(` ${paint(\"bold\", \"Tags and release notes\")} ${paint(\"dim\", names)}`);\n if (!(await confirm(context, `Tag ${names} and publish their release notes?`, true))) {\n output.line(paint(\"dim\", \"Nothing ran.\"));\n return false;\n }\n const created = tags.filter(({ needsTag }) => needsTag);\n const steps: Step[] = [\n ...created.map((tag) => ({\n label: `tag ${tag.tag} on ${tag.sha.slice(0, 7)}`,\n run: async () =>\n services.sourceControl.tag(\n tag.tag,\n tag.sha,\n `${tag.tag}\\n\\n${await notesFor(context, tag)}`,\n ),\n // Kept here unpushed, the next run would take it for done and never push it.\n undo: {\n label: `delete the tag ${tag.tag} here`,\n run: () => services.sourceControl.deleteTag(tag.tag),\n byHand: () => [`git tag --delete ${tag.tag}`],\n },\n })),\n ...(created.length > 0\n ? [\n {\n label: \"push the tags\",\n run: () => services.sourceControl.pushTags(created.map(({ tag }) => tag)),\n // Once on origin, a tag is the release; the next run fetches it and publishes its notes.\n kept: {\n label: `${created.map(({ tag }) => tag).join(\", \")} ${created.length > 1 ? \"stay\" : \"stays\"} on origin`,\n byHand: () => [\"shiplane tag\"],\n },\n },\n ]\n : []),\n ...tags\n .filter(({ needsNotes }) => needsNotes)\n .map((tag) => ({\n label: `release notes for ${tag.tag}`,\n run: async () =>\n services.codeHost.createRelease(\n tag.tag,\n await notesFor(context, tag),\n tag.app === release.units[0]?.name,\n previousTag({\n tags: await services.sourceControl.tags(),\n unit: tag.app,\n version: tag.version,\n format: release.tagFormat,\n }) ?? undefined,\n ),\n })),\n ];\n return runSteps(context, steps);\n};\n","import type { Environment } from \"../domain/environment\";\nimport type { OpenPr, ReleaseStep } from \"../domain/releasePr\";\nimport type { ReleaseTag } from \"../domain/tags\";\nimport type { ReleaseContext } from \"./context\";\nimport { nextStep, RELEASE_BRANCH_PREFIX } from \"../domain/releasePr\";\nimport { scopeChoices } from \"../domain/scope\";\nimport { tagName } from \"../domain/tags\";\nimport { readScope } from \"./readScope\";\nimport { reasonOf } from \"./say\";\nimport { missingTags } from \"./tagRelease\";\nimport { checkout, decideContext, moduleOf, unitTarget } from \"./targets\";\n\nexport interface UnitStatus {\n unit: string;\n target: string;\n version: string;\n tag: string;\n tagged: boolean;\n changesets: number;\n /** Something to release to this environment. */\n pending: boolean;\n hint: string;\n /** What its plugin reads from its own platform, such as each EAS build's verdict. */\n live?: unknown;\n}\n\nexport interface ReleaseStatus {\n environment: Environment;\n units: UnitStatus[];\n releasePrs: OpenPr[];\n untagged: ReleaseTag[];\n next: ReleaseStep;\n}\n\n/** Where every unit stands on an environment, and the step a release takes next. Reads only. */\nexport const readStatus = async (\n context: ReleaseContext,\n environment: Environment,\n): Promise<ReleaseStatus> => {\n const info = await readScope(context, environment);\n const choices = scopeChoices(info, environment);\n const [releasePrs, untagged] = await Promise.all([\n context.services.codeHost.openPrsFrom(RELEASE_BRANCH_PREFIX).catch(() => []),\n missingTags(context),\n ]);\n const at = await checkout(context);\n const live = async (name: string) => {\n const unit = context.release.units.find((candidate) => candidate.name === name);\n const target = unit && unitTarget(context, { unit, environment, ...at });\n if (!target?.module.inspect) return {};\n const inspected = await target.module\n .inspect(decideContext(context), target.input)\n .catch((error: unknown) => ({\n error: reasonOf(error),\n }));\n return { live: inspected };\n };\n const units = await Promise.all(\n info.map(async (entry) => {\n const choice = choices.find(({ app }) => app === entry.app);\n const unit = context.release.units.find(({ name }) => name === entry.app);\n return {\n unit: entry.app,\n target: (unit && moduleOf(context, unit)?.provider) ?? \"\",\n version: entry.version,\n tag: tagName(entry.app, entry.version, context.release.tagFormat),\n tagged: entry.tagged,\n changesets: entry.changesets,\n pending: choice?.pending ?? false,\n hint: choice?.hint ?? \"\",\n ...(await live(entry.app)),\n };\n }),\n );\n return {\n environment,\n units,\n releasePrs,\n untagged,\n next: nextStep({\n pending: info.reduce((sum, { changesets }) => sum + changesets, 0),\n releasePrs,\n untagged: untagged.length,\n }),\n };\n};\n","import type { Environment } from \"../domain/environment\";\nimport type { ReleaseContext } from \"./context\";\nimport { readStatus } from \"./readStatus\";\nimport { fail, listed, paint, reasonOf } from \"./say\";\n\n/** What a step of a unit does: its `prepare` command, or shipping it. */\nexport type Stage = \"prepare\" | \"ship\";\n\n/** One thing a ship runs: a job from this machine, or a workflow run dispatched. */\nexport interface ShipStep {\n label: string;\n run: () => Promise<unknown>;\n /** The tags left unshipped when it fails. */\n tags: string[];\n /** The unit it ships, or the units of a dispatched run, as a person reads them. */\n unit: string;\n stage: Stage;\n}\n\nexport type Outcome = \"success\" | \"failed\" | \"skipped\";\n\n/** How each unit went, in the order it shipped. */\nexport type Outcomes = Map<string, Record<Stage, Outcome>>;\n\n/** A failed ship left its tag unshipped: the next run's first question offers it again. */\nconst offerAgain = ({ output }: ReleaseContext, tags: string[]) =>\n output.line(` ${paint(\"dim\", `Run shiplane again: it offers ${listed(tags)} again`)}`);\n\n/** On this machine: each step under its progress line, in order; the first failure stops the rest. */\nconst runInOrder = async (context: ReleaseContext, steps: readonly ShipStep[]) => {\n for (const [index, { label, run, tags }] of steps.entries()) {\n try {\n await context.progress.during(label, \"working\", run, { index, total: steps.length });\n } catch (error) {\n fail(context, `${label} failed`, `${reasonOf(error)}, nothing after it ran.`);\n offerAgain(context, tags);\n return false;\n }\n }\n return true;\n};\n\n/**\n * On a runner: every unit goes, each in its own log group. A failed step skips the rest of its\n * unit, never the next unit.\n */\nconst runEvery = async (\n context: ReleaseContext,\n steps: readonly ShipStep[],\n outcomes: Outcomes,\n) => {\n const { output } = context;\n let open: string | undefined;\n for (const [index, { label, run, unit, stage }] of steps.entries()) {\n if (unit !== open) {\n if (open !== undefined) output.line(\"::endgroup::\");\n output.line(`::group::${unit}`);\n open = unit;\n }\n const outcome = outcomes.get(unit) ?? { prepare: \"skipped\", ship: \"skipped\" };\n outcomes.set(unit, outcome);\n if (Object.values(outcome).includes(\"failed\")) continue;\n try {\n await context.progress.during(label, \"working\", run, { index, total: steps.length });\n outcome[stage] = \"success\";\n } catch (error) {\n outcome[stage] = \"failed\";\n fail(context, `${label} failed`, `${reasonOf(error)}, the next unit still goes.`);\n }\n }\n if (open !== undefined) output.line(\"::endgroup::\");\n return ![...outcomes.values()].some((outcome) => Object.values(outcome).includes(\"failed\"));\n};\n\n/**\n * Runs a ship's steps. On a runner (`options.ci`) every unit goes and `outcomes` records how; on\n * this machine the first failure stops the rest. False when one failed.\n */\nexport const runShipSteps = (\n context: ReleaseContext,\n steps: readonly ShipStep[],\n outcomes: Outcomes = new Map(),\n) => (context.options.ci ? runEvery(context, steps, outcomes) : runInOrder(context, steps));\n\n/** Text kept on one table cell. */\nconst cell = (text: string) => text.replaceAll(\"|\", \"\\\\|\").replaceAll(\"\\n\", \" \");\n\nconst table = (head: string[], rows: string[][]) =>\n [head, head.map(() => \"---\"), ...rows]\n .map((row) => `| ${row.map(cell).join(\" | \")} |`)\n .join(\"\\n\");\n\n/** The runner's run page, when it has one: GitHub Actions names it in `GITHUB_STEP_SUMMARY`. */\nconst summaryFile = (context: ReleaseContext) =>\n context.options.ci ? context.shell.env(\"GITHUB_STEP_SUMMARY\") : undefined;\n\n/** On a runner's run page: each unit about to ship, in release order, and where it stands. */\nexport const writePlan = async (\n context: ReleaseContext,\n environment: Environment,\n units: ReadonlySet<string>,\n) => {\n const file = summaryFile(context);\n if (!file) return;\n const status = await readStatus(context, environment);\n const rows = status.units\n .filter(({ unit }) => units.has(unit))\n .map(({ unit, target, version, hint }) => [unit, target, version, hint]);\n context.files.append(\n file,\n `### Ship to ${environment}\\n\\n${table([\"Unit\", \"Target\", \"Version\", \"Where it stands\"], rows)}\\n\\n`,\n );\n};\n\n/** On a runner's run page: how each unit's prepare and ship went. */\nexport const writeResult = (context: ReleaseContext, outcomes: Outcomes) => {\n const file = summaryFile(context);\n if (!file) return;\n const rows = [...outcomes].map(([unit, { prepare, ship }]) => [unit, prepare, ship]);\n context.files.append(file, `### Result\\n\\n${table([\"Unit\", \"Prepare\", \"Ship\"], rows)}\\n\\n`);\n};\n","import type { DeployPath, WebShip } from \"../domain/deploys\";\nimport type { Environment } from \"../domain/environment\";\nimport type { WorkflowJob } from \"../domain/shipRoute\";\nimport type { ReleaseUnit } from \"../domain/unit\";\nimport type { AppInput, ReleaseModule } from \"../modules/module\";\nimport type { Deploy } from \"../ports/code-host.port\";\nimport type { Decision, Job, ShipKind } from \"../ports/delivery.port\";\nimport type { Shipment } from \"./askPath\";\nimport type { ReleaseContext } from \"./context\";\nimport type { Outcomes, ShipStep } from \"./shipSteps\";\nimport { onlyVersionFiles, shipsFrom, webShip } from \"../domain/deploys\";\nimport { yesAllowed } from \"../domain/governance\";\nimport { prepareLine } from \"../domain/prepare\";\nimport { choosesPath, forcedPath, routeChoice, shipRuns } from \"../domain/shipRoute\";\nimport { askPaths, ciLabel, pathLabel } from \"./askPath\";\nimport { checkEnvBeforeDeploy } from \"./checkEnvBeforeDeploy\";\nimport { runFollowUps } from \"./followUps\";\nimport { mapLimit } from \"./mapLimit\";\nimport { pullRequestFirst } from \"./pullRequestFirst\";\nimport { deployedOn } from \"./readScope\";\nimport { signIn, signInsOf } from \"./requirements\";\nimport { confirm, fail, paint } from \"./say\";\nimport { runShipSteps, writePlan, writeResult } from \"./shipSteps\";\nimport {\n checkout,\n decideContext,\n destination,\n dispatchShip,\n environmentLabel,\n jobInput,\n runHere,\n shipPlanOf,\n unitTag,\n versionFiles,\n} from \"./targets\";\n\ninterface Ready {\n unit: ReleaseUnit;\n module: ReleaseModule;\n input: AppInput;\n kind: ShipKind;\n jobs: Job[];\n /** Its module decided for itself: the moved-past check is already its own. */\n decided: boolean;\n /** Why this machine cannot ship it, as its module decided. */\n notLocal: string | null;\n /** The person already said go for it. */\n confirmed: boolean;\n}\n\nconst WEB_STATUS: Record<Exclude<WebShip, \"deploy\">, string> = {\n deploying: \"deploying already\",\n shipped: \"already there\",\n \"not-on-preview\": \"not on preview yet: ship it there first\",\n};\n\n/** A web unit decides from GitHub Deployments, which a ship records once it rolled out. */\nconst webDecision = (\n context: ReleaseContext,\n module: ReleaseModule,\n input: AppInput,\n history: Deploy[],\n): Decision => {\n const { jobs } = shipPlanOf(context, module, input);\n const ship = webShip({\n environment: input.environment,\n run: deployedOn(history, input.tag, input.environment),\n onPreview: deployedOn(history, input.tag, \"preview\") === \"done\",\n });\n return ship === \"deploy\"\n ? { action: \"ship\", kind: \"deploy\", jobs }\n : { action: \"none\", status: WEB_STATUS[ship] };\n};\n\n/**\n * Where a choice stands, then the person's pick: its jobs ship, or nothing does and it is held.\n * With nobody to answer, a choice that says so fails instead.\n */\nconst chosen = async (\n context: ReleaseContext,\n choice: Extract<Decision, { action: \"choose\" }>,\n): Promise<Extract<Decision, { action: \"ship\" | \"none\" | \"fail\" }>> => {\n const { output, prompter, options } = context;\n // Only a choice that names what to say refuses unattended; any other is asked whenever it can be.\n if (choice.unattended && (!prompter.interactive || options.ci)) {\n return { action: \"fail\", ...choice.unattended };\n }\n output.line();\n choice.lines.forEach((line) => output.line(` ${line}`));\n output.line();\n const value = prompter.interactive\n ? await prompter.select(\n choice.question,\n choice.options.map(({ value, label, hint, disabled }) => ({\n value,\n label,\n hint,\n disabled,\n })),\n choice.suggested,\n )\n : null;\n const picked = choice.options.find((option) => option.value === value);\n picked?.then?.forEach((line) => output.line(` ${line}`));\n const jobs = picked?.jobs ?? [];\n return jobs.length > 0\n ? {\n action: \"ship\",\n kind: choice.kind ?? \"update\",\n jobs,\n ...(choice.notLocal ? { notLocal: choice.notLocal } : {}),\n ...(choice.confirmed ? { confirmed: true } : {}),\n }\n : { action: \"none\", status: choice.held };\n};\n\n/** Units checked at once: their platforms answer slowly, each on its own. */\nconst CHECKS_AT_ONCE = 4;\n\n/**\n * What every picked unit needs on the environment, in dispatch order, said as it goes. Every unit is\n * checked at once, then each is settled in order. A module may first need a small PR merged (a\n * version moving): it opens, merges, and that unit and every one after it decide again. Null when\n * one of them refused.\n */\nconst decideAll = async (\n context: ReleaseContext,\n environment: Environment,\n scope: ReadonlySet<string> | undefined,\n): Promise<Ready[] | null> => {\n const { release, services, output } = context;\n const recorded = await services.codeHost.deployments().catch(() => []);\n const picked = release.units.flatMap((unit) => {\n const found = unitTag(context, unit);\n if ((scope && !scope.has(unit.name)) || !found) return [];\n return [{ unit, ...found }];\n });\n const tagged = await mapLimit(\n picked,\n CHECKS_AT_ONCE,\n async ({ module, tag }) =>\n module.decide !== undefined || (await services.sourceControl.tagCommit(tag)) !== null,\n );\n const units = picked\n .filter((_, index) => tagged[index])\n .map(({ unit, module, tag }) => {\n const decide = async () => {\n const at = await checkout(context);\n const input = jobInput(context, module, unit, { tag, environment, ...at });\n const decision = module.decide\n ? await module.decide(decideContext(context), input)\n : webDecision(context, module, input, recorded);\n return { input, decision };\n };\n const checked = module.kind === \"published-package\" ? module.provider : environment;\n const label = module.releaseOnly\n ? `Checking what ${tag} needs`\n : `Checking what ${tag} needs on ${checked}`;\n const on = module.releaseOnly ? null : checked;\n return { unit, module, tag, decide, label, on };\n });\n const [only] = units;\n const places = new Set(units.map(({ on }) => on));\n const [place] = places;\n const batchLabel = `Checking what ${units.length} units need${places.size === 1 && place ? ` on ${place}` : \"\"}`;\n let done = 0;\n const firstLook = !only\n ? []\n : units.length === 1\n ? [await context.progress.during(only.label, \"thinking\", only.decide)]\n : await context.progress.during(\n batchLabel,\n \"thinking\",\n () =>\n mapLimit(units, CHECKS_AT_ONCE, async ({ decide }) => {\n const result = await decide();\n done += 1;\n return result;\n }),\n { done: () => done, total: units.length },\n );\n const ready: Ready[] = [];\n // A merged PR moves main: every unit after it decides again on the new commit.\n let moved = false;\n for (const [index, { unit, module, tag, decide, label }] of units.entries()) {\n const looked = firstLook[index];\n if (!looked) continue;\n let { input, decision } = moved\n ? await context.progress.during(label, \"thinking\", decide)\n : looked;\n while (decision.action === \"pull-request\") {\n const merged = await pullRequestFirst(context, decision);\n if (merged === \"failed\") return null;\n if (merged === \"declined\") {\n decision = { action: \"none\", status: \"left for later\" };\n break;\n }\n moved = true;\n ({ input, decision } = await decide());\n }\n if (decision.action === \"choose\") decision = await chosen(context, decision);\n if (decision.action === \"fail\") {\n fail(context, decision.title, decision.detail, decision.commands);\n return null;\n }\n if (decision.action === \"none\") {\n output.line(` ${paint(\"dim\", \"·\")} ${tag} ${paint(\"dim\", decision.status)}`);\n continue;\n }\n ready.push({\n unit,\n module,\n input,\n kind: decision.kind,\n jobs: decision.jobs,\n decided: module.decide !== undefined,\n notLocal: decision.notLocal ?? null,\n confirmed: decision.confirmed === true,\n });\n }\n return ready;\n};\n\n/** Why a path cannot ship a unit, or null when it can. */\nconst blockedOn = async (\n context: ReleaseContext,\n path: DeployPath,\n { input, jobs, decided, notLocal }: Ready,\n): Promise<string | null> => {\n const { services } = context;\n if (path === \"ci\") {\n const workflow = services.ciPipeline.shipWorkflow;\n // Where a ref holds the workflow is the pipeline's to say; one that says nothing is not checked.\n const file = services.ciPipeline.workflowFile?.(workflow);\n for (const { ci } of jobs) {\n if (!ci) return \"only ships from this machine\";\n if (file === undefined) continue;\n if ((await services.sourceControl.fileAt(ci.ref, file)) !== null) continue;\n const onMain =\n ci.ref !== input.defaultBranch &&\n (await services.sourceControl.fileAt(input.defaultBranch, file)) !== null;\n return onMain ? `predates ${workflow}` : `no ${workflow}`;\n }\n return null;\n }\n if (decided) return notLocal;\n const changed = await services.sourceControl.diffNames(input.tag, \"HEAD\");\n const sinceTagOnlyVersionFiles = onlyVersionFiles(changed, versionFiles(context));\n return shipsFrom(path, { sinceTagOnlyVersionFiles })\n ? null\n : `${input.defaultBranch} moved past it`;\n};\n\n/** What to do instead, when the path a person forced cannot ship a unit. */\nconst instead = (context: ReleaseContext, forced: DeployPath) =>\n forced === \"ci\"\n ? \"ship it from this machine\"\n : `this machine builds its checkout, ship it through ${ciLabel(context.services.ciPipeline)}`;\n\nconst takes = (context: ReleaseContext, path: DeployPath) =>\n `ships ${path === \"ci\" ? \"through\" : \"from\"} ${pathLabel(context.services.ciPipeline, path)}`;\n\n/**\n * The way a unit ships: the forced one when it can, the only one left when the other cannot, or\n * asked. Said whenever it is not asked.\n */\nconst routeOf = async (\n context: ReleaseContext,\n entry: Ready,\n forced: DeployPath | undefined,\n): Promise<DeployPath | \"ask\" | \"skip\" | \"stuck\"> => {\n const say = (mark: string, why: string) =>\n context.output.line(` ${mark} ${entry.input.tag} ${paint(\"dim\", why)}`);\n if (forced) {\n const why = await blockedOn(context, forced, entry);\n if (!why) return forced;\n say(paint(\"yellow\", \"!\"), `${why}: ${instead(context, forced)}`);\n return \"skip\";\n }\n const ci = await blockedOn(context, \"ci\", entry);\n const local = await blockedOn(context, \"local\", entry);\n const choice = routeChoice({ ci, local });\n // Both ways can: the config's way when it names one, else the person picks.\n if (choice.route === \"ask\") return context.release.via ?? \"ask\";\n if (choice.route === \"stuck\") {\n say(paint(\"red\", \"✗\"), `${ci}, and ${local}: nothing can ship it`);\n return \"stuck\";\n }\n say(paint(\"dim\", \"·\"), `${choice.blocked}: ${takes(context, choice.route)}`);\n return choice.route;\n};\n\nconst shipmentOf =\n (shipWorkflow: string) =>\n ({ unit, module, input, jobs }: Ready): Shipment => ({\n item: { app: unit.name, tag: input.tag, kind: \"deploy\" },\n workflows: jobs.some(({ ci }) => ci) ? [shipWorkflow] : [],\n typicalMinutes: module.typicalMinutes,\n });\n\n/** Each job the workflow ships, in order, with the commit its ref tags: the default branch moves, so it has none. */\nconst workflowJobs = async ({ services }: ReleaseContext, entries: readonly Ready[]) => {\n const refs = entries.flatMap(({ unit, jobs, input }) =>\n jobs.flatMap(({ ci }) =>\n ci ? [{ unit: unit.name, ref: ci.ref, moves: ci.ref === input.defaultBranch }] : [],\n ),\n );\n const jobs: WorkflowJob[] = [];\n for (const { unit, ref, moves } of refs) {\n const commit = moves ? null : await services.sourceControl.tagCommit(ref);\n jobs.push({ unit, ref, commit });\n }\n return jobs;\n};\n\n/** `Ship a through <the CI pipeline>`, or each tag with its way when they differ. */\nconst shipQuestion = (\n going: Ready[],\n paths: ReadonlyMap<Ready, DeployPath>,\n environment: string,\n context: ReleaseContext,\n) => {\n const label = environmentLabel(\n context,\n going.map(({ unit }) => unit.name),\n environment,\n );\n const used = [...new Set(going.flatMap((entry) => paths.get(entry) ?? []))];\n const [only] = used;\n const names = going\n .map((entry) => {\n const path = paths.get(entry);\n return used.length > 1 && path\n ? `${entry.input.tag} (${pathLabel(context.services.ciPipeline, path)})`\n : entry.input.tag;\n })\n .join(\", \");\n const how =\n used.length === 1 && only ? ` through ${pathLabel(context.services.ciPipeline, only)}` : \"\";\n return `Ship ${names} ${label === \"live\" ? \"live\" : `to ${label}`}${how}?`;\n};\n\n/** Production refuses --yes and asks for its name; on a runner, the person typed it before the dispatch. */\nconst mayStart = async (context: ReleaseContext, environment: Environment) => {\n const { output, prompter, options } = context;\n if (options.ci) return true;\n if (!yesAllowed(environment, options.yes)) {\n fail(context, \"No --yes on production\", \"every production step asks a person.\", [\n \"shiplane ship --channel production\",\n ]);\n return false;\n }\n if (environment !== \"production\") return true;\n if (await prompter.typed('Type \"production\" to start:', \"production\")) return true;\n output.line(paint(\"dim\", \"Nothing ran.\"));\n return false;\n};\n\n/**\n * The path each unit that chooses one takes: said when only one can, else asked. Null when the\n * person was asked and gave no answer. A picked unit nothing can ship fails the run, after the\n * others shipped.\n */\nconst pathsOf = async (\n context: ReleaseContext,\n {\n environment,\n ready,\n forced,\n }: { environment: Environment; ready: readonly Ready[]; forced: DeployPath | undefined },\n) => {\n const paths = new Map<Ready, DeployPath>();\n const unanswered: Ready[] = [];\n let stuck = false;\n for (const entry of ready.filter(choosesPath)) {\n const route = await routeOf(context, entry, forced);\n if (route === \"ask\") unanswered.push(entry);\n if (route === \"stuck\") stuck = true;\n if (route === \"ci\" || route === \"local\") paths.set(entry, route);\n }\n if (unanswered.length === 0) return { paths, stuck };\n const answers = await askPaths(\n context,\n environment,\n unanswered.map(shipmentOf(context.services.ciPipeline.shipWorkflow)),\n );\n if (!answers) return null;\n unanswered.forEach((entry, index) => {\n const answer = answers[index];\n if (answer) paths.set(entry, answer);\n });\n return { paths, stuck };\n};\n\n/** The person said no: preview offers production instead, which asks for its name on its own rules. */\nconst declined = async (\n context: ReleaseContext,\n {\n environment,\n scope,\n via,\n }: { environment: Environment; scope?: ReadonlySet<string>; via?: DeployPath },\n): Promise<boolean> => {\n const { prompter } = context;\n const instead =\n environment === \"preview\" &&\n prompter.interactive &&\n (await prompter.confirm(\"Ship to production instead?\"));\n if (instead) return shipTo(context, \"production\", { scope, via });\n context.progress.say(\"resting\", paint(\"dim\", \"Nothing shipped.\"));\n return true;\n};\n\n/** The unit's `prepare` from the config, run from the root before it ships from this machine. */\nconst prepareStep = (context: ReleaseContext, { unit, input }: Ready): ShipStep[] => {\n const { release, shell } = context;\n if (release.prepare === undefined) return [];\n const line = prepareLine(release.prepare, unit);\n return [\n {\n label: `prepare ${input.tag}: ${line}`,\n run: async () => {\n const status = await shell.attach(\"sh\", [\"-c\", line], { cwd: release.root });\n if (status !== 0) throw new Error(`${line} exited with ${status}`);\n },\n tags: [input.tag],\n unit: unit.name,\n stage: \"prepare\",\n },\n ];\n};\n\n/**\n * Ships every picked unit its environment does not run yet, and returns once each one is\n * triggered: EAS builds and workflows go on on their own, a Fly deploy from here once rolled out.\n * Production asks for its name first. False on a failure.\n */\nexport const shipTo = async (\n context: ReleaseContext,\n environment: Environment,\n {\n scope,\n via,\n envChecked = new Set(),\n }: {\n scope?: ReadonlySet<string>;\n via?: DeployPath;\n /** Units whose env this run already checked on this environment. */\n envChecked?: ReadonlySet<string>;\n },\n): Promise<boolean> => {\n const { output, prompter, options, services } = context;\n if (!(await mayStart(context, environment))) return false;\n const ready = await decideAll(context, environment, scope);\n if (!ready) return false;\n if (ready.length === 0) {\n context.progress.say(\n \"resting\",\n paint(\"dim\", `Nothing to ship ${destination(context, scope ?? [], environment)}.`),\n );\n return true;\n }\n const toCheck = ready.map(({ unit }) => unit).filter(({ name }) => !envChecked.has(name));\n const listing = new Set(\n toCheck.filter((unit) => unit.checkEnvBeforeDeploy).map(({ name }) => name),\n );\n const signedIn =\n listing.size === 0 ||\n (await signIn(context, {\n requirements: signInsOf(context.release, listing),\n again: \"ship again\",\n }));\n if (!signedIn) return false;\n if (!(await checkEnvBeforeDeploy(context, { environment, units: toCheck }))) return false;\n const routed = await pathsOf(context, {\n environment,\n ready,\n forced: forcedPath({ ci: options.ci, via }),\n });\n if (!routed) {\n output.line(paint(\"dim\", \" Nothing shipped.\"));\n // Cancelled by the person is fine; no terminal to ask is a failure a script should see.\n return prompter.interactive;\n }\n const { paths, stuck } = routed;\n const going = ready.filter((entry) => !choosesPath(entry) || paths.has(entry));\n if (going.length === 0) return !stuck;\n // A job run from its tag's worktree leaves this checkout alone.\n const runsHere = going.some(\n (entry) => paths.get(entry) === \"local\" && entry.jobs.some(({ from }) => !from),\n );\n if (runsHere && !(await services.sourceControl.isClean())) {\n fail(\n context,\n \"Uncommitted changes\",\n \"this machine ships its checkout: commit or stash them first.\",\n );\n return false;\n }\n if (\n going.some(({ confirmed }) => !confirmed) &&\n !(await confirm(\n context,\n shipQuestion(going, paths, environment, context),\n environment === \"preview\",\n ))\n ) {\n return declined(context, { environment, scope, via });\n }\n const here = going.filter((entry) => paths.get(entry) !== \"ci\");\n const runs = shipRuns(\n await workflowJobs(\n context,\n going.filter((entry) => paths.get(entry) === \"ci\"),\n ),\n );\n const workflow = services.ciPipeline.shipWorkflow;\n const steps: ShipStep[] = [\n ...here.flatMap((entry) => [\n ...prepareStep(context, entry),\n ...entry.jobs.map((job) => ({\n label: job.label,\n run: () => runHere(context, job, entry.input),\n tags: [entry.input.tag],\n unit: entry.unit.name,\n stage: \"ship\" as const,\n })),\n ]),\n ...runs.map((run) => ({\n label: `ship ${run.units.join(\", \")} from ${run.ref} (${workflow})`,\n run: () => dispatchShip(context, run, environment),\n tags: going.filter(({ unit }) => run.units.includes(unit.name)).map(({ input }) => input.tag),\n unit: run.units.join(\", \"),\n stage: \"ship\" as const,\n })),\n ];\n await writePlan(context, environment, new Set(going.map(({ unit }) => unit.name)));\n const outcomes: Outcomes = new Map();\n const shipped = await runShipSteps(context, steps, outcomes);\n writeResult(context, outcomes);\n if (!shipped) return false;\n const names = going.map(({ input }) => input.tag).join(\", \");\n const where = destination(\n context,\n going.map(({ unit }) => unit.name),\n environment,\n );\n output.line();\n context.progress.say(\n \"happy\",\n `${paint([\"bold\", \"green\"], \"✓ Triggered.\")} ${paint(\"dim\", `${names}, shipping ${where} on their own.`)}`,\n );\n await runFollowUps(\n context,\n going.map(({ unit, input }) => ({ unit, tag: input.tag, environment })),\n );\n if (runs.length > 0) {\n output.line(` ${paint(\"cyan\", \"gh run list --limit 5\")}`);\n }\n // A package has no channel to read, so status has nothing to show for one.\n if (going.some(({ module }) => module.kind !== \"published-package\")) {\n output.line(` ${paint(\"cyan\", `shiplane status --channel ${environment}`)}`);\n }\n output.line();\n return !stuck;\n};\n","import type { OpenPr, ReleaseStep } from \"../domain/releasePr\";\nimport type { ReleaseTag } from \"../domain/tags\";\nimport type { ReleaseContext } from \"./context\";\nimport { nextStep, RELEASE_BRANCH_PREFIX } from \"../domain/releasePr\";\nimport { plural } from \"../domain/words\";\nimport { checkEnvBeforeDeploy } from \"./checkEnvBeforeDeploy\";\nimport { openReleasePr, printSummary } from \"./openReleasePr\";\nimport { pickScope } from \"./pickScope\";\nimport { prepareRelease } from \"./prepareRelease\";\nimport { preflight } from \"./requirements\";\nimport { listed, paint } from \"./say\";\nimport { shipTo } from \"./ship\";\nimport { runSteps } from \"./steps\";\nimport { missingTags, tagRelease } from \"./tagRelease\";\nimport { destination } from \"./targets\";\nimport { waitForMerge } from \"./waitForMerge\";\n\n/** The commits main gained since a release PR's branch, or none when the host did not say. */\nconst movedPast = async (context: ReleaseContext, pr: OpenPr, originMain: string) => {\n if (!pr.head) return [];\n return context.services.sourceControl.commitsBetween(pr.head, originMain).catch(() => []);\n};\n\n/** Why a stale release PR closed, said on it, so a reviewer landing there knows where to go. */\nconst closedComment = (replacement: readonly OpenPr[], subjects: readonly string[]) =>\n [\n `Closed by shiplane: ${plural(subjects.length, \"commit\")} ${subjects.length === 1 ? \"was\" : \"were\"} merged into main after this release PR was opened, so its changelog no longer matched what would ship.`,\n `Replaced by ${listed(replacement.map(({ number }) => `#${number}`))}, which versions everything merged so far. Please review that one.`,\n \"\",\n ...subjects.map((subject) => `- ${subject}`),\n ].join(\"\\n\");\n\n/**\n * Release PRs main moved past are replaced: a fresh one versions everything merged, then each\n * stale one closes with a comment pointing to it. The open ones, or null when that failed.\n */\nconst refreshStale = async (\n context: ReleaseContext,\n prs: OpenPr[],\n scope: ReadonlySet<string>,\n): Promise<OpenPr[] | null> => {\n const { originMain } = await context.services.sourceControl.position();\n const moved = await Promise.all(prs.map((pr) => movedPast(context, pr, originMain)));\n const subjects = [...new Set(moved.flat().map(({ subject }) => subject))];\n if (subjects.length === 0) return prs;\n const { output, progress } = context;\n const names = listed(prs.map(({ number }) => `#${number}`));\n progress.say(\n \"thinking\",\n `↻ Release ${names} is out of date: ${plural(subjects.length, \"commit\")} landed on main since.`,\n );\n output.line(paint(\"dim\", \" Replacing it so the changelog matches what ships.\"));\n const prepared = await prepareRelease(context, scope);\n const opened = await openReleasePr(context, prepared, prs);\n if (!opened) return null;\n for (const pr of prs)\n await context.services.codeHost.closePr(pr, closedComment(opened, subjects));\n output.line(\n ` ${paint(\"green\", \"✓\")} Opened ${listed(opened.map(({ number }) => `#${number}`))}${context.release.flow.approval === \"required\" ? \" (needs approval again)\" : \"\"} ${paint(\"green\", \"✓\")} Closed ${names}, with a comment pointing to it`,\n );\n return opened;\n};\n\nconst STAGES = [\"What to release\", \"Versions\", \"Release PR\", \"Merge\", \"Tags\", \"Ship\"] as const;\n\ntype Stage = (name: (typeof STAGES)[number]) => void;\n\n/** A new release PR for the picked units: the open ones, or the run's result when it ends here. */\nconst openRelease = async (\n context: ReleaseContext,\n { scope, stage }: { scope: ReadonlySet<string>; stage: Stage },\n): Promise<OpenPr[] | boolean> => {\n const { output, progress } = context;\n stage(\"Versions\");\n const prepared = await progress.during(\n \"Planning each app's version with changesets, and what its target ships\",\n \"thinking\",\n () => prepareRelease(context, scope),\n );\n if (prepared.bumps.length === 0 && prepared.packages === 0) {\n printSummary(context, prepared);\n output.line(\n paint(\"dim\", \" Nothing to version for these units: the others wait for a later release.\"),\n );\n return true;\n }\n stage(\"Release PR\");\n return (await openReleasePr(context, prepared)) ?? false;\n};\n\n/** The open release PRs, replaced when main moved past them; false when that failed. */\nconst pickUpRelease = async (\n context: ReleaseContext,\n { prs, scope }: { prs: OpenPr[]; scope: ReadonlySet<string> },\n): Promise<OpenPr[] | false> => {\n const fresh = await refreshStale(context, prs, scope);\n if (!fresh) return false;\n if (fresh !== prs) return fresh;\n const waiting = context.release.flow.approval === \"required\" ? \"approval\" : \"a merge\";\n context.progress.say(\n \"thinking\",\n `↻ Picking up release ${listed(fresh.map(({ number }) => `#${number}`))}: still waiting for ${waiting}`,\n );\n context.output.line(paint(\"dim\", \" To cancel it, close it on GitHub.\"));\n return fresh;\n};\n\n/** The release PRs this run waits on, said as it picks up; the run's result when it ends here. */\nconst releasePrsOf = async (\n context: ReleaseContext,\n {\n step,\n scope,\n missing,\n stage,\n }: {\n step: ReleaseStep;\n scope: ReadonlySet<string>;\n missing: readonly ReleaseTag[];\n stage: Stage;\n },\n): Promise<OpenPr[] | boolean> => {\n if (step.step === \"release-pr\") return openRelease(context, { scope, stage });\n if (step.step === \"wait-merge\") return pickUpRelease(context, { prs: step.prs, scope });\n if (missing.length === 0) return [];\n context.progress.say(\"thinking\", `↻ Picking up a merged release`);\n context.output.line(\n paint(\n \"dim\",\n ` Left to do: tag ${plural(missing.length, \"version\")} → ship ${destination(\n context,\n missing.map(({ app }) => app),\n \"preview\",\n )}`,\n ),\n );\n return [];\n};\n\n/**\n * `release` on preview: the release PR, the wait for its merge, the tags, then the ship. It reads where things\n * stand first, so a run stopped anywhere picks up where it left off. False when something failed.\n */\nexport const releaseToPreview = async (context: ReleaseContext): Promise<boolean> => {\n const { output, services, progress } = context;\n const stage = (name: (typeof STAGES)[number]) => progress.stage(STAGES, STAGES.indexOf(name));\n stage(\"What to release\");\n const picked = await pickScope(context, \"preview\");\n if (!picked || picked.scope.size === 0) {\n progress.say(\"resting\", paint(\"dim\", \"Nothing ran.\"));\n return true;\n }\n if (!(await preflight(context, picked.scope))) return false;\n const picking = context.release.units.filter(({ name }) => picked.scope.has(name));\n if (!(await checkEnvBeforeDeploy(context, { environment: \"preview\", units: picking }))) {\n return false;\n }\n const covered = picked.info.filter(({ app }) => picked.scope.has(app));\n const [releasePrs, missing] = await progress.during(\n \"Looking for an open release PR and versions not tagged yet\",\n \"thinking\",\n () => Promise.all([services.codeHost.openPrsFrom(RELEASE_BRANCH_PREFIX), missingTags(context)]),\n );\n const step = nextStep({\n pending: covered.reduce((sum, { changesets }) => sum + changesets, 0),\n releasePrs,\n untagged: missing.length,\n });\n const prs = await releasePrsOf(context, { step, scope: picked.scope, missing, stage });\n if (typeof prs === \"boolean\") return prs;\n let current = context;\n if (prs.length > 0) stage(\"Merge\");\n for (const pr of prs) {\n output.line();\n const outcome = await waitForMerge(context, pr);\n if (outcome === \"closed\") {\n progress.say(\"resting\", `○ Release #${pr.number} was closed: nothing shipped.`);\n output.line(paint(\"dim\", \" Run shiplane to open a new release with everything pending.\"));\n return true;\n }\n if (outcome === \"left\") {\n output.line(paint(\"dim\", ` Left #${pr.number} waiting. Run shiplane once it's approved.`));\n return true;\n }\n progress.say(\"happy\", `${paint(\"green\", \"✓\")} Release PR #${pr.number} merged`);\n }\n if (prs.length > 0) {\n const from = await services.sourceControl.defaultBranch();\n const pulled = await runSteps(context, [\n { label: `switch to ${from}`, run: () => services.sourceControl.switchTo(from) },\n { label: `pull ${from}`, run: () => services.sourceControl.pull() },\n ]);\n if (!pulled) return false;\n current = { ...context, release: await context.load() };\n }\n const tags = prs.length > 0 ? await missingTags(current) : missing;\n if (tags.length > 0) stage(\"Tags\");\n if (!(await tagRelease(current, tags))) return false;\n stage(\"Ship\");\n // A unit the release took along unpicked is tagged with the rest, so it ships with them too.\n return shipTo(current, \"preview\", {\n scope: new Set([...picked.scope, ...tags.map(({ app }) => app)]),\n envChecked: picked.scope,\n });\n};\n","import type { OnDefault } from \"../domain/branchRelease\";\nimport type { OpenPr } from \"../domain/releasePr\";\nimport type { Channel } from \"../domain/testChannel\";\nimport type { BranchPlan, Here } from \"./branchPublish\";\nimport type { ReleaseContext } from \"./context\";\nimport { branchChoice } from \"../domain/branchRelease\";\nimport { channelFor, channelProblem } from \"../domain/testChannel\";\nimport { plural } from \"../domain/words\";\nimport { planBranch, printPlan, publishBranch } from \"./branchPublish\";\nimport { releaseToPreview } from \"./releaseToPreview\";\nimport { fail, paint, reasonOf } from \"./say\";\nimport { runSteps } from \"./steps\";\n\nconst whereHere = async ({ services }: ReleaseContext): Promise<Here> => {\n const [{ branch, head, originMain }, defaultBranch] = await Promise.all([\n services.sourceControl.position(),\n services.sourceControl.defaultBranch(),\n ]);\n return { branch, head, defaultBranch, originMain };\n};\n\nconst refuseDirty = (context: ReleaseContext) => {\n fail(\n context,\n \"Uncommitted changes\",\n \"commit or stash them first, a test version publishes the commit you are on.\",\n );\n return false;\n};\n\nconst printOthers = ({ output }: ReleaseContext, others: readonly string[]) =>\n others.forEach((name) =>\n output.line(\n ` ${paint(\"dim\", \"–\")} ${name} ${paint(\"dim\", \"test release not available yet: npm packages only\")}`,\n ),\n );\n\nconst nothingToPublish = ({ progress, services }: ReleaseContext, plan: BranchPlan) => {\n const why =\n plan.others.length > 0\n ? \"nothing to publish: no pending unit is an npm package\"\n : `nothing pending: a test release publishes what the changesets release, add one with ${services.versioning.nextChange}`;\n progress.say(\"resting\", why);\n return true;\n};\n\n/**\n * In a terminal, with more than one package pending, the person keeps the ones to test, all\n * offered; null on cancel. Otherwise the plan as it is.\n */\nconst pickPackages = async (\n { prompter }: ReleaseContext,\n plan: BranchPlan,\n): Promise<BranchPlan | null> => {\n if (plan.publish.length < 2) return plan;\n const names = plan.publish.map(({ unit }) => unit.name);\n const kept = await prompter.multiselect(\n \"Which pending packages get a test release?\",\n plan.publish.map(({ unit, version }) => ({\n value: unit.name,\n label: unit.name,\n hint: version,\n })),\n names,\n );\n if (kept === null || kept.length === 0) return null;\n return { ...plan, publish: plan.publish.filter(({ unit }) => kept.includes(unit.name)) };\n};\n\nconst whatPublishes = ({ publish }: BranchPlan) => {\n const [only] = publish;\n return publish.length === 1 && only ? only.version : plural(publish.length, \"package\");\n};\n\n/** The person picks a test release or the real one from the default branch; null on cancel. */\nconst askHow = ({ prompter }: ReleaseContext, { here, plan }: { here: Here; plan: BranchPlan }) =>\n prompter.select(\n `You're on ${here.branch}, not ${here.defaultBranch}.`,\n [\n {\n value: \"publish\",\n label: \"Publish a test release\",\n hint: `${whatPublishes(plan)} → npm tag ${plan.tag}`,\n },\n {\n value: \"switch\",\n label: `Switch to ${here.defaultBranch}`,\n hint: `git switch ${here.defaultBranch} && git pull, then the real release`,\n },\n ],\n \"publish\",\n );\n\n/** Switches to the default branch, pulls it, then runs the real release from there. */\nconst switchAndRelease = async (context: ReleaseContext, { defaultBranch }: Here) => {\n const { sourceControl } = context.services;\n const pulled = await runSteps(context, [\n { label: `switch to ${defaultBranch}`, run: () => sourceControl.switchTo(defaultBranch) },\n { label: `pull ${defaultBranch}`, run: () => sourceControl.pull() },\n ]);\n if (!pulled) return false;\n return releaseToPreview({ ...context, release: await context.load() });\n};\n\n/** What the test version publishes on the channel; null, said, when its registry cannot say. */\nconst planOn = async (context: ReleaseContext, here: Here, channel: Channel) => {\n try {\n return await planBranch(context, { here, channel });\n } catch (error) {\n fail(context, `Cannot number ${channel}`, reasonOf(error));\n return null;\n }\n};\n\n/** Plans what the test version publishes, asks when asked to, then publishes it or only shows it. */\nconst publishTest = async (\n context: ReleaseContext,\n {\n here,\n pr,\n ask,\n pick,\n channel,\n dryRun,\n }: {\n here: Here;\n pr: OpenPr | null;\n ask: boolean;\n /** Ask which pending packages to keep. */\n pick: boolean;\n channel: Channel;\n dryRun: boolean;\n },\n) => {\n if (!dryRun && !(await context.services.sourceControl.isClean())) return refuseDirty(context);\n const plan = await planOn(context, here, channel);\n if (!plan) return false;\n printOthers(context, plan.others);\n if (plan.publish.length === 0) return nothingToPublish(context, plan);\n if (dryRun) return printPlan(context, plan);\n const answer = ask ? await askHow(context, { here, plan }) : \"publish\";\n if (answer === \"switch\") return switchAndRelease(context, here);\n const picked = answer === null ? null : pick ? await pickPackages(context, plan) : plan;\n if (picked === null) {\n context.progress.say(\"resting\", paint(\"dim\", \"Nothing ran.\"));\n return true;\n }\n return publishBranch(context, { here, pr, plan: picked });\n};\n\n/**\n * `shiplane` where it runs: on the default branch, the real release; elsewhere, or for `shiplane\n * test-release`, a test version of the npm packages the pending changesets release, on the branch's\n * channel (a snapshot unless `testRelease` says otherwise), commented on its pull request when it\n * has one. False when refused or failed.\n */\nexport const branchRelease = async (\n context: ReleaseContext,\n {\n onDefault,\n channel: picked,\n dryRun = false,\n }: {\n onDefault: OnDefault;\n /** The channel for this run, over the one `testRelease` gives the branch. */\n channel?: string;\n /** Show what would publish, at which versions and tag, and publish nothing. */\n dryRun?: boolean;\n },\n): Promise<boolean> => {\n const problem = picked === undefined ? null : channelProblem(picked);\n if (problem) {\n fail(context, \"Not a channel\", problem);\n return false;\n }\n const here = await whereHere(context);\n const choice = branchChoice({\n onDefaultBranch: here.branch === here.defaultBranch,\n onDefault,\n yes: context.options.yes,\n interactive: context.prompter.interactive,\n });\n if (choice === \"release\") return releaseToPreview(context);\n const channel = picked ?? channelFor(here.branch, context.release.testRelease);\n const pr = dryRun ? null : await context.services.codeHost.prForBranch(here.branch);\n // A channel named on the command line is the answer: nothing left to ask.\n const ask = choice === \"ask\" && picked === undefined && !dryRun;\n const pick = context.prompter.interactive && !context.options.yes && !dryRun;\n return publishTest(context, { here, pr, ask, pick, channel, dryRun });\n};\n","import type { z } from \"zod\";\n\nimport type { SetupContext } from \"./setupContext\";\nimport { paint } from \"./say\";\nimport { documentedKeys } from \"./setupFiles\";\n\n/**\n * `shiplane docs <module or adapter>`: every key a unit file takes, described, with its default. A\n * module name reads the release config; an adapter name, the official adapters and those composed.\n */\nexport const docsFor = async (context: SetupContext, name: string) => {\n const { output } = context;\n const release = await context.load();\n const module = release.modules.find((candidate) => candidate.name === name);\n const adapters = [\n ...context.adapters,\n ...release.modules.map(({ provider, settings }) => ({ name: provider, settings })),\n ];\n const adapter = adapters.find((candidate) => candidate.name === name);\n const found: { title: string; settings: z.ZodObject } | undefined = module\n ? {\n title: `module: ${module.name} ${paint(\"dim\", `with ${module.provider}`)}`,\n settings: module.settings,\n }\n : adapter && {\n title: `${adapter.name} ${paint(\"dim\", \"adapter\")}`,\n settings: adapter.settings,\n };\n if (!found) {\n const known = [\n ...new Set([\n ...release.modules.map((candidate) => candidate.name),\n ...adapters.map((candidate) => candidate.name),\n ]),\n ];\n output.line(`${paint(\"red\", \"✗\")} no module or adapter \"${name}\": ${known.join(\", \")}`);\n return false;\n }\n const keys = documentedKeys(found.settings);\n const width = Math.max(8, ...keys.map(({ key }) => key.length)) + 2;\n output.line();\n output.line(` ${paint(\"bold\", found.title)}`);\n output.line();\n keys.forEach(({ key, description, default: fallback, required }) => {\n const note = required\n ? paint(\"yellow\", \"required\")\n : fallback === undefined\n ? \"optional\"\n : `default: ${typeof fallback === \"string\" ? fallback : JSON.stringify(fallback)}`;\n output.line(` ${key.padEnd(width)}${description}`);\n output.line(` ${\" \".repeat(width)}${paint(\"dim\", note)}`);\n });\n output.line();\n return true;\n};\n","import type { SetupContext } from \"./setupContext\";\nimport { paint } from \"./say\";\nimport { addToConfig, CONFIG_FILE, factoryName, releasePackage } from \"./setupFiles\";\n\nconst adapterFile = (\n name: string,\n factory: string,\n pkg: string,\n) => `import { defineServerHosting, z } from \"${pkg}\";\n\n/** Hosts a server on ${name}. Replace the command with the one that deploys it. */\nexport const ${factory} = () =>\n defineServerHosting({\n name: \"${name}\",\n settings: z.object({\n service: z.string().describe(\"What to deploy\"),\n }),\n describe: ({ options }) => \\`\\${options.service} on ${name}\\`,\n jobs: ({ tag, options }) => [\n {\n label: \\`deploy \\${tag} to \\${options.service}\\`,\n local: [{ command: \"echo\", args: [\"deploy\", options.service] }],\n },\n ],\n });\n`;\n\nconst testFile = (\n name: string,\n factory: string,\n pkg: string,\n) => `import { serverHostingContract, serverHostingFake } from \"${pkg}/testing\";\n\nimport { ${factory} } from \"./${name}\";\n\n// The contract every server host passes, run on this adapter and on the Fake tests use in its place.\nserverHostingContract([\n { adapter: ${factory}(), settings: { service: \"web-preview\" } },\n { adapter: serverHostingFake(), settings: { service: \"web-preview\" } },\n]);\n`;\n\n/**\n * `shiplane adapter new <name>`: a server hosting adapter, the port's contract suite run on it and on\n * its Fake, and a module for it in the root config.\n */\nexport const newAdapter = async (context: SetupContext, name: string): Promise<boolean> => {\n const { output, files } = context;\n if (!/^[a-z][a-z0-9-]*$/.test(name)) {\n output.line(\n `${paint(\"red\", \"✗\")} an adapter name is lowercase words joined by dashes, like my-host`,\n );\n return false;\n }\n const factory = `${factoryName(name)}ServerHosting`;\n const pkg = releasePackage(files);\n const file = `release/adapters/${name}.ts`;\n if (files.exists(file)) {\n output.line(`${paint(\"red\", \"✗\")} ${file} already exists`);\n return false;\n }\n const config = addToConfig(\n files.read(CONFIG_FILE) ?? \"\",\n {\n factory: \"backendService\",\n port: \"serverHosting\",\n adapter: factory,\n name,\n from: `./release/adapters/${name}`,\n },\n pkg,\n );\n if (!config) {\n output.line(\n `${paint(\"red\", \"✗\")} ${CONFIG_FILE} has no modules list to add it to: run shiplane setup first`,\n );\n return false;\n }\n files.write(file, adapterFile(name, factory, pkg));\n files.write(`release/adapters/${name}.test.ts`, testFile(name, factory, pkg));\n files.write(CONFIG_FILE, config);\n output.line(\n `${paint(\"green\", \"◇\")} Wrote ${file}, its contract test, and a ${name} module in ${CONFIG_FILE}`,\n );\n output.line(\n `${paint(\"dim\", \"└\")} Next: point an app at it with ${paint(\"cyan\", `module: ${name}`)}`,\n );\n return Promise.resolve(true);\n};\n","import type { Environment } from \"../domain/environment\";\nimport type { Shipped } from \"../modules/module\";\nimport type { ReleaseContext } from \"./context\";\nimport { prepareLine } from \"../domain/prepare\";\nimport { ciLabel } from \"./askPath\";\nimport { planFollowUps } from \"./followUps\";\nimport { releaseOrder } from \"./releaseOrder\";\nimport { paint } from \"./say\";\nimport { checkout, commandLine, environmentLabel, shipPlanOf, unitTarget } from \"./targets\";\n\n/**\n * `--dry-run`: every command shipping the current tags would run, both ways, in release order,\n * then what the features would do. It runs nothing and asks nothing; it reads git, and the code host\n * for features.\n */\nexport const planShips = async (context: ReleaseContext, environment: Environment) => {\n const { release, services, output } = context;\n const at = await checkout(context);\n output.line();\n output.line(\n ` ${paint(\"bold\", \"Plan\")} ${paint(\"dim\", \"·\")} ${environmentLabel(context, [], environment)} ${paint(\"dim\", \"· nothing runs\")}`,\n );\n output.line(` ${paint(\"bold\", \"Order\")} ${releaseOrder(release.units)}`);\n const shipped: Shipped[] = [];\n for (const unit of release.units) {\n const target = unitTarget(context, { unit, environment, ...at });\n if (!target) continue;\n const { module, tag, input } = target;\n const tagged = (await services.sourceControl.tagCommit(tag)) !== null;\n if (tagged && !module.releaseOnly) shipped.push({ unit, tag, environment });\n const plan = shipPlanOf(context, module, input);\n output.line();\n output.line(\n ` ${paint(\"bold\", tag)} → ${plan.where}${tagged ? \"\" : paint(\"yellow\", \" (not tagged yet: release first)\")}`,\n );\n plan.jobs.forEach((job, index) => {\n output.line(` ${paint(\"dim\", \"this machine\")}`);\n if (index === 0 && release.prepare !== undefined) {\n output.line(` sh -c ${JSON.stringify(prepareLine(release.prepare, unit))}`);\n }\n job.local.forEach((command) => output.line(` ${commandLine(command)}`));\n if (job.record)\n output.line(\n ` ${paint(\"dim\", `then record ${tag} on ${environment} in GitHub Deployments`)}`,\n );\n if (job.ci) {\n const pipeline = services.ciPipeline;\n const inputs = { units: unit.name, environment };\n output.line(` ${paint(\"dim\", ciLabel(pipeline))}`);\n output.line(\n ` ${pipeline.dispatchLine?.(pipeline.shipWorkflow, job.ci.ref, inputs) ?? `dispatch ${pipeline.shipWorkflow} on ${job.ci.ref} with units=${unit.name}, environment=${environment}`}`,\n );\n }\n });\n }\n await planFollowUps(context, shipped);\n output.line();\n};\n","import type { Released } from \"../domain/companions\";\nimport type { DeployPath } from \"../domain/deploys\";\nimport type { ReleaseContext } from \"./context\";\nimport { releasedTogether } from \"../domain/companions\";\nimport { scopeChoices } from \"../domain/scope\";\nimport { changelogSection, tagName } from \"../domain/tags\";\nimport { pickScope } from \"./pickScope\";\nimport { confirm, listed, paint } from \"./say\";\nimport { shipTo } from \"./ship\";\nimport { checkout, decideContext, unitTarget } from \"./targets\";\n\nconst STAGES = [\"What to promote\", \"Ship\"] as const;\n\n/** Each unit's version on preview with its notes, read from its tag. */\nconst releasedVersions = async (\n { release, services }: ReleaseContext,\n apps: readonly string[],\n): Promise<Released[]> =>\n Promise.all(\n release.units\n .filter(({ name }) => apps.includes(name))\n .map(async ({ name, dir, version }) => {\n const changelog = await services.sourceControl.fileAt(\n tagName(name, version, release.tagFormat),\n services.versioning.changelogFile(dir),\n );\n return { app: name, version, notes: changelogSection(changelog ?? \"\", version) };\n }),\n );\n\n/**\n * Which units production gets: the person's pick, plus what preview only ever ran with it when they\n * accept. Offered ticked with why, never added silently. Null when cancelled.\n */\nexport const pickPromotion = async (context: ReleaseContext): Promise<Set<string> | null> => {\n const { output } = context;\n const picked = await pickScope(context, \"production\");\n if (!picked || picked.scope.size === 0) return null;\n const left = scopeChoices(picked.info, \"production\")\n .filter(({ app, pending }) => pending && !picked.scope.has(app))\n .map(({ app }) => app);\n if (left.length === 0) return picked.scope;\n const companions = await context.progress.during(\n \"Reading the notes of what preview runs, to see what went there together\",\n \"thinking\",\n async () =>\n releasedTogether(\n await releasedVersions(context, [...picked.scope]),\n await releasedVersions(context, left),\n ),\n );\n if (companions.length === 0) return picked.scope;\n const names = companions.map(({ app }) => app);\n const partners = [...new Set(companions.flatMap(({ with: partner }) => partner))];\n output.line();\n output.line(\n ` ${paint([\"bold\", \"yellow\"], \"!\")} ${paint(\"bold\", `Preview runs ${listed(names)} with what you picked:`)}`,\n );\n companions.forEach(({ app, version, why }) =>\n output.line(` ${app.padEnd(11)}${version.padEnd(10)}${paint(\"dim\", why)}`),\n );\n output.line();\n const versions = companions.map(({ app, version }) => `${app} ${version}`);\n const them = companions.length === 1 ? \"it\" : \"them\";\n if (\n await confirm(\n context,\n `Promote ${listed(versions)} too? Preview has only run ${them} with ${listed(partners)}.`,\n true,\n )\n ) {\n return new Set([...picked.scope, ...names]);\n }\n const promoted = picked.info\n .filter(({ app }) => partners.includes(app))\n .map(({ app, version }) => `${app} ${version}`);\n output.line(\n paint(\n \"dim\",\n ` ${listed(names)} ${companions.length === 1 ? \"stays\" : \"stay\"} on preview: production runs ${listed(promoted)} next to the ${listed(names)} it has.`,\n ),\n );\n return picked.scope;\n};\n\n/** How each picked unit does on preview, said; when one looks unwell, asks before going on. */\nconst previewLooksWell = async (context: ReleaseContext, scope: ReadonlySet<string>) => {\n const { output, release } = context;\n const at = await checkout(context);\n const reads = await context.progress.during(\n \"Reading how preview runs what you picked\",\n \"thinking\",\n () =>\n Promise.all(\n release.units\n .filter(({ name }) => scope.has(name))\n .map(async (unit) => {\n const target = unitTarget(context, { unit, environment: \"preview\", ...at });\n if (!target?.module.health) return [];\n const health = await target.module\n .health(decideContext(context), target.input)\n .catch(() => null);\n return health ? [{ tag: target.tag, ...health }] : [];\n }),\n ),\n );\n const healths = reads.flat();\n if (healths.length === 0) return true;\n output.line();\n healths.forEach(({ tag, ok, summary }) =>\n output.line(\n ` ${ok ? paint(\"green\", \"✓\") : paint([\"bold\", \"yellow\"], \"!\")} ${tag.padEnd(18)}${paint(\"dim\", summary)}`,\n ),\n );\n output.line();\n const unwell = healths.filter(({ ok }) => !ok);\n if (unwell.length === 0) return true;\n const reasons = unwell.map(({ tag, why }) => `${tag}: ${why ?? \"looks unwell\"}`);\n return confirm(context, `Promote anyway? ${reasons.join(\"; \")}.`, false);\n};\n\n/** Production, from what preview runs: every unit picked, its name typed, each step asked. */\nexport const promote = async (context: ReleaseContext, via: DeployPath | undefined) => {\n context.progress.stage(STAGES, 0);\n const scope = await pickPromotion(context);\n if (!scope) return true;\n if (!(await previewLooksWell(context, scope))) {\n context.output.line(paint(\"dim\", \" Nothing promoted.\"));\n return true;\n }\n context.progress.stage(STAGES, 1);\n return shipTo(context, \"production\", { scope, via });\n};\n","/** A port a custom adapter fills: the flow's four, then the four ways an app is delivered. */\nexport interface CustomPort {\n /** `ciPipeline`: the key it takes in `releaseFlow`, or the module option. */\n key: string;\n /** `CiPipelinePort`. */\n type: string;\n /** \"CI pipeline\", as a person reads it. */\n label: string;\n kind: \"flow\" | \"delivery\";\n /** The contract's subject beyond `port`, or the settings a delivery contract runs with. */\n subject: string;\n}\n\nexport const CUSTOM_PORTS = {\n sourceControl: {\n key: \"sourceControl\",\n type: \"SourceControlPort\",\n label: \"source control\",\n kind: \"flow\",\n subject: `head: async () => (await port.position()).head,\n // TODO: write a file the repository does not track yet.\n change: () => Promise.resolve(),`,\n },\n codeHost: {\n key: \"codeHost\",\n type: \"CodeHostPort\",\n label: \"code host\",\n kind: \"flow\",\n subject: `// TODO: a branch pushed with one commit, a tag, an issue comments can go on.\n branch: (name) => Promise.resolve(name),\n tag: () => Promise.resolve(\"app@1.0.0\"),\n issue: { repository: \"acme/repo\", number: 1 },`,\n },\n ciPipeline: {\n key: \"ciPipeline\",\n type: \"CiPipelinePort\",\n label: \"CI pipeline\",\n kind: \"flow\",\n subject: `// TODO: a workflow that exists and has never run.\n idle: \"ship.yml\",`,\n },\n versioning: {\n key: \"versioning\",\n type: \"VersioningPort\",\n label: \"versioning\",\n kind: \"flow\",\n subject: `// TODO: a package this workspace holds, and its folder.\n workspace: { name: \"@acme/api\", folder: \"apps/api\" },`,\n },\n serverHosting: {\n key: \"serverHosting\",\n type: \"ServerHostingPort\",\n label: \"server hosting\",\n kind: \"delivery\",\n subject: `{}`,\n },\n staticHosting: {\n key: \"staticHosting\",\n type: \"StaticHostingPort\",\n label: \"static hosting\",\n kind: \"delivery\",\n subject: `{}`,\n },\n mobileDistribution: {\n key: \"mobileDistribution\",\n type: \"MobileDistributionPort\",\n label: \"mobile distribution\",\n kind: \"delivery\",\n subject: `{}`,\n },\n packageRegistry: {\n key: \"packageRegistry\",\n type: \"PackageRegistryPort\",\n label: \"package registry\",\n kind: \"delivery\",\n subject: `{}`,\n },\n} as const satisfies Record<string, CustomPort>;\n\nexport type CustomPortKey = keyof typeof CUSTOM_PORTS;\n\n/** `jenkinsCiPipeline` → `jenkins-ci-pipeline`. */\nexport const kebab = (name: string) => name.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\n\n/** A factory name a person can type: a letter, then letters and digits. */\nexport const isFactoryName = (name: string) => /^[a-z][a-zA-Z0-9]*$/.test(name);\n\n/** The name offered first: `customCiPipeline`. */\nexport const suggestedName = (port: CustomPortKey) =>\n `custom${port.charAt(0).toUpperCase()}${port.slice(1)}`;\n\n/** Where a custom adapter lives, and what the config imports it from. */\nexport const customFiles = (name: string) => ({\n file: `shiplane/adapters/${kebab(name)}.ts`,\n test: `shiplane/adapters/${kebab(name)}.test.ts`,\n from: `./shiplane/adapters/${kebab(name)}`,\n});\n\nconst share = (name: string) =>\n ` * Works? Share it: publish it as shiplane-${kebab(name)}, or open a pull request at\n * https://github.com/arnaud-zg/packages so everyone gets it.`;\n\n/** The adapter's file: shiplane's in-memory one under your name, ready to be replaced. */\nexport const renderCustomAdapter = (port: CustomPortKey, name: string, pkg: string) => {\n const { type, label, kind } = CUSTOM_PORTS[port];\n const memory = `${port}Memory`;\n if (kind === \"delivery\") {\n return `import type { DeliveryAdapter, ${type} } from \"${pkg}\";\nimport { z } from \"${pkg}\";\nimport { ${memory} } from \"${pkg}/memory\";\n\n/**\n * ${name}: your own ${label}. It starts in memory: it records each delivery it is asked for and\n * ships nothing, so the release runs end to end while you write it. To make it real, replace the\n * spread with define${type.replace(/Port$/, \"\")}({ ... }) from \"${pkg}\" (see: shiplane docs ${port}).\n * ${kebab(name)}.test.ts runs the contract every ${label} passes.\n${share(name)}\n */\nexport const ${name} = (): DeliveryAdapter<${type}> => ({\n ...${memory}(),\n name: \"${name}\",\n // The keys an app's unit file gives it: add yours, such as z.object({ service: z.string() }).\n settings: z.object({}),\n});\n`;\n }\n return `import type { ${type}, ServiceAdapter } from \"${pkg}\";\nimport { ${memory} } from \"${pkg}/memory\";\n\n/**\n * ${name}: your own ${label}. It starts in memory: it records each call and does nothing real, so\n * the release runs end to end while you write it. Replace its methods one at a time;\n * ${kebab(name)}.test.ts runs the contract every ${label} passes.\n${share(name)}\n */\nexport const ${name} = (): ServiceAdapter<${type}> => ({\n name: \"${name}\",\n create: (context) => {\n const port: ${type} = ${memory}().create(context);\n // TODO: replace what it does with your own calls, for example:\n // port.someMethod = async (...args) => { ... };\n return port;\n },\n});\n`;\n};\n\n/** Its test: the port's contract, run on it. */\nexport const renderCustomTest = (port: CustomPortKey, name: string, pkg: string) => {\n const { kind, subject } = CUSTOM_PORTS[port];\n const contract = `${port}Contract`;\n const file = `./${kebab(name)}`;\n if (kind === \"delivery\") {\n return `import { ${contract} } from \"${pkg}/testing\";\n\nimport { ${name} } from \"${file}\";\n\n// The contract every ${CUSTOM_PORTS[port].label} passes. TODO: the settings an app gives it.\n${contract}([{ adapter: ${name}(), settings: ${subject} }]);\n`;\n }\n return `import { ${contract}, systemShell } from \"${pkg}/testing\";\n\nimport { ${name} } from \"${file}\";\n\n// The contract every ${CUSTOM_PORTS[port].label} passes: green means ${name} is done.\n${contract}(\"${name}\", () => {\n const port = ${name}().create({ root: process.cwd(), shell: systemShell });\n return Promise.resolve({\n port,\n ${subject}\n });\n});\n`;\n};\n","import path from \"node:path\";\n\nimport type { ReleaseUnit } from \"../domain/unit\";\nimport type { SetupContext } from \"./setupContext\";\nimport { readManifest } from \"./manifest\";\nimport { checkStatus, requirementsOf } from \"./requirements\";\nimport { paint, reasonOf } from \"./say\";\nimport { checkout, commandLine, shipPlanOf, unitTarget } from \"./targets\";\n\nclass StepFailed extends Error {}\n\n/** A failed check, said: a spinner already said a check that did not pass; one that broke says why. */\nconst sayFailed = (context: SetupContext, { label, error }: { label: string; error: unknown }) => {\n if (error instanceof StepFailed && context.progress) return;\n context.output.line(` ${paint(\"red\", \"✗\")} ${label}`);\n if (error instanceof StepFailed) return;\n context.output.line(` ${paint(\"dim\", reasonOf(error))}`);\n};\n\n/** One rehearsal check under a spinner when there is one: true when `work` says it passed. */\nconst check = async (context: SetupContext, label: string, work: () => Promise<boolean>) => {\n const run = async () => {\n if (!(await work())) throw new StepFailed();\n };\n const runPlain = async () => {\n await run();\n context.output.line(` ${paint(\"green\", \"✓\")} ${label}`);\n };\n try {\n await (context.progress ? context.progress.during(label, \"working\", run) : runPlain());\n return true;\n } catch (error) {\n sayFailed(context, { label, error });\n return false;\n }\n};\n\n/** The package manager this repository runs scripts with. */\nexport const runner = (context: SetupContext) =>\n context.files.exists(\"pnpm-lock.yaml\")\n ? \"pnpm\"\n : context.files.exists(\"yarn.lock\")\n ? \"yarn\"\n : context.files.exists(\"bun.lock\") || context.files.exists(\"bun.lockb\")\n ? \"bun\"\n : \"npm\";\n\n/** How a unit builds: its `buildCommand:`, else its package.json \"build\" script, else nothing. */\nexport const buildCommandOf = (context: SetupContext, unit: ReleaseUnit) => {\n if (unit.buildCommand)\n return { command: \"sh\", args: [\"-c\", unit.buildCommand], shown: unit.buildCommand };\n if (!readManifest({ files: context.files, dir: unit.dir })?.scripts?.build) return null;\n const pm = runner(context);\n return { command: pm, args: [\"run\", \"build\"], shown: `${pm} run build` };\n};\n\n/**\n * A release played through with nothing pushed, published or deployed: the config loads, every app\n * builds, every ship plan resolves, every sign-in is there. Each failure says how to fix it.\n */\nexport const rehearse = async (context: SetupContext): Promise<boolean> => {\n const { output, shell, root } = context;\n output.line();\n output.line(\n ` ${paint(\"bold\", \"Rehearsal\")} ${paint(\"dim\", \"· nothing is pushed, published or deployed\")}`,\n );\n const release = await context.load();\n if (release.problems.length > 0) {\n release.problems.forEach(({ file, line, message, hint }) => {\n output.line(\n ` ${paint(\"red\", \"✗\")} ${line === undefined ? file : `${file}:${line}`} ${message}`,\n );\n if (hint) output.line(` ${paint(\"dim\", hint)}`);\n });\n return false;\n }\n const builds = release.units.flatMap((unit) => {\n const build = buildCommandOf(context, unit);\n return build ? [{ unit, build }] : [];\n });\n const results: {\n unit: ReleaseUnit;\n shown: string;\n failed: boolean;\n seconds: string;\n tail: string[];\n }[] = [];\n const built =\n builds.length === 0 ||\n (await check(\n context,\n `build ${builds.length} app${builds.length === 1 ? \"\" : \"s\"}`,\n async () => {\n results.push(\n ...(await Promise.all(\n builds.map(async ({ unit, build }) => {\n const started = Date.now();\n const result = await shell.capture(build.command, build.args, {\n cwd: path.join(root, unit.dir),\n });\n return {\n unit,\n shown: build.shown,\n failed: result.status !== 0,\n seconds: `${((Date.now() - started) / 1000).toFixed(1)}s`,\n tail: `${result.stderr}${result.stdout}`.trim().split(\"\\n\").slice(-3),\n };\n }),\n )),\n );\n return results.every(({ failed }) => !failed);\n },\n ));\n for (const { unit, shown, failed, seconds, tail } of results) {\n output.line(\n ` ${failed ? paint(\"red\", \"✗\") : paint(\"green\", \"✓\")} ${unit.dir.padEnd(18)}${paint(\"dim\", `${shown} ${seconds}`)}`,\n );\n if (!failed) continue;\n tail.forEach((line) => output.line(` ${paint(\"dim\", line)}`));\n output.line(` ${paint(\"dim\", `fix the build, or set buildCommand: in ${unit.file}`)}`);\n }\n\n const releaseContext = context.compose?.(release);\n const planned =\n !releaseContext ||\n (await check(context, `plan ${release.units.length} apps, nothing runs`, async () => {\n const at = await checkout(releaseContext);\n for (const unit of release.units) {\n const target = unitTarget(releaseContext, { unit, environment: \"preview\", ...at });\n if (target) shipPlanOf(releaseContext, target.module, target.input);\n }\n return true;\n }));\n\n let signedIn = true;\n for (const requirement of requirementsOf(release)) {\n const status = await checkStatus(shell, root, requirement);\n if (await check(context, requirement.label, () => Promise.resolve(status === 0))) continue;\n signedIn = false;\n const fix =\n status === 127\n ? `not installed: ${requirement.check.command}`\n : requirement.fix\n ? `run ${commandLine(requirement.fix)}, then shiplane setup`\n : \"not available here\";\n output.line(` ${paint(\"dim\", fix)}`);\n }\n return built && planned && signedIn;\n};\n","import path from \"node:path\";\n\nimport type { ReleaseModule } from \"../modules/module\";\nimport type { AnyDeliveryAdapter } from \"../modules/suggest\";\nimport type { FolderView } from \"../ports/delivery.port\";\nimport type { CustomPortKey } from \"./customAdapter\";\nimport type { SetupContext } from \"./setupContext\";\nimport type { FlowChoice, FlowPort, ModuleEntry } from \"./setupFiles\";\nimport { moduleFor } from \"../modules/suggest\";\nimport { callerWrite, renovateWrite } from \"./callerWorkflow\";\nimport { UNIT_FILE, UNIT_FILES } from \"./config/readUnitFile\";\nimport { expandPatterns, workspacePatterns } from \"./config/workspaceFolders\";\nimport {\n customFiles,\n isFactoryName,\n kebab,\n renderCustomAdapter,\n renderCustomTest,\n suggestedName,\n} from \"./customAdapter\";\nimport { askOptions } from \"./initRelease\";\nimport { readManifest } from \"./manifest\";\nimport { rehearse, runner } from \"./rehearse\";\nimport { paint } from \"./say\";\nimport {\n addToConfig,\n CHANGESETS_CLI,\n CHANGESETS_CONFIG,\n COMMITS_VERSIONING,\n CONFIG_FILE,\n DEFAULT_FLOW,\n FLOW_PORTS,\n folderView,\n placeModule,\n releasePackage,\n renderConfig,\n renderUnit,\n SCHEMA_FILE,\n schemaLineFor,\n schemaText,\n} from \"./setupFiles\";\nimport { unattended } from \"./unattended\";\n\n/** A file setup writes: its text, and whether it is new. */\nexport interface Write {\n file: string;\n text: string;\n created: boolean;\n /** Why setup writes it, said beside it when that is not plain from the file. */\n reason?: string;\n}\n\nconst ok = paint(\"green\", \"✓\");\nconst unsure = paint(\"yellow\", \"?\");\n\nconst CHANGESETS_CONFIG_FILE = \".changeset/config.json\";\n\n/** What a flow port is called, and what proves the ready-made adapter fits. */\nconst FLOW_LABEL: Record<FlowPort, { label: string; ready: string }> = {\n sourceControl: { label: \"Source control\", ready: \"git\" },\n codeHost: { label: \"Code host\", ready: \"GitHub\" },\n ciPipeline: { label: \"CI pipeline\", ready: \"GitHub Actions\" },\n versioning: { label: \"Versioning\", ready: \"Changesets\" },\n};\n\n/** The kinds of app a person picks from, in their words, and the delivery each one needs. */\nconst APP_KINDS = [\n { value: \"server-hosting\", label: \"Backend service\", hint: \"a server that runs\" },\n { value: \"static-hosting\", label: \"Web application\", hint: \"static files on a CDN\" },\n { value: \"mobile-distribution\", label: \"Mobile application\", hint: \"store builds and updates\" },\n { value: \"package-registry\", label: \"Published package\", hint: \"a library others install\" },\n { value: \"skip\", label: \"Internal tool\", hint: \"versioned, never deployed\" },\n] as const;\n\ntype AppKind = (typeof APP_KINDS)[number][\"value\"];\n\nconst CUSTOM_PORT_OF: Record<Exclude<AppKind, \"skip\">, CustomPortKey> = {\n \"server-hosting\": \"serverHosting\",\n \"static-hosting\": \"staticHosting\",\n \"mobile-distribution\": \"mobileDistribution\",\n \"package-registry\": \"packageRegistry\",\n};\n\nconst MODULE_OF: Record<CustomPortKey, string> = {\n sourceControl: \"\",\n codeHost: \"\",\n ciPipeline: \"\",\n versioning: \"\",\n serverHosting: \"backendService\",\n staticHosting: \"webApp\",\n mobileDistribution: \"mobileApp\",\n packageRegistry: \"publishedPackage\",\n};\n\n/** What proves each ready-made flow adapter fits this repository: hard evidence only. */\nconst flowEvidence = async (context: SetupContext): Promise<Record<FlowPort, string | null>> => {\n const { files, shell, root } = context;\n const remote = files.exists(\".git\")\n ? (await shell.capture(\"git\", [\"remote\", \"get-url\", \"origin\"], { cwd: root })).stdout.trim()\n : \"\";\n const github = /github\\.com[:/]([^/]+\\/[^/.]+)/.exec(remote)?.[1];\n const workflows = files.list(\".github/workflows\").filter((file) => /\\.ya?ml$/.test(file));\n return {\n sourceControl: files.exists(\".git\") ? \".git\" : null,\n codeHost: github ? `remote github.com/${github}` : null,\n ciPipeline: workflows[0] ? `.github/workflows/${workflows[0]}` : null,\n versioning: files.exists(CHANGESETS_CONFIG_FILE) ? CHANGESETS_CONFIG_FILE : null,\n };\n};\n\n/** A name for a custom adapter: asked, checked, unused. Null when cancelled. */\nconst askName = async (\n context: SetupContext,\n port: CustomPortKey,\n initial: string,\n): Promise<string | null> => {\n const { prompter, output, files } = context;\n for (;;) {\n const name = await prompter.text(\"Name it (you can rename it later)\", initial);\n if (name === null) return null;\n if (!isFactoryName(name)) {\n output.line(` ${paint(\"red\", \"✗\")} ${name}: a name like ${suggestedName(port)}`);\n continue;\n }\n if (files.exists(customFiles(name).file)) {\n output.line(` ${paint(\"red\", \"✗\")} ${customFiles(name).file} already exists`);\n continue;\n }\n return name;\n }\n};\n\n/** The custom adapter's two files. */\nconst customWrites = (port: CustomPortKey, name: string, pkg: string): Write[] => [\n { file: customFiles(name).file, text: renderCustomAdapter(port, name, pkg), created: true },\n { file: customFiles(name).test, text: renderCustomTest(port, name, pkg), created: true },\n];\n\n/** What both ways of versioning need: the changesets config, and its CLI when it is missing. */\nconst changesetsWrites = ({ files }: SetupContext): Write[] => {\n const manifest = readManifest({ files, dir: \".\" });\n const present = { ...manifest?.dependencies, ...manifest?.devDependencies }[CHANGESETS_CLI.name];\n return [\n { file: CHANGESETS_CONFIG_FILE, text: CHANGESETS_CONFIG, created: true },\n ...(manifest === null || present\n ? []\n : [\n {\n file: \"package.json\",\n text: `${JSON.stringify(\n {\n ...manifest,\n devDependencies: {\n ...manifest.devDependencies,\n [CHANGESETS_CLI.name]: CHANGESETS_CLI.version,\n },\n },\n null,\n 2,\n )}\\n`,\n created: false,\n },\n ]),\n ];\n};\n\n/** How a repository with no changesets config releases: asked once, commits unless told. */\nconst chooseVersioning = async (\n context: SetupContext,\n yes: boolean,\n writes: Write[],\n pkg: string,\n): Promise<FlowChoice | null> => {\n const { prompter } = context;\n const picked = unattended({ prompter, options: { yes } })\n ? \"commits\"\n : await prompter.select(\n \"How do you want to release?\",\n [\n {\n value: \"commits\",\n label: \"From commits\",\n hint: \"feat, fix and ! set the version, nothing to write\",\n },\n {\n value: \"changesets\",\n label: \"From changesets\",\n hint: \"you write what ships, and when\",\n },\n { value: \"custom\", label: \"Custom\", hint: \"a no-op in memory you implement\" },\n ],\n \"commits\",\n );\n if (picked === null) return null;\n if (picked === \"custom\") {\n const name = await askName(context, \"versioning\", suggestedName(\"versioning\"));\n if (name === null) return null;\n writes.push(...customWrites(\"versioning\", name, pkg));\n return { factory: name, from: customFiles(name).from };\n }\n writes.push(...changesetsWrites(context));\n return picked === \"commits\" ? COMMITS_VERSIONING : DEFAULT_FLOW.versioning;\n};\n\n/** The flow, from what the repository proves; asked part by part when unsure or when asked to. */\nconst chooseFlow = async (\n context: SetupContext,\n yes: boolean,\n needsPerson: string[],\n writes: Write[],\n pkg: string,\n): Promise<Record<FlowPort, FlowChoice> | null> => {\n const { output, prompter } = context;\n const evidence = await flowEvidence(context);\n output.line(paint(\"bold\", \" Flow\"));\n FLOW_PORTS.forEach((port) => {\n const proof = evidence[port];\n const { label, ready } = FLOW_LABEL[port];\n output.line(\n proof\n ? ` ${ok} ${ready.padEnd(16)}${paint(\"dim\", proof)}`\n : ` ${unsure} ${label.padEnd(16)}${paint(\"dim\", \"not sure: nothing here proves one\")}`,\n );\n });\n const sure = FLOW_PORTS.every((port) => evidence[port] !== null);\n // Proven: nothing to ask. The rehearsal and \"Write it?\" are the check.\n if (sure) return DEFAULT_FLOW;\n const missing = FLOW_PORTS.filter((port) => !evidence[port] && port !== \"versioning\");\n if (yes && missing.length > 0) {\n needsPerson.push(\n ...missing.map((port) => `the ${FLOW_LABEL[port].label.toLowerCase()} (nothing proves one)`),\n );\n return null;\n }\n const flow = { ...DEFAULT_FLOW };\n // Only how it versions is left open: the rest is proven, so nothing else is asked.\n for (const port of missing.length > 0 ? FLOW_PORTS : ([\"versioning\"] as const)) {\n if (port === \"versioning\" && !evidence.versioning) {\n const choice = await chooseVersioning(context, yes, writes, pkg);\n if (choice === null) return null;\n flow.versioning = choice;\n continue;\n }\n const { label, ready } = FLOW_LABEL[port];\n const picked = await prompter.select(\n `${label}?`,\n [\n {\n value: \"ready\",\n label: ready,\n hint: `${DEFAULT_FLOW[port].from}${evidence[port] ? \"\" : \", not found here\"}`,\n },\n { value: \"custom\", label: \"Custom\", hint: \"a no-op in memory you implement\" },\n ],\n evidence[port] ? \"ready\" : \"custom\",\n );\n if (picked === null) return null;\n if (picked === \"custom\") {\n const name = await askName(context, port, suggestedName(port));\n if (name === null) return null;\n flow[port] = { factory: name, from: customFiles(name).from };\n writes.push(...customWrites(port, name, pkg));\n }\n }\n return flow;\n};\n\n/** Where the apps live: prefilled from the workspace when those folders exist, else typed. */\nconst chooseFolders = async (\n context: SetupContext,\n yes: boolean,\n needsPerson: string[],\n): Promise<string[] | null> => {\n const { prompter, output, files } = context;\n const known = workspacePatterns(files).filter(\n (pattern) => pattern.startsWith(\"!\") || expandPatterns(files, [pattern]).length > 0,\n );\n const found = expandPatterns(files, known).filter((dir) => dir !== \".\");\n output.line();\n output.line(paint(\"bold\", \" Apps\"));\n if (found.length === 0 && yes) {\n needsPerson.push(\"where the apps are (no workspace folders found)\");\n return null;\n }\n const listed = known.filter((pattern) => !pattern.startsWith(\"!\")).join(\", \");\n const taken =\n found.length > 0 &&\n (yes ||\n (await prompter.confirm(\n `Your apps and packages are in ${listed} (${found.length} folders)?`,\n true,\n )));\n if (taken) return known;\n for (;;) {\n const typed = await prompter.text(\"Where are your apps and packages? (e.g. apps/*, web)\");\n if (typed === null) return null;\n const patterns = typed\n .split(\",\")\n .map((part) => part.trim())\n .filter(Boolean);\n const empty = patterns.filter((pattern) => expandPatterns(files, [pattern]).length === 0);\n if (patterns.length > 0 && empty.length === 0) return patterns;\n output.line(\n ` ${paint(\"red\", \"✗\")} ${empty.join(\", \") || \"nothing typed\"} matches no folder: try again`,\n );\n }\n};\n\n/** Folders under these patterns with a manifest and no unit file yet. */\nconst newFolders = (context: SetupContext, patterns: readonly string[]): FolderView[] =>\n expandPatterns(context.files, patterns)\n .filter((dir) => dir !== \".\" && context.files.exists(path.posix.join(dir, \"package.json\")))\n .filter((dir) => !UNIT_FILES.some((name) => context.files.exists(path.posix.join(dir, name))))\n .map((dir) => folderView(context.files, dir));\n\ninterface Placed {\n folder: FolderView;\n module: string;\n options: Record<string, unknown>;\n reason?: string;\n}\n\n/** How a folder ships: taken when an adapter is sure, asked otherwise. Null: not shipped. */\nconst placeFolder = async (\n context: SetupContext,\n folder: FolderView,\n state: {\n yes: boolean;\n needsPerson: string[];\n modules: ReleaseModule[];\n entries: ModuleEntry[];\n writes: Write[];\n pkg: string;\n },\n): Promise<Placed | \"skip\" | null> => {\n const { prompter, output, adapters } = context;\n const sure = adapters\n .map((adapter) => ({ adapter, detection: adapter.detect?.(folder) ?? null }))\n .find(({ detection }) => detection?.certainty === \"found\");\n const place = (adapter: AnyDeliveryAdapter) => {\n const { name, entry } = placeModule(adapter, state.modules, state.pkg);\n if (entry) {\n state.entries.push(entry);\n state.modules.push(moduleFor(adapter, name));\n }\n return name;\n };\n if (sure?.detection) {\n const kind = APP_KINDS.find(({ value }) => value === sure.adapter.capability)?.label ?? \"\";\n output.line(\n ` ${ok} ${folder.dir.padEnd(18)}${kind} → ${sure.adapter.name} ${paint(\"dim\", `proof: ${sure.detection.reason}`)}`,\n );\n const options = await askOptions(\n context,\n folder,\n sure.adapter,\n sure.detection.options,\n state.yes,\n );\n return {\n folder,\n module: place(sure.adapter),\n options,\n reason: sure.detection.reason,\n };\n }\n if (state.yes) {\n state.needsPerson.push(`${folder.dir} (no adapter is sure what it is)`);\n return null;\n }\n output.line(` ${unsure} ${folder.dir.padEnd(18)}${paint(\"dim\", \"not sure what this is\")}`);\n // The modules the config already has come first: your own adapters included.\n const answer = await prompter.select<string>(`What is ${folder.dir}?`, [\n ...state.modules.map((module) => ({\n value: `module:${module.name}`,\n label: `Like ${module.name}`,\n hint: `${module.kind} on ${module.provider}, already in your config`,\n })),\n ...APP_KINDS.map(({ value, label, hint }) => ({ value, label, hint })),\n ]);\n if (answer === null) return null;\n if (answer.startsWith(\"module:\")) {\n return { folder, module: answer.slice(\"module:\".length), options: {} };\n }\n const kind = answer as AppKind;\n if (kind === \"skip\") return \"skip\";\n const fitting = adapters.filter((a) => a.capability === kind);\n const picked =\n fitting.length === 0\n ? \"custom\"\n : await prompter.select(\n `Where does ${folder.dir} go?`,\n [\n ...fitting.map((adapter) => ({ value: adapter.name, label: adapter.name })),\n { value: \"custom\", label: \"Custom\", hint: \"a no-op adapter you implement\" },\n ],\n fitting[0]?.name,\n );\n if (picked === null) return null;\n const adapter = fitting.find(({ name }) => name === picked);\n if (adapter) {\n const options = await askOptions(context, folder, adapter, {}, false);\n return { folder, module: place(adapter), options };\n }\n const port = CUSTOM_PORT_OF[kind];\n const name = await askName(\n context,\n port,\n `${path.posix.basename(folder.dir)}Delivery`.replace(/-([a-z])/g, (_m, c: string) =>\n c.toUpperCase(),\n ),\n );\n if (name === null) return null;\n const module = kebab(name);\n state.entries.push({\n factory: MODULE_OF[port],\n port,\n adapter: name,\n name: module,\n from: customFiles(name).from,\n });\n state.writes.push(...customWrites(port, name, state.pkg));\n return { folder, module, options: {} };\n};\n\n/** The config: written whole the first time, else the new modules added to the one there. */\nconst configWrites = (\n { files }: SetupContext,\n {\n existing,\n entries,\n pkg,\n flow,\n patterns,\n }: {\n existing: boolean;\n entries: readonly ModuleEntry[];\n pkg: string;\n flow: Record<FlowPort, FlowChoice> | null;\n patterns: string[] | null;\n },\n): Write[] => {\n if (!existing) {\n const units =\n patterns && patterns.join() !== workspacePatterns(files).join() ? patterns : undefined;\n const text = renderConfig(entries, pkg, flow ?? DEFAULT_FLOW, units);\n return [{ file: CONFIG_FILE, text, created: true }];\n }\n if (entries.length === 0) return [];\n const before = files.read(CONFIG_FILE) ?? \"\";\n const config = entries.reduce((text, entry) => addToConfig(text, entry, pkg) ?? text, before);\n return [{ file: CONFIG_FILE, text: config, created: false }];\n};\n\n/** The command that builds a folder: its unit's, its package.json script's, or one asked once. */\nconst buildFor = async (\n context: SetupContext,\n folder: FolderView,\n yes: boolean,\n): Promise<string | null> => {\n if (readManifest({ files: context.files, dir: folder.dir })?.scripts?.build) return null;\n if (yes) return null;\n const typed = await context.prompter.text(\n `${folder.dir} has no \"build\" script. Command to build it? (empty: nothing to build)`,\n );\n return typed?.trim() ? typed.trim() : null;\n};\n\n/**\n * `shiplane setup`: the one command to set releases up and keep them right. It reads the\n * repository, takes what it can prove, asks only the rest, then rehearses a release (builds, plan,\n * sign-ins) with nothing pushed or deployed. Files are kept only when the rehearsal passes. Run\n * again, it says all is set or offers what changed.\n */\nexport const setup = async (context: SetupContext, { yes }: { yes: boolean }): Promise<boolean> => {\n const { output, prompter, files } = context;\n const pkg = releasePackage(files);\n const needsPerson: string[] = [];\n const writes: Write[] = [];\n output.line();\n output.line(` ${paint(\"bold\", \"shiplane setup\")} ${paint(\"dim\", path.basename(context.root))}`);\n output.line();\n\n const existing = files.exists(CONFIG_FILE) ? await context.load() : null;\n if (existing && existing.problems.length > 0) {\n existing.problems.forEach(({ file, line, message, hint }) => {\n output.line(\n ` ${paint(\"red\", \"✗\")} ${paint(\"bold\", line === undefined ? file : `${file}:${line}`)} ${message}`,\n );\n if (hint) output.line(` ${paint(\"dim\", hint)}`);\n });\n output.line(` ${paint(\"dim\", \"Fix these, then run shiplane setup again. Nothing written.\")}`);\n return false;\n }\n\n const flow = existing ? null : await chooseFlow(context, yes, needsPerson, writes, pkg);\n if (existing) output.line(` ${ok} flow ${paint(\"dim\", CONFIG_FILE)}`);\n if (!existing && !flow && needsPerson.length === 0) return cancelled(context);\n\n const patterns = existing\n ? existing.units.length > 0\n ? workspacePatterns(files)\n : await chooseFolders(context, yes, needsPerson)\n : await chooseFolders(context, yes, needsPerson);\n if (!patterns && needsPerson.length === 0) return cancelled(context);\n if (existing && existing.units.length > 0) {\n output.line(\n ` ${ok} ${existing.units.length} apps ${paint(\"dim\", \"unchanged, your edits kept\")}`,\n );\n }\n\n const modules: ReleaseModule[] = [...(existing?.modules ?? [])];\n const entries: ModuleEntry[] = [];\n const placed: Placed[] = [];\n for (const folder of patterns ? newFolders(context, patterns) : []) {\n const result = await placeFolder(context, folder, {\n yes,\n needsPerson,\n modules,\n entries,\n writes,\n pkg,\n });\n if (result === null && needsPerson.length === 0) return cancelled(context);\n if (result && result !== \"skip\") {\n const buildCommand = await buildFor(context, folder, yes);\n placed.push(\n buildCommand ? { ...result, options: { buildCommand, ...result.options } } : result,\n );\n }\n }\n\n if (needsPerson.length > 0) {\n output.line();\n output.line(\n ` ${paint(\"red\", \"✗\")} ${needsPerson.length} thing${needsPerson.length === 1 ? \"\" : \"s\"} need${needsPerson.length === 1 ? \"s\" : \"\"} a person:`,\n );\n needsPerson.forEach((item) => output.line(` ${item}`));\n output.line(` ${paint(\"dim\", \"Run shiplane setup without --yes. Nothing written.\")}`);\n return false;\n }\n\n writes.unshift(\n ...configWrites(context, { existing: existing !== null, entries, pkg, flow, patterns }),\n );\n placed.forEach(({ folder, module, options, reason }) =>\n writes.push({\n file: path.posix.join(folder.dir, UNIT_FILE),\n text: renderUnit(module, options, { reason, schemaLine: schemaLineFor(folder.dir) }),\n created: true,\n }),\n );\n\n // The workflow that ships on CI: from the config there, or once a new one is written.\n const caller = existing ? await callerWrite(context, existing) : null;\n if (caller) writes.push(caller);\n const renovate = existing ? renovateWrite(context, existing, caller?.text) : null;\n if (renovate) writes.push(renovate);\n\n if (writes.length === 0) {\n const passed = await rehearse(context);\n if (passed) output.line(` ${ok} all set`);\n return passed;\n }\n\n // Written to rehearse on, put back as they were unless it passes.\n const before = [...writes.map(({ file }) => file), SCHEMA_FILE].map((file) => ({\n file,\n text: files.read(file),\n }));\n writes.forEach(({ file, text }) => files.write(file, text));\n if (existing === null || entries.length > 0) {\n const release = await context.load();\n if (release.modules.length > 0) files.write(SCHEMA_FILE, schemaText(release.modules));\n const written = existing ? null : await callerWrite(context, release);\n if (written) {\n before.push({ file: written.file, text: null });\n files.write(written.file, written.text);\n writes.push(written);\n }\n const renovate = existing ? null : renovateWrite(context, release);\n if (renovate) {\n before.push({ file: renovate.file, text: files.read(renovate.file) });\n files.write(renovate.file, renovate.text);\n writes.push(renovate);\n }\n }\n const passed = await rehearse(context);\n const keep = passed && (yes || (await prompter.confirm(\"Releasable. Write it?\", true)));\n if (!keep) {\n before.forEach(({ file, text }) =>\n text === null ? files.remove(file) : files.write(file, text),\n );\n output.line(\n ` ${paint(\"dim\", passed ? \"Nothing written.\" : \"Fix it, then run shiplane setup again. Nothing written.\")}`,\n );\n return false;\n }\n writes.forEach(({ file, created, reason }) =>\n output.line(\n ` ${created ? paint(\"green\", \"+\") : paint(\"yellow\", \"~\")} ${file}${reason ? ` ${paint(\"dim\", reason)}` : \"\"}`,\n ),\n );\n const custom = writes.some(({ file }) => file.startsWith(\"shiplane/adapters/\"));\n if (custom) {\n output.line(\n ` ${paint(\"dim\", \"Custom adapters start in memory: fill them in until their contract test passes.\")}`,\n );\n output.line(\n ` ${paint(\"dim\", \"Works? Share it as shiplane-<name>, or open a pull request at github.com/arnaud-zg/packages.\")}`,\n );\n }\n const fromCommits = flow\n ? flow.versioning.factory === COMMITS_VERSIONING.factory\n : existing?.flow.versioning.name === \"commits\";\n const next = fromCommits ? \"erge a commit\" : \"dd a changeset, merge\";\n const install = writes.some(({ file }) => file === \"package.json\");\n const start = fromCommits ? \"m\" : \"a\";\n output.line();\n output.line(\n ` ${ok} ${paint(\"bold\", \"Ready.\")} ${install ? `Run ${runner(context)} install, then ${start}` : start.toUpperCase()}${next}, and run ${paint(\"cyan\", \"shiplane\")}`,\n );\n return true;\n};\n\nconst cancelled = (context: SetupContext) => {\n context.output.line(` ${paint(\"dim\", \"Nothing written.\")}`);\n return false;\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\n\nimport type { ManifestReader } from \"../../ports/manifest.port\";\nimport { PackageJsonSchema } from \"../../application/manifest\";\n\nconst PackageSchema = PackageJsonSchema.pipe(z.object({ name: z.string(), version: z.string() }));\n\nexport const packageJsonManifest: ManifestReader = {\n read: (root, dir) => {\n const file = path.join(root, dir, \"package.json\");\n if (!fs.existsSync(file)) return null;\n const parsed = PackageSchema.safeParse(JSON.parse(fs.readFileSync(file, \"utf8\")));\n return parsed.success ? parsed.data : null;\n },\n};\n","import type { Ora } from \"ora\";\nimport ora from \"ora\";\n\nconst TICK_MS = 140;\n\n/** What the live line shows: its frames (the mascot, or ora's dots), its text, what trails it. */\nexport interface LiveSpinner {\n frames?: readonly string[];\n text: string;\n suffix?: () => string;\n}\n\n/**\n * The one line the release redraws in place, an ora spinner. Anything else printed goes above it,\n * and a prompt or a child process holds it so the terminal is theirs meanwhile.\n */\nclass LiveLine {\n private spinner: Ora | null = null;\n private held = 0;\n\n get busy() {\n return this.spinner !== null;\n }\n\n show({ frames, text, suffix }: LiveSpinner, animate: boolean) {\n this.spinner = ora({\n text,\n suffixText: suffix,\n stream: process.stdout,\n discardStdin: false,\n isEnabled: animate,\n ...(frames && frames.length > 0\n ? { spinner: { interval: TICK_MS, frames: [...frames] } }\n : { spinner: \"dots\" }),\n });\n if (this.held === 0) this.spinner.start();\n }\n\n /** Ends the live line with a symbol kept on screen: ✓, ✗ or !. */\n finish(symbol: string, text?: string) {\n const spinner = this.spinner;\n this.spinner = null;\n if (!spinner) return;\n if (this.held > 0) {\n process.stdout.write(`${symbol} ${text ?? spinner.text}\\n`);\n return;\n }\n spinner.stopAndPersist({ symbol, ...(text === undefined ? {} : { text }) });\n }\n\n clear() {\n this.spinner?.stop();\n this.spinner = null;\n }\n\n /** Prints a line above the live one. */\n above(text: string) {\n const live = this.spinner && this.held === 0 ? this.spinner : null;\n live?.clear();\n process.stdout.write(`${text}\\n`);\n live?.render();\n }\n\n /** Gives the terminal to `work`, a prompt or a child process, then draws the live line again. */\n async hold<T>(work: () => Promise<T>) {\n if (this.spinner && this.held === 0) this.spinner.stop();\n this.held += 1;\n try {\n return await work();\n } finally {\n this.held -= 1;\n if (this.spinner && this.held === 0) this.spinner.start();\n }\n }\n}\n\nexport const liveLine = new LiveLine();\n","import { execFile, spawn } from \"node:child_process\";\nimport path from \"node:path\";\n\nimport type { RunOptions, Shell } from \"../../ports/shell.port\";\nimport { liveLine } from \"../terminal/live-line\";\n\n// eas prints megabytes of fingerprint JSON: the default 1 MB buffer is far too small.\nconst MAX_BUFFER = 256 * 1024 * 1024;\n\n// The tools this CLI drives read their own variables (GH_TOKEN, EXPO_TOKEN, FLY_API_TOKEN).\n\nconst environment = (options: RunOptions) => ({ ...process.env, ...options.env });\n\nexport const systemShell: Shell = {\n capture: (command, args, options = {}) =>\n new Promise((resolve) => {\n const child = execFile(\n command,\n [...args],\n { cwd: options.cwd, env: environment(options), maxBuffer: MAX_BUFFER },\n (error, stdout, stderr) => {\n // A command that is not installed answers 127, as a shell would.\n const code = error?.code;\n const status = !error ? 0 : typeof code === \"number\" ? code : code === \"ENOENT\" ? 127 : 1;\n resolve({ status, stdout, stderr });\n },\n );\n if (options.input !== undefined) child.stdin?.end(options.input);\n }),\n // A child writing to the terminal owns it: the live line steps aside meanwhile.\n attach: (command, args, options = {}) =>\n liveLine.hold(\n () =>\n new Promise<number>((resolve) => {\n const child = spawn(command, [...args], {\n cwd: options.cwd,\n env: environment(options),\n stdio: options.input === undefined ? \"inherit\" : [\"pipe\", \"inherit\", \"inherit\"],\n });\n if (options.input !== undefined) child.stdin?.end(options.input);\n child.on(\"error\", () => resolve(127));\n child.on(\"close\", (code) => resolve(code ?? 1));\n }),\n ),\n\n env: (name) => process.env[name],\n prependPath: (dir) => {\n process.env.PATH = [dir, process.env.PATH].filter(Boolean).join(path.delimiter);\n },\n};\n","import { styleText } from \"node:util\";\n\nimport type { Display, MascotDrawing, MascotMoment, Mood } from \"../../domain/display\";\nimport type { BatchPlace, Progress, StepPlace } from \"../../ports/terminal.port\";\nimport { progressBar } from \"../../domain/display\";\nimport { liveLine } from \"./live-line\";\n\n/**\n * The mascot in colour: red when worried, green when happy. The hedgehog is coloured part by part,\n * spines, face, then what he holds; any other mascot as a whole.\n */\nexport const paintMascot = (mascot: MascotDrawing, moment: MascotMoment) => {\n const { mood } = moment;\n const text = mascot.draw(moment);\n if (mood === \"worried\") return styleText(\"red\", text);\n if (!mascot.hedgehog) return mood === \"happy\" ? styleText(\"green\", text) : text;\n const frame = [...text];\n const face = frame.slice(5, 10).join(\"\");\n return `${styleText(\"yellow\", frame.slice(0, 5).join(\"\"))}${styleText(mood === \"happy\" ? [\"bold\", \"green\"] : \"bold\", face)}${styleText(\"cyan\", frame.slice(10).join(\"\"))}`;\n};\n\nconst elapsed = (since: number) => {\n const seconds = Math.round((Date.now() - since) / 1000);\n return seconds < 60\n ? `${seconds}s`\n : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, \"0\")}s`;\n};\n\n/** Cuts `text` to what the terminal shows on one line, so redrawing it in place stays clean. */\nconst fit = (text: string, taken: number) => {\n const room = Math.max(20, (process.stdout.columns || 100) - taken);\n return text.length > room ? `${text.slice(0, room - 1)}…` : text;\n};\n\ntype Place = StepPlace | BatchPlace;\n\nconst counterOf = (step?: Place) =>\n step && \"index\" in step ? `${step.index + 1}/${step.total} ` : \"\";\n\nconst batchOf = (step?: Place) => (step && \"done\" in step ? step : null);\n\n/**\n * Progress in a terminal. Verbose: the journey bar, what it reads, each step redrawn in place with\n * its time, the mascot beside it. Not verbose: only each step's name, as before. A CI log or a pipe\n * gets plain lines, never a redraw.\n */\nexport const terminalProgress = (display: Display, inPlace: boolean): Progress => {\n const mascot = (mood: Mood, tick: number, label = \"\") =>\n display.mascot\n ? `${paintMascot(display.mascot, { mood, tick: display.motion ? tick : 0, label })} `\n : \"\";\n const taken = (step?: Place) =>\n 2 +\n (display.mascot ? display.mascot.width + 1 : 0) +\n counterOf(step).length +\n (batchOf(step) ? 8 : 0) +\n 8;\n\n const during = async <T>(\n label: string,\n mood: Mood,\n work: () => Promise<T>,\n step?: Place,\n ): Promise<T> => {\n const counter = styleText(\"dim\", counterOf(step));\n const batch = batchOf(step);\n if (!display.verbose) {\n if (step && !batch) {\n liveLine.above(\"\");\n liveLine.above(styleText([\"bold\", \"cyan\"], `▶ ${label}`));\n }\n return work();\n }\n const text = fit(label, taken(step));\n if (!inPlace || liveLine.busy) {\n liveLine.above(` ${mascot(mood, 0, label)}${counter}${text}`);\n return work();\n }\n const started = Date.now();\n const time = () =>\n styleText(\"dim\", `${batch ? `${batch.done()}/${batch.total} ` : \"\"}${elapsed(started)}`);\n const drawing = display.mascot;\n liveLine.show(\n {\n ...(drawing\n ? {\n frames: Array.from({ length: display.motion ? drawing.frames(mood) : 1 }, (_, tick) =>\n paintMascot(drawing, { mood, tick, label }),\n ),\n }\n : {}),\n text: `${counter}${text}`,\n suffix: time,\n },\n true,\n );\n try {\n const result = await work();\n liveLine.finish(` ${styleText(\"green\", \"✓\")}`, `${counter}${text} ${time()}`);\n return result;\n } catch (error) {\n liveLine.finish(` ${styleText(\"red\", \"✗\")}`, `${counter}${text} ${time()}`);\n throw error;\n }\n };\n\n return {\n stage: (stages, index) => {\n if (!display.verbose) return;\n const bar = styleText(\"green\", progressBar(index + 1, stages.length, 18));\n liveLine.above(\"\");\n liveLine.above(\n ` ${bar} ${styleText(\"dim\", `${index + 1}/${stages.length}`)} ${styleText(\"bold\", stages[index] ?? \"\")}`,\n );\n },\n during,\n say: (mood, text) =>\n liveLine.above(display.mascot ? ` ${mascot(mood, 0, text)}${text}` : text),\n };\n};\n","import { emitKeypressEvents } from \"node:readline\";\nimport { createInterface } from \"node:readline/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { styleText } from \"node:util\";\nimport type { CANCEL_SYMBOL, Option } from \"@clack/prompts\";\nimport { confirm, isCancel, multiselect, select, text } from \"@clack/prompts\";\n\nimport type { Display } from \"../../domain/display\";\nimport type { Choice, Clock, Output, Prompter } from \"../../ports/terminal.port\";\nimport { liveLine } from \"./live-line\";\nimport { paintMascot } from \"./terminal-progress.adapter\";\n\nexport const terminalOutput: Output = {\n line: (line = \"\") => liveLine.above(line),\n};\n\n/** Whether this process runs inside a GitHub Actions job. */\n\nexport const onGitHubActions = () => process.env.GITHUB_ACTIONS === \"true\";\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n sleep: async (ms) => {\n await sleep(ms);\n },\n};\n\nconst FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n\n/** A spinner, or the mascot waiting, on one line until a listed key is pressed or `ms` pass. Ctrl-C ends the process. */\nconst waitForKey = (display: Display, label: string, ms: number, keys: readonly string[]) =>\n new Promise<string | null>((resolve) => {\n const startedAt = Date.now();\n let frame = 0;\n const draw = () => {\n const seconds = Math.round((Date.now() - startedAt) / 1000);\n const tick = frame++;\n const glyph = display.mascot\n ? paintMascot(display.mascot, {\n mood: \"waiting\",\n tick: display.motion ? Math.floor(tick / 5) : 0,\n label,\n })\n : styleText(\"cyan\", FRAMES[tick % FRAMES.length] ?? \"\");\n process.stdout.write(`\\r ${glyph} ${label} ${styleText(\"dim\", `${seconds}s`)}`);\n };\n const timer = setInterval(draw, 80);\n const finish = (key: string | null) => {\n clearInterval(timer);\n clearTimeout(timeout);\n process.stdin.off(\"keypress\", onKey);\n process.stdin.setRawMode(false);\n process.stdin.pause();\n process.stdout.write(\"\\r\\u001B[2K\");\n resolve(key);\n };\n const onKey = (_text: string, key: { name?: string; ctrl?: boolean } | undefined) => {\n if (key?.ctrl && key.name === \"c\") {\n finish(null);\n process.stdout.write(\n `${styleText(\"dim\", \" Stopped waiting. release picks up right here.\")}\\n`,\n );\n process.exit(130);\n }\n if (key?.name && keys.includes(key.name)) finish(key.name);\n };\n const timeout = setTimeout(() => finish(null), ms);\n emitKeypressEvents(process.stdin);\n process.stdin.setRawMode(true);\n process.stdin.resume();\n process.stdin.on(\"keypress\", onKey);\n });\n\n// clack types an option per primitive value; a Choice has the same fields.\nconst asOptions = <Value extends string>(choices: Choice<Value>[]) =>\n choices as unknown as Option<Value>[];\n\nconst orNull = <Value>(answer: Value | typeof CANCEL_SYMBOL): Value | null =>\n isCancel(answer) ? null : answer;\n\nconst NO_MASCOT: Display = { verbose: false, mascot: null, motion: false };\n\n/** Questions through @clack/prompts, each owning the terminal; without one, every answer is no. */\nexport const terminalPrompter = (display: Display = NO_MASCOT): Prompter => {\n const interactive = Boolean(process.stdin.isTTY);\n const hold = <T>(work: () => Promise<T>) => liveLine.hold(work);\n return {\n interactive,\n confirm: (question, initial = false) =>\n hold(\n async () =>\n interactive &&\n orNull(await confirm({ message: question, initialValue: initial })) === true,\n ),\n typed: (question, word) =>\n hold(async () => {\n if (!interactive) return false;\n const prompt = createInterface({ input: process.stdin, output: process.stdout });\n const answer = await prompt.question(`${styleText(\"bold\", question)} `);\n prompt.close();\n return answer.trim() === word;\n }),\n select: (message, choices, initial) =>\n hold(async () =>\n interactive\n ? orNull(await select({ message, options: asOptions(choices), initialValue: initial }))\n : null,\n ),\n multiselect: (message, choices, initial) =>\n hold(async () =>\n interactive\n ? orNull(\n await multiselect({\n message,\n options: asOptions(choices),\n initialValues: initial,\n required: false,\n }),\n )\n : null,\n ),\n text: (message, initial) =>\n hold(async () =>\n interactive ? orNull(await text({ message, initialValue: initial })) : null,\n ),\n waitForKey: (label, ms, keys) =>\n hold(async () => {\n if (interactive) return waitForKey(display, label, ms, keys);\n await sleep(ms);\n return null;\n }),\n };\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createJiti } from \"jiti\";\n\nimport type { DeployPath } from \"../../domain/deploys\";\nimport type { DisplayChoice } from \"../../domain/display\";\nimport type { TestReleaseBranches } from \"../../domain/testChannel\";\nimport type { ReleaseUnit } from \"../../domain/unit\";\nimport type { Feature, ReleaseFlow, ReleaseModule } from \"../../modules/module\";\nimport type { ServiceAdapter } from \"../../ports/adapter.port\";\nimport type { ManifestReader } from \"../../ports/manifest.port\";\nimport type { ConfigProblem } from \"./problem\";\nimport type { UnitFile } from \"./readUnitFile\";\nimport { PrepareSchema } from \"../../domain/prepare\";\nimport { DEFAULT_TAG_FORMAT, TAG_FORMATS, tagFormatNamed } from \"../../domain/tags\";\nimport { channelProblem } from \"../../domain/testChannel\";\nimport { releaseFlow } from \"../releaseFlow\";\nimport { reasonOf } from \"../say\";\nimport { sortProblems } from \"./problem\";\nimport { readUnitFile, UNIT_FILE, UNIT_FILES } from \"./readUnitFile\";\nimport { isRecord, referencesIn, valueAt } from \"./values\";\nimport { expandPatterns, workspacePatterns } from \"./workspaceFolders\";\n\nconst EXTENSIONS = [\"ts\", \"mts\", \"js\", \"mjs\"];\n\n/** The config's names, the one from before shiplane last: still read, listed to rename. */\nexport const CONFIG_FILES = [\n ...EXTENSIONS.map((extension) => `shiplane.config.${extension}`),\n ...EXTENSIONS.map((extension) => `release.config.${extension}`),\n];\n\n/** A file still under its name from before shiplane, and the name it takes. */\nexport interface Rename {\n from: string;\n to: string;\n}\n\nconst renameOf = (file: string): Rename | null =>\n /(^|\\/)release\\.(config|unit)\\./.test(file)\n ? { from: file, to: file.replace(/(^|\\/)release\\./, \"$1shiplane.\") }\n : null;\n\n/** The release as composed: the flow, the modules in release order, the features, then the apps. */\nexport interface Release {\n root: string;\n flow: ReleaseFlow;\n /** What gets released, in release order. */\n modules: ReleaseModule[];\n /** What happens around a release, in the order they run. */\n features: Feature[];\n /** In release order: by module, then by name inside a module. The first is the Latest release. */\n units: ReleaseUnit[];\n problems: ConfigProblem[];\n /** How a tag names a version, such as `{name}@{version}`. */\n tagFormat: string;\n /** How a unit ships when both ways can, as the config asks; unset, each ship asks. */\n via?: DeployPath;\n /** How much the release says while it runs, as the config asks. */\n display?: DisplayChoice;\n /** Files still under their name from before shiplane. */\n renames?: Rename[];\n /** The template of a test version's pull request comment; `comments.table` when unset. */\n testComment?: string;\n /** Which channel each branch's test release publishes on; unset, every branch a snapshot. */\n testRelease?: TestReleaseBranches;\n /** Run from the root before each unit ships from this machine, its placeholders filled. */\n prepare?: string;\n}\n\ntype Composed = Pick<\n Release,\n | \"flow\"\n | \"modules\"\n | \"features\"\n | \"display\"\n | \"tagFormat\"\n | \"testComment\"\n | \"testRelease\"\n | \"via\"\n | \"prepare\"\n> & {\n units?: string[];\n};\n\nexport interface LoadOptions {\n /** Where `shiplane` resolves from inside the config; by default, this very package. */\n aliases?: Record<string, string>;\n /** Where each unit's name and version come from: its package.json, as `cli/compose` wires it. */\n manifests: ManifestReader;\n}\n\nexport const findConfig = (root: string) =>\n CONFIG_FILES.map((file) => path.join(root, file)).find((file) => fs.existsSync(file));\n\n// The name a config imports the CLI under.\nconst NAMES = [\"shiplane\"];\n\nconst resolves = (specifier: string) => {\n try {\n return fileURLToPath(import.meta.resolve(specifier));\n } catch {\n return null;\n }\n};\n\n// One alias per entry: a bare \"shiplane\" alias would also rewrite \"shiplane/fly\" into a path\n// under index.js.\nconst selfAliases = (): Record<string, string> => {\n const own = NAMES.find((name) => resolves(name) !== null);\n if (!own) return {};\n return Object.fromEntries(\n [\"\", \"/plugin\", \"/testing\"].flatMap((sub) => {\n const target = resolves(`${own}${sub}`);\n return target ? NAMES.map((name) => [`${name}${sub}`, target]) : [];\n }),\n );\n};\n\n/** A port no flow fills yet: a release that never loaded has nothing to run on. */\nconst unset = <Port>(port: string): ServiceAdapter<Port> => ({\n name: \"unset\",\n create: () => {\n throw new Error(`no ${port} adapter: shiplane.config.ts sets none`);\n },\n});\n\n/** The flow of a release that did not load: every port unset. */\nconst unsetFlow = () =>\n releaseFlow({\n sourceControl: unset(\"sourceControl\"),\n codeHost: unset(\"codeHost\"),\n ciPipeline: unset(\"ciPipeline\"),\n versioning: unset(\"versioning\"),\n });\n\nconst FLOW_MISSING = [\n \"flow is missing: give it one, such as\",\n \"flow: releaseFlow({ sourceControl: gitSourceControl(), codeHost: gitHubCodeHost(),\",\n \"ciPipeline: gitHubActionsCiPipeline(), versioning: changesetsVersioning() }),\",\n \"from the shiplane-git, shiplane-github and shiplane-changesets plugins\",\n].join(\" \");\n\nconst typed = (value: unknown, type: string) =>\n isRecord(value) && value.type === type && typeof value.name === \"string\";\n\nconst isFlow = (value: unknown): value is ReleaseFlow => isRecord(value) && value.type === \"flow\";\nconst isModule = (value: unknown): value is ReleaseModule => typed(value, \"module\");\nconst isFeature = (value: unknown): value is Feature => typed(value, \"feature\");\n\nconst listOf = <Item>(\n value: unknown,\n key: string,\n is: (candidate: unknown) => candidate is Item,\n example: string,\n): Item[] => {\n if (value === undefined) return [];\n if (!Array.isArray(value)) throw new Error(`${key} is not a list, such as ${key}: [${example}]`);\n return value.map((item: unknown, index) => {\n if (!is(item)) throw new Error(`${key}[${index}] is not one of its ${key}, such as ${example}`);\n return item;\n });\n};\n\nconst LEFTOVERS: Record<string, string> = {\n plugins:\n \"plugins is gone: defineRelease takes flow, modules and features, such as modules: [backendService({ serverHosting: flyServerHosting() })]\",\n latest: \"latest is gone: the first app of the first module is the Latest release\",\n};\n\n/** The modules, their names unique and their adapters' settings free of `module`. */\nconst checkModules = (modules: readonly ReleaseModule[], features: readonly Feature[]) => {\n const names = [...modules, ...features].map(({ name }) => name);\n names.forEach((name, index) => {\n if (names.indexOf(name) !== index) {\n throw new Error(\n `two modules are named \"${name}\": give one its own, such as { name: \"${name}-2\", ... }`,\n );\n }\n });\n const clash = modules.find(({ settings }) => \"module\" in settings.shape);\n if (clash) {\n throw new Error(\n `\"module\" is reserved for the unit file's module, yet ${clash.name}'s adapter takes it`,\n );\n }\n};\n\nconst tagFormatOf = (tag: unknown) => {\n if (tag === undefined) return DEFAULT_TAG_FORMAT;\n const format = typeof tag === \"string\" ? tagFormatNamed(tag) : undefined;\n if (!format?.includes(\"{version}\")) {\n const names = Object.keys(TAG_FORMATS)\n .map((name) => `\"${name}\"`)\n .join(\", \");\n throw new Error(`tag is one of ${names}, or a format naming the version, such as \"v{version}\"`);\n }\n return format;\n};\n\nconst readConfig = async (file: string, aliases: Record<string, string>): Promise<Composed> => {\n const jiti = createJiti(import.meta.url, { alias: aliases, moduleCache: false, fsCache: false });\n const loaded: unknown = await jiti.import(file, { default: true });\n if (!isRecord(loaded)) throw new Error(\"its default export is not defineRelease({ modules })\");\n for (const [key, message] of Object.entries(LEFTOVERS)) {\n if (key in loaded) throw new Error(message);\n }\n if (loaded.flow === undefined) throw new Error(FLOW_MISSING);\n if (!isFlow(loaded.flow)) {\n throw new Error(\"flow is not a release flow, such as flow: releaseFlow({ ... })\");\n }\n const modules = listOf(loaded.modules, \"modules\", isModule, \"webApp({ ... })\");\n const features = listOf(loaded.features, \"features\", isFeature, \"releaseComments({ ... })\");\n checkModules(modules, features);\n const units = Array.isArray(loaded.units)\n ? loaded.units.filter((unit): unit is string => typeof unit === \"string\")\n : undefined;\n const display = isRecord(loaded.display) ? loaded.display : {};\n const flag = (value: unknown) => (typeof value === \"boolean\" ? value : undefined);\n return {\n flow: loaded.flow,\n modules,\n features,\n units,\n display: { verbose: flag(display.verbose), mascot: mascotOf(display.mascot) },\n tagFormat: tagFormatOf(loaded.tag),\n ...testCommentOf(loaded.testComment),\n ...testReleaseOf(loaded.testRelease),\n via: viaOf(loaded.via),\n ...prepareOf(loaded.prepare),\n };\n};\n\n/** The config's `prepare`, its placeholders known; the first problem is thrown. */\nconst prepareOf = (value: unknown) => {\n if (value === undefined) return {};\n const parsed = PrepareSchema.safeParse(value);\n if (!parsed.success) throw new Error(parsed.error.issues[0]?.message);\n return { prepare: parsed.data };\n};\n\nconst testCommentOf = (value: unknown) => {\n if (value === undefined) return {};\n if (typeof value !== \"string\") {\n throw new Error('testComment is a template, such as comments.compact or \"Try it: {install}\"');\n }\n return { testComment: value };\n};\n\n/** The config's `testRelease`: a branch → channel map, every channel a name npm takes. */\nconst testReleaseOf = (value: unknown) => {\n if (value === undefined) return {};\n if (!isRecord(value)) {\n throw new Error(\n 'testRelease maps a branch to a channel, such as testReleases.gitflow or { main: \"nightly\" }',\n );\n }\n const branches = Object.fromEntries(\n Object.entries(value).map(([branch, channel]) => {\n const problem = typeof channel === \"string\" ? channelProblem(channel) : \"not a channel name\";\n if (problem) throw new Error(`testRelease \"${branch}\": ${problem}`);\n return [branch, channel as string];\n }),\n );\n return { testRelease: branches };\n};\n\n/** The config names a way by its port, never its provider: \"ci\" is whatever CI the flow uses. */\nconst viaOf = (via: unknown): DeployPath | undefined => {\n if (via === undefined) return undefined;\n if (via === \"ci\" || via === \"local\") return via;\n throw new Error('via is \"ci\" (the CI pipeline) or \"local\" (this machine)');\n};\n\n/** A config's mascot: true, false, frames per mood, or a function; anything else is ignored. */\nconst mascotOf = (value: unknown): DisplayChoice[\"mascot\"] => {\n if (typeof value === \"boolean\" || typeof value === \"function\")\n return value as DisplayChoice[\"mascot\"];\n if (!isRecord(value)) return undefined;\n const frames = Object.entries(value).filter(\n ([, list]) => Array.isArray(list) && list.every((frame) => typeof frame === \"string\"),\n );\n return frames.length > 0 ? Object.fromEntries(frames) : undefined;\n};\n\ninterface Read {\n unit: ReleaseUnit;\n file: UnitFile;\n}\n\n/** Apps in release order: by module as the config lists them, then by name. */\nconst inReleaseOrder = (read: readonly Read[], modules: readonly ReleaseModule[]) => {\n const rank = (unit: ReleaseUnit) => modules.findIndex(({ name }) => name === unit.module);\n return [...read].sort(\n (left, right) =>\n rank(left.unit) - rank(right.unit) || left.unit.name.localeCompare(right.unit.name),\n );\n};\n\nconst referenceProblems = ({ unit, file }: Read, ordered: readonly Read[]): ConfigProblem[] =>\n referencesIn(unit.options).flatMap(({ unit: name, key, at }) => {\n const other = ordered.find((candidate) => candidate.unit.name === name)?.unit;\n const line = file.lineOf(at);\n if (!other) {\n return [{ file: unit.file, line, message: `\"${name}\" has no ${UNIT_FILE} to read from` }];\n }\n if (valueAt(other.options, key.split(\".\")) === undefined) {\n return [{ file: unit.file, line, message: `\"${name}\" has no \"${key}\" in ${other.file}` }];\n }\n const position = (target: ReleaseUnit) =>\n ordered.findIndex((candidate) => candidate.unit === target);\n if (other !== unit && position(other) > position(unit)) {\n return [\n {\n file: unit.file,\n line,\n message: `\"${unit.name}\" reads ${name}.${key}, which is released after it`,\n hint:\n other.module === unit.module\n ? `${unit.name} and ${name} share ${unit.module}: give ${name} a module of its own, listed first`\n : `move ${other.module} before ${unit.module} in the modules of shiplane.config.ts`,\n },\n ];\n }\n return [];\n });\n\n/**\n * The release as written: what `shiplane.config.ts` composes, and one app per folder that holds a\n * `shiplane.unit.yml`, in release order. Every problem is collected, never thrown.\n */\nexport const loadRelease = async (root: string, options: LoadOptions): Promise<Release> => {\n const empty = (problems: ConfigProblem[]): Release => ({\n root,\n flow: unsetFlow(),\n tagFormat: DEFAULT_TAG_FORMAT,\n modules: [],\n features: [],\n units: [],\n problems,\n });\n const configFile = findConfig(root);\n if (!configFile) {\n return empty([\n {\n file: \"shiplane.config.ts\",\n message: \"No shiplane.config.ts in this repository\",\n hint: \"shiplane setup writes it, with a shiplane.unit.yml next to each app\",\n },\n ]);\n }\n let config: Composed;\n try {\n config = await readConfig(configFile, options.aliases ?? selfAliases());\n } catch (error) {\n const reason = reasonOf(error);\n return empty([\n { file: path.basename(configFile), message: `it did not load: ${reason.split(\"\\n\")[0]}` },\n ]);\n }\n const { manifests } = options;\n const problems: ConfigProblem[] = [];\n const features = config.features.map(({ name }) => name);\n const read: Read[] = expandPatterns(root, config.units ?? workspacePatterns(root)).flatMap(\n (dir) => {\n const relative = UNIT_FILES.map((name) => path.posix.join(dir, name)).find((file) =>\n fs.existsSync(path.join(root, file)),\n );\n if (!relative) return [];\n const result = readUnitFile(\n relative,\n fs.readFileSync(path.join(root, relative), \"utf8\"),\n config.modules,\n features,\n );\n problems.push(...result.problems);\n const manifest = manifests.read(root, dir);\n if (!manifest) {\n problems.push({\n file: relative,\n message: \"no package.json next to it to read its name and version\",\n });\n }\n if (!result.unit || !manifest) return [];\n const unit: ReleaseUnit = {\n name: dir === \".\" ? manifest.name.replace(/^@[^/]+\\//, \"\") : path.posix.basename(dir),\n dir,\n file: relative,\n packageName: manifest.name,\n version: manifest.version,\n module: result.unit.module,\n ...(result.unit.buildCommand ? { buildCommand: result.unit.buildCommand } : {}),\n ...(result.unit.checkEnvBeforeDeploy\n ? { checkEnvBeforeDeploy: result.unit.checkEnvBeforeDeploy }\n : {}),\n options: result.unit.options,\n after: [],\n };\n return [{ unit, file: result.unit }];\n },\n );\n\n const ordered = inReleaseOrder(read, config.modules);\n ordered.forEach((entry, index) => {\n const twin = ordered.findIndex(({ unit }) => unit.name === entry.unit.name);\n if (twin !== index) {\n problems.push({\n file: entry.unit.file,\n message: `two folders are both named \"${entry.unit.name}\"`,\n hint: `rename one of ${ordered[twin]?.unit.dir} and ${entry.unit.dir}`,\n });\n }\n problems.push(...referenceProblems(entry, ordered));\n entry.unit.after = [\n ...new Set(referencesIn(entry.unit.options).map(({ unit }) => unit)),\n ].filter((name) => name !== entry.unit.name && ordered.some(({ unit }) => unit.name === name));\n });\n\n if (ordered.length > 1 && !config.tagFormat.includes(\"{name}\")) {\n problems.push({\n file: path.basename(configFile),\n message: `tag \"${config.tagFormat}\" names no unit, so ${ordered.length} units would share each tag`,\n hint: 'add {name} to the format, such as \"{name}--v{version}\", or release one unit',\n });\n }\n\n return {\n root,\n flow: config.flow,\n modules: config.modules,\n features: config.features,\n ...(config.via ? { via: config.via } : {}),\n units: ordered.map(({ unit }) => unit),\n problems: sortProblems(problems),\n display: config.display,\n renames: [path.basename(configFile), ...ordered.map(({ unit }) => unit.file)].flatMap(\n (file) => renameOf(file) ?? [],\n ),\n tagFormat: config.tagFormat,\n ...(config.testComment === undefined ? {} : { testComment: config.testComment }),\n ...(config.testRelease === undefined ? {} : { testRelease: config.testRelease }),\n ...(config.prepare === undefined ? {} : { prepare: config.prepare }),\n };\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { PackageJsonSchema } from \"../application/manifest\";\n\nconst CORE = \"shiplane\";\n\nconst manifestAt = (dir: string) => {\n const manifest = path.join(dir, \"package.json\");\n if (!fs.existsSync(manifest)) return null;\n return PackageJsonSchema.safeParse(JSON.parse(fs.readFileSync(manifest, \"utf8\"))).data ?? null;\n};\n\n/** The shiplane package holding `from`: the nearest folder above it whose package.json is shiplane's. */\nexport const coreDir = (from: string): string => {\n let dir = from;\n while (manifestAt(dir)?.name !== CORE) {\n const parent = path.dirname(dir);\n if (parent === dir) throw new Error(`${CORE} not found above ${from}`);\n dir = parent;\n }\n return dir;\n};\n\n/** The version of the shiplane running, from its own package.json. */\nexport const installedVersion = (from = import.meta.dirname): string | undefined =>\n manifestAt(coreDir(from))?.version;\n","import fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { z } from \"zod\";\n\nimport type { AnyDeliveryAdapter } from \"../modules/suggest\";\nimport { shellServerHosting } from \"../adapters/server-hosting/shell-server-hosting.adapter\";\nimport { isRecord } from \"../application/config/values\";\nimport { PackageJsonSchema } from \"../application/manifest\";\n\n/** A plugin's own word on what setup may offer: `\"shiplane\": { \"adapters\": [\"flyServerHosting\"] }`. */\nconst PluginManifestSchema = z.object({\n shiplane: z.object({ adapters: z.array(z.string()).optional() }).optional(),\n});\n\nconst readJson = (file: string): unknown => JSON.parse(fs.readFileSync(file, \"utf8\"));\n\n/**\n * The delivery adapters setup can offer: the built-in shell adapter, then each one a plugin this\n * repository depends on names in its package.json. A plugin that does not load is skipped.\n */\nexport const installedAdapters = async (root: string): Promise<AnyDeliveryAdapter[]> => {\n const manifestFile = path.join(root, \"package.json\");\n if (!fs.existsSync(manifestFile)) return [shellServerHosting()];\n const manifest = PackageJsonSchema.safeParse(readJson(manifestFile)).data;\n const names = Object.keys({ ...manifest?.dependencies, ...manifest?.devDependencies });\n const require = createRequire(manifestFile);\n const found = await Promise.all(\n names.map(async (name): Promise<AnyDeliveryAdapter[]> => {\n try {\n const own = PluginManifestSchema.safeParse(\n readJson(require.resolve(`${name}/package.json`)),\n );\n const factories = own.data?.shiplane?.adapters ?? [];\n if (factories.length === 0) return [];\n const loaded: unknown = await import(pathToFileURL(require.resolve(name)).href);\n if (!isRecord(loaded)) return [];\n return factories.flatMap((factory) => {\n const make = loaded[factory];\n return typeof make === \"function\" ? [make() as AnyDeliveryAdapter] : [];\n });\n } catch {\n return [];\n }\n }),\n );\n return [...found.flat(), shellServerHosting()];\n};\n","import type { LoadOptions, Release } from \"../application/config/loadRelease\";\nimport type { ReleaseContext, Services } from \"../application/context\";\nimport type { SetupContext } from \"../application/setupContext\";\nimport type { DisplayChoice } from \"../domain/display\";\nimport type { Open } from \"../modules/module\";\nimport type { Shell } from \"../ports/shell.port\";\nimport type { Output, Progress, Prompter } from \"../ports/terminal.port\";\nimport { nodeFiles } from \"../adapters/files/node-files.adapter\";\nimport { packageJsonManifest } from \"../adapters/manifest/package-json-manifest.adapter\";\nimport { systemShell } from \"../adapters/shell/system-shell.adapter\";\nimport { terminalProgress } from \"../adapters/terminal/terminal-progress.adapter\";\nimport {\n onGitHubActions,\n systemClock,\n terminalOutput,\n terminalPrompter,\n} from \"../adapters/terminal/terminal.adapter\";\nimport { loadRelease } from \"../application/config/loadRelease\";\nimport { resolveDisplay } from \"../domain/display\";\nimport { installedVersion } from \"./installed\";\nimport { installedAdapters } from \"./plugins\";\n\n/** The release as written on disk, each unit's name and version read from its package.json. */\nexport const loadReleaseOnDisk = (root: string, options: Partial<LoadOptions> = {}) =>\n loadRelease(root, { ...options, manifests: options.manifests ?? packageJsonManifest });\n\n/** Creates each port the flow runs on, for this repository. */\nexport const composeServices = (release: Release, open: Open): Services => ({\n sourceControl: open(release.flow.sourceControl),\n codeHost: open(release.flow.codeHost),\n ciPipeline: open(release.flow.ciPipeline),\n versioning: open(release.flow.versioning),\n});\n\n/** Ports created on demand, in this repository, through this shell. */\nexport const opener =\n (root: string, shell: Shell): Open =>\n (adapter) =>\n adapter.create({ root, shell });\n\n/** What a run may take instead of this machine's: a scripted person, a recorded terminal or shell. */\nexport interface ContextIo {\n prompter?: Prompter;\n output?: Output;\n progress?: Progress;\n shell?: Shell;\n /** Where `shiplane` resolves from inside the config. */\n aliases?: Record<string, string>;\n /** What setup runs on instead of this machine's: files, adapters, the release loader. */\n setup?: Partial<SetupContext>;\n}\n\n/** A context wired to this machine: its shell, its terminal, its clock, unless `io` says otherwise. */\nexport const composeContext = (\n release: Release,\n { yes, display: flags }: { yes: boolean; display: DisplayChoice },\n io: ContextIo = {},\n): ReleaseContext => {\n const ci = onGitHubActions() || systemShell.env(\"CI\") === \"true\";\n const tty = Boolean(process.stdout.isTTY);\n const display = resolveDisplay(release.display ?? {}, flags, {\n tty,\n ci,\n noMotion: Boolean(systemShell.env(\"NO_MOTION\")),\n });\n const { shell = systemShell } = io;\n const output = io.output ?? terminalOutput;\n const open = opener(release.root, shell);\n return {\n release,\n load: () => loadReleaseOnDisk(release.root, { aliases: io.aliases }),\n services: composeServices(release, open),\n open,\n prompter: io.prompter ?? terminalPrompter(display),\n output,\n progress: io.progress ?? terminalProgress(display, tty && !ci),\n clock: systemClock,\n shell,\n files: nodeFiles(release.root),\n options: { yes, ci: onGitHubActions() },\n };\n};\n\n/** What setup, doctor and the rest need: the repository on disk and the adapters installed. */\nexport const composeSetup = async (\n root: string,\n io: Partial<SetupContext> = {},\n): Promise<SetupContext> => {\n const ci = onGitHubActions() || systemShell.env(\"CI\") === \"true\";\n const tty = Boolean(process.stdout.isTTY);\n const display = resolveDisplay(\n {},\n { mascot: false },\n {\n tty,\n ci,\n noMotion: Boolean(systemShell.env(\"NO_MOTION\")),\n },\n );\n return {\n root,\n files: nodeFiles(root),\n shell: systemShell,\n prompter: terminalPrompter(),\n output: terminalOutput,\n adapters: io.adapters ?? (await installedAdapters(root)),\n load: () => loadReleaseOnDisk(root),\n progress: terminalProgress(display, tty && !ci),\n compose: (release) => composeContext(release, { yes: true, display: { mascot: false } }),\n version: installedVersion(),\n ...io,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAMA,MAAa,aAAa,SAAwB;CAChD,MAAM,MAAM,SAAiB,KAAK,KAAK,MAAM,KAAK;AAClD,QAAO;EACL,SAAS,SAAS,GAAG,WAAW,GAAG,KAAK,CAAC;EACzC,OAAO,SAAU,GAAG,WAAW,GAAG,KAAK,CAAC,GAAG,GAAG,aAAa,GAAG,KAAK,EAAE,OAAO,GAAG;EAC/E,QAAQ,MAAM,SAAS;AACrB,MAAG,UAAU,KAAK,QAAQ,GAAG,KAAK,CAAC,EAAE,E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