@icebreakers/monorepo 5.8.1 → 5.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/{baseline-Cnw2O2JV.mjs → baseline-BlxungFN.mjs} +1 -1
  2. package/dist/{catalog-DWrBLClC.mjs → catalog-CQZ5CVOo.mjs} +3 -3
  3. package/dist/cli.mjs +377 -65
  4. package/dist/{commands-CayOzFY-.mjs → commands-B8PCzovx.mjs} +747 -126
  5. package/dist/{config-BfvlEAis.mjs → config-CSFv-i8P.mjs} +3 -3
  6. package/dist/{create-flow-CmbddTMr.mjs → create-flow-BCK_XMR0.mjs} +3 -3
  7. package/dist/{deps-C-9vium9.mjs → deps-DevSlsLS.mjs} +3 -3
  8. package/dist/{execute-DT-DjHFK.mjs → execute-Cv2NP1bu.mjs} +2 -2
  9. package/dist/{execute-NrC2ym6M.mjs → execute-kNjCRTO6.mjs} +2 -2
  10. package/dist/{format-4H_J7wGG.mjs → format-cnhwJird.mjs} +1 -1
  11. package/dist/{index-D61zjikU.d.mts → index-VZQIHM49.d.mts} +10 -1
  12. package/dist/index.d.mts +30 -3
  13. package/dist/index.mjs +9 -9
  14. package/dist/{inputs-hoTJICnb.mjs → inputs-B-Rksu2z.mjs} +1 -1
  15. package/dist/{npm-CjOsZ7tH.mjs → npm-Bpa3MkM-.mjs} +2 -2
  16. package/dist/{plan-BA_10vfL.mjs → plan-X3Duh8-J.mjs} +1 -1
  17. package/dist/{run-ohOkzTLN.mjs → run-DYYWhKQC.mjs} +4 -4
  18. package/dist/{save-HSOp4zHC.mjs → save-_0MWD4aR.mjs} +3 -3
  19. package/dist/{scan-gJt1WqW4.mjs → scan-Cp_-_wVJ.mjs} +7 -2
  20. package/dist/{template-drift-D8CpRENe.mjs → template-drift-DFlrYma0.mjs} +3 -3
  21. package/dist/tooling-entry.d.mts +1 -1
  22. package/dist/tooling-entry.mjs +2 -2
  23. package/dist/{transaction-CkjiAvNJ.mjs → transaction-Y0NQLCUf.mjs} +2 -2
  24. package/dist/{tsconfig-01vm_d3r.mjs → tsconfig--yFOJ-F0.mjs} +11 -4
  25. package/dist/{vitest-WPpMJqzw.mjs → vitest-WDIpuaQL.mjs} +1 -1
  26. package/dist/{workspace-tasks-BPSq4jjn.mjs → workspace-tasks-Cjlcu-SJ.mjs} +5 -5
  27. package/package.json +3 -5
@@ -1,19 +1,19 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
- import { A as referenceTarget, B as saveKnipBaseline, C as loadCompiler, D as ownershipFile, E as exists$1, Gt as getWorkspacePackages, Ht as clearWorkspaceCache, I as getKnipConfigurationSuggestions, J as getWorkspaceGraph, Jt as GitClient, K as mergeText, M as formatEnvironmentCache, O as readText, P as checkEnvironmentCache, R as planKnipCheck, S as configReader, St as localize, T as compare$1, Tt as resolveRepoctlLocale, Ut as getWorkspaceData, W as analyzeTurboRuns, Wt as getWorkspacePackageSummaries, Z as getWorkspaceImpact, _ as planTemplateLink, _t as assetsDir$1, at as record$3, b as planGenerate, c as loadTemplateInstanceRegistry$1, ct as renderCreateNewProject, dt as migrateLegacyToolingReferences, et as compareGraphValues, f as recoverTemplateUpgrade, ft as setByPath, g as applyTemplateLinkPlan, gt as validateCleanTargets, h as loadTemplateUpgradeJournal, ht as isWithin, it as readInput, j as relativeFile, jt as fs$2, k as referencePath, l as rebuildTemplateInstanceBaseline, lt as rewriteTemplateSnapshotReferences, m as planTemplateUpgrade, mt as assertSafePath, nt as workspaceDependencyTypes, o as listTemplateInstances, ot as safeFile, p as applyTemplateUpgradePlan, pt as stageFileTransaction, q as withOperationLock, qt as findWorkspacePackages, rt as hash$1, s as loadTemplateBaseline$1, tt as resolveWorkspaceGraphNode, u as relocateTemplateInstance, w as validateGraph, x as generators, xt as templatesDir, y as applyGeneratePlan, yt as packageDir$1, z as runKnipCheck } from "./workspace-tasks-BPSq4jjn.mjs";
3
- import { a as resolveFullWorkspaceCheckPlan, c as verifyCommitMsg, d as runPnpmCommand, f as logger, i as getKnownRepoCheckCommands, l as verifyPreCommit, n as resolveAffectedCheckContext, o as resolveRecommendedCheckPlan, r as resolveAffectedCheckPlan, s as runRecommendedCheck, t as runCheckWithReport, u as verifyStagedTypecheck } from "./execute-NrC2ym6M.mjs";
4
- import { B as presetPackageName, C as checkedFile, E as relativeFile$1, F as normalizeTemplateSourceRequest, G as commandConfigDirectory, L as sourceRequestKey, O as package_default$1, P as normalizeTemplateRemoteSource, R as templateSourcePath, S as canonicalDirectory, T as readOptional$1, U as appendConfigPath, V as presetVersion, _ as listToolingCapabilities, b as presetRelativePath, d as loadMonorepoConfig, f as loadMonorepoConfigDetails, g as presetAssetTarget, j as ConfigValidationError, k as version$2, n as defineTsconfigConfig, p as resolveCommandConfig, u as getRepoctlConfigCandidates, v as installedPresetDirectory, w as hash$2, x as readPresetFile, y as parsePresetJson } from "./tsconfig-01vm_d3r.mjs";
5
- import { c as selectCommandOverrides, i as rangesOverlap, l as chinaMirrorsEnvs, r as parseSpecifier, s as resolveCommandValues } from "./scan-gJt1WqW4.mjs";
6
- import { A as record$4, C as baselineDirectory, D as parseBaseline, E as isRootAsset, F as toWorkspaceAssetPath, M as summarizeChecks, O as templatePackage, S as checkDependencyAdmission, T as encodeBaseline, a as applyDoctorSuppressions, b as parseWorkspaceLockfile, c as collectSelectedDoctorChecks, d as recommendedRepoScripts, f as inspectInstallSecurity, g as isLegacyReleaseWorkflow, h as supportedVersion, i as hasTemplateDriftIssues, j as getWorkspacePatterns, k as getAssetTargets, l as getDoctorRuleIds, m as settingState, o as validateDoctorSuppressions, p as readSecuritySources, r as formatTemplateDriftReport, s as validateDoctorConfiguration, t as checkTemplateDrift, u as selectDoctorRules, v as inspectPnpmRuntime, w as baselinePath, y as lockfileRecord } from "./template-drift-D8CpRENe.mjs";
7
- import { t as writeDependencyTransaction } from "./transaction-CkjiAvNJ.mjs";
8
- import { i as applyDependencyFixPlan, r as planDependencyFix, t as checkDependencies } from "./deps-C-9vium9.mjs";
9
- import { i as applyCatalogMigrationPlan, n as checkCatalogs, r as planCatalogMigration } from "./catalog-DWrBLClC.mjs";
2
+ import { A as referenceTarget, B as saveKnipBaseline, C as loadCompiler, D as ownershipFile, E as exists$1, Gt as getWorkspacePackages, Ht as clearWorkspaceCache, I as getKnipConfigurationSuggestions, J as getWorkspaceGraph, Jt as GitClient, K as mergeText, M as formatEnvironmentCache, O as readText, P as checkEnvironmentCache, R as planKnipCheck, S as configReader, St as localize, T as compare$1, Tt as resolveRepoctlLocale, Ut as getWorkspaceData, W as analyzeTurboRuns, Wt as getWorkspacePackageSummaries, Z as getWorkspaceImpact, _ as planTemplateLink, _t as assetsDir$1, at as record$3, b as planGenerate, c as loadTemplateInstanceRegistry$1, ct as renderCreateNewProject, dt as migrateLegacyToolingReferences, et as compareGraphValues, f as recoverTemplateUpgrade, ft as setByPath, g as applyTemplateLinkPlan, gt as validateCleanTargets, h as loadTemplateUpgradeJournal, ht as isWithin, it as readInput, j as relativeFile, jt as fs$2, k as referencePath, l as rebuildTemplateInstanceBaseline, lt as rewriteTemplateSnapshotReferences, m as planTemplateUpgrade, mt as assertSafePath, nt as workspaceDependencyTypes, o as listTemplateInstances, ot as safeFile, p as applyTemplateUpgradePlan, pt as stageFileTransaction, q as withOperationLock, qt as findWorkspacePackages, rt as hash$1, s as loadTemplateBaseline$1, tt as resolveWorkspaceGraphNode, u as relocateTemplateInstance, w as validateGraph, x as generators, xt as templatesDir, y as applyGeneratePlan, yt as packageDir$1, z as runKnipCheck } from "./workspace-tasks-Cjlcu-SJ.mjs";
3
+ import { a as resolveFullWorkspaceCheckPlan, c as verifyCommitMsg, d as runPnpmCommand, f as logger, i as getKnownRepoCheckCommands, l as verifyPreCommit, n as resolveAffectedCheckContext, o as resolveRecommendedCheckPlan, r as resolveAffectedCheckPlan, s as runRecommendedCheck, t as runCheckWithReport, u as verifyStagedTypecheck } from "./execute-kNjCRTO6.mjs";
4
+ import { B as presetPackageName, C as checkedFile, E as relativeFile$1, F as normalizeTemplateSourceRequest, G as commandConfigDirectory, L as sourceRequestKey, O as package_default$1, P as normalizeTemplateRemoteSource, R as templateSourcePath, S as canonicalDirectory, T as readOptional$1, U as appendConfigPath, V as presetVersion, _ as listToolingCapabilities, b as presetRelativePath, d as loadMonorepoConfig, f as loadMonorepoConfigDetails, g as presetAssetTarget, j as ConfigValidationError, k as version$2, n as defineTsconfigConfig, p as resolveCommandConfig, u as getRepoctlConfigCandidates, v as installedPresetDirectory, w as hash$2, x as readPresetFile, y as parsePresetJson } from "./tsconfig--yFOJ-F0.mjs";
5
+ import { c as selectCommandOverrides, i as rangesOverlap, l as chinaMirrorsEnvs, r as parseSpecifier, s as resolveCommandValues } from "./scan-Cp_-_wVJ.mjs";
6
+ import { A as record$4, C as baselineDirectory, D as parseBaseline, E as isRootAsset, F as toWorkspaceAssetPath, M as summarizeChecks, O as templatePackage, S as checkDependencyAdmission, T as encodeBaseline, a as applyDoctorSuppressions, b as parseWorkspaceLockfile, c as collectSelectedDoctorChecks, d as recommendedRepoScripts, f as inspectInstallSecurity, g as isLegacyReleaseWorkflow, h as supportedVersion, i as hasTemplateDriftIssues, j as getWorkspacePatterns, k as getAssetTargets, l as getDoctorRuleIds, m as settingState, o as validateDoctorSuppressions, p as readSecuritySources, r as formatTemplateDriftReport, s as validateDoctorConfiguration, t as checkTemplateDrift, u as selectDoctorRules, v as inspectPnpmRuntime, w as baselinePath, y as lockfileRecord } from "./template-drift-DFlrYma0.mjs";
7
+ import { t as writeDependencyTransaction } from "./transaction-Y0NQLCUf.mjs";
8
+ import { i as applyDependencyFixPlan, r as planDependencyFix, t as checkDependencies } from "./deps-DevSlsLS.mjs";
9
+ import { i as applyCatalogMigrationPlan, n as checkCatalogs, r as planCatalogMigration } from "./catalog-CQZ5CVOo.mjs";
10
10
  import { createRequire, isBuiltin } from "node:module";
11
11
  import { findWorkspaceDir } from "@pnpm/find-workspace-dir";
12
12
  import { readWorkspaceManifest } from "@pnpm/workspace.read-manifest";
13
13
  import path, { normalize } from "pathe";
14
14
  import process from "node:process";
15
- import { access, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, unlink, utimes, writeFile } from "node:fs/promises";
16
- import { execFile, execFileSync, spawnSync } from "node:child_process";
15
+ import { access, appendFile, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, unlink, utimes, writeFile } from "node:fs/promises";
16
+ import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
17
17
  import fs$1, { constants, createReadStream, existsSync } from "node:fs";
18
18
  import semver, { coerce, compare, gt, gte, lte, minVersion, parse, satisfies, subset, valid, validRange } from "semver";
19
19
  import validatePackageName from "validate-npm-package-name";
@@ -33,6 +33,8 @@ import { glob } from "tinyglobby";
33
33
  import * as JSONC from "comment-json";
34
34
  import { parse as parse$2, stringify as stringify$1 } from "comment-json";
35
35
  import { performance } from "node:perf_hooks";
36
+ import Config from "@npmcli/config";
37
+ import definitionsModule from "@npmcli/config/lib/definitions/index.js";
36
38
  import micromatch from "micromatch";
37
39
  import { build } from "esbuild";
38
40
  //#region src/commands/ai.ts
@@ -1458,7 +1460,7 @@ async function downloadGitTemplate(source, directory, timeout) {
1458
1460
  async function resolveRemoteTemplateSource(source, templatePath = ".", options = {}) {
1459
1461
  const request = normalizeTemplateSourceRequest(source, templatePath);
1460
1462
  const cwd = path$1.resolve(options.cwd ?? process.cwd());
1461
- const npm = request.source.kind === "npm" ? await import("./npm-CjOsZ7tH.mjs") : void 0;
1463
+ const npm = request.source.kind === "npm" ? await import("./npm-Bpa3MkM-.mjs") : void 0;
1462
1464
  const configuration = request.source.kind === "npm" ? await npm.npmTemplateConfiguration(request.source, cwd) : void 0;
1463
1465
  if (request.source.kind === "npm") request.source.registry = configuration.registry;
1464
1466
  const cacheDir = path$1.resolve(cwd, options.cacheDir ?? path$1.join(process.env["XDG_CACHE_HOME"] ?? path$1.join(homedir(), ".cache"), "repoctl", "template-sources-v1"));
@@ -3692,7 +3694,9 @@ var package_default = {
3692
3694
  "postinstall": "pnpm run build",
3693
3695
  "commit": "commit",
3694
3696
  "commitlint": "commitlint --edit",
3695
- "sync": "turbo run sync",
3697
+ "sync": "pnpm sync:npmmirror",
3698
+ "sync:npmmirror": "repo release sync-npmmirror --all",
3699
+ "release:sync-npmmirror": "repo release sync-npmmirror --published",
3696
3700
  "inspector": "npx @eslint/config-inspector",
3697
3701
  "build:inspector": "pnpm build && npx @eslint/config-inspector build",
3698
3702
  "-------": "---------------",
@@ -4779,6 +4783,18 @@ function buildGitHubReleaseBodyFromChangelog(packageName, packageVersion, change
4779
4783
  }], metadata), metadata);
4780
4784
  }
4781
4785
  //#endregion
4786
+ //#region src/commands/release/stages/verification.ts
4787
+ const verified = Symbol("repoctl verified stage");
4788
+ function authorizeVerification(options) {
4789
+ return {
4790
+ ...options,
4791
+ [verified]: true
4792
+ };
4793
+ }
4794
+ function hasVerification(options) {
4795
+ return options[verified] === true;
4796
+ }
4797
+ //#endregion
4782
4798
  //#region src/commands/release/workspace-protocol.ts
4783
4799
  const EXPECTED_WORKSPACE_SPEC = "workspace:*";
4784
4800
  const DEPENDENCY_SECTIONS = [
@@ -4848,6 +4864,7 @@ function verificationEnvironment(options) {
4848
4864
  return env;
4849
4865
  }
4850
4866
  async function runQualityScripts(options) {
4867
+ if (hasVerification(options)) return;
4851
4868
  await assertWorkspaceDependencyProtocols(options.cwd);
4852
4869
  const config = resolveCommandValues("release", options.config).values;
4853
4870
  const verificationOptions = {
@@ -4858,6 +4875,7 @@ async function runQualityScripts(options) {
4858
4875
  runScripts(config.hooks?.verify ?? [], verificationOptions);
4859
4876
  }
4860
4877
  function runReleaseHooks(phase, options) {
4878
+ if (phase === "beforeVersion" && hasVerification(options)) return;
4861
4879
  runScripts(options.config?.hooks?.[phase] ?? [], options);
4862
4880
  }
4863
4881
  function runAfterPublishHooks(packages, options) {
@@ -5536,74 +5554,282 @@ var PublishState = class {
5536
5554
  }
5537
5555
  };
5538
5556
  //#endregion
5539
- //#region src/commands/release/publish/registry.ts
5540
- const visibilityBudget = 9e5;
5541
- const refreshBudget = 3e5;
5542
- const pollInterval = 1e4;
5543
- const progressInterval = 6e4;
5557
+ //#region src/commands/release/registry/cli.ts
5558
+ async function queryNpm(args, timeout, options) {
5559
+ const settings = {
5560
+ cwd: options.cwd,
5561
+ env: getReleaseEnv(options),
5562
+ encoding: "utf8",
5563
+ shell: false,
5564
+ timeout,
5565
+ killSignal: "SIGKILL",
5566
+ stdio: [
5567
+ "ignore",
5568
+ "pipe",
5569
+ "pipe"
5570
+ ]
5571
+ };
5572
+ if (options.spawn) return options.spawn("npm", args, settings);
5573
+ return new Promise((resolve) => {
5574
+ const child = spawn("npm", args, settings);
5575
+ let stdout = "";
5576
+ let stderr = "";
5577
+ let error;
5578
+ child.on("error", (value) => {
5579
+ error = value;
5580
+ });
5581
+ child.stdout.on("data", (value) => {
5582
+ stdout += String(value);
5583
+ });
5584
+ child.stderr.on("data", (value) => {
5585
+ stderr += String(value);
5586
+ });
5587
+ child.on("close", (status) => resolve({
5588
+ status,
5589
+ stdout,
5590
+ stderr,
5591
+ ...error ? { error } : {}
5592
+ }));
5593
+ });
5594
+ }
5595
+ //#endregion
5596
+ //#region src/commands/release/registry/configuration.ts
5597
+ const require = createRequire(import.meta.url);
5598
+ async function registryConfiguration(options) {
5599
+ const config = new Config({
5600
+ ...definitionsModule,
5601
+ npmPath: path.dirname(require.resolve("@npmcli/config/package.json")),
5602
+ argv: [],
5603
+ cwd: options.cwd,
5604
+ env: getReleaseEnv(options)
5605
+ });
5606
+ await config.load();
5607
+ const access = new Map(await Promise.all((await getWorkspacePackages(options.cwd)).map(async (pkg) => {
5608
+ const manifest = JSON.parse(await readFile(pkg.pkgJsonPath, "utf8"));
5609
+ return [pkg.manifest.name, manifest.publishConfig?.access];
5610
+ })));
5611
+ return (name) => {
5612
+ const scope = name.startsWith("@") ? name.split("/")[0] : void 0;
5613
+ const registry = String((scope ? config.flat[`${scope}:registry`] : void 0) ?? config.flat["registry"]);
5614
+ const authenticated = Object.entries(config.flat).some(([key, value]) => /(?:^|:)(?:_authToken|_auth|_password|username|certfile|keyfile)$/.test(key) && Boolean(value));
5615
+ const configuredTransport = [
5616
+ "proxy",
5617
+ "httpsProxy",
5618
+ "ca",
5619
+ "cert",
5620
+ "key",
5621
+ "localAddress"
5622
+ ].some((key) => Boolean(config.flat[key])) || config.flat["strictSSL"] === false;
5623
+ return registry.replace(/\/$/, "") === "https://registry.npmjs.org" && access.get(name) !== "restricted" && !configuredTransport && !authenticated;
5624
+ };
5625
+ }
5626
+ //#endregion
5627
+ //#region src/commands/release/registry/settings.ts
5628
+ function registrySettings(options) {
5629
+ const config = resolveCommandValues("release", options.config).values.registry;
5630
+ return {
5631
+ concurrency: config.concurrency,
5632
+ requestTimeoutMs: config.requestTimeoutMs,
5633
+ visibilityTimeoutMs: config.visibilityTimeoutMs
5634
+ };
5635
+ }
5636
+ /** All workers and their retries consume the same deadline. */
5637
+ async function mapConcurrent(items, concurrency, task) {
5638
+ const results = [];
5639
+ let next = 0;
5640
+ let failure;
5641
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => {
5642
+ while (next < items.length && !failure) {
5643
+ const index = next++;
5644
+ try {
5645
+ results[index] = await task(items[index]);
5646
+ } catch (error) {
5647
+ failure = error;
5648
+ }
5649
+ }
5650
+ }));
5651
+ if (failure) throw failure;
5652
+ return results;
5653
+ }
5654
+ //#endregion
5655
+ //#region src/commands/release/registry/index.ts
5544
5656
  function sleep(milliseconds, options) {
5545
5657
  return options.sleep?.(milliseconds) ?? new Promise((resolve) => setTimeout(resolve, milliseconds));
5546
5658
  }
5547
- async function refreshRegistry(state, options, packages = state.candidates, deadline = performance.now() + refreshBudget) {
5548
- const unknown = [];
5549
- const pending = state.unconfirmed(packages);
5550
- for (const [index, pkg] of pending.entries()) {
5551
- const remaining = Math.floor(deadline - performance.now());
5552
- if (remaining <= 0) {
5553
- unknown.push(...pending.slice(index));
5554
- break;
5555
- }
5556
- const result = (options.spawn ?? spawnSync)("npm", [
5557
- "view",
5558
- packageKey(pkg),
5559
- "version"
5560
- ], {
5561
- cwd: options.cwd,
5562
- encoding: "utf8",
5563
- env: getReleaseEnv(options),
5564
- shell: false,
5565
- stdio: [
5566
- "ignore",
5567
- "pipe",
5568
- "pipe"
5569
- ],
5570
- timeout: Math.min(1e4, remaining),
5571
- killSignal: "SIGKILL"
5572
- });
5573
- if (result.status === 0 && outputText(result.stdout).trim() === pkg.version) {
5574
- state.confirm(pkg);
5575
- await state.save(options.cwd, "confirming");
5576
- } else if (result.error || result.status === 0 || !/\bE404\b/.test(outputText(result.stderr))) unknown.push(pkg);
5659
+ var RetryableQuery = class extends Error {};
5660
+ const clients = /* @__PURE__ */ new WeakMap();
5661
+ function registryClient(options) {
5662
+ let client = clients.get(options);
5663
+ if (!client) {
5664
+ client = new RegistryClient(options);
5665
+ clients.set(options, client);
5666
+ }
5667
+ return client;
5668
+ }
5669
+ var RegistryClient = class {
5670
+ options;
5671
+ versions = /* @__PURE__ */ new Map();
5672
+ configuration;
5673
+ constructor(options) {
5674
+ this.options = options;
5675
+ }
5676
+ async publicHttp(name) {
5677
+ if (this.options.spawn && !this.options.registryFetch) return false;
5678
+ this.configuration ??= registryConfiguration(this.options);
5679
+ return (await this.configuration)(name);
5680
+ }
5681
+ async http(url, timeout) {
5682
+ const controller = new AbortController();
5683
+ const timer = setTimeout(() => controller.abort(), timeout);
5684
+ try {
5685
+ const response = await (this.options.registryFetch ?? globalThis.fetch)(url, {
5686
+ signal: controller.signal,
5687
+ redirect: "error",
5688
+ headers: {
5689
+ "accept": "application/json",
5690
+ "cache-control": "no-cache"
5691
+ }
5692
+ });
5693
+ if (response.status === 404) {
5694
+ await response.body?.cancel();
5695
+ return;
5696
+ }
5697
+ if (!response.ok) {
5698
+ await response.body?.cancel();
5699
+ if ([401, 403].includes(response.status)) throw new ReleaseCommandError(`npm authentication failed (HTTP ${response.status}); check registry permissions`);
5700
+ if (response.status === 429 || response.status >= 500) throw new RetryableQuery(`HTTP ${response.status}`);
5701
+ throw new ReleaseCommandError(`npm registry query failed (HTTP ${response.status}); registry state is unknown`);
5702
+ }
5703
+ return await response.json();
5704
+ } catch (error) {
5705
+ if (error instanceof ReleaseCommandError || error instanceof RetryableQuery) throw error;
5706
+ throw new RetryableQuery(controller.signal.aborted ? `request timed out after ${timeout}ms` : error instanceof Error ? error.name : "network error");
5707
+ } finally {
5708
+ clearTimeout(timer);
5709
+ }
5710
+ }
5711
+ async inspect(pkg, deadline, fields = "metadata") {
5712
+ const settings = registrySettings(this.options);
5713
+ const http = await this.publicHttp(pkg.name);
5714
+ let reason = "request deadline exhausted";
5715
+ for (let attempt = 0; attempt < 3; attempt++) {
5716
+ const timeout = Math.floor(Math.min(settings.requestTimeoutMs, deadline - performance.now()));
5717
+ if (timeout <= 0) break;
5718
+ try {
5719
+ let data;
5720
+ if (http) {
5721
+ const name = encodeURIComponent(pkg.name);
5722
+ data = this.versions.get(packageKey(pkg)) ?? await this.http(`https://registry.npmjs.org/${name}/${encodeURIComponent(pkg.version)}`, timeout);
5723
+ if (data === void 0) return;
5724
+ if (!data || typeof data !== "object" || data.version !== pkg.version) throw new ReleaseCommandError(`npm returned invalid metadata for ${packageKey(pkg)}; registry state is unknown`);
5725
+ this.versions.set(packageKey(pkg), data);
5726
+ if (fields === "metadata") {
5727
+ const remaining = Math.floor(Math.min(settings.requestTimeoutMs, deadline - performance.now()));
5728
+ if (remaining <= 0) throw new RetryableQuery("dist-tag request deadline exhausted");
5729
+ const tags = await this.http(`https://registry.npmjs.org/-/package/${name}/dist-tags`, remaining);
5730
+ data = {
5731
+ ...data,
5732
+ "dist-tags": tags ?? {}
5733
+ };
5734
+ }
5735
+ } else {
5736
+ const result = await queryNpm([
5737
+ "view",
5738
+ packageKey(pkg),
5739
+ ...fields === "version" ? ["version"] : ["--json"]
5740
+ ], timeout, this.options);
5741
+ const output = `${String(result.stdout ?? "")}\n${String(result.stderr ?? "")}`;
5742
+ if (result.status !== 0) {
5743
+ if (!result.error && /\bE404\b/.test(output)) return;
5744
+ if (/\b(?:E401|E403|ENEEDAUTH)\b/.test(output)) throw new ReleaseCommandError(`npm authentication failed for ${packageKey(pkg)}`);
5745
+ throw new RetryableQuery(result.error?.name ?? output.match(/\b(?:E[A-Z]+|429|5\d\d)\b/)?.[0] ?? "npm query failed");
5746
+ }
5747
+ data = fields === "version" ? { version: String(result.stdout).trim() } : JSON.parse(String(result.stdout));
5748
+ }
5749
+ if (!data || typeof data !== "object" || data.version !== pkg.version) throw new ReleaseCommandError(`npm returned invalid metadata for ${packageKey(pkg)}; registry state is unknown`);
5750
+ return data;
5751
+ } catch (error) {
5752
+ if (!(error instanceof RetryableQuery)) throw error;
5753
+ reason = error.message;
5754
+ logger.warn(`Registry query ${packageKey(pkg)}: ${reason} (attempt ${attempt + 1}/3)`);
5755
+ const delay = Math.min(1e3 * 2 ** attempt, Math.max(0, deadline - performance.now()));
5756
+ if (attempt < 2 && delay) {
5757
+ await sleep(delay, this.options);
5758
+ if (this.options.sleep) deadline -= delay;
5759
+ }
5760
+ }
5761
+ }
5762
+ throw new ReleaseCommandError(`npm registry state is unknown for ${packageKey(pkg)} after bounded retries; no upload attempted (${reason})`);
5577
5763
  }
5764
+ };
5765
+ //#endregion
5766
+ //#region src/commands/release/publish/registry.ts
5767
+ async function refreshRegistry(state, options, packages = state.candidates, deadline = performance.now() + registrySettings(options).visibilityTimeoutMs) {
5768
+ const unknown = [];
5769
+ const client = registryClient(options);
5770
+ await mapConcurrent(state.unconfirmed(packages), registrySettings(options).concurrency, async (pkg) => {
5771
+ try {
5772
+ if (await client.inspect(pkg, deadline, "version")) state.confirm(pkg);
5773
+ } catch (error) {
5774
+ if (error instanceof ReleaseCommandError && error.message.includes("authentication failed")) throw error;
5775
+ unknown.push(pkg);
5776
+ logger.warn(error instanceof Error ? error.message : String(error));
5777
+ }
5778
+ });
5779
+ await state.save(options.cwd, "confirming");
5578
5780
  return unknown;
5579
5781
  }
5580
- async function confirmVisibility(state, options, packages, initialDelay = 0) {
5581
- let remaining = visibilityBudget;
5782
+ async function confirmVisibility(state, options, packages, initialDelay = 0, distTag) {
5783
+ const settings = registrySettings(options);
5784
+ const budget = settings.visibilityTimeoutMs;
5785
+ const started = performance.now();
5786
+ let virtualWait = 0;
5787
+ const elapsed = () => performance.now() - started + virtualWait;
5788
+ const tagged = /* @__PURE__ */ new Set();
5789
+ const pending = () => distTag ? packages.filter((pkg) => !tagged.has(packageKey(pkg))) : state.unconfirmed(packages);
5582
5790
  let delay = initialDelay;
5583
5791
  let lastProgress = 0;
5584
- let pendingVersions = state.unconfirmed(packages).map(packageKey).join(", ");
5585
- if (pendingVersions && !options.quiet) logger.info(`Waiting up to ${visibilityBudget / 6e4} minutes for npm registry visibility; pending versions: ${pendingVersions}`);
5586
- while (state.unconfirmed(packages).length && remaining > 0) {
5587
- const started = performance.now();
5588
- const wait = Math.min(delay, remaining);
5589
- if (wait) await sleep(wait, options);
5590
- remaining -= Math.max(wait, performance.now() - started);
5591
- const queryStarted = performance.now();
5592
- await refreshRegistry(state, options, packages, queryStarted + remaining);
5593
- await state.save(options.cwd, "confirming");
5594
- remaining -= performance.now() - queryStarted;
5595
- const elapsed = visibilityBudget - remaining;
5596
- const nextPendingVersions = state.unconfirmed(packages).map(packageKey).join(", ");
5597
- if (nextPendingVersions && remaining > 0 && !options.quiet && (nextPendingVersions !== pendingVersions || elapsed - lastProgress >= progressInterval)) {
5598
- logger.info(`Waiting for npm registry visibility (${Math.floor(elapsed / 1e3)}s/${visibilityBudget / 1e3}s); pending versions: ${nextPendingVersions}`);
5599
- lastProgress = elapsed;
5600
- }
5601
- pendingVersions = nextPendingVersions;
5602
- delay = pollInterval;
5603
- }
5604
- const pending = state.unconfirmed(packages);
5605
- if (pending.length) throw new ReleaseCommandError(`npm registry visibility confirmation timed out after ${visibilityBudget / 6e4} minutes; pending versions: ${pending.map(packageKey).join(", ")}. Upload evidence is preserved in repoctl-publish-progress.json; resume confirmation without re-uploading accepted versions.`);
5606
- if (packages.length && !options.quiet) logger.info("npm registry visibility confirmed for all requested versions.");
5792
+ let pendingVersions = pending().map(packageKey).join(", ");
5793
+ if (pendingVersions && !options.quiet) logger.info(`Waiting up to ${budget / 6e4} minutes for npm registry visibility${distTag ? ` and dist-tag ${distTag}` : ""}; pending versions: ${pendingVersions}`);
5794
+ try {
5795
+ while (pending().length && elapsed() < budget) {
5796
+ const wait = Math.min(delay, budget - elapsed());
5797
+ if (wait) {
5798
+ const before = performance.now();
5799
+ await sleep(wait, options);
5800
+ virtualWait += Math.max(0, wait - (performance.now() - before));
5801
+ }
5802
+ if (elapsed() >= budget) break;
5803
+ const deadline = performance.now() + Math.max(0, budget - elapsed());
5804
+ if (distTag) await mapConcurrent(pending(), settings.concurrency, async (pkg) => {
5805
+ const remote = await registryClient(options).inspect(pkg, deadline);
5806
+ if (remote) {
5807
+ state.accept([pkg]);
5808
+ if (remote["dist-tags"]?.[distTag] === pkg.version) {
5809
+ state.confirm(pkg);
5810
+ tagged.add(packageKey(pkg));
5811
+ }
5812
+ }
5813
+ });
5814
+ else {
5815
+ const unknown = await refreshRegistry(state, options, packages, deadline);
5816
+ if (unknown.length && elapsed() < budget) throw new ReleaseCommandError(`npm registry state is unknown after bounded retries: ${unknown.map(packageKey).join(", ")}; upload evidence preserved`);
5817
+ }
5818
+ await state.save(options.cwd, "confirming");
5819
+ const next = pending().map(packageKey).join(", ");
5820
+ if (next && elapsed() < budget && !options.quiet && (next !== pendingVersions || elapsed() - lastProgress >= 6e4)) {
5821
+ logger.info(`Waiting for npm registry visibility (${Math.floor(elapsed() / 1e3)}s/${budget / 1e3}s); pending versions: ${next}`);
5822
+ lastProgress = elapsed();
5823
+ }
5824
+ pendingVersions = next;
5825
+ delay = elapsed() < 3e4 ? 2e3 : elapsed() < 12e4 ? 5e3 : 1e4;
5826
+ }
5827
+ if (pending().length) throw new ReleaseCommandError(`npm registry visibility confirmation timed out after ${budget / 6e4} minutes; pending versions: ${pending().map(packageKey).join(", ")}${distTag ? ` (including dist-tag ${distTag})` : ""}. Upload evidence is preserved in repoctl-publish-progress.json; resume confirmation without re-uploading accepted versions.`);
5828
+ if (packages.length && !options.quiet) logger.info("npm registry visibility confirmed for all requested versions.");
5829
+ } catch (error) {
5830
+ await state.save(options.cwd, "failed");
5831
+ throw error;
5832
+ }
5607
5833
  }
5608
5834
  //#endregion
5609
5835
  //#region src/commands/release/publish/index.ts
@@ -5632,16 +5858,16 @@ async function publishWithRetry(args, options, candidates, confirmAll = false, r
5632
5858
  state.accept(await readPublishSummary(options.cwd));
5633
5859
  await state.save(options.cwd, "publishing");
5634
5860
  if (result.status === 0) {
5635
- await confirmVisibility(state, options, recovering ? candidates : state.acceptedPackages);
5636
- await state.save(options.cwd, "complete");
5861
+ if (!options.deferConfirmation) await confirmVisibility(state, options, recovering ? candidates : state.acceptedPackages);
5862
+ await state.save(options.cwd, options.deferConfirmation ? "confirming" : "complete");
5637
5863
  return;
5638
5864
  }
5639
5865
  recovering = true;
5640
- await refreshRegistry(state, options);
5641
- await state.save(options.cwd, "publishing");
5642
5866
  const transient = isTransientPublishFailure(result.output);
5643
5867
  const conflict = isPublishConflict(result.output);
5644
5868
  if (!transient && !conflict) throw new ReleaseCommandError(`command failed: pnpm ${args.join(" ")}`, result.status ?? 1);
5869
+ await refreshRegistry(state, options);
5870
+ await state.save(options.cwd, "publishing");
5645
5871
  if (!state.pendingUploads.length || conflict && !transient) {
5646
5872
  await confirmVisibility(state, options, candidates, state.unconfirmed(candidates).length ? 2e4 : 0);
5647
5873
  await state.save(options.cwd, "complete");
@@ -5778,44 +6004,14 @@ function releaseStateKey(repository, distTag, candidates) {
5778
6004
  }
5779
6005
  //#endregion
5780
6006
  //#region src/commands/release/lifecycle/registry.ts
5781
- /** 明确的 E404 才代表不存在;其余失败不能作为重新上传的依据。 */
5782
- async function inspectRegistry(pkg, options) {
5783
- for (let attempt = 0; attempt < 3; attempt++) {
5784
- const result = (options.spawn ?? spawnSync)("npm", [
5785
- "view",
5786
- packageKey(pkg),
5787
- "--json"
5788
- ], {
5789
- cwd: options.cwd,
5790
- env: getReleaseEnv(options),
5791
- encoding: "utf8",
5792
- shell: false,
5793
- stdio: [
5794
- "ignore",
5795
- "pipe",
5796
- "pipe"
5797
- ],
5798
- timeout: 1e4,
5799
- killSignal: "SIGKILL"
5800
- });
5801
- const output = `${String(result.stdout ?? "")}
5802
- ${String(result.stderr ?? "")}`;
5803
- if (result.status === 0) {
5804
- try {
5805
- const data = JSON.parse(String(result.stdout));
5806
- if (data.version === pkg.version) return data;
5807
- } catch {}
5808
- throw new ReleaseCommandError(`npm returned invalid metadata for ${packageKey(pkg)}; registry state is unknown`);
5809
- }
5810
- if (/\bE404\b/.test(output) && !result.error) return;
5811
- if (/\b(?:E401|E403|ENEEDAUTH)\b/.test(output)) throw new ReleaseCommandError(`npm authentication failed for ${packageKey(pkg)}`);
5812
- if (attempt < 2) await sleep(1e3 * 2 ** attempt, options);
5813
- }
5814
- throw new ReleaseCommandError(`npm registry state is unknown for ${packageKey(pkg)} after bounded retries; no upload attempted`);
6007
+ /** Only an explicit 404 proves absence; unknown state must never cause an upload. */
6008
+ function inspectRegistry(pkg, options, deadline) {
6009
+ const settings = registrySettings(options);
6010
+ return registryClient(options).inspect(pkg, deadline ?? performance.now() + Math.min(settings.visibilityTimeoutMs, settings.requestTimeoutMs * 6 + 3e3));
5815
6011
  }
5816
6012
  //#endregion
5817
- //#region src/commands/release/lifecycle/index.ts
5818
- async function publishLifecycle(options, selected, distTag = "latest") {
6013
+ //#region src/commands/release/lifecycle/session.ts
6014
+ async function openLifecycle(options, selected, distTag = "latest") {
5819
6015
  const github = resolveGitHub(options);
5820
6016
  if (!github.readReleaseState || !github.writeReleaseState || !github.ensureTag || !github.listReleases) throw new ReleaseCommandError("Release recovery requires checkpoint, tag and release query operations");
5821
6017
  const env = getReleaseEnv(options);
@@ -5832,7 +6028,11 @@ async function publishLifecycle(options, selected, distTag = "latest") {
5832
6028
  let revision = snapshot?.revision;
5833
6029
  const releases = new Map((await github.listReleases()).map((release) => [release.tag_name, release]));
5834
6030
  const registry = /* @__PURE__ */ new Map();
5835
- for (const pkg of candidates) registry.set(packageKey(pkg), await inspectRegistry(pkg, options));
6031
+ const settings = registrySettings(options);
6032
+ const deadline = performance.now() + Math.min(settings.visibilityTimeoutMs, settings.requestTimeoutMs * 6 + 3e3);
6033
+ await mapConcurrent(candidates, settings.concurrency, async (pkg) => {
6034
+ registry.set(packageKey(pkg), await inspectRegistry(pkg, options, deadline));
6035
+ });
5836
6036
  const tags = /* @__PURE__ */ new Map();
5837
6037
  if (github.readTagTarget) for (const pkg of candidates) tags.set(packageKey(pkg), await github.readTagTarget(packageKey(pkg)));
5838
6038
  let state;
@@ -5869,7 +6069,7 @@ async function publishLifecycle(options, selected, distTag = "latest") {
5869
6069
  }
5870
6070
  if (!packages.length) {
5871
6071
  logger.info("No unfinished release targets found.");
5872
- return [];
6072
+ return;
5873
6073
  }
5874
6074
  const legacy = packages.some((pkg) => registry.has(packageKey(pkg)) && registry.get(packageKey(pkg)));
5875
6075
  state = {
@@ -5904,10 +6104,10 @@ async function publishLifecycle(options, selected, distTag = "latest") {
5904
6104
  metadata: state.packages.filter((pkg) => !releases.has(packageKey(pkg))).map(packageKey),
5905
6105
  hooks: state.hooks
5906
6106
  }, null, 2));
5907
- return state.packages.map(({ name, version }) => ({
6107
+ return { preview: state.packages.map(({ name, version }) => ({
5908
6108
  name,
5909
6109
  version
5910
- }));
6110
+ })) };
5911
6111
  }
5912
6112
  state.writer = randomUUID();
5913
6113
  state.complete = false;
@@ -5920,12 +6120,26 @@ async function publishLifecycle(options, selected, distTag = "latest") {
5920
6120
  name,
5921
6121
  version
5922
6122
  }));
6123
+ return {
6124
+ github,
6125
+ env,
6126
+ rule,
6127
+ state,
6128
+ save,
6129
+ packages,
6130
+ registry,
6131
+ releases
6132
+ };
6133
+ }
6134
+ //#endregion
6135
+ //#region src/commands/release/lifecycle/index.ts
6136
+ async function upload(session, options, distTag) {
6137
+ const { state, save, packages, registry, rule } = session;
5923
6138
  const confirmed = new PublishState(packages);
5924
6139
  confirmed.accept(state.accepted);
5925
6140
  for (const pkg of packages) if (registry.get(packageKey(pkg))) confirmed.confirm(pkg);
5926
- if (state.npm === "running") await confirmVisibility(confirmed, options, packages);
5927
- else if (confirmed.unconfirmed(state.accepted).length) await confirmVisibility(confirmed, options, state.accepted);
5928
- const missing = packages.filter((pkg) => !confirmed.acceptedPackages.some((item) => packageKey(item) === packageKey(pkg)));
6141
+ if (state.npm === "running" && (!state.uploadComplete || packages.some((pkg) => !state.accepted.some((accepted) => packageKey(accepted) === packageKey(pkg))))) await confirmVisibility(confirmed, options, packages);
6142
+ const missing = confirmed.pendingUploads;
5929
6143
  if (missing.length) {
5930
6144
  runReleaseHooks("beforePublish", options);
5931
6145
  const actual = await getPublishCandidates(options.cwd);
@@ -5933,7 +6147,7 @@ async function publishLifecycle(options, selected, distTag = "latest") {
5933
6147
  if (rule) assertReleaseLineVersions(rule, actual);
5934
6148
  await clearPublishSummary(options.cwd);
5935
6149
  state.npm = "running";
5936
- state.complete = false;
6150
+ state.uploadComplete = false;
5937
6151
  await save();
5938
6152
  try {
5939
6153
  await publishWithRetry([
@@ -5945,7 +6159,10 @@ async function publishLifecycle(options, selected, distTag = "latest") {
5945
6159
  "--tag",
5946
6160
  distTag,
5947
6161
  ...missing.flatMap((pkg) => ["--filter", pkg.name])
5948
- ], options, packages, true, {
6162
+ ], {
6163
+ ...options,
6164
+ deferConfirmation: true
6165
+ }, packages, true, {
5949
6166
  accepted: confirmed.acceptedPackages,
5950
6167
  save: async (accepted) => {
5951
6168
  state.accepted = accepted;
@@ -5957,15 +6174,33 @@ async function publishLifecycle(options, selected, distTag = "latest") {
5957
6174
  await save();
5958
6175
  throw error;
5959
6176
  }
5960
- }
5961
- for (const pkg of packages) {
5962
- const remote = await inspectRegistry(pkg, options);
5963
- if (!remote || remote["dist-tags"]?.[distTag] !== pkg.version) throw new ReleaseCommandError(`npm version/dist-tag ${distTag} is not confirmed for ${packageKey(pkg)}; release remains incomplete`);
6177
+ } else state.accepted = confirmed.acceptedPackages;
6178
+ state.uploadComplete = packages.every((pkg) => state.accepted.some((accepted) => packageKey(accepted) === packageKey(pkg)));
6179
+ await save();
6180
+ }
6181
+ async function confirm(session, options, distTag) {
6182
+ const { state, packages, save } = session;
6183
+ if (state.npm !== "running" && packages.some((pkg) => !state.accepted.some((accepted) => packageKey(accepted) === packageKey(pkg)))) throw new ReleaseCommandError("Confirmation requires accepted upload evidence for every release target; run upload first");
6184
+ const confirmed = new PublishState(packages, async (accepted) => {
6185
+ state.accepted = accepted;
6186
+ await save();
6187
+ });
6188
+ confirmed.accept(state.accepted);
6189
+ try {
6190
+ await confirmVisibility(confirmed, options, packages, 0, distTag);
6191
+ } catch (error) {
6192
+ state.npm = "failed";
6193
+ await save();
6194
+ throw error;
5964
6195
  }
5965
6196
  state.npm = "complete";
5966
6197
  state.accepted = packages;
5967
6198
  await save();
5968
6199
  await writeFile(path.join(options.cwd, "pnpm-publish-summary.json"), JSON.stringify({ publishedPackages: packages }));
6200
+ }
6201
+ async function finalize(session, options) {
6202
+ const { github, state, packages, releases, env, save } = session;
6203
+ if (state.npm !== "complete") throw new ReleaseCommandError("Finalize requires completed version/dist-tag confirmation; run confirm first");
5969
6204
  for (const pkg of state.packages) {
5970
6205
  await github.ensureTag({
5971
6206
  tag: packageKey(pkg),
@@ -5988,7 +6223,16 @@ async function publishLifecycle(options, selected, distTag = "latest") {
5988
6223
  state.complete = true;
5989
6224
  await save();
5990
6225
  logger.success(`Release lifecycle complete: ${packages.map(packageKey).join(", ")}`);
5991
- return packages;
6226
+ }
6227
+ async function publishLifecycle(options, selected, distTag = "latest") {
6228
+ const session = await openLifecycle(options, selected, distTag);
6229
+ if (!session) return [];
6230
+ if ("preview" in session) return session.preview;
6231
+ const stage = options.stage ?? "all";
6232
+ if (stage === "all" || stage === "upload") await upload(session, options, distTag);
6233
+ if (stage === "all" || stage === "confirm") await confirm(session, options, distTag);
6234
+ if (stage === "all" || stage === "finalize") await finalize(session, options);
6235
+ return session.packages;
5992
6236
  }
5993
6237
  //#endregion
5994
6238
  //#region src/core/oidc/identity.ts
@@ -6829,6 +7073,382 @@ async function readReleaseTriggerContext(options) {
6829
7073
  };
6830
7074
  }
6831
7075
  //#endregion
7076
+ //#region src/commands/release/stages/receipt.ts
7077
+ function ordered(value) {
7078
+ if (Array.isArray(value)) return value.map(ordered);
7079
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, ordered(item)]));
7080
+ return value;
7081
+ }
7082
+ function stageDirectory(options) {
7083
+ const directory = capture("git", ["rev-parse", "--git-dir"], options);
7084
+ if (!directory) throw new ReleaseCommandError("Staged release requires a Git checkout");
7085
+ return path.resolve(options.cwd, directory, "repoctl-release-ci");
7086
+ }
7087
+ async function stageIdentity(options) {
7088
+ const env = getReleaseEnv(options);
7089
+ const untracked = capture("git", [
7090
+ "ls-files",
7091
+ "--others",
7092
+ "--exclude-standard",
7093
+ "-z"
7094
+ ], options).split("\0").filter(Boolean).filter((file) => ![
7095
+ "repoctl-ci-progress.json",
7096
+ "repoctl-publish-progress.json",
7097
+ "repoctl-release-progress.json",
7098
+ "pnpm-publish-summary.json"
7099
+ ].includes(file));
7100
+ const value = {
7101
+ files: await Promise.all(untracked.sort().map(async (file) => [file, createHash("sha256").update(await readFile(path.join(options.cwd, file))).digest("hex")])),
7102
+ repository: env["GITHUB_REPOSITORY"] ?? capture("git", [
7103
+ "remote",
7104
+ "get-url",
7105
+ "origin"
7106
+ ], options),
7107
+ source: capture("git", ["rev-parse", "HEAD"], options),
7108
+ diff: capture("git", [
7109
+ "diff",
7110
+ "--binary",
7111
+ "HEAD"
7112
+ ], options),
7113
+ candidates: (await getPublishCandidates(options.cwd)).map(packageKey).sort(),
7114
+ configuration: options.config,
7115
+ branch: options.branch ?? env["GITHUB_REF_NAME"],
7116
+ mode: resolveReleaseMode(options),
7117
+ recovery: options.sourceSha ?? env["REPO_RELEASE_RECOVERY_SOURCE_SHA"],
7118
+ selection: [options.packageName ?? env["REPO_RELEASE_PACKAGE"], options.packageVersion ?? env["REPO_RELEASE_VERSION"]],
7119
+ dryRun: options.dryRun ?? env["REPO_RELEASE_DRY_RUN"] === "true",
7120
+ run: [env["GITHUB_RUN_ID"], env["GITHUB_RUN_ATTEMPT"]]
7121
+ };
7122
+ return createHash("sha256").update(JSON.stringify(ordered(value))).digest("hex");
7123
+ }
7124
+ async function saveReceipt(receipt, options) {
7125
+ const directory = stageDirectory(options);
7126
+ await mkdir(directory, { recursive: true });
7127
+ const exclude = path.resolve(directory, "../info/exclude");
7128
+ await mkdir(path.dirname(exclude), { recursive: true });
7129
+ const previous = await readFile(exclude, "utf8").catch((error) => {
7130
+ if (error.code !== "ENOENT") throw error;
7131
+ return "";
7132
+ });
7133
+ const ignored = [
7134
+ "repoctl-ci-progress.json",
7135
+ "repoctl-publish-progress.json",
7136
+ "repoctl-release-progress.json",
7137
+ "pnpm-publish-summary.json"
7138
+ ].map((file) => `/${file}`).filter((file) => !previous.split("\n").includes(file));
7139
+ if (ignored.length) await appendFile(exclude, `\n${ignored.join("\n")}\n`);
7140
+ const filename = path.join(directory, "receipt.json");
7141
+ const temporary = `${filename}.${randomUUID()}.tmp`;
7142
+ await writeFile(temporary, `${JSON.stringify(receipt, null, 2)}\n`);
7143
+ await rename(temporary, filename);
7144
+ await writeFile(path.join(options.cwd, "repoctl-ci-progress.json"), `${JSON.stringify(receipt, null, 2)}\n`);
7145
+ }
7146
+ async function readReceipt(options) {
7147
+ try {
7148
+ const receipt = JSON.parse(await readFile(path.join(stageDirectory(options), "receipt.json"), "utf8"));
7149
+ if (receipt.schemaVersion !== 1 || receipt.identity !== await stageIdentity(options)) throw new ReleaseCommandError("Stale release stage receipt: repository, source, candidates, configuration or run changed; restart at plan and verify");
7150
+ return receipt;
7151
+ } catch (error) {
7152
+ if (error.code === "ENOENT") throw new ReleaseCommandError("Release stage receipt missing; run plan and verify first");
7153
+ throw error;
7154
+ }
7155
+ }
7156
+ async function stageOutput(options, values) {
7157
+ const filename = getReleaseEnv(options)["GITHUB_OUTPUT"];
7158
+ if (filename) await appendFile(filename, `${Object.entries(values).map(([key, value]) => `${key}=${value}`).join("\n")}\n`);
7159
+ }
7160
+ async function reportStage(receipt, options, stage, started, status, progressCwd = options.cwd) {
7161
+ let accepted = [];
7162
+ let targets = receipt.candidates;
7163
+ try {
7164
+ const progress = JSON.parse(await readFile(path.join(progressCwd, "repoctl-publish-progress.json"), "utf8"));
7165
+ targets = progress.candidates ?? targets;
7166
+ accepted = stage === "confirm" ? progress.confirmedPackages ?? [] : progress.acceptedPackages ?? [];
7167
+ } catch (error) {
7168
+ if (error.code !== "ENOENT") logger.warn("Could not read publish progress for stage summary; durable checkpoint is preserved");
7169
+ }
7170
+ const pending = [
7171
+ "upload",
7172
+ "confirm",
7173
+ "finalize"
7174
+ ].includes(stage) && receipt.publish ? targets.filter((pkg) => !accepted.some((item) => packageKey(item) === packageKey(pkg))).map(packageKey) : [];
7175
+ const elapsedMs = Math.round(performance.now() - started);
7176
+ const count = ["upload", "confirm"].includes(stage) ? accepted.length : targets.length;
7177
+ receipt.stages.push({
7178
+ stage,
7179
+ elapsedMs,
7180
+ status,
7181
+ count,
7182
+ pending
7183
+ });
7184
+ logger.info(`Release ${stage}: ${status}; ${(elapsedMs / 1e3).toFixed(2)}s; completed ${count}; pending ${pending.join(", ") || "(none)"}`);
7185
+ const summary = getReleaseEnv(options)["GITHUB_STEP_SUMMARY"];
7186
+ if (summary) await appendFile(summary, `### Release ${stage}\n\n- Status: ${status}\n- Duration: ${(elapsedMs / 1e3).toFixed(2)}s\n- Completed: ${count}\n- Pending: ${pending.join(", ") || "(none)"}\n\n`);
7187
+ await saveReceipt(receipt, options);
7188
+ }
7189
+ //#endregion
7190
+ //#region src/commands/release/stages/source.ts
7191
+ async function stagedSource(options, create = false, install = false) {
7192
+ const source = options.sourceSha ?? getReleaseEnv(options)["REPO_RELEASE_RECOVERY_SOURCE_SHA"]?.trim();
7193
+ if (!source) return {
7194
+ options,
7195
+ selected: void 0
7196
+ };
7197
+ const mode = resolveReleaseMode(options);
7198
+ const rule = await resolveStableReleaseBranch(options, "publish");
7199
+ if (!/^[a-f0-9]{40}$/.test(source) || !["publish", "publish-unpublished"].includes(mode)) throw new ReleaseCommandError("source-sha requires a full commit SHA and a publish mode");
7200
+ if (capture("git", ["rev-parse", "--is-shallow-repository"], options) !== "false") throw new ReleaseCommandError("Source recovery requires full Git history");
7201
+ run("git", [
7202
+ "merge-base",
7203
+ "--is-ancestor",
7204
+ source,
7205
+ `refs/remotes/origin/${rule.branch}`
7206
+ ], options);
7207
+ const root = path.join(stageDirectory(options), "source");
7208
+ const cwd = path.join(root, "checkout");
7209
+ const env = {
7210
+ ...getReleaseEnv(options),
7211
+ REPO_RELEASE_SOURCE_SHA: source
7212
+ };
7213
+ let recovery = {
7214
+ ...options,
7215
+ cwd,
7216
+ branch: rule.branch,
7217
+ env
7218
+ };
7219
+ if (create) {
7220
+ await rm(root, {
7221
+ recursive: true,
7222
+ force: true
7223
+ });
7224
+ await mkdir(root, { recursive: true });
7225
+ run("git", [
7226
+ "clone",
7227
+ "--shared",
7228
+ "--no-checkout",
7229
+ options.cwd,
7230
+ cwd
7231
+ ], options);
7232
+ run("git", [
7233
+ "remote",
7234
+ "set-url",
7235
+ "origin",
7236
+ capture("git", [
7237
+ "remote",
7238
+ "get-url",
7239
+ "origin"
7240
+ ], options)
7241
+ ], recovery);
7242
+ run("git", [
7243
+ "checkout",
7244
+ "--detach",
7245
+ source
7246
+ ], recovery);
7247
+ }
7248
+ if (capture("git", ["rev-parse", "HEAD"], recovery) !== source || capture("git", [
7249
+ "diff",
7250
+ "--binary",
7251
+ "HEAD"
7252
+ ], recovery)) throw new ReleaseCommandError("Recovery checkout changed; restart at plan and verify");
7253
+ clearWorkspaceCache();
7254
+ const candidates = await readSourceCandidates(recovery, source);
7255
+ assertReleaseLineVersions(rule, candidates);
7256
+ if (!candidates.length || await hasPendingIntents(cwd)) throw new ReleaseCommandError("Source must contain prepared release versions and no pending intents");
7257
+ const name = options.packageName ?? env["REPO_RELEASE_PACKAGE"];
7258
+ const version = options.packageVersion ?? env["REPO_RELEASE_VERSION"];
7259
+ if ((name || version) && !candidates.some((pkg) => pkg.name === name && pkg.version === version)) throw new ReleaseCommandError("Requested package/version is not part of the source release");
7260
+ const github = resolveGitHub(options);
7261
+ let selected = candidates;
7262
+ const workspace = await getPublishCandidates(cwd);
7263
+ const repository = env["GITHUB_REPOSITORY"];
7264
+ if (repository && github.readReleaseState) {
7265
+ const checkpoint = await github.readReleaseState(releaseStateKey(repository, rule.distTag, workspace));
7266
+ if (checkpoint) {
7267
+ if (checkpoint.state.packages.some((pkg) => pkg.target !== source || !candidates.some((item) => packageKey(item) === packageKey(pkg)))) throw new ReleaseCommandError("Existing checkpoint belongs to another source release");
7268
+ selected = workspace;
7269
+ }
7270
+ }
7271
+ if (!(options.dryRun ?? env["REPO_RELEASE_DRY_RUN"] === "true")) {
7272
+ recovery = {
7273
+ ...recovery,
7274
+ env: await sourcePackageManagerEnvironment(recovery, root)
7275
+ };
7276
+ if (install) run("pnpm", ["install", "--frozen-lockfile"], recovery);
7277
+ if (!create || install) {
7278
+ const config = await resolveCommandConfig("release", cwd);
7279
+ recovery = {
7280
+ ...recovery,
7281
+ config: {
7282
+ ...config,
7283
+ branches: options.config?.branches ?? {}
7284
+ }
7285
+ };
7286
+ }
7287
+ }
7288
+ return {
7289
+ options: {
7290
+ ...recovery,
7291
+ github
7292
+ },
7293
+ selected
7294
+ };
7295
+ }
7296
+ //#endregion
7297
+ //#region src/commands/release/stages/index.ts
7298
+ const stages = [
7299
+ "plan",
7300
+ "verify",
7301
+ "prepare",
7302
+ "upload",
7303
+ "confirm",
7304
+ "finalize"
7305
+ ];
7306
+ async function plan(options) {
7307
+ const mode = resolveReleaseMode(options);
7308
+ const event = getReleaseEnv(options)["GITHUB_EVENT_NAME"]?.trim();
7309
+ let action = "publish";
7310
+ if (mode === "auto" && event && event !== "workflow_dispatch" && !shouldRunRelease(await readReleaseTriggerContext(options))) action = "skip";
7311
+ else if (mode === "reconcile") action = "reconcile";
7312
+ else if (options.sourceSha ?? getReleaseEnv(options)["REPO_RELEASE_RECOVERY_SOURCE_SHA"]) await stagedSource(options, true);
7313
+ else if (mode === "prepare") action = "prepare";
7314
+ else if (mode === "auto") action = (await resolveReleaseBranch(options)).kind === "prerelease" ? "prerelease" : await hasPendingIntents(options.cwd) ? "prepare" : "publish";
7315
+ else if (!["publish", "publish-unpublished"].includes(mode)) throw new ReleaseCommandError(`Unknown release CI mode: ${mode}`);
7316
+ if (mode === "publish-unpublished" && !(options.sourceSha ?? getReleaseEnv(options)["REPO_RELEASE_RECOVERY_SOURCE_SHA"])) {
7317
+ const env = getReleaseEnv(options);
7318
+ const name = options.packageName ?? env["REPO_RELEASE_PACKAGE"];
7319
+ const version = options.packageVersion ?? env["REPO_RELEASE_VERSION"];
7320
+ if (!name || !version || !(await getPublishCandidates(options.cwd)).some((pkg) => pkg.name === name && pkg.version === version)) throw new ReleaseCommandError("publish-unpublished requires a matching workspace package and exact version");
7321
+ }
7322
+ return {
7323
+ schemaVersion: 1,
7324
+ id: randomUUID(),
7325
+ identity: await stageIdentity(options),
7326
+ action,
7327
+ publish: !["skip", "prepare"].includes(action),
7328
+ done: [],
7329
+ candidates: await getPublishCandidates(options.cwd),
7330
+ stages: []
7331
+ };
7332
+ }
7333
+ async function verify(options, action) {
7334
+ const dryRun = options.dryRun ?? getReleaseEnv(options)["REPO_RELEASE_DRY_RUN"] === "true";
7335
+ if (action === "reconcile" || dryRun) return;
7336
+ if (getReleaseEnv(options)["REPO_RELEASE_SOURCE_SHA"]) {
7337
+ await runQualityScripts(options);
7338
+ return;
7339
+ }
7340
+ const rule = await resolveReleaseBranch(options);
7341
+ const pending = await hasPendingIntents(options.cwd);
7342
+ if (action === "prepare" && !pending) return;
7343
+ if (action === "prepare" || action === "prerelease" && pending) {
7344
+ if (action === "prepare" && rule.kind === "prerelease") throw new ReleaseCommandError("Stable preparation requires a stable release branch");
7345
+ if (rule.kind === "prerelease") await assertLaneAssignments(rule.lane, options);
7346
+ else await assertStableLaneAssignments(options);
7347
+ await assertPlannedLine(rule, options);
7348
+ await assertPreviousReleaseComplete(options, rule.distTag);
7349
+ runReleaseHooks("beforeVersion", options);
7350
+ } else if (rule.kind === "prerelease") {
7351
+ await assertLaneAssignments(rule.lane, options);
7352
+ assertReleaseLineVersions(rule, await getPublishCandidates(options.cwd));
7353
+ } else await assertStablePublish(options, false);
7354
+ await runQualityScripts(options);
7355
+ }
7356
+ async function releaseCiStage(options) {
7357
+ const stage = options.stage;
7358
+ if (!stages.includes(stage)) throw new ReleaseCommandError(`Unknown release CI stage ${stage}; expected all, ${stages.join(", ")}`);
7359
+ const started = performance.now();
7360
+ const receipt = stage === "plan" ? await plan(options) : await readReceipt(options);
7361
+ if (stage !== "plan" && !receipt.done.includes(stages[stages.indexOf(stage) - 1])) throw new ReleaseCommandError(`Release ${stage} requires the preceding stage to complete; restart at plan if interrupted`);
7362
+ if (receipt.done.includes(stage)) {
7363
+ await stageOutput(options, {
7364
+ run: receipt.action !== "skip",
7365
+ publish: receipt.publish
7366
+ });
7367
+ return receipt;
7368
+ }
7369
+ await saveReceipt(receipt, options);
7370
+ let effective = options;
7371
+ try {
7372
+ if (receipt.action !== "skip") {
7373
+ const source = stage === "plan" ? void 0 : await stagedSource(options, false, stage === "verify");
7374
+ effective = source?.options ?? options;
7375
+ if (!["plan", "verify"].includes(stage) && receipt.effectiveIdentity !== await stageIdentity(effective)) throw new ReleaseCommandError("Verified source/configuration changed; restart at plan and verify");
7376
+ const github = resolveGitHub(effective);
7377
+ if (!github.readReleaseState || !github.writeReleaseState) throw new ReleaseCommandError("Staged release requires durable GitHub checkpoint operations");
7378
+ if (stage === "verify") await verify({
7379
+ ...effective,
7380
+ github
7381
+ }, receipt.action);
7382
+ else if (stage === "prepare") {
7383
+ const authorized = authorizeVerification({
7384
+ ...effective,
7385
+ github
7386
+ });
7387
+ if (receipt.action === "prepare") await createReleasePullRequest(authorized);
7388
+ else if (receipt.action === "prerelease") {
7389
+ let ready = !await hasPendingIntents(effective.cwd);
7390
+ await releasePrerelease(authorized, async () => {
7391
+ ready = true;
7392
+ return [];
7393
+ });
7394
+ receipt.publish = ready;
7395
+ }
7396
+ receipt.identity = await stageIdentity(options);
7397
+ receipt.candidates = source?.selected ?? await getPublishCandidates(effective.cwd);
7398
+ } else if ([
7399
+ "upload",
7400
+ "confirm",
7401
+ "finalize"
7402
+ ].includes(stage) && receipt.publish) {
7403
+ if (receipt.action === "reconcile") {
7404
+ if (stage === "finalize") await reconcileRelease(effective);
7405
+ } else {
7406
+ const rule = await resolveReleaseBranch(effective);
7407
+ const env = getReleaseEnv(effective);
7408
+ const name = options.packageName ?? env["REPO_RELEASE_PACKAGE"];
7409
+ const version = options.packageVersion ?? env["REPO_RELEASE_VERSION"];
7410
+ const selected = source?.selected ?? (resolveReleaseMode(options) === "publish-unpublished" ? [{
7411
+ name: name ?? "",
7412
+ version: version ?? ""
7413
+ }] : void 0);
7414
+ if (selected?.some((pkg) => !receipt.candidates.some((candidate) => candidate.name === pkg.name && candidate.version === pkg.version))) throw new ReleaseCommandError("Recovery package/version does not match prepared candidates");
7415
+ await publishLifecycle({
7416
+ ...effective,
7417
+ stage,
7418
+ github
7419
+ }, selected, rule.distTag);
7420
+ }
7421
+ }
7422
+ } else logger.info("No release trigger detected; skipping release CI.");
7423
+ if (!receipt.done.includes(stage)) receipt.done.push(stage);
7424
+ await stageOutput(options, {
7425
+ run: receipt.action !== "skip",
7426
+ publish: receipt.publish
7427
+ });
7428
+ receipt.identity = await stageIdentity(options);
7429
+ receipt.effectiveIdentity = await stageIdentity(effective);
7430
+ await reportStage(receipt, options, stage, started, "complete", effective.cwd);
7431
+ } catch (error) {
7432
+ await reportStage(receipt, options, stage, started, "failed", effective.cwd);
7433
+ throw error;
7434
+ } finally {
7435
+ if (effective.cwd !== options.cwd) {
7436
+ for (const file of [
7437
+ "repoctl-publish-progress.json",
7438
+ "repoctl-release-progress.json",
7439
+ "pnpm-publish-summary.json"
7440
+ ]) await copyFile(path.join(effective.cwd, file), path.join(options.cwd, file)).catch((error) => {
7441
+ if (error.code !== "ENOENT") throw error;
7442
+ });
7443
+ if (stage === "finalize" && receipt.done.includes("finalize")) await rm(path.join(stageDirectory(options), "source"), {
7444
+ recursive: true,
7445
+ force: true
7446
+ });
7447
+ }
7448
+ }
7449
+ return receipt;
7450
+ }
7451
+ //#endregion
6832
7452
  //#region src/commands/release/ci.ts
6833
7453
  async function createReleasePullRequest(options) {
6834
7454
  const rule = await resolveStableReleaseBranch(options, "prepare");
@@ -6968,6 +7588,7 @@ async function releaseCi(options) {
6968
7588
  ...options,
6969
7589
  config: options.config ?? await resolveCommandConfig("release", options.cwd) ?? {}
6970
7590
  };
7591
+ if (options.stage && options.stage !== "all") return releaseCiStage(options);
6971
7592
  const source = options.sourceSha ?? getReleaseEnv(options)["REPO_RELEASE_RECOVERY_SOURCE_SHA"]?.trim();
6972
7593
  if (source) return recoverSource({
6973
7594
  ...options,