UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

834 lines (833 loc) • 33.1 kB
import { t as parseJsonWithJson5Fallback } from "./parse-json-compat-DoWUfD79.mjs"; import { i as resolveConfigEnvVars } from "./env-substitution-CgVeOqUd.mjs"; import { i as isMissingPathError } from "./errno-DFcoqIT9.mjs"; import { l as resolveConfigIncludeWritePath, n as ConfigIncludeError, o as hashConfigIncludeRaw, p as isPathInside, s as isInternalIncludeWriteTarget } from "./includes-wjVi5Ymt.mjs"; import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { w as root } from "./fs-safe-BbWvmdVn.mjs"; import { a as projectIncludeModelPolicyWrite } from "./model-policy-allowlist-migration-Dd1EwQdo.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { m as withConfigReadEnvChanges, o as createConfigRuntimeEnvBase, r as cloneEnvWithPlatformSemantics, t as applyConfigEnvVars } from "./config-env-vars-ByeGN-9N.mjs"; import { i as formatInvalidConfigDetails, r as createInvalidConfigError } from "./io.invalid-config-DK-BYZ4Y.mjs"; import { i as hashConfigRaw, n as containsConfigIncludeDirective, p as resolveConfigSnapshotHash } from "./io.read-helpers-qAcqsRC0.mjs"; import { D as rollbackConfigFileWriteIfUnchanged, b as createConfigFileWriteGuard, g as captureConfigFileWritePathProof, i as withConfigWriteLock, n as markActiveConfigMutationPath, t as captureConfigWriteLockGuard } from "./write-lock-Bg9nHsHM.mjs"; import { a as getRuntimeConfigSnapshot, b as resolveConfigWriteAfterWrite, c as getRuntimeConfigSourceSnapshot, l as hasManagedRuntimeConfigWriteOwner, m as preflightRuntimeSnapshotWrite, p as preflightManagedRuntimeConfigWrite, r as finalizeRuntimeSnapshotWrite, s as getRuntimeConfigSnapshotRefreshHandler, x as resolveConfigWriteFollowUp } from "./runtime-snapshot-WbwbY5b7.mjs"; import { t as getConfigValueAtPath } from "./config-paths-DTAbnrwT.mjs"; import { n as hasWebhookMigrationProgress } from "./io.meta-BrkFioo1.mjs"; import { t as ConfigMutationConflictError } from "./mutation-conflict-Bs0nsNWn.mjs"; import { i as mergeConfigWriteOptions, r as createConfigWriteAuthorityGuard } from "./write-authority-l37tp55r.mjs"; import { h as withDeferredPluginMigrationsCurrent, m as withDeferredPluginConfigRollback } from "./deferred-plugin-migrations-C_CU0aKR.mjs"; import { a as preserveDeferredPluginMigrationConfig, c as setDeferredPluginMigrationConfigFacts, l as applyUnsetPathsForWrite, o as readConfigWriteMigrationFacts, u as resolveManagedUnsetPathsForWrite } from "./deferred-plugin-migration-config-B3TJC-SY.mjs"; import { r as projectLegacyRuntimeConfigWrite } from "./runtime-source-projection-DTwMWCo9.mjs"; import { i as validateConfigObjectWithPlugins } from "./validation-DSwgLhC7.mjs"; import { i as assertManagedRuntimeEnvPublicationCurrent, s as resolveManagedRuntimeEnvBaseline, t as createConfigIO } from "./io.factory-DEa_bi2j.mjs"; import { r as warnIfJSON5CommentsWillBeStripped } from "./io.warnings-BbJvBO5E.mjs"; import { t as GATEWAY_CONFIG_SELECTION_ENV_KEYS } from "./gateway-env-selection-yOcr26em.mjs"; import { g as recordUpdateDoctorConfigFileWrite, s as assertUpdateDoctorConfigInputHash } from "./update-doctor-result-DwaI51On.mjs"; import { r as assertConfigWriteAllowedInCurrentMode } from "./config-write-guard-CxNxfJ_I.mjs"; import { t as resolveWriteEnvSnapshotForPath } from "./env-preserve-D_8K8swo.mjs"; import { n as configWriteCommittedSnapshot } from "./io.types-tZoWfCaZ.mjs"; import { s as recoverConfigWriteFailure } from "./io.write-errors-CuPAqPbq.mjs"; import { C as copyRuntimeConfigWriteApplication, E as publishRuntimeConfigWrite, l as readConfigFileSnapshotForWrite, x as writeConfigFile } from "./io.runtime-DsJ2dLCQ.mjs"; import "./io-4QsrsWTJ.mjs"; import { n as getLegacyTopLevelIncludeBoundary, r as resolveIncludeWriteBoundary, t as collectChangedConfigPaths } from "./include-write-boundary-Dpj_7ftL.mjs"; import { i as projectConfigWriteSource, n as prepareConfigWriteValues, t as injectExplicitlySetPaths } from "./io.write-prepare-B19yEmrf.mjs"; import { n as prepareConfigFileWrite } from "./backup-rotation-DIugSdzV.mjs"; import { t as rejectConfigNonFiniteNumbers } from "./value-tree-Deh4eoFD.mjs"; import fs from "node:fs"; import path from "node:path"; import fs$1 from "node:fs/promises"; import { isDeepStrictEqual } from "node:util"; //#region src/config/mutate.include-io.ts function formatJsonFileValue(e) { rejectConfigNonFiniteNumbers(e); return `${JSON.stringify(e, null, 2)}\n`; } async function resolveRootBoundIncludeFile(e) { const t = resolveConfigIncludeWritePath(e); const n = [path.dirname(e.configPath), ...e.allowedRoots]; for (const e of n) { const n = await fs$1.realpath(e).catch(() => null); if (!n || !isPathInside(n, t)) continue; const r = path.relative(n, t); if (!r || path.isAbsolute(r) || r.split(path.sep)[0] === "..") continue; return { absolutePath: t, relativePath: r, root: await root(n, { hardlinks: "reject", mkdir: true, mode: 384, symlinks: "reject" }) }; } throw new Error(`Config include write path has no approved existing root: ${t}`); } async function resolveExpectedRootBoundIncludeFile(e) { let t; try { t = await resolveRootBoundIncludeFile(e); } catch (e) { if (e instanceof ConfigIncludeError || e instanceof Error && e.message.startsWith("Config include write path has no approved existing root:")) throw new ConfigMutationConflictError("included config target changed since last load"); throw e; } if (path.normalize(t.absolutePath) !== path.normalize(e.expectedAbsolutePath)) throw new ConfigMutationConflictError("included config target changed since last load"); return t; } async function readRootBoundFileRawIfExists(e) { try { return await e.root.readText(e.relativePath); } catch (e) { if (isMissingPathError(e)) return null; throw e; } } async function assertRootConfigStillMatchesSnapshot(e) { let t = null; try { t = await fs$1.readFile(e.path, "utf-8"); } catch (e) { if (!isMissingPathError(e)) throw e; } if (hashConfigIncludeRaw(t) !== hashConfigIncludeRaw(e.exists ? e.raw ?? null : null)) throw new ConfigMutationConflictError("config changed while preparing include write"); } async function assertIncludeGraphStillMatchesSnapshot(e) { await assertRootConfigStillMatchesSnapshot(e.snapshot); for (const [t, n] of Object.entries(e.writeOptions?.includeFileHashesForWrite ?? {})) { const r = e.writeOptions?.includeFileTargetsForWrite?.[t]; if (!r) throw new ConfigMutationConflictError("included config target changed since last load"); const i = await resolveExpectedRootBoundIncludeFile({ configPath: e.snapshot.path, includePath: t, allowedRoots: [path.dirname(r)], expectedAbsolutePath: r }); const a = t === e.includePath ? e.includeHash : n; if (hashConfigIncludeRaw(await readRootBoundFileRawIfExists(i)) !== a) throw new ConfigMutationConflictError("included config changed while preparing write"); } } async function rollbackJsonFileWriteIfUnchanged(e) { const t = await rollbackConfigFileWriteIfUnchanged({ configPath: e.target.absolutePath, previousSnapshot: { path: e.target.absolutePath, exists: e.previousRaw !== null, raw: e.previousRaw }, committedHash: hashConfigRaw(e.committedRaw), fsModule: fs, ...e.pathProof.captureRollbackProof(), preserveDirectoryMode: true, durable: true, destinationHardlinks: "reject", withPublication: e.pathProof.withPublication }); if (t) recordUpdateDoctorConfigFileWrite(e.target.absolutePath, hashConfigRaw(e.committedRaw), hashConfigRaw(e.previousRaw)); return t; } async function writeRootBoundJsonFile(e) { e.assertConfigPathForWrite(); await e.preCommitRuntimePreflight?.(); e.assertConfigPathForWrite(); const t = await resolveExpectedRootBoundIncludeFile({ configPath: e.configPath, includePath: e.includePath, allowedRoots: e.allowedRoots, expectedAbsolutePath: e.expectedTargetPath }); e.assertConfigPathForWrite(); await e.assertIncludeGraphForWrite(); e.assertConfigPathForWrite(); const n = await readRootBoundFileRawIfExists(t); e.assertConfigPathForWrite(); if (hashConfigIncludeRaw(n) !== hashConfigIncludeRaw(e.expectedRaw)) throw new ConfigMutationConflictError("included config changed while preparing write"); const r = captureConfigFileWritePathProof(e.includePath, t.absolutePath, fs); const i = createConfigWriteAuthorityGuard(() => { e.assertConfigPathForWrite(); r.assertCurrent(); }); const a = formatJsonFileValue(e.value); e.assertConfigPathForWrite(); warnIfJSON5CommentsWillBeStripped({ raw: n, filePath: t.absolutePath, skipOutputLogs: e.skipOutputLogs }); const o = { phase: "unpublished" }; const s = createConfigFileWriteGuard(t.absolutePath, fs, i, { snapshot: { path: t.absolutePath, exists: n !== null, raw: n }, includeGraph: e.includeGraph, validateUtf8: true, targetPathProof: r, preserveDirectoryMode: true, onRootRemoved: () => { o.phase = "removed"; }, onRootPublished: () => { o.phase = "published"; } }); const c = { ...r, assertCurrent: () => { e.assertOwnerForRollback(); s.assertPublishedIdentity(); }, captureRollbackProof: () => s.captureRollbackProof(e.assertOwnerForRollback), withPublication: (t, n) => e.databaseAccess === "none" ? t() : withDeferredPluginConfigRollback({ configPath: e.configPath, env: e.env, assertCurrent: e.assertOwnerForRollback }, t, n) }; try { try { var l = _usingCtx(); const r = l.a(await prepareConfigFileWrite({ configPath: t.absolutePath, previousRaw: n, content: a, warn: (t) => { if (!e.skipOutputLogs) console.warn(t); }, fsModule: s.fileSystem, assertCurrent: s.assertCurrent, assertBeforeMutation: s.assertBeforeMutation, onDestinationState: s.onDestinationState, destinationHardlinks: "reject", durable: true })); await e.beforeCommit?.(); s.assertCurrent(); const publish = () => { e.assertBeforePublish?.(); r.publish(); o.phase = "published"; recordUpdateDoctorConfigFileWrite(t.absolutePath, hashConfigRaw(n), hashConfigRaw(a)); }; if (e.databaseAccess === "none") publish(); else withDeferredPluginMigrationsCurrent({ env: e.env, configPath: e.configPath, expectedPending: e.deferredPluginMigrations, phase: "config include publication" }, publish); await e.assertIncludeGraphForWrite(hashConfigIncludeRaw(a)); s.assertCurrent(); s.assertPublishedIdentity(); } catch (e) { l.e = e; } finally { await l.d(); } } catch (e) { if (o.phase === "unpublished") throw e; return await recoverConfigWriteFailure({ configPath: t.absolutePath, publication: o.phase === "removed" ? "partial" : "complete", cause: e, restoreFile: () => rollbackJsonFileWriteIfUnchanged({ target: t, previousRaw: n, committedRaw: o.phase === "published" ? a : null, pathProof: c }) }); } return c; } //#endregion //#region src/config/mutate.snapshot.ts async function readConfigSnapshotForMutation(e) { const t = { ...e.writeOptions?.skipPluginValidation ? { skipPluginValidation: true } : {}, ...e.writeOptions?.observe === false ? { observe: false } : {}, ...e.writeOptions?.deferredPluginMigrations !== void 0 ? { deferredPluginMigrations: e.writeOptions.deferredPluginMigrations } : {}, ...e.writeOptions?.preservedLegacyRootKeys ? { preservedLegacyRootKeys: e.writeOptions.preservedLegacyRootKeys } : {} }; if (e.io) return await e.io.readConfigFileSnapshotForWrite(t); if (e.ownedConfigPathForWrite) { const { skipPluginValidation: n, ...r } = t; const i = { ...r, configPath: e.ownedConfigPathForWrite, ...n ? { pluginValidation: "skip" } : {} }; return await (hasManagedRuntimeConfigWriteOwner(e.ownedConfigPathForWrite) ? createConfigIO({ ...i, env: createConfigRuntimeEnvBase(resolveManagedRuntimeEnvBaseline().sourceConfig, process.env, { preservedKeys: GATEWAY_CONFIG_SELECTION_ENV_KEYS }) }) : createConfigIO(i)).readConfigFileSnapshotForWrite(); } return await readConfigFileSnapshotForWrite(t); } //#endregion //#region src/config/mutate.ts const DEFAULT_CONFIG_MUTATION_RETRY_ATTEMPTS = 5; function assertBaseHashMatches(e, t) { const n = resolveConfigSnapshotHash(e) ?? null; if (t !== void 0 && t !== n) throw new ConfigMutationConflictError("config changed since last load"); return n; } function assertExpectedConfigPathMatches(e, t) { if (t !== void 0 && t !== e.path) throw new ConfigMutationConflictError("config path changed since last load", { retryable: false }); } /** Serialize config writers without requiring a schema-valid snapshot. */ async function withConfigMutationLock(e, t) { const n = e.assertCurrent; n?.(); return e.io ? await t() : await withConfigWriteLock(e.lockPath ?? resolveConfigPath(), t, void 0, n); } function mergeConfigMutationWriteOptions(e, t) { return copyRuntimeConfigWriteApplication(t, mergeConfigWriteOptions(e, t)); } function createConfigMutationOwnership(e, t) { const n = mergeConfigMutationWriteOptions(e.writeOptions, t); return { expectedConfigPath: n.expectedConfigPath ?? e.snapshot.path, ownedConfigPathForWrite: n.ownedConfigPathForWrite, assertConfigPathForWrite: n.assertConfigPathForWrite }; } async function withConfigMutationSnapshotLock(e, t) { let n = path.resolve(e?.ownedConfigPathForWrite ?? resolveConfigPath()); for (let r = 0; r < 3; r += 1) { e?.assertConfigPathForWrite?.(); const r = await withConfigMutationLock({ lockPath: n, assertCurrent: e?.assertCurrent }, async () => { const r = await readConfigSnapshotForMutation({ ownedConfigPathForWrite: e?.ownedConfigPathForWrite, writeOptions: e }); captureConfigWriteLockGuard(n)?.(); e?.assertConfigPathForWrite?.(); const i = path.resolve(r.snapshot.path); if (i !== n) return { done: false, lockPath: i }; return { done: true, value: await t(r) }; }); if (r.done) return r.value; n = r.lockPath; } throw new ConfigMutationConflictError("config path changed repeatedly while acquiring lock", { retryable: false }); } /** * Run a multi-phase operation under the canonical cross-process write lock. * Nested mutation helpers are reentrant through activeConfigMutationLocks. */ async function withConfigMutationExclusive(e) { return await withConfigMutationSnapshotLock(void 0, (t) => e(t.snapshot.sourceConfig)); } /** * One include-owned write decision for the guarded writer and Doctor's * eligibility check; a split decision lets Doctor advertise an include write * that the writer then declines. Null means the write belongs to the root writer. */ function resolveIncludeOwnedWriteCandidate(e) { if (e.writeOptions?.persistCanonicalAgentRoster === true || hasWebhookMigrationProgress(e.snapshot.sourceConfig, e.nextConfig)) return null; const t = { inputBasis: e.writeOptions?.inputBase === "source" ? { kind: "source", config: e.snapshot.sourceConfig } : void 0, runtimeConfig: e.snapshot.runtimeConfig, sourceConfig: e.snapshot.sourceConfig, nextConfig: !e.io && e.writeOptions?.inputBase === void 0 ? projectLegacyRuntimeConfigWrite(e.nextConfig) : e.nextConfig, unsetPaths: resolveManagedUnsetPathsForWrite(e.writeOptions?.unsetPaths), explicitSetPaths: e.writeOptions?.explicitSetPaths, explicitSetValueSource: e.writeOptions?.explicitSetValueSource ?? e.nextConfig }; const n = applyUnsetPathsForWrite(injectExplicitlySetPaths({ ...t, valueSource: t.explicitSetValueSource, persistedCandidate: projectConfigWriteSource(t) }), t.unsetPaths); const r = prepareConfigWriteValues({ snapshot: e.snapshot, nextConfig: n, writeOptions: e.writeOptions, env: e.io?.env ?? process.env, explicitSetPaths: e.writeOptions?.explicitSetPaths }); const i = projectIncludeModelPolicyWrite({ config: r.authoredConfig, previousConfig: e.snapshot.sourceConfig, explicitSetPaths: e.writeOptions?.explicitSetPaths }); let a = collectChangedConfigPaths(r.authoredSourceConfig, i); if (a.paths.length === 0 && !a.rootChanged && i !== r.authoredConfig) a = collectChangedConfigPaths(r.authoredSourceConfig, r.authoredConfig); if (a.rootChanged || a.paths.length === 0) return null; const o = e.snapshot.includeProvenance === void 0 ? getLegacyTopLevelIncludeBoundary({ snapshot: e.snapshot, changed: a }) : resolveIncludeWriteBoundary({ provenance: e.snapshot.includeProvenance, changed: a }); if (!o || getConfigValueAtPath(i, o.boundaryPath) === void 0) return null; if (e.writeOptions?.allowIncludeAncestorExplicitSetPaths && e.writeOptions.explicitSetPaths?.some((e) => e.length > o.boundaryPath.length && o.boundaryPath.every((t, n) => t === e[n]))) return null; return { nextConfig: i, ...o, includePath: path.normalize(o.includePath) }; } /** * Resolve the authored $include file that solely owns every changed path of this * write. Callers that add root-level metadata before persisting (Doctor wizard * state) must consult this first: an extra root key would push the change set * outside the boundary and force the guarded root writer to reject the write. */ function resolveConfigIncludeWriteBoundary(e) { const t = resolveIncludeOwnedWriteCandidate({ snapshot: e.snapshot, nextConfig: e.nextConfig, writeOptions: { inputBase: "source", persistCanonicalAgentRoster: e.persistCanonicalAgentRoster, explicitSetPaths: e.explicitSetPaths } }); return t && isInternalIncludeWriteTarget({ configPath: e.snapshot.path, includePath: t.includePath }) ? { boundaryPath: t.boundaryPath, includePath: t.includePath } : null; } function snapshotProvesBrokenInclude(e, t) { return !e.valid && e.issues.some((e) => /Failed to (?:read|parse) include file:/.test(e.message) && e.message.includes(t)); } async function tryWriteIncludeOwnedConfigMutation(e) { const t = resolveIncludeOwnedWriteCandidate({ snapshot: e.snapshot, nextConfig: e.nextConfig, writeOptions: e.writeOptions, io: e.io }); if (!t) return null; const { nextConfig: n, boundaryPath: r, includePath: i } = t; const a = captureConfigWriteLockGuard(e.snapshot.path); const o = createConfigWriteAuthorityGuard(e.writeOptions?.assertCurrent, a); o(); const s = e.io?.env ?? process.env; const c = []; const l = e.writeOptions?.includeFileTargetsForWrite?.[i]; if (!l) throw new ConfigMutationConflictError("included config target changed since last load"); const u = e.writeOptions?.assertConfigPathForWrite; if (!u) return null; u(); const d = await fs$1.realpath(path.dirname(e.snapshot.path)); o(); if (!isPathInside(d, l)) throw new Error(`Config mutation cannot update external $include target ${i}; edit the included file directly or move it under the config directory.`); return await withConfigWriteLock(e.snapshot.path, () => withConfigWriteLock(l, async () => { const t = captureConfigWriteLockGuard(l); const a = createConfigWriteAuthorityGuard(o, t); a(); const d = await resolveExpectedRootBoundIncludeFile({ configPath: e.snapshot.path, includePath: i, allowedRoots: c, expectedAbsolutePath: l }); a(); const f = await readRootBoundFileRawIfExists(d); a(); const p = hashConfigIncludeRaw(f); const m = e.writeOptions?.includeFileHashesForWrite?.[i]; if (m !== void 0 && m !== p) throw new ConfigMutationConflictError("included config changed since last load"); const h = resolveWriteEnvSnapshotForPath({ actualConfigPath: e.snapshot.path, expectedConfigPath: e.writeOptions?.expectedConfigPath, envSnapshotForRestore: e.writeOptions?.envSnapshotForRestore }) ?? e.io?.env ?? process.env; const g = snapshotProvesBrokenInclude(e.snapshot, i); if (f === null && (!g || m === void 0)) throw new ConfigMutationConflictError("included config changed since last load"); const _ = getConfigValueAtPath(n, r); if (f !== null) { let t; let n = false; try { t = parseJsonWithJson5Fallback(f); n = true; } catch { if (!g || m === void 0) throw new ConfigMutationConflictError("included config changed since last load"); } if (n) { if (containsConfigIncludeDirective(t)) return null; const n = resolveConfigEnvVars(t, h, { onMissing: () => {} }); const i = e.snapshot.sourceConfigBeforeMigrations ?? e.snapshot.sourceConfig; const a = getConfigValueAtPath(i, r); if (!isDeepStrictEqual(n, a)) throw new ConfigMutationConflictError("included config changed since last load"); } } const v = hasManagedRuntimeConfigWriteOwner(e.snapshot.path); const y = v ? resolveManagedRuntimeEnvBaseline() : void 0; const b = y ? createConfigRuntimeEnvBase(y.sourceConfig, process.env, { preservedKeys: GATEWAY_CONFIG_SELECTION_ENV_KEYS }) : cloneEnvWithPlatformSemantics(s); applyConfigEnvVars(n, b); const x = resolveConfigEnvVars(n, b, { onMissing: () => {} }); const S = validateConfigObjectWithPlugins(x, { ...e.writeOptions?.skipPluginValidation ? { pluginValidation: "skip" } : {}, deferredPluginMigrations: e.deferredPluginMigrations }); if (!S.ok) throw createInvalidConfigError(e.snapshot.path, formatInvalidConfigDetails(S.issues)); const C = getRuntimeConfigSnapshot(); const w = getRuntimeConfigSourceSnapshot(); const T = Boolean(C); const E = Boolean(C && w); let D = /* @__PURE__ */ new Map(); let O; if (y) { D = await preflightManagedRuntimeConfigWrite(e.snapshot.path, x, e.writeOptions?.runtimeRefresh); assertManagedRuntimeEnvPublicationCurrent(y.publication); } else O = await preflightRuntimeSnapshotWrite({ nextSourceConfig: x, refreshOptions: e.writeOptions?.runtimeRefresh, formatRefreshError: (e) => formatErrorMessage(e), createRefreshError: (e, t) => new Error(`Config write blocked before committing ${i}: active SecretRef resolution failed: ${e}`, { cause: t }) }); a(); const k = formatJsonFileValue(_); const A = hashConfigIncludeRaw(k); const j = e.writeOptions?.preCommitRuntimePreflight; const assertIncludeGraphForWrite = (t = p) => assertIncludeGraphStillMatchesSnapshot({ snapshot: e.snapshot, writeOptions: e.writeOptions, includePath: i, includeHash: t }); const M = await writeRootBoundJsonFile({ env: s, databaseAccess: e.writeOptions?.databaseAccess, deferredPluginMigrations: e.deferredPluginMigrations, configPath: e.snapshot.path, includePath: i, allowedRoots: c, expectedTargetPath: l, value: _, expectedRaw: f, includeGraph: { hashes: { ...e.writeOptions?.includeFileHashesForWrite, [e.snapshot.path]: hashConfigIncludeRaw(e.snapshot.raw) }, targets: { ...e.writeOptions?.includeFileTargetsForWrite, [e.snapshot.path]: fs.realpathSync(e.snapshot.path) } }, assertIncludeGraphForWrite, assertConfigPathForWrite: () => { a(); u(); if (y) assertManagedRuntimeEnvPublicationCurrent(y.publication); }, assertOwnerForRollback: a, beforeCommit: e.writeOptions?.beforeCommit, assertBeforePublish: e.writeOptions?.assertBeforePublish, skipOutputLogs: e.writeOptions?.skipOutputLogs, preCommitRuntimePreflight: async () => { await j?.(x); } }); const assertPostCommitCurrent = () => { M.assertCurrent(); u(); }; let N; try { assertPostCommitCurrent(); if (y) assertManagedRuntimeEnvPublicationCurrent(y.publication); if (e.writeOptions?.skipRuntimeSnapshotRefresh && !T && !getRuntimeConfigSnapshotRefreshHandler()) return { persistedHash: null, persistedConfig: x, persistedSourceConfig: x }; const t = await withConfigReadEnvChanges(s, (t) => { N = t; return withConfigWriteLock(e.snapshot.path, () => readConfigSnapshotForMutation({ ownedConfigPathForWrite: e.snapshot.path, io: e.io, writeOptions: { ...e.writeOptions, observe: false } }), s, assertPostCommitCurrent); }); assertPostCommitCurrent(); const n = t.snapshot; await assertIncludeGraphForWrite(A); assertPostCommitCurrent(); assertExpectedConfigPathMatches(n, e.snapshot.path); const r = resolveConfigSnapshotHash(n); if (!n.valid) throw createInvalidConfigError(e.snapshot.path, formatInvalidConfigDetails(n.issues)); if (!r) throw new Error(`No persisted config hash was available after rereading ${e.snapshot.path}.`); const notifyCommittedWrite = () => { publishRuntimeConfigWrite({ configPath: e.snapshot.path, snapshot: n, sourceConfig: n.sourceConfig, previousSourceConfig: e.snapshot.sourceConfig, writtenSourceConfig: x, runtimeConfig: n.runtimeConfig, persistedHash: r, deferRuntimeActivation: v, preparedCandidates: D, writeOptions: e.writeOptions, afterWrite: e.afterWrite }); }; if (y) assertManagedRuntimeEnvPublicationCurrent(y.publication); await finalizeRuntimeSnapshotWrite({ assertCurrent: assertPostCommitCurrent, nextSourceConfig: n.sourceConfig, refreshOptions: e.writeOptions?.runtimeRefresh, hadBothSnapshots: E, freshConfig: n.runtimeConfig, notifyCommittedWrite, preflightResult: O, deferRuntimeActivation: v, formatRefreshError: (e) => formatErrorMessage(e), createRefreshError: (e, t) => new Error(`runtime snapshot refresh failed: ${e}`, { cause: t }) }); assertPostCommitCurrent(); return { persistedHash: r, persistedConfig: n.sourceConfig, persistedSourceConfig: x }; } catch (e) { return await recoverConfigWriteFailure({ configPath: d.absolutePath, cause: e, restoreFile: () => rollbackJsonFileWriteIfUnchanged({ target: d, previousRaw: f, committedRaw: k, pathProof: M }), restoreEffects: () => { a(); N?.(); } }); } }, s, o), s, o); } async function replaceConfigFile(e) { e.writeOptions?.assertConfigPathForWrite?.(); if (!e.snapshot && !e.io) return await withConfigMutationSnapshotLock(e.writeOptions, async (t) => await replaceConfigFileUnlocked({ ...e, snapshot: t.snapshot, writeOptions: mergeConfigMutationWriteOptions(t.writeOptions, e.writeOptions) })); return await withConfigMutationLock({ io: e.io, lockPath: e.snapshot?.path, assertCurrent: e.writeOptions?.assertCurrent }, async () => await replaceConfigFileUnlocked(e)); } async function replaceConfigFileUnlocked(e) { const { snapshot: t, writeOptions: n } = e.snapshot ? { snapshot: e.snapshot, writeOptions: e.writeOptions ?? {} } : await readConfigSnapshotForMutation({ io: e.io, writeOptions: e.writeOptions }); const r = mergeConfigMutationWriteOptions(n, e.writeOptions); const i = r.databaseAccess === "none" ? void 0 : await readConfigWriteMigrationFacts(t, e.io?.env); const a = preserveDeferredPluginMigrationConfig({ sourceConfig: t.sourceConfig, nextConfig: e.sourceConfig ?? e.nextConfig, pending: i ?? [], writeOptions: r }); r.inputBase = e.sourceConfig ? "source" : r.inputBase; r.assertConfigPathForWrite?.(); assertExpectedConfigPathMatches(t, r.expectedConfigPath); assertConfigWriteAllowedInCurrentMode({ configPath: t.path }); markActiveConfigMutationPath(t.path); assertUpdateDoctorConfigInputHash(t.path, hashConfigRaw(t.raw)); const o = assertBaseHashMatches(t, e.baseHash); const s = resolveConfigWriteAfterWrite(e.afterWrite ?? e.writeOptions?.afterWrite); let c = await tryWriteIncludeOwnedConfigMutation({ snapshot: t, nextConfig: a, deferredPluginMigrations: i, afterWrite: s, writeOptions: r, io: e.io }); if (c) setDeferredPluginMigrationConfigFacts(c.persistedConfig, i); else { const n = copyRuntimeConfigWriteApplication(r, { baseSnapshot: t, ...r, afterWrite: s }); const i = e.io ? n.preCommitRuntimePreflight : void 0; if (e.io) n.preCommitRuntimePreflight = async (e) => { await preflightRuntimeSnapshotWrite({ nextSourceConfig: e, refreshOptions: n.runtimeRefresh, formatRefreshError: (e) => formatErrorMessage(e), createRefreshError: (e, n) => new Error(`Config write blocked before committing ${t.path}: active SecretRef resolution failed: ${e}`, { cause: n }) }); await i?.(e); }; const o = await (e.io?.writeConfigFile ?? writeConfigFile)(a, n); const l = o?.[configWriteCommittedSnapshot]; c = { persistedHash: l?.hash ?? (o && !containsConfigIncludeDirective(o.persistedConfig) ? o.persistedHash : null), persistedConfig: l?.sourceConfig ?? o?.persistedConfig ?? a, persistedSourceConfig: o?.persistedSourceConfig }; } return { path: t.path, previousHash: o, snapshot: t, nextConfig: c.persistedConfig, persistedHash: c.persistedHash, persistedSourceConfig: c.persistedSourceConfig, afterWrite: s, followUp: resolveConfigWriteFollowUp(s) }; } async function commitPreparedConfigMutation(e) { const t = await replaceConfigFileUnlocked({ nextConfig: e.nextConfig, snapshot: e.snapshot, baseHash: e.baseHash, writeOptions: copyRuntimeConfigWriteApplication(e.writeOptions, { ...e.writeOptions, afterWrite: e.afterWrite }), io: e.io }); return { config: t.nextConfig, persistedHash: t.persistedHash, persistedSourceConfig: t.persistedSourceConfig, afterWrite: t.afterWrite }; } async function transformConfigFileAttempt(e, t, n, r) { n?.assertConfigPathForWrite?.(); const { snapshot: i, writeOptions: a } = r ?? await readConfigSnapshotForMutation({ ...n?.ownedConfigPathForWrite ? { ownedConfigPathForWrite: n.ownedConfigPathForWrite } : {}, io: e.io, writeOptions: e.writeOptions }); let o = mergeConfigMutationWriteOptions(a, e.writeOptions); if (n) { if (n.expectedConfigPath === void 0) { n.expectedConfigPath = o.expectedConfigPath ?? i.path; n.ownedConfigPathForWrite = o.ownedConfigPathForWrite; n.assertConfigPathForWrite = o.assertConfigPathForWrite; } o = copyRuntimeConfigWriteApplication(o, { ...o, expectedConfigPath: n.expectedConfigPath, ...n.ownedConfigPathForWrite ? { ownedConfigPathForWrite: n.ownedConfigPathForWrite } : {}, ...n.assertConfigPathForWrite ? { assertConfigPathForWrite: n.assertConfigPathForWrite } : {} }); } o.assertConfigPathForWrite?.(); assertExpectedConfigPathMatches(i, o.expectedConfigPath); assertConfigWriteAllowedInCurrentMode({ configPath: i.path }); markActiveConfigMutationPath(i.path); const s = assertBaseHashMatches(i, e.baseHash); const c = e.base === "runtime" ? i.runtimeConfig : i.sourceConfig; o.inputBase = e.base ?? "source"; const l = resolveConfigWriteAfterWrite(e.afterWrite ?? e.writeOptions?.afterWrite); const u = await e.transform(c, { snapshot: i, previousHash: s, attempt: t }, { envSnapshotForRestore: a.envSnapshotForRestore }); const d = await (e.commit ?? commitPreparedConfigMutation)({ nextConfig: u.nextConfig, snapshot: i, ...s !== null ? { baseHash: s } : {}, writeOptions: o, afterWrite: l, io: e.io }); const f = d.afterWrite ?? l; return { path: i.path, previousHash: s, snapshot: i, nextConfig: d.config, persistedHash: d.persistedHash, persistedSourceConfig: d.persistedSourceConfig, result: u.result, attempts: t + 1, afterWrite: f, followUp: resolveConfigWriteFollowUp(f) }; } async function runConfigTransform(e, t = false) { e.writeOptions?.assertConfigPathForWrite?.(); const n = t ? e.maxAttempts ?? DEFAULT_CONFIG_MUTATION_RETRY_ATTEMPTS : 1; if (!Number.isInteger(n) || n < 1) throw new Error("Config mutation maxAttempts must be a positive integer."); const runWithPrepared = async (r) => { const i = r ? createConfigMutationOwnership(r, e.writeOptions) : t ? {} : void 0; for (let t = 0; t < n; t += 1) try { return await transformConfigFileAttempt(e, t, i, t === 0 ? r : void 0); } catch (e) { if (e instanceof ConfigMutationConflictError && e.retryable && t < n - 1) continue; throw e; } throw new Error("Config mutation retry loop exhausted unexpectedly."); }; if (!e.io) return await withConfigMutationSnapshotLock(e.writeOptions, runWithPrepared); return await withConfigMutationLock({ io: e.io, assertCurrent: e.writeOptions?.assertCurrent }, async () => await runWithPrepared()); } async function transformConfigFile(e) { return await runConfigTransform(e); } async function transformConfigFileWithRetry(e) { return await runConfigTransform(e, true); } function configMutationTransform(e) { return { base: e.base, baseHash: e.baseHash, afterWrite: e.afterWrite, writeOptions: e.writeOptions, io: e.io, transform: async (t, n) => { const r = structuredClone(t); return { nextConfig: r, result: await e.mutate(r, n) }; } }; } async function mutateConfigFile(e) { return await transformConfigFile(configMutationTransform(e)); } async function mutateConfigFileWithRetry(e) { return await transformConfigFileWithRetry(configMutationTransform(e)); } //#endregion export { transformConfigFile as a, withConfigMutationLock as c, resolveConfigIncludeWriteBoundary as i, mutateConfigFileWithRetry as n, transformConfigFileWithRetry as o, replaceConfigFile as r, withConfigMutationExclusive as s, mutateConfigFile as t };