gencow 0.1.261 → 0.1.263
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/app-response-error.mjs +8 -2
- package/lib/deploy-app-creation.mjs +2 -0
- package/lib/deploy-app-target.mjs +33 -0
- package/lib/deploy-package-runtime.mjs +16 -32
- package/lib/deploy-prod-target.mjs +2 -0
- package/lib/deploy-project-config-load.mjs +32 -0
- package/lib/deploy-runtime.mjs +3 -0
- package/lib/deploy-static-fullstack-runtime.mjs +8 -1
- package/lib/env-command.mjs +101 -19
- package/package.json +4 -4
- package/runtime/server.mjs +4 -7
- package/runtime/tooling.mjs +102 -50
- package/scripts/codegen-named-import-check.ts +8 -2
- package/scripts/tooling-codegen-runtime.ts +132 -55
package/runtime/server.mjs
CHANGED
|
@@ -8803,7 +8803,7 @@ ${argsDigest}`;const signature=sign3(null,Buffer.from(payload),scheduledJobDeliv
|
|
|
8803
8803
|
ELSE FALSE
|
|
8804
8804
|
END`}async function isDeploymentExecutorLifecycleAuthority(input2){const slotPort=deploymentExecutorSlotPort(input2.slotId);if(!slotPort||!input2.nodeId.trim())return false;try{if(await holdsActiveSlot(input2.db,input2.nodeId,slotPort))return true;if(!input2.allowAcceptanceCandidate)return false;const leaseRows=rowsFromUnknown4(await input2.db.execute(acceptanceLeasePortSql(input2.nodeId)));return leaseRows[0]?.leasePort===slotPort}catch{return false}}async function holdsActiveSlot(db,nodeId,slotPort){const nodeRows=rowsFromUnknown4(await db.execute(sql97`SELECT active_port AS "activePort" FROM platform_nodes WHERE id = ${nodeId} LIMIT 1`));const nodePort=nodeRows[0]?.activePort;if(nodePort!=null&&String(nodePort).trim()){return String(nodePort).trim()===slotPort}const runtimeRows=rowsFromUnknown4(await db.execute(sql97`SELECT value AS "activePort" FROM platform_runtime_state WHERE key = 'active_platform_port' LIMIT 1`));const runtimePort=runtimeRows[0]?.activePort;return runtimePort!=null&&String(runtimePort).trim()===slotPort}var DEPLOYMENT_ACCEPTANCE_LEASE_KEY_PREFIX;var init_deployment_executor_lifecycle_authority=__esm({"../platform/src/deployment-executor-lifecycle-authority.ts"(){"use strict";DEPLOYMENT_ACCEPTANCE_LEASE_KEY_PREFIX="deployment_acceptance_candidate"}});import{createHash as createHash43,randomUUID as randomUUID32}from"node:crypto";import{and as and13,desc as desc4,eq as eq16,inArray as inArray8,sql as sql98}from"drizzle-orm";var init_app_release_finalize_store=__esm({"../platform/src/app-release-finalize-store.ts"(){"use strict";init_schema();init_app_release_retention();init_app_release_attempt_failure_store();init_app_serving_route_static_store();init_app_serving_route_receipt_store();init_app_serving_route_convergence_poll();init_deployment_executor_lifecycle_authority()}});import{createHash as createHash44,randomUUID as randomUUID33}from"node:crypto";import{and as and14,eq as eq17}from"drizzle-orm";function appReleaseAttemptOwnedActivation(row,component,deploymentId){if(deploymentId===null||row.state!=="activating")return false;const owner=component==="backend"?row.backendDeploymentId:row.staticDeploymentId;return owner===deploymentId}function appReleaseAttemptAcceptsComponentDeployment(row,component,deploymentId=null){let expected;try{expected=JSON.parse(row.expectedComponentsJson)}catch{return false}if(!expected.includes(component))return false;if(appReleaseAttemptOwnedActivation(row,component,deploymentId))return true;const sourceRequired=expected.includes("backend");const sourceStored=row.sourceObjectRef!==null;return row.state==="source_stored"||row.state==="deploying"||row.state==="received"&&!sourceRequired&&!sourceStored}function fail10(code){throw new Error(code)}async function recordAppReleaseComponent(input2){await input2.db.transaction(async tx=>{const row=(await tx.select().from(appReleaseAttempts).where(and14(eq17(appReleaseAttempts.id,input2.attemptId),eq17(appReleaseAttempts.appId,input2.appId),eq17(appReleaseAttempts.environment,input2.environment))))[0];if(!row)return fail10("APP_RELEASE_ATTEMPT_NOT_FOUND");const expected=JSON.parse(row.expectedComponentsJson);if(!expected.includes(input2.component))return fail10("APP_RELEASE_COMPONENT_UNEXPECTED");const owned=appReleaseAttemptOwnedActivation(row,input2.component,input2.deploymentId);if(!appReleaseAttemptAcceptsComponentDeployment(row,input2.component,input2.deploymentId)){return fail10("APP_RELEASE_STATE_CONFLICT")}const field=input2.component==="backend"?row.backendDeploymentId:row.staticDeploymentId;if(field&&field!==input2.deploymentId)return fail10("APP_RELEASE_COMPONENT_CONFLICT");if(input2.component==="static"&&!input2.staticGenerationRef){return fail10("APP_RELEASE_STATIC_GENERATION_REQUIRED")}if(input2.component==="static"&&!input2.artifactReceipt)return fail10("APP_RELEASE_ARTIFACT_REQUIRED");if(owned){if(input2.component==="static"&&input2.staticGenerationRef!==row.staticGenerationRef){return fail10("APP_RELEASE_ARTIFACT_CONFLICT")}return}if(input2.artifactReceipt){const expectedKind=input2.component==="backend"?"backend_artifact":"static_artifact";if(input2.artifactReceipt.kind!==expectedKind){return fail10("APP_RELEASE_ARTIFACT_INVALID")}const objectRows=await tx.select().from(appReleaseObjects).where(and14(eq17(appReleaseObjects.attemptId,input2.attemptId),eq17(appReleaseObjects.kind,expectedKind)));const existingObject=objectRows[0];if(existingObject&&existingObject.objectRef!==input2.artifactReceipt.ref){return fail10("APP_RELEASE_ARTIFACT_CONFLICT")}if(!existingObject){await tx.insert(appReleaseObjects).values({id:randomUUID33(),appId:input2.appId,attemptId:input2.attemptId,kind:expectedKind,objectRef:input2.artifactReceipt.ref,sha256:input2.artifactReceipt.sha256,bytes:input2.artifactReceipt.bytes,state:"live"})}}await tx.update(appReleaseAttempts).set({state:"deploying",reservedBytes:0,...input2.component==="backend"?{backendDeploymentId:input2.deploymentId}:{staticDeploymentId:input2.deploymentId,staticGenerationRef:input2.staticGenerationRef},updatedAt:new Date}).where(eq17(appReleaseAttempts.id,input2.attemptId))})}var init_app_release_store=__esm({"../platform/src/app-release-store.ts"(){"use strict";init_schema();init_app_release_unbound_attempt_lease();init_app_release_finalize_store();init_app_release_attempt_failure_store()}});function resolveDeploymentReleaseEnvironment(input2){if(input2.releaseEnvironment==="dev"||input2.releaseEnvironment==="prod"){return input2.releaseEnvironment}return input2.executionEnvironment==="dev"||input2.executionEnvironment==="prod"?input2.executionEnvironment:null}function releaseBindingMatchesExecutionScope(input2){if(input2.releaseEnvironment!=="dev"&&input2.releaseEnvironment!=="prod")return false;if(input2.component==="static"&&input2.executionEnvironment!=="static")return false;if(input2.component==="backend"&&input2.executionEnvironment==="static")return false;return input2.executionEnvironment==="static"||input2.executionEnvironment===input2.releaseEnvironment}function deploymentRecoveryScopesOverlap(input2){const candidateReleaseEnvironment=resolveDeploymentReleaseEnvironment({executionEnvironment:input2.candidateExecutionEnvironment,releaseEnvironment:input2.candidateReleaseEnvironment});const incomingReleaseEnvironment=resolveDeploymentReleaseEnvironment({executionEnvironment:input2.incomingExecutionEnvironment,releaseEnvironment:input2.incomingReleaseEnvironment});const candidateStaticUnbound=input2.candidateExecutionEnvironment==="static"&&candidateReleaseEnvironment===null;const incomingStaticUnbound=input2.incomingExecutionEnvironment==="static"&&incomingReleaseEnvironment===null;if(candidateStaticUnbound||incomingStaticUnbound)return true;if(incomingReleaseEnvironment!==null){return candidateReleaseEnvironment===incomingReleaseEnvironment}return input2.candidateExecutionEnvironment===input2.incomingExecutionEnvironment}var init_deployment_release_scope=__esm({"../platform/src/deployment-release-scope.ts"(){"use strict";init_app_release_store()}});import{mkdtemp,mkdir as mkdir4,rm,writeFile as writeFile3}from"node:fs/promises";import{tmpdir as tmpdir5}from"node:os";import{join as join15}from"node:path";async function withTarBufferFile(bundle,operation){const workDir=await mkdtemp(join15(tmpdir5(),"gencow-tar-buffer-"));const archivePath2=join15(workDir,"bundle.tar.gz");try{await writeFile3(archivePath2,bundle,{flag:"wx",mode:384});return await operation(archivePath2)}finally{await rm(workDir,{recursive:true,force:true})}}var init_tar_buffer_extract=__esm({"../platform/src/tar-buffer-extract.ts"(){"use strict";init_index_min()}});import{createHash as createHash45}from"node:crypto";import{createReadStream}from"node:fs";import{chmod as chmod2,cp,lstat as lstat2,mkdir as mkdir5,open as open4,readdir as readdir3}from"node:fs/promises";import{relative as relative11,resolve as resolve56,sep as sep2}from"node:path";function normalizePath2(path5){const normalized=path5.replace(/^\.\//u,"").replace(/\/+$/u,"").normalize("NFC");if(!normalized||Buffer.byteLength(normalized)>1024||normalized!==path5.replace(/^\.\//u,"").replace(/\/+$/u,"")||normalized.startsWith("/")||/^[A-Za-z]:/u.test(normalized)||normalized.includes("\\")||/[\u0000-\u001f\u007f]/u.test(normalized)||normalized.split("/").length>32||normalized.split("/").some(part=>!part||part==="."||part==="..")){throw new Error("unsafe artifact path")}return normalized}function hashArtifactClosure(files){const canonical=[...files].sort((left,right)=>left.path<right.path?-1:left.path>right.path?1:0);return createHash45("sha256").update(canonical.map(file2=>`${file2.path}\0${file2.size}\0${file2.sha256}
|
|
8805
8805
|
`).join("")).digest("hex")}function validateArtifactFiles(files){const seen=new Set;const validated=files.map(file2=>{const keys2=Object.keys(file2).sort();const path5=normalizePath2(file2.path);if(keys2.join(",")!=="path,sha256,size"||seen.has(path5)||!Number.isSafeInteger(file2.size)||file2.size<0||!/^[a-f0-9]{64}$/u.test(file2.sha256)){throw new Error("invalid artifact file metadata")}seen.add(path5);return{path:path5,size:file2.size,sha256:file2.sha256}});return validated.sort((left,right)=>left.path<right.path?-1:left.path>right.path?1:0)}async function hashArtifactFile(path5){const hash9=createHash45("sha256");for await(const chunk2 of createReadStream(path5))hash9.update(chunk2);return hash9.digest("hex")}async function walk(root2,directory=root2){const files=[];const dirs=[directory];for(const entry of await readdir3(directory,{withFileTypes:true})){const path5=resolve56(directory,entry.name);const stats=await lstat2(path5);if(stats.isSymbolicLink())throw new Error("artifact link is forbidden");if(stats.isDirectory()){const nested=await walk(root2,path5);files.push(...nested.files);dirs.push(...nested.dirs);continue}if(!stats.isFile())throw new Error("artifact special file is forbidden");const artifactPath=relative11(root2,path5).split(sep2).join("/");files.push({path:artifactPath,size:stats.size,sha256:await hashArtifactFile(path5)})}return{files,dirs}}function sameFiles(left,right){return JSON.stringify(validateArtifactFiles(left))===JSON.stringify(validateArtifactFiles(right))}async function extractVerifiedArtifact(bundle,target,expectedFiles){const files=validateArtifactFiles(expectedFiles);const allowedFiles=new Set(files.map(file2=>file2.path));await mkdir5(target,{recursive:true,mode:448});await withTarBufferFile(bundle,async archivePath2=>{await fo({cwd:target,file:archivePath2,strict:true,noChmod:true,filter(entryPath,entry){const entryType=entry.type;const isDirectory=entryType==="Directory";if(isDirectory&&(entryPath==="."||entryPath==="./"))return false;const path5=normalizePath2(isDirectory?entryPath.replace(/\/+$/u,""):entryPath);if(isDirectory)return false;if(entryType!=="File"&&entryType!=="OldFile")throw new Error("unsafe artifact entry");if(!allowedFiles.has(path5))throw new Error("unexpected artifact file");return true}})});await verifyArtifactTree(target,files,false)}async function verifyArtifactTree(root2,expectedFiles,sealed){const tree=await walk(root2);if(!sameFiles(tree.files,expectedFiles))throw new Error("artifact file closure mismatch");if(!sealed)return;for(const file2 of tree.files){if(((await lstat2(resolve56(root2,file2.path))).mode&511)!==292){throw new Error("artifact file is not sealed")}}for(const directory of tree.dirs){if(((await lstat2(directory)).mode&511)!==365){throw new Error("artifact directory is not sealed")}}}async function syncPath(path5){const handle=await open4(path5,"r");try{await handle.sync()}finally{await handle.close()}}async function syncArtifactTree(root2){const tree=await walk(root2);for(const file2 of tree.files)await syncPath(resolve56(root2,file2.path));for(const directory of tree.dirs.reverse())await syncPath(directory)}async function sealArtifactTree(root2){const tree=await walk(root2);for(const file2 of tree.files)await chmod2(resolve56(root2,file2.path),292);for(const directory of tree.dirs.reverse())await chmod2(directory,365);await verifyArtifactTree(root2,tree.files,true)}async function makeArtifactTreeWritable(root2){const tree=await walk(root2);for(const directory of tree.dirs)await chmod2(directory,493);for(const file2 of tree.files)await chmod2(resolve56(root2,file2.path),420)}async function copyVerifiedArtifact(source,target,expectedFiles){await cp(source,target,{recursive:true,force:false,errorOnExist:true});await verifyArtifactTree(target,expectedFiles,false)}async function syncArtifactPath(path5){await syncPath(path5)}var init_app_deployment_artifact_filesystem=__esm({"../platform/src/app-deployment-artifact-filesystem.ts"(){"use strict";init_index_min();init_tar_buffer_extract()}});function parseArtifactMetadata(bytes2){if(bytes2.length===0||bytes2.length>MAX_ARTIFACT_METADATA_BYTES){throw new Error("artifact metadata size is invalid")}const parsed=JSON.parse(bytes2.toString("utf8"));if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)||Object.keys(parsed).sort().join(",")!==FIELDS2.join(",")||parsed.version!==1||!SHA2566.test(parsed.appScopeSha256??"")||!SHA2566.test(parsed.artifactSha256??"")||!SHA2566.test(parsed.rawArchiveSha256??"")||!Number.isSafeInteger(parsed.rawArchiveBytes)||Number(parsed.rawArchiveBytes)<=0||Number(parsed.rawArchiveBytes)>MAX_RAW_ARCHIVE_BYTES||!Array.isArray(parsed.files)||parsed.files.length>1e4){throw new Error("artifact metadata is invalid")}return{version:1,appScopeSha256:parsed.appScopeSha256,artifactSha256:parsed.artifactSha256,rawArchiveSha256:parsed.rawArchiveSha256,rawArchiveBytes:parsed.rawArchiveBytes,files:validateArtifactFiles(parsed.files)}}var SHA2566,FIELDS2,MAX_ARTIFACT_METADATA_BYTES,MAX_RAW_ARCHIVE_BYTES;var init_app_deployment_artifact_metadata=__esm({"../platform/src/app-deployment-artifact-metadata.ts"(){"use strict";init_app_deployment_artifact_filesystem();SHA2566=/^[a-f0-9]{64}$/u;FIELDS2=["version","appScopeSha256","artifactSha256","rawArchiveSha256","rawArchiveBytes","files"].sort();MAX_ARTIFACT_METADATA_BYTES=16*1024*1024;MAX_RAW_ARCHIVE_BYTES=100*1024*1024}});import{createHash as createHash46,randomUUID as randomUUID34}from"node:crypto";import{chmod as chmod3,mkdir as mkdir6,mkdtemp as mkdtemp2,readFile as readFile5,rename as rename3,rm as rm2,stat as stat6,writeFile as writeFile4}from"node:fs/promises";import{dirname as dirname14,join as join16}from"node:path";function fail11(code,cause,stage,pathContext,failureKind,filesystemCode){throw new AppDeploymentArtifactError(code,cause===void 0?void 0:{cause},stage,filesystemCode,pathContext,failureKind)}function filesystemErrorCode(error62){const code=error62?.code;return typeof code==="string"&&/^[A-Z0-9_]{2,16}$/u.test(code)?code:void 0}function failStoreUnavailable(error62,stage,pathContext,failureKind="store_unavailable"){const code=filesystemErrorCode(error62);return fail11("ARTIFACT_STORE_UNAVAILABLE",error62,stage,pathContext,failureKind,code)}function failArtifactAbsent(error62,stage){return fail11("ARTIFACT_NOT_FOUND",error62,stage,"artifact_leaf","artifact_absent",filesystemErrorCode(error62))}function failArtifactIntegrity(cause,stage,pathContext,filesystemCode=filesystemErrorCode(cause)){return fail11("ARTIFACT_INTEGRITY_MISMATCH",cause,stage,pathContext,"integrity_invalid",filesystemCode)}function failFilesystemObservation(error62,stage,pathContext,missingKind){const code=filesystemErrorCode(error62);if(code==="ENOENT"&&missingKind==="artifact_absent")return failArtifactAbsent(error62,stage);if(code==="ENOENT"&&missingKind==="integrity_invalid"){return failArtifactIntegrity(error62,stage,pathContext,code)}if(code==="ENOENT"&&missingKind==="scope_missing"){return fail11("ARTIFACT_NOT_FOUND",error62,stage,pathContext,"scope_missing",code)}if(code&&["EISDIR","ENOTDIR","ELOOP"].includes(code)&&["artifact_leaf","ready_marker","metadata","bundle","source","cache_entry"].includes(pathContext)){return failArtifactIntegrity(error62,stage,pathContext,code)}return failStoreUnavailable(error62,stage,pathContext,"store_unavailable")}function sha2567(value2){return createHash46("sha256").update(value2).digest("hex")}function appScopeSha256(scope){const appId=String(scope.appId);if(typeof scope.appId==="number"&&(!Number.isSafeInteger(scope.appId)||scope.appId<=0)||!appId||appId.length>128||/[\u0000-\u001f\u007f]/u.test(appId)||!/^[a-z][a-z0-9_-]{0,31}$/u.test(scope.environment)){return fail11("ARTIFACT_ADMISSION_INVALID")}return sha2567(JSON.stringify([typeof scope.appId,appId,scope.environment]))}function parseArtifactRef(scope,artifactRef){const match2=ARTIFACT_REF2.exec(artifactRef);const expectedScope=appScopeSha256(scope);if(!match2){return fail11("ARTIFACT_ADMISSION_INVALID",void 0,"artifact_lookup","artifact_reference","reference_invalid")}if(match2[1]!==expectedScope){return fail11("ARTIFACT_NOT_FOUND",void 0,"artifact_lookup","artifact_reference","scope_mismatch")}return{appScopeSha256:match2[1],artifactSha256:match2[2]}}function artifactResult(path5,artifactRef,metadata){return{artifactRef,artifactSha256:metadata.artifactSha256,artifactBytes:metadata.rawArchiveBytes,rawArchiveSha256:metadata.rawArchiveSha256,artifactPath:path5,sourcePath:join16(path5,"source")}}async function isRenameCollision(error62,target){const code=error62?.code;if(code==="EEXIST"||code==="ENOTEMPTY")return true;if(code!=="EACCES")return false;return stat6(target).then(stats=>stats.isDirectory()).catch(()=>false)}async function finalizePublishedArtifact(target,parent,artifactSha256){const readyPath=join16(parent,`${artifactSha256}.ready`);await chmod3(target,365);try{await writeFile4(readyPath,artifactSha256,{mode:292,flag:"wx"});await syncArtifactPath(readyPath)}catch(error62){if(error62?.code!=="EEXIST")throw error62;if(await readFile5(readyPath,"utf8")!==artifactSha256){return fail11("ARTIFACT_INTEGRITY_MISMATCH")}}await syncArtifactPath(parent)}async function removeStaging(path5){await makeArtifactTreeWritable(path5).catch(()=>{});await rm2(path5,{recursive:true,force:true})}function createAppDeploymentArtifactStore(options){const statPath=options.statImpl??stat6;async function read(input2){const ref=parseArtifactRef(input2,input2.artifactRef);const path5=join16(options.artifactRoot,"v1",ref.appScopeSha256,ref.artifactSha256);const readyPath=join16(options.artifactRoot,"v1",ref.appScopeSha256,`${ref.artifactSha256}.ready`);const scopes=[{path:options.artifactRoot,context:"store_root"},{path:join16(options.artifactRoot,"v1"),context:"store_version"},{path:dirname14(path5),context:"app_scope"}];for(const scope of scopes){let scopeStats;try{scopeStats=await statPath(scope.path)}catch(error62){return failFilesystemObservation(error62,"artifact_store_scope",scope.context,"scope_missing")}if(!scopeStats.isDirectory()){return failFilesystemObservation(Object.assign(new Error,{code:"ENOTDIR"}),"artifact_store_scope",scope.context)}}let artifactStats;try{artifactStats=await statPath(path5)}catch(error62){if(filesystemErrorCode(error62)==="ENOENT"){for(const scope of scopes){let currentScope;try{currentScope=await statPath(scope.path)}catch(scopeError){return failFilesystemObservation(scopeError,"artifact_store_scope",scope.context,"scope_missing")}if(!currentScope.isDirectory()){return failFilesystemObservation(Object.assign(new Error,{code:"ENOTDIR"}),"artifact_store_scope",scope.context)}}}return failFilesystemObservation(error62,"artifact_lookup","artifact_leaf","artifact_absent")}if(!artifactStats.isDirectory()){return failArtifactIntegrity(void 0,"artifact_lookup","artifact_leaf")}let marker;let markerStats;try{marker=await readFile5(readyPath,"utf8");markerStats=await stat6(readyPath)}catch(error62){return failFilesystemObservation(error62,"artifact_lookup","ready_marker","integrity_invalid")}if(marker!==ref.artifactSha256||(markerStats.mode&511)!==292){return failArtifactIntegrity(void 0,"artifact_lookup","ready_marker")}let metadataStats;try{const metadataPath=join16(path5,"artifact.json");metadataStats=await stat6(metadataPath)}catch(error62){return failFilesystemObservation(error62,"artifact_verification","metadata","integrity_invalid")}if(metadataStats.size===0||metadataStats.size>MAX_ARTIFACT_METADATA_BYTES){return failArtifactIntegrity(void 0,"artifact_verification","metadata")}let metadataBytes;try{metadataBytes=await readFile5(join16(path5,"artifact.json"))}catch(error62){return failFilesystemObservation(error62,"artifact_verification","metadata","integrity_invalid")}let metadata;try{metadata=parseArtifactMetadata(metadataBytes)}catch(error62){return failArtifactIntegrity(error62,"artifact_verification","metadata")}const bundlePath=join16(path5,"source.tar.gz");let bundleStats;let bundleSha256;try{bundleStats=await stat6(bundlePath);bundleSha256=await hashArtifactFile(bundlePath)}catch(error62){return failFilesystemObservation(error62,"artifact_verification","bundle","integrity_invalid")}let artifactSealStats;try{artifactSealStats=await stat6(path5)}catch(error62){return failFilesystemObservation(error62,"artifact_verification","artifact_leaf","integrity_invalid")}if(metadata.appScopeSha256!==ref.appScopeSha256||metadata.artifactSha256!==ref.artifactSha256||hashArtifactClosure(metadata.files)!==metadata.artifactSha256||bundleStats.size!==metadata.rawArchiveBytes||bundleSha256!==metadata.rawArchiveSha256||(artifactSealStats.mode&511)!==365||(metadataStats.mode&511)!==292||(bundleStats.mode&511)!==292){return failArtifactIntegrity(void 0,"artifact_verification","metadata")}try{await verifyArtifactTree(join16(path5,"source"),metadata.files,true)}catch(error62){if(filesystemErrorCode(error62)){return failFilesystemObservation(error62,"artifact_verification","source","integrity_invalid")}return failArtifactIntegrity(error62,"artifact_verification","source")}return artifactResult(path5,input2.artifactRef,metadata)}async function publish(input2){const scopeHash=appScopeSha256(input2);let files;try{files=validateArtifactFiles(input2.admission.files);if(sha2567(input2.bundle)!==input2.admission.recomputed.rawArchiveSha256||input2.bundle.length!==input2.admission.recomputed.compressedBytes||hashArtifactClosure(files)!==input2.admission.sourceClosureSha256){return fail11("ARTIFACT_ADMISSION_INVALID")}}catch(error62){if(error62 instanceof AppDeploymentArtifactError)throw error62;return fail11("ARTIFACT_ADMISSION_INVALID")}const artifactSha256=input2.admission.sourceClosureSha256;const artifactRef=`app-artifact-v1.${scopeHash}.${artifactSha256}`;const parent=join16(options.artifactRoot,"v1",scopeHash);const target=join16(parent,artifactSha256);const tempRoot=join16(options.artifactRoot,".tmp");let rootStats;try{rootStats=await stat6(options.artifactRoot)}catch(error62){if(filesystemErrorCode(error62)==="ENOENT")rootStats=null;else return failFilesystemObservation(error62,"artifact_publish","store_root")}if(rootStats&&!rootStats.isDirectory()){return failFilesystemObservation(Object.assign(new Error,{code:"ENOTDIR"}),"artifact_publish","store_root")}try{await mkdir6(parent,{recursive:true,mode:448});await mkdir6(tempRoot,{recursive:true,mode:448})}catch(error62){return failFilesystemObservation(error62,"artifact_publish","store_root")}let staging;try{staging=await mkdtemp2(join16(tempRoot,`${scopeHash}-${randomUUID34()}-`))}catch(error62){return failFilesystemObservation(error62,"artifact_publish","store_root")}const metadata={version:1,appScopeSha256:scopeHash,artifactSha256,rawArchiveSha256:input2.admission.recomputed.rawArchiveSha256,rawArchiveBytes:input2.bundle.length,files};try{const sourcePath=join16(staging,"source");await extractVerifiedArtifact(input2.bundle,sourcePath,files);await writeFile4(join16(staging,"source.tar.gz"),input2.bundle,{mode:384,flag:"wx"});await writeFile4(join16(staging,"artifact.json"),JSON.stringify(metadata),{mode:384,flag:"wx"});await syncArtifactTree(sourcePath);await syncArtifactPath(join16(staging,"source.tar.gz"));await syncArtifactPath(join16(staging,"artifact.json"));await sealArtifactTree(sourcePath);await chmod3(join16(staging,"source.tar.gz"),292);await chmod3(join16(staging,"artifact.json"),292);try{await rename3(staging,target)}catch(error62){if(!await isRenameCollision(error62,target))throw error62;await removeStaging(staging)}await finalizePublishedArtifact(target,parent,artifactSha256);return await read({...input2,artifactRef})}catch(error62){await removeStaging(staging).catch(()=>{});if(error62 instanceof AppDeploymentArtifactError)throw error62;if(filesystemErrorCode(error62)){return failFilesystemObservation(error62,"artifact_publish","artifact_leaf")}return fail11("ARTIFACT_INTEGRITY_MISMATCH")}}async function materialize(input2){const artifact=await read(input2);const ref=parseArtifactRef(input2,input2.artifactRef);if(!input2.nodeId||input2.nodeId.length>128||/[\u0000-\u001f\u007f]/u.test(input2.nodeId)){return fail11("ARTIFACT_CACHE_INTEGRITY_MISMATCH")}const nodeScope=sha2567(input2.nodeId);const parent=join16(options.cacheRoot,"v1",nodeScope,ref.appScopeSha256);const target=join16(parent,ref.artifactSha256);for(const scopePath of[options.cacheRoot,join16(options.cacheRoot,"v1"),join16(options.cacheRoot,"v1",nodeScope),parent]){let scopeStats;try{scopeStats=await stat6(scopePath)}catch(error62){if(filesystemErrorCode(error62)!=="ENOENT"){return failFilesystemObservation(error62,"artifact_cache","cache_scope")}try{await mkdir6(scopePath,{recursive:true,mode:448});scopeStats=await stat6(scopePath)}catch(createError){return failFilesystemObservation(createError,"artifact_cache","cache_scope","scope_missing")}}if(!scopeStats.isDirectory()){return failFilesystemObservation(Object.assign(new Error,{code:"ENOTDIR"}),"artifact_cache","cache_scope")}}let metadata;try{metadata=parseArtifactMetadata(await readFile5(join16(artifact.artifactPath,"artifact.json")))}catch(error62){if(filesystemErrorCode(error62)){return failFilesystemObservation(error62,"artifact_verification","metadata","integrity_invalid")}return failArtifactIntegrity(error62,"artifact_verification","metadata")}try{const targetStats=await stat6(target);if(targetStats.isDirectory()){await chmod3(target,365);await verifyArtifactTree(target,metadata.files,true);return{...artifact,runtimePath:target,nodeScope}}return failArtifactIntegrity(void 0,"artifact_cache","cache_entry")}catch(error62){if(filesystemErrorCode(error62)!=="ENOENT"){if(filesystemErrorCode(error62)){return failFilesystemObservation(error62,"artifact_cache","cache_entry","integrity_invalid")}return fail11("ARTIFACT_CACHE_INTEGRITY_MISMATCH",error62,"artifact_cache","cache_entry","integrity_invalid")}}const staging=join16(parent,`.${ref.artifactSha256}-${randomUUID34()}`);try{await copyVerifiedArtifact(artifact.sourcePath,staging,metadata.files);await syncArtifactTree(staging);await sealArtifactTree(staging);await chmod3(staging,493);try{await rename3(staging,target)}catch(error62){if(!await isRenameCollision(error62,target))throw error62;await removeStaging(staging)}await chmod3(target,365);await syncArtifactPath(parent);await verifyArtifactTree(target,metadata.files,true);return{...artifact,runtimePath:target,nodeScope}}catch(error62){await removeStaging(staging).catch(()=>{});if(error62 instanceof AppDeploymentArtifactError)throw error62;if(filesystemErrorCode(error62)){return failFilesystemObservation(error62,"artifact_cache","cache_entry","integrity_invalid")}return fail11("ARTIFACT_CACHE_INTEGRITY_MISMATCH",error62,"artifact_cache","cache_entry","integrity_invalid")}}async function deleteArtifact(input2){const ref=parseArtifactRef(input2,input2.artifactRef);const parent=join16(options.artifactRoot,"v1",ref.appScopeSha256);const target=join16(parent,ref.artifactSha256);const readyPath=join16(parent,`${ref.artifactSha256}.ready`);await makeArtifactTreeWritable(target).catch(error62=>{if(error62.code!=="ENOENT")throw error62});await rm2(target,{recursive:true,force:true});await rm2(readyPath,{force:true})}return{publish,read,materialize,delete:deleteArtifact}}var ARTIFACT_REF2,AppDeploymentArtifactError;var init_app_deployment_artifact_store=__esm({"../platform/src/app-deployment-artifact-store.ts"(){"use strict";init_app_deployment_artifact_filesystem();init_app_deployment_artifact_metadata();ARTIFACT_REF2=/^app-artifact-v1\.([a-f0-9]{64})\.([a-f0-9]{64})$/u;AppDeploymentArtifactError=class extends Error{constructor(code,options,stage,filesystemCode,pathContext,failureKind){super(code,options);this.code=code;this.stage=stage;this.filesystemCode=filesystemCode;this.pathContext=pathContext;this.failureKind=failureKind;this.name="AppDeploymentArtifactError"}code;stage;filesystemCode;pathContext;failureKind}}});function createBlankIndexScanner(){let bomPossible=true;let bomMatched=0;let openerMatched=0;let state2="text";let hasContent=false;return{push(chunk2){for(const byte of chunk2){if(hasContent)return;if(bomPossible){if(byte===UTF8_BOM[bomMatched]){bomMatched+=1;if(bomMatched===UTF8_BOM.length)bomPossible=false;continue}if(bomMatched>0){hasContent=true;return}bomPossible=false}switch(state2){case"text":if(openerMatched>0){if(byte===COMMENT_OPENER[openerMatched]){openerMatched+=1;if(openerMatched===COMMENT_OPENER.length){openerMatched=0;state2="commentStart"}continue}hasContent=true;return}if(byte===LT){openerMatched=1;continue}if(!ASCII_WHITESPACE.has(byte)){hasContent=true;return}continue;case"commentStart":if(byte===GT)state2="text";else state2=byte===DASH?"commentStartDash":"comment";continue;case"commentStartDash":if(byte===DASH)state2="commentEnd";else if(byte===GT)state2="text";else state2="comment";continue;case"comment":if(byte===DASH)state2="commentEndDash";continue;case"commentEndDash":state2=byte===DASH?"commentEnd":"comment";continue;case"commentEnd":if(byte===GT)state2="text";else if(byte===BANG)state2="commentEndBang";else if(byte!==DASH)state2="comment";continue;case"commentEndBang":if(byte===GT)state2="text";else state2=byte===DASH?"commentEndDash":"comment";continue}}},finish(){if(hasContent||bomMatched===1||bomMatched===2)return false;if(openerMatched>0)return false;return true}}}function staticSiteEntrypointRejection(entry){if(!entry||!entry.isFile)return STATIC_SITE_ENTRYPOINT_MISSING_CODE;if(entry.size===0||entry.blank)return STATIC_ARTIFACT_INDEX_EMPTY_CODE;return null}var STATIC_SITE_ENTRYPOINT_MISSING_CODE,STATIC_ARTIFACT_INDEX_EMPTY_CODE,STATIC_INDEX_BLANK_SCAN_LIMIT_BYTES,UTF8_BOM,COMMENT_OPENER,ASCII_WHITESPACE,LT,GT,BANG,DASH;var init_static_site_entrypoint_policy=__esm({"../platform/src/static-site-entrypoint-policy.ts"(){"use strict";STATIC_SITE_ENTRYPOINT_MISSING_CODE="STATIC_SITE_ENTRYPOINT_REQUIRED";STATIC_ARTIFACT_INDEX_EMPTY_CODE="STATIC_ARTIFACT_INDEX_EMPTY";STATIC_INDEX_BLANK_SCAN_LIMIT_BYTES=64*1024;UTF8_BOM=[239,187,191];COMMENT_OPENER=[60,33,45,45];ASCII_WHITESPACE=new Set([32,9,10,13,12,11]);LT=60;GT=62;BANG=33;DASH=45}});import{createHash as createHash47}from"node:crypto";function fail12(code,details){throw new DeployArchiveAdmissionError(code,details)}function normalizeEntryPath(rawPath,directory){if(!rawPath||Buffer.byteLength(rawPath)>1024||/[\u0000-\u001f\u007f]/.test(rawPath)||rawPath.includes("\\")){return fail12("DEPLOY_ARCHIVE_PATH_INVALID")}const withoutDot=rawPath.replace(/^\.\//,"");const normalized=(directory?withoutDot.replace(/\/+$/,""):withoutDot).normalize("NFC");const segments=normalized.split("/");if(!normalized||normalized!==(directory?withoutDot.replace(/\/+$/,""):withoutDot)||normalized.startsWith("/")||/^[A-Za-z]:/.test(normalized)||segments.some(segment=>!segment||segment==="."||segment==="..")){return fail12("DEPLOY_ARCHIVE_PATH_INVALID")}return normalized}function sha2568(value2){return createHash47("sha256").update(value2).digest("hex")}function equalContractValue(left,right){return JSON.stringify(left)===JSON.stringify(right)}function isMetadataFile(path5){return SELECTED_METADATA.has(path5)||PROJECT_AUTH_SCHEMA_PATTERN.test(path5)||LEGACY_AUTH_SCHEMA_PATTERN.test(path5)}function findRootIndexEntry(inspection){const entry=inspection.files.find(file2=>file2.path==="index.html");return entry?{isFile:true,size:entry.size,blank:inspection.rootIndexBlank===true}:void 0}function findRuntimeEntry(files){return files.find(file2=>RUNTIME_ENTRY_PATTERN.test(file2.path))?.path??null}async function inspectDeployArchive(bundle,overrides={}){const limits={...DEFAULT_LIMITS2,...overrides};if(bundle.length===0||bundle.length>limits.maxCompressedBytes){return fail12("DEPLOY_ARCHIVE_COMPRESSED_SIZE_LIMIT")}const paths=new Map;const knownDirectoryPrefixes=new Set;const caseFolded=new Map;const files=[];let rootIndexBlank=null;const metadata=new Map;let entryCount=0;let uncompressedBytes=0;let streamError=null;const inspectArchiveFile=archivePath2=>Ct({file:archivePath2,strict:true,onentry(entry){const isDirectory=entry.type==="Directory";if(!isDirectory&&entry.type!=="File"&&entry.type!=="OldFile"){streamError??=new DeployArchiveAdmissionError("DEPLOY_ARCHIVE_ENTRY_TYPE_INVALID");entry.resume();return}if(isDirectory&&(entry.path==="."||entry.path==="./")){entry.resume();return}let path5;try{path5=normalizeEntryPath(entry.path,isDirectory)}catch(error62){streamError??=error62;entry.resume();return}entryCount+=1;if(entryCount>limits.maxEntries)streamError??=new DeployArchiveAdmissionError("DEPLOY_ARCHIVE_ENTRY_LIMIT");const segments=path5.split("/");if(segments.length>limits.maxDepth){streamError??=new DeployArchiveAdmissionError("DEPLOY_ARCHIVE_DEPTH_LIMIT")}const prefixes=segments.map((_4,index27)=>segments.slice(0,index27+1).join("/"));const hasCaseFoldCollision=prefixes.some(prefix=>{const known=caseFolded.get(prefix.toLocaleLowerCase("en-US"));return known!==void 0&&known!==prefix});if(paths.has(path5)||hasCaseFoldCollision){streamError??=new DeployArchiveAdmissionError("DEPLOY_ARCHIVE_PATH_COLLISION")}const ancestors=prefixes.slice(0,-1);for(const ancestor of ancestors){if(paths.get(ancestor)==="file"){streamError??=new DeployArchiveAdmissionError("DEPLOY_ARCHIVE_PATH_COLLISION")}}if(!isDirectory&&knownDirectoryPrefixes.has(path5)){streamError??=new DeployArchiveAdmissionError("DEPLOY_ARCHIVE_PATH_COLLISION")}paths.set(path5,isDirectory?"directory":"file");for(const ancestor of ancestors)knownDirectoryPrefixes.add(ancestor);for(const prefix of prefixes){const folded=prefix.toLocaleLowerCase("en-US");if(!caseFolded.has(folded))caseFolded.set(folded,prefix)}if(isDirectory){entry.resume();return}uncompressedBytes+=entry.size;if(uncompressedBytes>limits.maxUncompressedBytes){streamError??=new DeployArchiveAdmissionError("DEPLOY_ARCHIVE_SIZE_LIMIT")}if(uncompressedBytes/bundle.length>limits.maxCompressionRatio){streamError??=new DeployArchiveAdmissionError("DEPLOY_ARCHIVE_COMPRESSION_LIMIT")}const hash9=createHash47("sha256");const chunks=[];let actualBytes=0;const isRootIndex=path5==="index.html";const blankScanner=isRootIndex&&entry.size<=STATIC_INDEX_BLANK_SCAN_LIMIT_BYTES?createBlankIndexScanner():null;const selectedMetadata=isMetadataFile(path5);const retain=selectedMetadata&&entry.size<=MAX_METADATA_BYTES;if(selectedMetadata&&!retain){streamError??=new DeployArchiveAdmissionError("DEPLOY_ARCHIVE_METADATA_LIMIT")}entry.on("data",chunk2=>{actualBytes+=chunk2.length;hash9.update(chunk2);blankScanner?.push(chunk2);if(retain)chunks.push(Buffer.from(chunk2))});entry.on("end",()=>{if(actualBytes!==entry.size){streamError??=new DeployArchiveAdmissionError("DEPLOY_ARCHIVE_SIZE_MISMATCH")}files.push({path:path5,size:actualBytes,sha256:hash9.digest("hex")});if(isRootIndex)rootIndexBlank=blankScanner?.finish()??false;if(retain)metadata.set(path5,Buffer.concat(chunks))})}});try{await withTarBufferFile(bundle,inspectArchiveFile)}catch{const observedError2=streamError;return fail12(observedError2?.code??"DEPLOY_ARCHIVE_FORMAT_INVALID")}const observedError=streamError;if(observedError)return fail12(observedError.code);const lockfiles=[...LOCKFILES].filter(([path5])=>metadata.has(path5));const unsupportedLockfiles=[...UNSUPPORTED_LOCKFILES].filter(path5=>metadata.has(path5));if(unsupportedLockfiles.length>0){return fail12("DEPLOY_ARCHIVE_PACKAGE_MANAGER_UNSUPPORTED",{files:unsupportedLockfiles.sort()})}if(lockfiles.length>1)return fail12("DEPLOY_ARCHIVE_DEPENDENCY_AMBIGUOUS");const projectAuth=[...metadata.keys()].filter(path5=>PROJECT_AUTH_SCHEMA_PATTERN.test(path5)).sort();const legacyAuth=[...metadata.keys()].filter(path5=>LEGACY_AUTH_SCHEMA_PATTERN.test(path5)).sort();if(projectAuth.length>1||legacyAuth.length>1||projectAuth.length&&legacyAuth.length){return fail12("DEPLOY_ARCHIVE_AUTH_SCHEMA_AMBIGUOUS",{files:[...projectAuth,...legacyAuth].sort()})}const authSchema=projectAuth[0]?{mode:"project",path:projectAuth[0]}:legacyAuth[0]?{mode:"legacy",path:legacyAuth[0]}:{mode:"builtin",path:null};files.sort((left,right)=>left.path<right.path?-1:left.path>right.path?1:0);const sourceClosureSha256=sha2568(files.map(file2=>`${file2.path}\0${file2.size}\0${file2.sha256}
|
|
8806
|
-
`).join(""));const lockfile=lockfiles[0];const packageBytes=metadata.get(PACKAGE_MANIFEST);let packageManagerDeclaration=null;if(packageBytes){try{const parsed=JSON.parse(packageBytes.toString("utf8"));packageManagerDeclaration=typeof parsed.packageManager==="string"?parsed.packageManager.trim():null}catch{return fail12("DEPLOY_ARCHIVE_PACKAGE_MANIFEST_INVALID")}}if(findRuntimeEntry(files)&&packageBytes){const dependencyLock=inspectPnpmDependencyLock({packageJsonText:packageBytes.toString("utf8"),pnpmLockText:lockfile?metadata.get(lockfile[0])?.toString("utf8"):null});if(!dependencyLock.ok){return fail12(dependencyLock.code,{files:[...dependencyLock.files]})}}const migrationBytes=metadata.get(MIGRATION_MANIFEST);let artifactIdentitySha256=null;let migrationCliVersion=null;if(migrationBytes){try{const manifest=JSON.parse(migrationBytes.toString("utf8"));artifactIdentitySha256=typeof manifest.artifactIdentitySha256==="string"?manifest.artifactIdentitySha256:null;migrationCliVersion=typeof manifest.cliVersion==="string"?manifest.cliVersion:null}catch{return fail12("MIGRATION_BUNDLE_MANIFEST_INVALID")}}const recomputed={rawArchiveSha256:sha2568(bundle),compressedBytes:bundle.length,uncompressedBytes,entryCount,fileCount:files.length,authSchema,dependencies:{packageManager:lockfile?.[1]??"none",manifestSha256:packageBytes?sha2568(packageBytes):null,lockfileSha256:lockfile?sha2568(metadata.get(lockfile[0])):null},migrationBundle:{manifestSha256:migrationBytes?sha2568(migrationBytes):null,requiredCapability:migrationBytes?artifactIdentitySha256?MIGRATION_ARTIFACT_IDENTITY_CAPABILITY_V2:MIGRATION_BUNDLE_CAPABILITY_V1:"none",...artifactIdentitySha256?{artifactIdentitySha256}:{}}};return{recomputed,sourceClosureSha256,files,rootIndexBlank,packageManagerDeclaration,...migrationCliVersion?{migrationCliVersion}:{}}}function admitInspectedDeployArchive(input2){const hasRuntimeEntry=findRuntimeEntry(input2.inspection.files);if(input2.expectedRuntime==="server"){if(input2.inspection.recomputed.dependencies.manifestSha256===null){return fail12("DEPLOY_ARCHIVE_PACKAGE_MANIFEST_REQUIRED")}if(input2.inspection.recomputed.dependencies.packageManager!=="pnpm"){return fail12("DEPLOY_ARCHIVE_PNPM_LOCK_REQUIRED")}if(input2.inspection.packageManagerDeclaration!==APPROVED_PACKAGE_MANAGER){return fail12("DEPLOY_ARCHIVE_PACKAGE_MANAGER_VERSION_UNSUPPORTED")}if(!hasRuntimeEntry)return fail12("DEPLOY_ARCHIVE_RUNTIME_ENTRY_REQUIRED")}else{if(hasRuntimeEntry)return fail12("DEPLOY_ARCHIVE_RUNTIME_CONFLICT");const entrypointRejection=staticSiteEntrypointRejection(findRootIndexEntry(input2.inspection));if(entrypointRejection)return fail12(entrypointRejection)}if(input2.claim.declaredRuntime!==input2.expectedRuntime||input2.claim.sourceBundleSha256!==input2.inspection.recomputed.rawArchiveSha256||!equalContractValue(input2.claim.authSchema,input2.inspection.recomputed.authSchema)||!equalContractValue(input2.claim.dependencies,input2.inspection.recomputed.dependencies)||!equalContractValue(input2.claim.migrationBundle,input2.inspection.recomputed.migrationBundle)){return fail12("DEPLOY_CLAIM_MISMATCH")}return{...input2.inspection,contractHash:hashAdmittedDeployClaimV1(input2.claim)}}async function admitDeployArchive(input2){const inspected=await inspectDeployArchiveForRuntime(input2);return admitInspectedDeployArchive({inspection:inspected,claim:input2.claim,expectedRuntime:input2.expectedRuntime})}async function inspectDeployArchiveForRuntime(input2){const inspected=await inspectDeployArchive(input2.bundle,input2.limits);const hasRuntimeEntry=findRuntimeEntry(inspected.files);if(input2.expectedRuntime==="server"){if(inspected.recomputed.dependencies.manifestSha256===null){return fail12("DEPLOY_ARCHIVE_PACKAGE_MANIFEST_REQUIRED")}if(!hasRuntimeEntry)return fail12("DEPLOY_ARCHIVE_RUNTIME_ENTRY_REQUIRED");if(inspected.packageManagerDeclaration!==APPROVED_PACKAGE_MANAGER){return fail12("DEPLOY_ARCHIVE_PACKAGE_MANAGER_VERSION_UNSUPPORTED")}}else{if(hasRuntimeEntry)return fail12("DEPLOY_ARCHIVE_RUNTIME_CONFLICT");const entrypointRejection=staticSiteEntrypointRejection(findRootIndexEntry(inspected));if(entrypointRejection)return fail12(entrypointRejection)}return inspected}var PACKAGE_MANIFEST,APPROVED_PACKAGE_MANAGER,MIGRATION_MANIFEST,LOCKFILES,UNSUPPORTED_LOCKFILES,CANONICAL_DEPLOY_BACKEND_ROOT,PROJECT_AUTH_SCHEMA_PATTERN,LEGACY_AUTH_SCHEMA_PATTERN,RUNTIME_ENTRY_PATTERN,SELECTED_METADATA,DEFAULT_LIMITS2,MAX_METADATA_BYTES,DeployArchiveAdmissionError;var init_deploy_archive_admission=__esm({"../platform/src/deploy-archive-admission.ts"(){"use strict";init_index_min();init_dist();init_deploy_contract_admission();init_tar_buffer_extract();init_static_site_entrypoint_policy();PACKAGE_MANIFEST="package.json";APPROVED_PACKAGE_MANAGER="pnpm@10.33.0";MIGRATION_MANIFEST=".gencow/migration-bundle-manifest.json";LOCKFILES=new Map([["pnpm-lock.yaml","pnpm"]]);UNSUPPORTED_LOCKFILES=new Set(["package-lock.json","npm-shrinkwrap.json","bun.lock","bun.lockb","yarn.lock"]);CANONICAL_DEPLOY_BACKEND_ROOT="gencow";PROJECT_AUTH_SCHEMA_PATTERN=new RegExp(`^${CANONICAL_DEPLOY_BACKEND_ROOT}/schema-auth\\.(?:ts|js)$`,"u");LEGACY_AUTH_SCHEMA_PATTERN=new RegExp(`^${CANONICAL_DEPLOY_BACKEND_ROOT}/(?:auth-schema\\.(?:ts|js)|generated/auth-schema\\.(?:ts|js))$`,"u");RUNTIME_ENTRY_PATTERN=new RegExp(`^${CANONICAL_DEPLOY_BACKEND_ROOT}/index\\.(?:ts|js)$`,"u");SELECTED_METADATA=new Set([PACKAGE_MANIFEST,MIGRATION_MANIFEST,...LOCKFILES.keys(),...UNSUPPORTED_LOCKFILES]);DEFAULT_LIMITS2={maxCompressedBytes:100*1024*1024,maxUncompressedBytes:200*1024*1024,maxEntries:1e4,maxDepth:32,maxCompressionRatio:100};MAX_METADATA_BYTES=1024*1024;DeployArchiveAdmissionError=class extends Error{constructor(code,details){super(code);this.code=code;this.details=details;this.name="DeployArchiveAdmissionError"}code;details}}});import{resolve as resolve57}from"node:path";import{and as and15,asc as asc2,eq as eq18,isNull as isNull7,ne as ne8,or as or7}from"drizzle-orm";function fail13(code,status,cause,publicDetails){throw new DeploymentAdmissionError(code,status,publicDetails,cause===void 0?void 0:{cause})}function mapArchiveAdmissionError(error62){console.warn("[deploy-admission] archive rejected",{code:error62.code,files:error62.details?.files??[]});const code=error62.code==="DEPLOY_ARCHIVE_AUTH_SCHEMA_AMBIGUOUS"?"AUTH_SCHEMA_PROVENANCE_AMBIGUOUS":error62.code;return fail13(code,400,error62,error62.details)}async function inspectDeploymentArchiveForRuntime(input2){try{return await inspectDeployArchiveForRuntime(input2)}catch(error62){if(error62 instanceof DeployArchiveAdmissionError)return mapArchiveAdmissionError(error62);throw error62}}async function admitDeploymentArchiveContract(input2){try{return await admitDeployArchive({bundle:input2.bundle,claim:input2.protocol.claim,expectedRuntime:input2.expectedRuntime})}catch(error62){if(error62 instanceof DeployArchiveAdmissionError)return mapArchiveAdmissionError(error62);throw error62}}function compareStableVersions(left,right){const parse4=value2=>value2.split("-")[0].split(".").map(Number);const[leftParts,rightParts]=[parse4(left),parse4(right)];for(let index27=0;index27<3;index27+=1){if(leftParts[index27]!==rightParts[index27])return leftParts[index27]-rightParts[index27]}return 0}function parseDeploymentProtocolRequest(input2){const encodedClaim=input2.getHeader(DEPLOY_CLAIM_HEADER);const protocol=input2.getHeader(DEPLOY_PROTOCOL_HEADER);const cliVersion=input2.getHeader(DEPLOY_CLI_VERSION_HEADER);if(!encodedClaim){if(protocol||cliVersion)return fail13("DEPLOY_CLAIM_HEADER_REQUIRED",400);if(input2.requireVersionedProtocol)return fail13("DEPLOY_CLI_UPGRADE_REQUIRED",426);return{lane:"legacy-observe",claim:null,contractHash:null}}let claim2;try{claim2=parseDeployClaimV1Header(encodedClaim)}catch(error62){return fail13("DEPLOY_CLAIM_INVALID",400,error62)}if(protocol!==String(claim2.protocolVersion)||cliVersion!==claim2.generatedBy.version){return fail13("DEPLOY_PROTOCOL_HEADER_MISMATCH",400)}if(compareStableVersions(cliVersion,MIN_DEPLOY_CLI_VERSION)<0){return fail13("DEPLOY_CLI_UPGRADE_REQUIRED",426)}if(claim2.declaredRuntime!==input2.expectedRuntime){return fail13("DEPLOY_RUNTIME_DECLARATION_MISMATCH",400)}return{lane:"v1-enforce",claim:claim2,contractHash:hashAdmittedDeployClaimV1(claim2)}}function deploymentProtocolResponseHeaders(lane){return{"X-Gencow-Deploy-Min-Protocol":"1","X-Gencow-Min-CLI-Version":MIN_DEPLOY_CLI_VERSION,"X-Gencow-Deploy-Lane":lane}}async function findCandidateCleanupDebt(input2){const unresolved=await input2.db.select({deploymentId:deployments.id}).from(deployments).leftJoin(appRuntimeInstances,and15(eq18(appRuntimeInstances.deploymentId,deployments.id),eq18(appRuntimeInstances.appId,deployments.appId))).where(and15(eq18(deployments.appId,input2.appId),eq18(deployments.env,input2.env),or7(and15(eq18(deployments.status,"failed"),eq18(deployments.candidateCleanupFailureCode,"RUNTIME_CANDIDATE_CLEANUP_INCOMPLETE")),and15(eq18(deployments.executorState,"recovery_required"),eq18(deployments.candidateCleanupFailureCode,"CANDIDATE_CLEANUP_PENDING"))),or7(isNull7(appRuntimeInstances.instanceId),ne8(appRuntimeInstances.state,"stopped"),isNull7(appRuntimeInstances.candidateCleanupCompletedAt)))).orderBy(asc2(deployments.id)).limit(1);return unresolved[0]??null}async function hasCandidateCleanupDebt(input2){return Boolean(await findCandidateCleanupDebt(input2))}async function assertCandidateCleanupTerminal(input2){if(await hasCandidateCleanupDebt(input2))fail13("RUNTIME_CANDIDATE_CLEANUP_INCOMPLETE",503)}async function findRecoveryRequiredDeployment(input2){const rows8=await input2.db.select({deploymentId:deployments.id,correlationId:deployments.correlationId,executionEnvironment:deployments.env,releaseEnvironment:appReleaseAttempts.environment,failureStage:deployments.failureStage,failureCode:deployments.failureCode}).from(deployments).leftJoin(appReleaseAttempts,and15(eq18(appReleaseAttempts.id,deployments.executorReleaseAttemptId),eq18(appReleaseAttempts.appId,deployments.appId))).where(and15(eq18(deployments.appId,input2.appId),eq18(deployments.status,"pending"),eq18(deployments.executorState,"recovery_required"))).orderBy(asc2(deployments.id));for(const row of rows8){if(!deploymentRecoveryScopesOverlap({candidateExecutionEnvironment:row.executionEnvironment,candidateReleaseEnvironment:row.releaseEnvironment,incomingExecutionEnvironment:input2.env,incomingReleaseEnvironment:input2.releaseEnvironment})){continue}if(row.executionEnvironment!=="static"&&row.failureStage==="route"&&row.failureCode===COMMITTED_ROUTE_BLOCKED_CODE){const exempt=await input2.db.select({id:deployments.id}).from(deployments).where(and15(eq18(deployments.id,row.deploymentId),eq18(deployments.appId,input2.appId),committedRouteBlockedSupersedable(input2.db))).limit(1);if(exempt[0])continue}if(await deploymentSupersededByNewerCommit({db:input2.db,appId:input2.appId,deploymentId:row.deploymentId})){continue}return{deploymentId:row.deploymentId,correlationId:row.correlationId}}return null}async function assertDeploymentRecoveryAdmissionOpen(input2){const blocker=await findRecoveryRequiredDeployment(input2);if(!blocker)return;const error62=new DeploymentAdmissionError("DEPLOYMENT_EXECUTOR_RECOVERY_REQUIRED",503);Object.assign(error62,{blockingOperationId:blocker.deploymentId,blockingCorrelationId:blocker.correlationId});throw error62}async function preallocateDeploymentRequest(input2){try{await assertCandidateCleanupTerminal({db:input2.db,appId:input2.appId,env:input2.env});await assertDeploymentRecoveryAdmissionOpen({db:input2.db,appId:input2.appId,env:input2.env,releaseEnvironment:input2.releaseEnvironment});return await preallocateDeploymentAttempt({db:input2.db,appId:input2.appId,env:input2.env,bundle:input2.bundle,declaredRuntime:input2.expectedRuntime,...input2.protocol.claim?{requestId:input2.protocol.claim.requestId,protocolVersion:input2.protocol.claim.protocolVersion,contractJson:JSON.stringify(input2.protocol.claim),contractHash:input2.protocol.contractHash}:{}})}catch(error62){if(error62?.message==="DEPLOY_IDEMPOTENCY_CONFLICT"){return fail13("DEPLOY_IDEMPOTENCY_CONFLICT",409,error62)}throw error62}}function classifyDeploymentReplay(attempt){if(!attempt.replayed)return{kind:"new"};if(attempt.status==="running"&&attempt.controlPlaneState==="active"){return{kind:"active"}}if(attempt.status==="failed")return{kind:"failed"};if(["received","admitted","materializing","candidate","ready"].includes(attempt.controlPlaneState)){return{kind:"resume",state:attempt.controlPlaneState}}return{kind:"in-progress"}}var DEPLOY_CLAIM_HEADER,DEPLOY_PROTOCOL_HEADER,DEPLOY_CLI_VERSION_HEADER,MIN_DEPLOY_CLI_VERSION,DeploymentAdmissionError;var init_deployment_request_admission=__esm({"../platform/src/deployment-request-admission.ts"(){"use strict";init_schema();init_deployment_committed_route_contract();init_deployment_superseded_by_newer_commit();init_deployment_release_scope();init_app_deployment_artifact_store();init_deploy_archive_admission();init_deploy_contract_admission();init_deployment_attempt_store();DEPLOY_CLAIM_HEADER="x-gencow-deploy-claim";DEPLOY_PROTOCOL_HEADER="x-gencow-deploy-protocol";DEPLOY_CLI_VERSION_HEADER="x-gencow-cli-version";MIN_DEPLOY_CLI_VERSION="0.1.189";DeploymentAdmissionError=class extends Error{constructor(code,status,publicDetails,options){super(code,options);this.code=code;this.status=status;this.publicDetails=publicDetails;this.name="DeploymentAdmissionError"}code;status;publicDetails}}});function isExactDependencyVersion(value2){return typeof value2==="string"&&value2.length<=128&&VERSION2.test(value2)}function isSafeDependencyDeclaration(value2){return typeof value2==="string"&&value2.length>0&&new TextEncoder().encode(value2).length<=256&&!CONTROL.test(value2)&&!/(?:password|secret|token|authorization)/iu.test(value2)&&(value2==="latest"||/^(?:workspace:)?[0-9vVxX*~^<>=|. +\-]+$/u.test(value2.replace(/[+-][0-9A-Za-z][0-9A-Za-z.-]*/gu,"")))}function safeDependencyDeclaration(value2){return isSafeDependencyDeclaration(value2)?value2:REDACTED_DECLARATION}function parseComparableVersion(value2){if(!isExactDependencyVersion(value2))return null;const match2=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(value2);if(!match2)return null;const prerelease=match2[4]?.split(".")??[];if(prerelease.some(id=>/^0\d+$/u.test(id)))return null;return{core:match2.slice(1,4).map(BigInt),prerelease}}function compareLockedToBom(locked,bom){const a=parseComparableVersion(locked);const b2=parseComparableVersion(bom);if(!a||!b2)return"unknown";for(const[index27,kind]of["major","minor","patch"].entries()){if(a.core[index27]!==b2.core[index27])return a.core[index27]>b2.core[index27]?"newer":kind}for(let i=0;i<Math.max(a.prerelease.length,b2.prerelease.length);i++){if(!a.prerelease.length)return"newer";if(!b2.prerelease.length)return"prerelease";const left=a.prerelease[i];const right=b2.prerelease[i];if(left===right)continue;if(left===void 0)return"prerelease";if(right===void 0)return"newer";const leftNumeric=/^\d+$/u.test(left);const rightNumeric=/^\d+$/u.test(right);if(leftNumeric!==rightNumeric)return leftNumeric?"prerelease":"newer";const newer=leftNumeric?BigInt(left)>BigInt(right):left>right;return newer?"newer":"prerelease"}return locked===bom?"matches":"build_metadata"}function formatDependencyVersionTable(packages,{includeExplanation=true}={}){const rows8=[["Package","package.json","Locked","Runtime BOM","Locked vs BOM"],...packages.map(p2=>[p2.packageName,safeDependencyDeclaration(p2.declared),parseComparableVersion(p2.lockedVersion)?p2.lockedVersion:"unknown",p2.bomVersion,DIFFERENCE_LABELS[compareLockedToBom(p2.lockedVersion,p2.bomVersion)]])];const widths=rows8[0].map((_4,column)=>Math.max(...rows8.map(row=>row[column].length)));const format=row=>row.map((cell,column)=>cell.padEnd(widths[column])).join(" | ").trimEnd();return[format(rows8[0]),widths.map(width=>"-".repeat(width)).join("-+-"),...rows8.slice(1).map(format),...includeExplanation?["Locked: pnpm-lock.yaml resolution, not a check of node_modules; unknown means unavailable."]:[]]}function formatLockedBomGuidance(packages,{includeStaleSummary=true}={}){const differences=packages.map(p2=>compareLockedToBom(p2.lockedVersion,p2.bomVersion));const mismatch=differences.some(difference=>difference!=="matches"&&difference!=="unknown");const older=differences.some(difference=>["major","minor","patch","prerelease"].includes(difference));return[...mismatch?["Local development may behave differently from hosted deployments because dependency versions differ.","Aligning local dependencies with the Runtime BOM helps keep behavior consistent."]:[],...older?[...includeStaleSummary?["Some lockfile resolutions are behind the hosted runtime."]:[],"Preview: gencow runtime sync --dry-run --install","Refresh and install: gencow runtime sync --install (preserves latest declarations)."]:[]]}var VERSION2,CONTROL,REDACTED_DECLARATION,DIFFERENCE_LABELS;var init_dependency_version_report=__esm({"../shared/dist/src/dependency-version-report.js"(){"use strict";VERSION2=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u;CONTROL=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u;REDACTED_DECLARATION="[redacted declaration]";DIFFERENCE_LABELS={unknown:"Unknown",matches:"Matches",newer:"Newer than hosted runtime",major:"Major mismatch \u2014 possible compatibility issues",minor:"Minor mismatch",patch:"Patch mismatch",prerelease:"Prerelease mismatch",build_metadata:"Build metadata differs (same precedence)"}}});function object3(value2){return value2!==null&&typeof value2==="object"&&!Array.isArray(value2)}function isPackage(value2){return typeof value2==="string"&&bytes(value2)<=214&&PACKAGE.test(value2)}function isMismatch(value2){return value2==="non_major_mismatch"||value2==="major_mismatch"}function isPolicy(value2){return value2==="warn"||value2==="reject-major"||value2==="reject-all"}function isManagedBomDiagnostic(value2){if(!object3(value2)||value2.schemaVersion!==1||typeof value2.releaseId!=="string"||!RELEASE.test(value2.releaseId)||!isPolicy(value2.policy)||value2.decision!=="warn"&&value2.decision!=="block"||!Array.isArray(value2.packages)||value2.packages.length>MAX_MANAGED_BOM_PACKAGES||!Number.isSafeInteger(value2.totalPackages)||!Number.isSafeInteger(value2.omittedPackages)||value2.omittedPackages<0||value2.totalPackages<1||value2.totalPackages!==value2.packages.length+value2.omittedPackages)return false;const names=new Set;for(const row of value2.packages){if(!object3(row)||!isPackage(row.packageName)||names.has(row.packageName)||!isExactDependencyVersion(row.bomVersion)||row.lockedVersion!==void 0&&!isExactDependencyVersion(row.lockedVersion)||!isMismatch(row.classification)||typeof row.declarationRedacted!=="boolean"||(row.declarationRedacted?row.declared!==REDACTED:!isSafeDependencyDeclaration(row.declared)))return false;names.add(row.packageName)}try{return bytes(JSON.stringify(value2))<=MAX_MANAGED_BOM_DIAGNOSTIC_BYTES}catch{return false}}function buildManagedBomWarning(input2){const warning={code:input2.abort?"MANAGED_BOM_MISMATCH":"MANAGED_BOM_WARNING",phase:"dependencies",message:input2.abort?"Managed dependency policy blocked deployment.":"Managed dependency policy emitted a warning.",count:1};if(!RELEASE.test(input2.releaseId)||!input2.mismatches.length)return warning;const rows8=new Map;const names=new Set(input2.mismatches.map(row=>row.packageName));for(const row of[...input2.mismatches].sort((a,b2)=>a.packageName<b2.packageName?-1:a.packageName>b2.packageName?1:0)){if(rows8.size>=MAX_MANAGED_BOM_PACKAGES||rows8.has(row.packageName)||!isPackage(row.packageName)||!Object.hasOwn(input2.managedPackages,row.packageName)||input2.managedPackages[row.packageName]!==row.bomVersion||!isExactDependencyVersion(row.bomVersion)||!isMismatch(row.classification))continue;const safe=isSafeDependencyDeclaration(row.declared);rows8.set(row.packageName,{packageName:row.packageName,declared:safe?row.declared:REDACTED,declarationRedacted:!safe,bomVersion:row.bomVersion,...isExactDependencyVersion(row.lockedVersion)?{lockedVersion:row.lockedVersion}:{},classification:row.classification})}const managedBom={schemaVersion:1,releaseId:input2.releaseId,policy:input2.policy,decision:input2.abort?"block":"warn",packages:[...rows8.values()],totalPackages:names.size,omittedPackages:names.size-rows8.size};if(isManagedBomDiagnostic(managedBom))warning.managedBom=managedBom;return warning}function publicManagedBomWarning(value2){if(!object3(value2)||value2.code!=="MANAGED_BOM_WARNING"&&value2.code!=="MANAGED_BOM_MISMATCH")return null;const blocked2=value2.code==="MANAGED_BOM_MISMATCH";const result3={code:value2.code,phase:"dependencies",message:blocked2?"Managed dependency policy blocked deployment.":"Managed dependency policy emitted a warning.",count:Number.isSafeInteger(value2.count)&&value2.count>0?Math.min(1e3,value2.count):1};if(isManagedBomDiagnostic(value2.managedBom)&&value2.managedBom.decision===(blocked2?"block":"warn")){const d=value2.managedBom;result3.managedBom={schemaVersion:1,releaseId:d.releaseId,policy:d.policy,decision:d.decision,packages:d.packages.map(p2=>({packageName:p2.packageName,declared:p2.declared,declarationRedacted:p2.declarationRedacted,bomVersion:p2.bomVersion,...p2.lockedVersion!==void 0?{lockedVersion:p2.lockedVersion}:{},classification:p2.classification})),totalPackages:d.totalPackages,omittedPackages:d.omittedPackages}}return result3}var MAX_MANAGED_BOM_PACKAGES,MAX_MANAGED_BOM_DIAGNOSTIC_BYTES,RELEASE,PACKAGE,REDACTED,bytes;var init_managed_bom_diagnostic=__esm({"../shared/dist/src/managed-bom-diagnostic.js"(){"use strict";init_dependency_version_report();MAX_MANAGED_BOM_PACKAGES=128;MAX_MANAGED_BOM_DIAGNOSTIC_BYTES=128*1024;RELEASE=/^sha256:[a-f0-9]{64}$/u;PACKAGE=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u;REDACTED="[redacted declaration]";bytes=value2=>new TextEncoder().encode(value2).length}});function hasVerifiedDeploymentExecutorCompletion(operation){if(operation.executorState!=="completed"||!operation.receiptJson||!operation.receiptSha256){return false}try{const receipt=readVerifiedDeploymentExecutorReceipt(operation);return receipt?.phase==="completed"&&DEPLOYMENT_EXECUTOR_COMPLETED_RECEIPT_CODES.has(receipt.code)&&operation.executorState==="completed"}catch{return false}}function readVerifiedDeploymentExecutorReceipt(operation){if(!operation.receiptJson||!operation.receiptSha256)return null;try{const receipt=sanitizeDeploymentExecutorReceipt(JSON.parse(operation.receiptJson));return hashDeploymentExecutorReceipt(receipt)===operation.receiptSha256?receipt:null}catch{return null}}var POST_COMMIT_ROUTE_ACK_RECOVERED_CODE,RUNTIME_COMMITTED_ACTIVATION_ROUTE_REPAIRED_CODE,STALE_STATIC_LIVE_RELEASE_CONVERGED_CODE,DEPLOYMENT_EXECUTOR_COMPLETED_RECEIPT_CODES;var init_deployment_executor_completion_contract=__esm({"../platform/src/deployment-executor-completion-contract.ts"(){"use strict";init_deployment_executor_operation();POST_COMMIT_ROUTE_ACK_RECOVERED_CODE="PLATFORM_DEPLOYMENT_EXECUTOR_POST_COMMIT_ROUTE_ACK_RECOVERED";RUNTIME_COMMITTED_ACTIVATION_ROUTE_REPAIRED_CODE="RUNTIME_COMMITTED_ACTIVATION_ROUTE_REPAIRED";STALE_STATIC_LIVE_RELEASE_CONVERGED_CODE="PLATFORM_STALE_STATIC_LIVE_RELEASE_CONVERGED";DEPLOYMENT_EXECUTOR_COMPLETED_RECEIPT_CODES=new Set(["PLATFORM_DEPLOYMENT_EXECUTOR_COMPLETED",POST_COMMIT_ROUTE_ACK_RECOVERED_CODE,RUNTIME_COMMITTED_ACTIVATION_ROUTE_REPAIRED_CODE,STALE_STATIC_LIVE_RELEASE_CONVERGED_CODE])}});import{and as and16,eq as eq19}from"drizzle-orm";function mergeWarningSnapshot(old,warning){const conflict3=old?.managedBom&&warning.managedBom&&JSON.stringify(old.managedBom)!==JSON.stringify(warning.managedBom);if(old?.managedBomConflict||warning.managedBomConflict||conflict3){if(conflict3)console.warn("MANAGED_BOM_DIAGNOSTIC_INCOMPLETE");return{code:warning.code,phase:warning.phase,message:warning.message,count:Math.max(old?.count??0,warning.count),managedBomConflict:true}}return{...old?.managedBom?old:warning,count:Math.max(old?.count??0,warning.count)}}function normalizeWarningSnapshots(input2){if(!Array.isArray(input2)||input2.length>1e3)throw new Error("DEPLOYMENT_EXECUTOR_RECEIPT_WARNING_INVALID");const normalized=new Map;for(let offset=0;offset<input2.length;offset+=MAX_RECEIPT_WARNINGS){for(const warning of sanitizeDeploymentExecutorWarnings(input2.slice(offset,offset+MAX_RECEIPT_WARNINGS))){const key2=warningKey(warning);normalized.set(key2,{...warning,count:Math.min(1e3,warning.count+(normalized.get(key2)?.count??0))})}}const snapshots=new Map;for(const warning of input2){const key2=warningKey(warning);snapshots.set(key2,mergeWarningSnapshot(snapshots.get(key2),warning))}return[...normalized.values()].map(warning=>({...snapshots.get(warningKey(warning)),count:warning.count}))}function mergeDeploymentExecutorWarnings(prior=[],next=[]){const warnings=new Map;for(const warning of[...normalizeWarningSnapshots(prior),...normalizeWarningSnapshots(next)]){const key2=warningKey(warning);warnings.set(key2,mergeWarningSnapshot(warnings.get(key2),warning))}const incomplete=[...warnings.values()].some(w2=>w2.code===INCOMPLETE_WARNING.code);const retained=[...warnings.values()].filter(w2=>w2.code!==INCOMPLETE_WARNING.code);retained.sort((a,b2)=>Number(REQUIRED_WARNING_CODES.has(b2.code))-Number(REQUIRED_WARNING_CODES.has(a.code))||warningKey(a).localeCompare(warningKey(b2)));const overflow=incomplete||retained.length>MAX_RECEIPT_WARNINGS;return sanitizeDeploymentExecutorWarnings(overflow?[...retained.slice(0,MAX_RECEIPT_WARNINGS-1),{...INCOMPLETE_WARNING}]:retained)}async function readStoredDeploymentReceipt(input2){const rows8=await input2.db.select({receiptJson:deployments.executorReceiptJson,receiptSha256:deployments.executorReceiptSha256}).from(deployments).where(and16(eq19(deployments.id,input2.deploymentId),eq19(deployments.appId,input2.appId))).limit(1);return rows8[0]}function warningsFromStoredDeploymentReceipt(row){if(!row||row.receiptJson===null&&row.receiptSha256===null)return[];const verified=readVerifiedDeploymentExecutorReceipt(row);if(verified)return verified.warnings??[];if(row.receiptSha256===null&&row.receiptJson!==null){try{const legacy=sanitizeDeploymentExecutorReceipt(JSON.parse(row.receiptJson));if(!legacy.warnings?.length)return[]}catch{}}throw new Error("DEPLOYMENT_EXECUTOR_WARNING_RECEIPT_UNVERIFIED")}async function carryDeploymentExecutorWarnings(input2){let prior;let deferredSince;try{const row=await readStoredDeploymentReceipt(input2);prior=warningsFromStoredDeploymentReceipt(row);deferredSince=row?readVerifiedDeploymentExecutorReceipt(row)?.deferredSince:void 0}catch(error62){if(error62 instanceof Error&&error62.message==="DEPLOYMENT_EXECUTOR_WARNING_RECEIPT_UNVERIFIED"&&input2.receipt.phase==="recovery_required"&&input2.receipt.code==="DEPLOYMENT_EXECUTOR_LEASE_RECORD_INVALID")return input2.receipt;throw error62}const warnings=mergeDeploymentExecutorWarnings(prior,input2.receipt.warnings);const nonterminal=!["completed","failed","recovery_required"].includes(input2.receipt.phase);return{...input2.receipt,...nonterminal&&deferredSince&&!input2.receipt.deferredSince?{deferredSince}:{},...warnings.length?{warnings}:{}}}function publicDeploymentExecutorWarnings(warnings){return warnings.map(w2=>publicManagedBomWarning(w2)??{code:w2.code,phase:w2.phase,message:w2.message,count:w2.count})}var INCOMPLETE_WARNING,REQUIRED_WARNING_CODES,warningKey;var init_deployment_executor_warning_receipt=__esm({"../platform/src/deployment-executor-warning-receipt.ts"(){"use strict";init_schema();init_managed_bom_diagnostic();init_deployment_executor_completion_contract();init_deployment_executor_operation();INCOMPLETE_WARNING={code:"DEPLOYMENT_WARNINGS_INCOMPLETE",phase:"diagnostics",message:"Some deployment warnings were omitted because the receipt reached its capacity.",count:1};REQUIRED_WARNING_CODES=new Set(["MANAGED_BOM_WARNING","MANAGED_BOM_MISMATCH","ROUTE_CONVERGENCE_BLOCKED","PLATFORM_STALE_ROUTE_ONLY_RESUME","PLATFORM_STALE_PROJECTION_DEFERRED","PLATFORM_STALE_RELEASE_PROJECTION_SKIPPED"]);warningKey=warning=>`${warning.phase}:${warning.code}:${warning.message}`}});import{and as and17,asc as asc3,eq as eq20,gt as gt5,inArray as inArray9,lte as lte4,ne as ne9,notExists,or as or8,sql as sql99}from"drizzle-orm";import{alias as alias2}from"drizzle-orm/pg-core";async function findActiveAppDeploymentExecutor(input2){return(await input2.db.select({id:deployments.id,correlationId:deployments.correlationId}).from(deployments).where(and17(eq20(deployments.appId,input2.appId),eq20(deployments.status,"pending"),inArray9(deployments.executorState,[...NONTERMINAL_DEPLOYMENT_EXECUTOR_STATES]))).limit(1))[0]??null}function attemptConditions(attempt){return and17(eq20(deployments.id,attempt.deploymentId),eq20(deployments.appId,attempt.appId),eq20(deployments.env,attempt.env),eq20(deployments.attemptId,attempt.attemptId))}async function enqueueDeploymentExecutorOperation(input2){const targetOwnerIdentity=parseDeploymentExecutorOwnerId(input2.targetOwnerId);if(!/^deployment-payload-v1\.[a-zA-Z0-9_-]{8,160}\.[a-f0-9]{64}$/u.test(input2.payloadRef)||!/^[a-z0-9][a-z0-9-]{0,62}$/u.test(input2.targetNodeId)||!/^[a-z0-9][a-z0-9-]{0,31}$/u.test(input2.targetSlotId)||!/^[a-f0-9]{40}$/u.test(input2.targetRevision)||!targetOwnerIdentity||targetOwnerIdentity.nodeId!==input2.targetNodeId||targetOwnerIdentity.slotId!==input2.targetSlotId||targetOwnerIdentity.revision!==input2.targetRevision||!/^[a-f0-9]{64}$/u.test(input2.targetGenerationDigest)||!input2.appInstanceId||!input2.userId||input2.releaseAttemptId!==void 0&&input2.releaseAttemptId!==null&&!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u.test(input2.releaseAttemptId)||input2.localProjectDir!==void 0&&input2.localProjectDir!==null&&(input2.localProjectDir.length>4096||/[\0\r\n]/u.test(input2.localProjectDir)||input2.localProjectDir.normalize("NFC")!==input2.localProjectDir||!input2.localProjectDir.startsWith("/")&&!/^[A-Za-z]:[\\/]/u.test(input2.localProjectDir)||input2.localProjectDir.replaceAll("\\","/").split("/").includes(".."))||!Number.isSafeInteger(input2.payloadBytes)||input2.payloadBytes<=0||input2.payloadBytes>100*1024*1024){throw new Error("DEPLOYMENT_EXECUTOR_PAYLOAD_REF_INVALID")}const maxQueuedOperations=input2.maxQueuedOperations??DEFAULT_MAX_QUEUED_OPERATIONS;const maxQueuedBytes=input2.maxQueuedBytes??DEFAULT_MAX_QUEUED_BYTES;const maxUserOperations=input2.maxUserOperations??DEFAULT_MAX_USER_OPERATIONS;const maxUserBytes=input2.maxUserBytes??DEFAULT_MAX_USER_BYTES;if(!Number.isSafeInteger(maxQueuedOperations)||maxQueuedOperations<1||!Number.isSafeInteger(maxQueuedBytes)||maxQueuedBytes<input2.payloadBytes||!Number.isSafeInteger(maxUserOperations)||maxUserOperations<1||!Number.isSafeInteger(maxUserBytes)||maxUserBytes<input2.payloadBytes){throw new Error("DEPLOYMENT_EXECUTOR_CAPACITY_CONFIG_INVALID")}const[appBusy,capacityRows,userCapacityRows]=await Promise.all([findActiveAppDeploymentExecutor({db:input2.db,appId:input2.attempt.appId}),input2.db.select({count:sql99`count(*)::integer`,bytes:sql99`coalesce(sum(${deployments.executorPayloadBytes}), 0)::bigint`}).from(deployments).where(and17(eq20(deployments.status,"pending"),eq20(deployments.executorTargetNodeId,input2.targetNodeId),inArray9(deployments.executorState,[...NONTERMINAL_DEPLOYMENT_EXECUTOR_STATES]))),input2.db.select({count:sql99`count(*)::integer`,bytes:sql99`coalesce(sum(${deployments.executorPayloadBytes}), 0)::bigint`,blockingOperationId:sql99`min(${deployments.id})::integer`,blockingCorrelationId:sql99`(array_agg(${deployments.correlationId} ORDER BY ${deployments.id}))[1]`}).from(deployments).innerJoin(apps,eq20(apps.id,deployments.appId)).where(and17(eq20(deployments.status,"pending"),eq20(apps.userId,input2.userId),eq20(deployments.executorState,"queued")))]);if(appBusy){throw new DeploymentExecutorAdmissionError("DEPLOYMENT_EXECUTOR_APP_BUSY",409,appBusy.id,appBusy.correlationId)}const queuedCount=Number(capacityRows[0]?.count??0);const queuedBytes=Number(capacityRows[0]?.bytes??0);if(queuedCount>=maxQueuedOperations||queuedBytes+input2.payloadBytes>maxQueuedBytes){throw new DeploymentExecutorAdmissionError("DEPLOYMENT_EXECUTOR_QUEUE_FULL",429)}const userCount=Number(userCapacityRows[0]?.count??0);const userBytes=Number(userCapacityRows[0]?.bytes??0);if(userCount>=maxUserOperations||userBytes+input2.payloadBytes>maxUserBytes){const blockingOperationId=Number(userCapacityRows[0]?.blockingOperationId??0);const blockingCorrelationId=userCapacityRows[0]?.blockingCorrelationId??null;throw new DeploymentExecutorAdmissionError("DEPLOYMENT_EXECUTOR_USER_QUEUE_FULL",429,Number.isSafeInteger(blockingOperationId)&&blockingOperationId>0?blockingOperationId:void 0,typeof blockingCorrelationId==="string"?blockingCorrelationId:void 0)}const now=input2.now??new Date;const expectedControlPlaneState=input2.expectedControlPlaneState??"admitted";const rows8=await input2.db.update(deployments).set({executorState:"queued",executorTargetNodeId:input2.targetNodeId,executorTargetSlotId:input2.targetSlotId,executorTargetRevision:input2.targetRevision,executorTargetOwnerId:input2.targetOwnerId,executorTargetGenerationDigest:input2.targetGenerationDigest,executorAppInstanceId:input2.appInstanceId,executorPayloadBytes:input2.payloadBytes,executorPayloadRef:input2.payloadRef,executorReleaseAttemptId:input2.releaseAttemptId??null,executorLocalProjectDir:input2.localProjectDir??null,executorQueuedAt:now,executorUpdatedAt:now}).where(and17(attemptConditions(input2.attempt),eq20(deployments.status,"pending"),eq20(deployments.controlPlaneState,expectedControlPlaneState),eq20(deployments.executorState,"not_queued"))).returning({id:deployments.id});if(rows8.length!==1){const conflictRows=await input2.db.select({status:deployments.status,controlPlaneState:deployments.controlPlaneState,executorState:deployments.executorState}).from(deployments).where(attemptConditions(input2.attempt)).limit(1);const conflict3=conflictRows[0];const safeState=value2=>typeof value2==="string"&&/^[a-z_]{2,40}$/u.test(value2)?value2.toUpperCase():"UNKNOWN";throw new Error(conflict3?`DEPLOYMENT_EXECUTOR_ENQUEUE_CONFLICT_${safeState(conflict3.status)}_${safeState(conflict3.controlPlaneState)}_${safeState(conflict3.executorState)}`:"DEPLOYMENT_EXECUTOR_ENQUEUE_CONFLICT_ATTEMPT_ABSENT")}}async function finishDeploymentExecutorOperation(input2){assertDeploymentExecutorTransition(input2.operation.executorState,input2.state);const receipt=sanitizeDeploymentExecutorReceipt(await carryDeploymentExecutorWarnings({db:input2.db,...input2.operation,receipt:input2.receipt}));const receiptJson=JSON.stringify(receipt);const now=input2.now??new Date;const rows8=await input2.db.update(deployments).set({executorState:input2.state,...input2.state==="recovery_required"?{}:{executorPayloadRef:null},executorReceiptJson:receiptJson,executorReceiptSha256:hashDeploymentExecutorReceipt(receipt),executorUpdatedAt:now,...input2.activation?{bundleHash:input2.activation.bundleHash,status:"running",controlPlaneState:"active",callableBackend:input2.activation.callableBackend,failureStage:null,failureCode:null,errorMessage:null}:{},...input2.failure?{failureStage:input2.failure.stage,failureCode:input2.failure.code,candidateCleanupFailureCode:input2.failure.candidateCleanupFailureCode??null,errorMessage:input2.failure.legacyMessage.slice(0,300)}:{},...input2.state==="failed"?{status:"failed",controlPlaneState:"failed"}:{},...input2.clearLease===false?{}:{attemptOwnerId:null,attemptLeaseExpiresAt:null}}).where(and17(eq20(deployments.id,input2.operation.deploymentId),eq20(deployments.appId,input2.operation.appId),eq20(deployments.attemptId,input2.operation.attemptId),eq20(deployments.attemptOwnerId,input2.operation.ownerId),eq20(deployments.executorLeaseEpoch,input2.operation.leaseEpoch),input2.allowExpiredLease?lte4(deployments.attemptLeaseExpiresAt,now):gt5(deployments.attemptLeaseExpiresAt,now),eq20(deployments.executorState,input2.operation.executorState))).returning({id:deployments.id});if(rows8.length!==1)throw new Error("DEPLOYMENT_EXECUTOR_TERMINAL_CONFLICT");input2.operation.executorState=input2.state}async function getOwnedDeploymentExecutorStatus(input2){const rows8=await input2.db.select({deploymentId:deployments.id,appId:deployments.appId,appName:apps.name,appPort:apps.port,currentStaticDeployId:apps.currentStaticDeployId,currentStaticGenerationRef:apps.currentStaticGenerationRef,appInstanceId:apps.instanceId,executorAppInstanceId:deployments.executorAppInstanceId,releaseAttemptId:deployments.executorReleaseAttemptId,releaseEnvironment:appReleaseAttempts.environment,staticSize:apps.staticSize,bundleHash:deployments.bundleHash,status:deployments.status,controlPlaneState:deployments.controlPlaneState,executorState:deployments.executorState,environment:deployments.env,targetNodeId:deployments.executorTargetNodeId,targetSlotId:deployments.executorTargetSlotId,targetRevision:deployments.executorTargetRevision,targetOwnerId:deployments.executorTargetOwnerId,targetGenerationDigest:deployments.executorTargetGenerationDigest,correlationId:deployments.correlationId,failureStage:deployments.failureStage,failureCode:deployments.failureCode,candidateCleanupFailureCode:deployments.candidateCleanupFailureCode,receiptJson:deployments.executorReceiptJson,receiptSha256:deployments.executorReceiptSha256,queuedAt:deployments.executorQueuedAt}).from(deployments).innerJoin(apps,eq20(apps.id,deployments.appId)).leftJoin(appReleaseAttempts,and17(eq20(appReleaseAttempts.id,deployments.executorReleaseAttemptId),eq20(appReleaseAttempts.appId,deployments.appId))).where(and17(eq20(deployments.id,input2.deploymentId),eq20(apps.userId,input2.userId))).limit(1);return rows8[0]??null}var NONTERMINAL_DEPLOYMENT_EXECUTOR_STATES,DEFAULT_MAX_QUEUED_OPERATIONS,DEFAULT_MAX_QUEUED_BYTES,DEFAULT_MAX_USER_OPERATIONS,DEFAULT_MAX_USER_BYTES,DeploymentExecutorAdmissionError;var init_deployment_executor_store=__esm({"../platform/src/deployment-executor-store.ts"(){"use strict";init_deployment_executor_warning_receipt();init_schema();init_postgres_temporal2();init_deployment_failure_contract();init_deployment_release_scope();init_deployment_executor_operation();NONTERMINAL_DEPLOYMENT_EXECUTOR_STATES=["queued","claimed","database_preparing","schema_executing","runtime_preparing","candidate_attesting","committing","reconciling"];DEFAULT_MAX_QUEUED_OPERATIONS=128;DEFAULT_MAX_QUEUED_BYTES=512*1024*1024;DEFAULT_MAX_USER_OPERATIONS=8;DEFAULT_MAX_USER_BYTES=200*1024*1024;DeploymentExecutorAdmissionError=class extends Error{constructor(code,httpStatus,blockingOperationId,blockingCorrelationId,requestId){super(code);this.code=code;this.httpStatus=httpStatus;this.blockingOperationId=blockingOperationId;this.blockingCorrelationId=blockingCorrelationId;this.requestId=requestId}code;httpStatus;blockingOperationId;blockingCorrelationId;requestId}}});function recoveryDeadlineDiagnostic(operation,statusAction){const seal=operation.deadlineSeal;if(operation.state!=="failed_delete_recovery_required"||!seal)return{};return{error:`Delete stopped in the ${seal.stage} stage and passed its recovery deadline. Inspect the same operation with ${statusAction}.`,stage:seal.stage,failedState:seal.failedState,...seal.causeCode?{causeCode:seal.causeCode}:{},stateImpact:DEADLINE_STATE_IMPACT[seal.stage],retryPrecondition:"Run the app delete again; it reopens this same operation. If it stops at the same stage with the same cause code, Platform must clear that cause first.",retryClass:"retryable-infra",userAction:"RETRY"}}function runtimeAbsenceDiagnostic(operation,statusAction){if(operation.lastErrorCode!=="APP_DELETE_RUNTIME_EXTERNAL_ABSENCE_SCOPE_REQUIRED"&&operation.lastErrorCode!=="APP_DELETE_RUNTIME_EXTERNAL_ABSENCE_UNPROVEN"){return{}}const stage=operation.state==="blocked_runtime_outcome_unknown"?"runtime-absence":operation.state==="failed_catalog_cleanup"?"pre-catalog":void 0;if(!stage)return{};const scopeRequired=operation.lastErrorCode==="APP_DELETE_RUNTIME_EXTERNAL_ABSENCE_SCOPE_REQUIRED";return{error:scopeRequired?`Delete cleanup is waiting for Platform to restore exact app placement and ownership. Inspect the same operation with ${statusAction}.`:`Delete cleanup is waiting for Platform to complete exact runtime-absence observation. Inspect the same operation with ${statusAction}.`,stage,capability:"runtime-absence",stateImpact:stage==="pre-catalog"?"The tenant database cleanup step completed, but independent absence is not yet verified; catalog deletion was not recorded. Runtime may have changed.":"The same delete receipt remains active; this runtime proof did not delete the catalog. Runtime or tenant database cleanup may already have occurred.",retryable:false,retryPrecondition:scopeRequired?"Platform must restore exact app placement, current node ownership, and app incarnation; then recheck the same receipt.":"Platform must complete exact runtime absence observation; then recheck the same receipt.",retryClass:"platform-action",userAction:"VIEW_DELETE_STATUS",nextAction:"VIEW_DELETE_STATUS"}}function catalogOnlyEffectDiagnostic(operation,statusAction){return operation.state==="failed_catalog_cleanup"&&["APP_DELETE_CATALOG_ONLY_EFFECTS_PRESENT","APP_DELETE_CATALOG_ONLY_IDENTITY_CHANGED"].includes(operation.lastErrorCode??"")?{error:`Delete cleanup found a changed catalog identity or runtime, deployment, child, or serving-route effect after admission. Inspect the same operation with ${statusAction}.`,stage:"pre-catalog",capability:"catalog-effect-reconciliation",stateImpact:"Tenant database cleanup may have completed, but catalog deletion was not recorded; the same app and delete receipt remain authoritative.",retryable:false,retryPrecondition:"Platform must classify and safely clear the newly observed effect, then reconcile the same delete receipt.",retryClass:"platform-action",userAction:"VIEW_DELETE_STATUS",nextAction:"VIEW_DELETE_STATUS"}:{}}function appDeleteStateDiagnostics(operation,statusAction){return{...runtimeAbsenceDiagnostic(operation,statusAction),...catalogOnlyEffectDiagnostic(operation,statusAction),...recoveryDeadlineDiagnostic(operation,statusAction)}}function blockedActiveWorkDiagnostic(operation,statusAction){if(operation.state!=="blocked_active_work")return{};return{error:`Delete is waiting for the app runtime to become idle and is being retried automatically. Inspect the same operation with ${statusAction}.`,stage:"runtime-stop",...operation.lastErrorCode?{causeCode:operation.lastErrorCode}:{},stateImpact:"The app is still running; its tenant data, routes, and catalog row were not changed by this delete.",retryable:true,retryPrecondition:"No action is needed first: the Platform retries this same operation about every 30 seconds until its recovery deadline. If it then reports failed_delete_recovery_required, run the app delete again.",retryClass:"platform-action",userAction:"VIEW_DELETE_STATUS",nextAction:"VIEW_DELETE_STATUS"}}var DEADLINE_STATE_IMPACT;var init_app_delete_result_diagnostics=__esm({"../platform/src/app-delete-result-diagnostics.ts"(){"use strict";DEADLINE_STATE_IMPACT={admission:"Deletion had not started any destructive step; the app, its routes, runtime, and tenant data are unchanged.","runtime-stop":"The app runtime stop did not finish. Tenant data and the app catalog row were not deleted.","tenant-database":"The runtime is stopped but tenant database cleanup did not finish. The app catalog row was not deleted.","catalog-finalize":"Runtime stop and tenant database cleanup may already be done, but the app catalog row was not deleted."}}});import{sql as sql100}from"drizzle-orm";function decodeAppDeleteErrorCode(stored){if(!stored?.startsWith(SEAL_PREFIX))return{code:stored,seal:null};const[failedState,cause,...extra]=stored.slice(SEAL_PREFIX.length).split(":");const stage=APP_DELETE_STAGE_BY_STATE[failedState??""];if(extra.length>0||!stage||!cause||cause!==NO_CAUSE&&!STABLE_CAUSE_PATTERN.test(cause)){return{code:APP_DELETE_RECOVERY_DEADLINE_CODE,seal:null}}return{code:APP_DELETE_RECOVERY_DEADLINE_CODE,seal:{failedState,stage,causeCode:cause===NO_CAUSE?null:cause}}}var APP_DELETE_RECOVERY_DEADLINE_CODE,SEAL_PREFIX,NO_CAUSE,STABLE_CAUSE_PATTERN,APP_DELETE_STAGE_BY_STATE;var init_app_delete_recovery_deadline=__esm({"../platform/src/app-delete-recovery-deadline.ts"(){"use strict";init_schema();APP_DELETE_RECOVERY_DEADLINE_CODE="APP_DELETE_RECOVERY_DEADLINE_EXCEEDED";SEAL_PREFIX=`${APP_DELETE_RECOVERY_DEADLINE_CODE}:`;NO_CAUSE="NONE";STABLE_CAUSE_PATTERN=/^[A-Z][A-Z0-9_]{2,127}$/u;APP_DELETE_STAGE_BY_STATE={accepted:"admission",stopping_children:"admission",draining_runtime:"runtime-stop",stop_dispatched:"runtime-stop",blocked_ownership_ambiguous:"runtime-stop",blocked_active_work:"runtime-stop",blocked_runtime_outcome_unknown:"runtime-stop",runtime_absent:"tenant-database",tenant_db_drop_pending:"tenant-database",failed_tenant_db_cleanup:"tenant-database",catalog_delete_pending:"catalog-finalize",failed_catalog_cleanup:"catalog-finalize",blocked_catalog_outcome_unknown:"catalog-finalize"}}});import{sql as sql101}from"drizzle-orm";async function redriveRejectedServingRouteDeliveryInTransaction(input2){await input2.tx.execute(sql101`
|
|
8806
|
+
`).join(""));const lockfile=lockfiles[0];const packageBytes=metadata.get(PACKAGE_MANIFEST);let packageManagerDeclaration=null;if(packageBytes){try{const parsed=JSON.parse(packageBytes.toString("utf8"));packageManagerDeclaration=typeof parsed.packageManager==="string"?parsed.packageManager.trim():null}catch{return fail12("DEPLOY_ARCHIVE_PACKAGE_MANIFEST_INVALID")}}if(findRuntimeEntry(files)&&packageBytes){const dependencyLock=inspectPnpmDependencyLock({packageJsonText:packageBytes.toString("utf8"),pnpmLockText:lockfile?metadata.get(lockfile[0])?.toString("utf8"):null});if(!dependencyLock.ok){return fail12(dependencyLock.code,{files:[...dependencyLock.files]})}}const migrationBytes=metadata.get(MIGRATION_MANIFEST);let artifactIdentitySha256=null;let migrationCliVersion=null;if(migrationBytes){try{const manifest=JSON.parse(migrationBytes.toString("utf8"));artifactIdentitySha256=typeof manifest.artifactIdentitySha256==="string"?manifest.artifactIdentitySha256:null;migrationCliVersion=typeof manifest.cliVersion==="string"?manifest.cliVersion:null}catch{return fail12("MIGRATION_BUNDLE_MANIFEST_INVALID")}}const recomputed={rawArchiveSha256:sha2568(bundle),compressedBytes:bundle.length,uncompressedBytes,entryCount,fileCount:files.length,authSchema,dependencies:{packageManager:lockfile?.[1]??"none",manifestSha256:packageBytes?sha2568(packageBytes):null,lockfileSha256:lockfile?sha2568(metadata.get(lockfile[0])):null},migrationBundle:{manifestSha256:migrationBytes?sha2568(migrationBytes):null,requiredCapability:migrationBytes?artifactIdentitySha256?MIGRATION_ARTIFACT_IDENTITY_CAPABILITY_V2:MIGRATION_BUNDLE_CAPABILITY_V1:"none",...artifactIdentitySha256?{artifactIdentitySha256}:{}}};return{recomputed,sourceClosureSha256,files,rootIndexBlank,packageManagerDeclaration,...migrationCliVersion?{migrationCliVersion}:{}}}function admitInspectedDeployArchive(input2){const hasRuntimeEntry=findRuntimeEntry(input2.inspection.files);if(input2.expectedRuntime==="server"){if(input2.inspection.recomputed.dependencies.manifestSha256===null){return fail12("DEPLOY_ARCHIVE_PACKAGE_MANIFEST_REQUIRED")}if(input2.inspection.recomputed.dependencies.packageManager!=="pnpm"){return fail12("DEPLOY_ARCHIVE_PNPM_LOCK_REQUIRED")}if(input2.inspection.packageManagerDeclaration!==APPROVED_PACKAGE_MANAGER){return fail12("DEPLOY_ARCHIVE_PACKAGE_MANAGER_VERSION_UNSUPPORTED")}if(!hasRuntimeEntry)return fail12("DEPLOY_ARCHIVE_RUNTIME_ENTRY_REQUIRED")}else{if(hasRuntimeEntry)return fail12("DEPLOY_ARCHIVE_RUNTIME_CONFLICT");const entrypointRejection=staticSiteEntrypointRejection(findRootIndexEntry(input2.inspection));if(entrypointRejection)return fail12(entrypointRejection)}if(input2.claim.declaredRuntime!==input2.expectedRuntime||input2.claim.sourceBundleSha256!==input2.inspection.recomputed.rawArchiveSha256||!equalContractValue(input2.claim.authSchema,input2.inspection.recomputed.authSchema)||!equalContractValue(input2.claim.dependencies,input2.inspection.recomputed.dependencies)||!equalContractValue(input2.claim.migrationBundle,input2.inspection.recomputed.migrationBundle)){return fail12("DEPLOY_CLAIM_MISMATCH")}return{...input2.inspection,contractHash:hashAdmittedDeployClaimV1(input2.claim)}}async function admitDeployArchive(input2){const inspected=await inspectDeployArchiveForRuntime(input2);return admitInspectedDeployArchive({inspection:inspected,claim:input2.claim,expectedRuntime:input2.expectedRuntime})}async function inspectDeployArchiveForRuntime(input2){const inspected=await inspectDeployArchive(input2.bundle,input2.limits);const hasRuntimeEntry=findRuntimeEntry(inspected.files);if(input2.expectedRuntime==="server"){if(inspected.recomputed.dependencies.manifestSha256===null){return fail12("DEPLOY_ARCHIVE_PACKAGE_MANIFEST_REQUIRED")}if(!hasRuntimeEntry)return fail12("DEPLOY_ARCHIVE_RUNTIME_ENTRY_REQUIRED");if(inspected.packageManagerDeclaration!==APPROVED_PACKAGE_MANAGER){return fail12("DEPLOY_ARCHIVE_PACKAGE_MANAGER_VERSION_UNSUPPORTED")}}else{if(hasRuntimeEntry)return fail12("DEPLOY_ARCHIVE_RUNTIME_CONFLICT");const entrypointRejection=staticSiteEntrypointRejection(findRootIndexEntry(inspected));if(entrypointRejection)return fail12(entrypointRejection)}return inspected}var PACKAGE_MANIFEST,APPROVED_PACKAGE_MANAGER,MIGRATION_MANIFEST,LOCKFILES,UNSUPPORTED_LOCKFILES,CANONICAL_DEPLOY_BACKEND_ROOT,PROJECT_AUTH_SCHEMA_PATTERN,LEGACY_AUTH_SCHEMA_PATTERN,RUNTIME_ENTRY_PATTERN,SELECTED_METADATA,DEFAULT_LIMITS2,MAX_METADATA_BYTES,DeployArchiveAdmissionError;var init_deploy_archive_admission=__esm({"../platform/src/deploy-archive-admission.ts"(){"use strict";init_index_min();init_dist();init_deploy_contract_admission();init_tar_buffer_extract();init_static_site_entrypoint_policy();PACKAGE_MANIFEST="package.json";APPROVED_PACKAGE_MANAGER="pnpm@10.33.0";MIGRATION_MANIFEST=".gencow/migration-bundle-manifest.json";LOCKFILES=new Map([["pnpm-lock.yaml","pnpm"]]);UNSUPPORTED_LOCKFILES=new Set(["package-lock.json","npm-shrinkwrap.json","bun.lock","bun.lockb","yarn.lock"]);CANONICAL_DEPLOY_BACKEND_ROOT="gencow";PROJECT_AUTH_SCHEMA_PATTERN=new RegExp(`^${CANONICAL_DEPLOY_BACKEND_ROOT}/schema-auth\\.(?:ts|js)$`,"u");LEGACY_AUTH_SCHEMA_PATTERN=new RegExp(`^${CANONICAL_DEPLOY_BACKEND_ROOT}/(?:auth-schema\\.(?:ts|js)|generated/auth-schema\\.(?:ts|js))$`,"u");RUNTIME_ENTRY_PATTERN=new RegExp(`^${CANONICAL_DEPLOY_BACKEND_ROOT}/index\\.(?:ts|js)$`,"u");SELECTED_METADATA=new Set([PACKAGE_MANIFEST,MIGRATION_MANIFEST,...LOCKFILES.keys(),...UNSUPPORTED_LOCKFILES]);DEFAULT_LIMITS2={maxCompressedBytes:100*1024*1024,maxUncompressedBytes:200*1024*1024,maxEntries:1e4,maxDepth:32,maxCompressionRatio:100};MAX_METADATA_BYTES=1024*1024;DeployArchiveAdmissionError=class extends Error{constructor(code,details){super(code);this.code=code;this.details=details;this.name="DeployArchiveAdmissionError"}code;details}}});import{resolve as resolve57}from"node:path";import{and as and15,asc as asc2,eq as eq18,isNull as isNull7,ne as ne8,or as or7}from"drizzle-orm";function fail13(code,status,cause,publicDetails){throw new DeploymentAdmissionError(code,status,publicDetails,cause===void 0?void 0:{cause})}function mapArchiveAdmissionError(error62){console.warn("[deploy-admission] archive rejected",{code:error62.code,files:error62.details?.files??[]});const code=error62.code==="DEPLOY_ARCHIVE_AUTH_SCHEMA_AMBIGUOUS"?"AUTH_SCHEMA_PROVENANCE_AMBIGUOUS":error62.code;return fail13(code,400,error62,error62.details)}async function inspectDeploymentArchiveForRuntime(input2){try{return await inspectDeployArchiveForRuntime(input2)}catch(error62){if(error62 instanceof DeployArchiveAdmissionError)return mapArchiveAdmissionError(error62);throw error62}}async function admitDeploymentArchiveContract(input2){try{return await admitDeployArchive({bundle:input2.bundle,claim:input2.protocol.claim,expectedRuntime:input2.expectedRuntime})}catch(error62){if(error62 instanceof DeployArchiveAdmissionError)return mapArchiveAdmissionError(error62);throw error62}}function compareStableVersions(left,right){const parse4=value2=>value2.split("-")[0].split(".").map(Number);const[leftParts,rightParts]=[parse4(left),parse4(right)];for(let index27=0;index27<3;index27+=1){if(leftParts[index27]!==rightParts[index27])return leftParts[index27]-rightParts[index27]}return 0}function parseDeploymentProtocolRequest(input2){const encodedClaim=input2.getHeader(DEPLOY_CLAIM_HEADER);const protocol=input2.getHeader(DEPLOY_PROTOCOL_HEADER);const cliVersion=input2.getHeader(DEPLOY_CLI_VERSION_HEADER);if(!encodedClaim){if(protocol||cliVersion)return fail13("DEPLOY_CLAIM_HEADER_REQUIRED",400);if(input2.requireVersionedProtocol)return fail13("DEPLOY_CLI_UPGRADE_REQUIRED",426);return{lane:"legacy-observe",claim:null,contractHash:null}}let claim2;try{claim2=parseDeployClaimV1Header(encodedClaim)}catch(error62){return fail13("DEPLOY_CLAIM_INVALID",400,error62)}if(protocol!==String(claim2.protocolVersion)||cliVersion!==claim2.generatedBy.version){return fail13("DEPLOY_PROTOCOL_HEADER_MISMATCH",400)}if(compareStableVersions(cliVersion,MIN_DEPLOY_CLI_VERSION)<0){return fail13("DEPLOY_CLI_UPGRADE_REQUIRED",426)}if(claim2.declaredRuntime!==input2.expectedRuntime){return fail13("DEPLOY_RUNTIME_DECLARATION_MISMATCH",400)}return{lane:"v1-enforce",claim:claim2,contractHash:hashAdmittedDeployClaimV1(claim2)}}function deploymentProtocolResponseHeaders(lane){return{"X-Gencow-Deploy-Min-Protocol":"1","X-Gencow-Min-CLI-Version":MIN_DEPLOY_CLI_VERSION,"X-Gencow-Deploy-Lane":lane}}async function findCandidateCleanupDebt(input2){const unresolved=await input2.db.select({deploymentId:deployments.id}).from(deployments).leftJoin(appRuntimeInstances,and15(eq18(appRuntimeInstances.deploymentId,deployments.id),eq18(appRuntimeInstances.appId,deployments.appId))).where(and15(eq18(deployments.appId,input2.appId),eq18(deployments.env,input2.env),or7(and15(eq18(deployments.status,"failed"),eq18(deployments.candidateCleanupFailureCode,"RUNTIME_CANDIDATE_CLEANUP_INCOMPLETE")),and15(eq18(deployments.executorState,"recovery_required"),eq18(deployments.candidateCleanupFailureCode,"CANDIDATE_CLEANUP_PENDING"))),or7(isNull7(appRuntimeInstances.instanceId),ne8(appRuntimeInstances.state,"stopped"),isNull7(appRuntimeInstances.candidateCleanupCompletedAt)))).orderBy(asc2(deployments.id)).limit(1);return unresolved[0]??null}async function hasCandidateCleanupDebt(input2){return Boolean(await findCandidateCleanupDebt(input2))}async function assertCandidateCleanupTerminal(input2){if(await hasCandidateCleanupDebt(input2))fail13("RUNTIME_CANDIDATE_CLEANUP_INCOMPLETE",503)}async function findRecoveryRequiredDeployment(input2){const rows8=await input2.db.select({deploymentId:deployments.id,correlationId:deployments.correlationId,executionEnvironment:deployments.env,releaseEnvironment:appReleaseAttempts.environment,failureStage:deployments.failureStage,failureCode:deployments.failureCode}).from(deployments).leftJoin(appReleaseAttempts,and15(eq18(appReleaseAttempts.id,deployments.executorReleaseAttemptId),eq18(appReleaseAttempts.appId,deployments.appId))).where(and15(eq18(deployments.appId,input2.appId),eq18(deployments.status,"pending"),eq18(deployments.executorState,"recovery_required"))).orderBy(asc2(deployments.id));for(const row of rows8){if(!deploymentRecoveryScopesOverlap({candidateExecutionEnvironment:row.executionEnvironment,candidateReleaseEnvironment:row.releaseEnvironment,incomingExecutionEnvironment:input2.env,incomingReleaseEnvironment:input2.releaseEnvironment})){continue}if(row.executionEnvironment!=="static"&&row.failureStage==="route"&&row.failureCode===COMMITTED_ROUTE_BLOCKED_CODE){const exempt=await input2.db.select({id:deployments.id}).from(deployments).where(and15(eq18(deployments.id,row.deploymentId),eq18(deployments.appId,input2.appId),committedRouteBlockedSupersedable(input2.db))).limit(1);if(exempt[0])continue}if(await deploymentSupersededByNewerCommit({db:input2.db,appId:input2.appId,deploymentId:row.deploymentId})){continue}return{deploymentId:row.deploymentId,correlationId:row.correlationId}}return null}async function assertDeploymentRecoveryAdmissionOpen(input2){const blocker=await findRecoveryRequiredDeployment(input2);if(!blocker)return;const error62=new DeploymentAdmissionError("DEPLOYMENT_EXECUTOR_RECOVERY_REQUIRED",503);Object.assign(error62,{blockingOperationId:blocker.deploymentId,blockingCorrelationId:blocker.correlationId});throw error62}async function preallocateDeploymentRequest(input2){try{await assertCandidateCleanupTerminal({db:input2.db,appId:input2.appId,env:input2.env});await assertDeploymentRecoveryAdmissionOpen({db:input2.db,appId:input2.appId,env:input2.env,releaseEnvironment:input2.releaseEnvironment});return await preallocateDeploymentAttempt({db:input2.db,appId:input2.appId,env:input2.env,bundle:input2.bundle,declaredRuntime:input2.expectedRuntime,...input2.protocol.claim?{requestId:input2.protocol.claim.requestId,protocolVersion:input2.protocol.claim.protocolVersion,contractJson:JSON.stringify(input2.protocol.claim),contractHash:input2.protocol.contractHash}:{}})}catch(error62){if(error62?.message==="DEPLOY_IDEMPOTENCY_CONFLICT"){return fail13("DEPLOY_IDEMPOTENCY_CONFLICT",409,error62)}throw error62}}function classifyDeploymentReplay(attempt){if(!attempt.replayed)return{kind:"new"};if(attempt.status==="running"&&attempt.controlPlaneState==="active"){return{kind:"active"}}if(attempt.status==="failed")return{kind:"failed"};if(["received","admitted","materializing","candidate","ready"].includes(attempt.controlPlaneState)){return{kind:"resume",state:attempt.controlPlaneState}}return{kind:"in-progress"}}var DEPLOY_CLAIM_HEADER,DEPLOY_PROTOCOL_HEADER,DEPLOY_CLI_VERSION_HEADER,MIN_DEPLOY_CLI_VERSION,DeploymentAdmissionError;var init_deployment_request_admission=__esm({"../platform/src/deployment-request-admission.ts"(){"use strict";init_schema();init_deployment_committed_route_contract();init_deployment_superseded_by_newer_commit();init_deployment_release_scope();init_app_deployment_artifact_store();init_deploy_archive_admission();init_deploy_contract_admission();init_deployment_attempt_store();DEPLOY_CLAIM_HEADER="x-gencow-deploy-claim";DEPLOY_PROTOCOL_HEADER="x-gencow-deploy-protocol";DEPLOY_CLI_VERSION_HEADER="x-gencow-cli-version";MIN_DEPLOY_CLI_VERSION="0.1.189";DeploymentAdmissionError=class extends Error{constructor(code,status,publicDetails,options){super(code,options);this.code=code;this.status=status;this.publicDetails=publicDetails;this.name="DeploymentAdmissionError"}code;status;publicDetails}}});function isExactDependencyVersion(value2){return typeof value2==="string"&&value2.length<=128&&VERSION2.test(value2)}function isSafeDependencyDeclaration(value2){return typeof value2==="string"&&value2.length>0&&new TextEncoder().encode(value2).length<=256&&!CONTROL.test(value2)&&!/(?:password|secret|token|authorization)/iu.test(value2)&&(value2==="latest"||/^(?:workspace:)?[0-9vVxX*~^<>=|. +\-]+$/u.test(value2.replace(/[+-][0-9A-Za-z][0-9A-Za-z.-]*/gu,"")))}function safeDependencyDeclaration(value2){return isSafeDependencyDeclaration(value2)?value2:REDACTED_DECLARATION}function parseComparableVersion(value2){if(!isExactDependencyVersion(value2))return null;const match2=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(value2);if(!match2)return null;const prerelease=match2[4]?.split(".")??[];if(prerelease.some(id=>/^0\d+$/u.test(id)))return null;return{core:match2.slice(1,4).map(BigInt),prerelease}}function compareLockedToBom(locked,bom){const a=parseComparableVersion(locked);const b2=parseComparableVersion(bom);if(!a||!b2)return"unknown";for(const[index27,kind]of["major","minor","patch"].entries()){if(a.core[index27]!==b2.core[index27])return a.core[index27]>b2.core[index27]?"newer":kind}for(let i=0;i<Math.max(a.prerelease.length,b2.prerelease.length);i++){if(!a.prerelease.length)return"newer";if(!b2.prerelease.length)return"prerelease";const left=a.prerelease[i];const right=b2.prerelease[i];if(left===right)continue;if(left===void 0)return"prerelease";if(right===void 0)return"newer";const leftNumeric=/^\d+$/u.test(left);const rightNumeric=/^\d+$/u.test(right);if(leftNumeric!==rightNumeric)return leftNumeric?"prerelease":"newer";const newer=leftNumeric?BigInt(left)>BigInt(right):left>right;return newer?"newer":"prerelease"}return locked===bom?"matches":"build_metadata"}function formatDependencyVersionTable(packages,{includeExplanation=true}={}){const rows8=[["Package","package.json","Locked","Runtime BOM","Locked vs BOM"],...packages.map(p2=>[p2.packageName,safeDependencyDeclaration(p2.declared),parseComparableVersion(p2.lockedVersion)?p2.lockedVersion:"unknown",p2.bomVersion,DIFFERENCE_LABELS[compareLockedToBom(p2.lockedVersion,p2.bomVersion)]])];const widths=rows8[0].map((_4,column)=>Math.max(...rows8.map(row=>row[column].length)));const format=row=>row.map((cell,column)=>cell.padEnd(widths[column])).join(" | ").trimEnd();return[format(rows8[0]),widths.map(width=>"-".repeat(width)).join("-+-"),...rows8.slice(1).map(format),...includeExplanation?["Locked: pnpm-lock.yaml resolution, not a check of node_modules; unknown means unavailable."]:[]]}function formatLockedBomGuidance(packages,{includeStaleSummary=true}={}){const differences=packages.map(p2=>compareLockedToBom(p2.lockedVersion,p2.bomVersion));const mismatch=differences.some(difference=>difference!=="matches"&&difference!=="unknown");const older=differences.some(difference=>["major","minor","patch","prerelease"].includes(difference));return[...mismatch?["Local development may behave differently from hosted deployments because dependency versions differ.","Aligning local dependencies with the Runtime BOM helps keep behavior consistent."]:[],...older?[...includeStaleSummary?["Some lockfile resolutions are behind the hosted runtime."]:[],"Preview: gencow runtime sync --dry-run --install","Refresh and install: gencow runtime sync --install (preserves latest declarations)."]:[]]}var VERSION2,CONTROL,REDACTED_DECLARATION,DIFFERENCE_LABELS;var init_dependency_version_report=__esm({"../shared/dist/src/dependency-version-report.js"(){"use strict";VERSION2=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u;CONTROL=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u;REDACTED_DECLARATION="[redacted declaration]";DIFFERENCE_LABELS={unknown:"Unknown",matches:"Matches",newer:"Newer than hosted runtime",major:"Major mismatch \u2014 possible compatibility issues",minor:"Minor mismatch",patch:"Patch mismatch",prerelease:"Prerelease mismatch",build_metadata:"Build metadata differs (same precedence)"}}});function object3(value2){return value2!==null&&typeof value2==="object"&&!Array.isArray(value2)}function isPackage(value2){return typeof value2==="string"&&bytes(value2)<=214&&PACKAGE.test(value2)}function isMismatch(value2){return value2==="non_major_mismatch"||value2==="major_mismatch"}function isPolicy(value2){return value2==="warn"||value2==="reject-major"||value2==="reject-all"}function isManagedBomDiagnostic(value2){if(!object3(value2)||value2.schemaVersion!==1||typeof value2.releaseId!=="string"||!RELEASE.test(value2.releaseId)||!isPolicy(value2.policy)||value2.decision!=="warn"&&value2.decision!=="block"||!Array.isArray(value2.packages)||value2.packages.length>MAX_MANAGED_BOM_PACKAGES||!Number.isSafeInteger(value2.totalPackages)||!Number.isSafeInteger(value2.omittedPackages)||value2.omittedPackages<0||value2.totalPackages<1||value2.totalPackages!==value2.packages.length+value2.omittedPackages)return false;const names=new Set;for(const row of value2.packages){if(!object3(row)||!isPackage(row.packageName)||names.has(row.packageName)||!isExactDependencyVersion(row.bomVersion)||row.lockedVersion!==void 0&&!isExactDependencyVersion(row.lockedVersion)||!isMismatch(row.classification)||typeof row.declarationRedacted!=="boolean"||(row.declarationRedacted?row.declared!==REDACTED:!isSafeDependencyDeclaration(row.declared)))return false;names.add(row.packageName)}try{return bytes(JSON.stringify(value2))<=MAX_MANAGED_BOM_DIAGNOSTIC_BYTES}catch{return false}}function buildManagedBomWarning(input2){const warning={code:input2.abort?"MANAGED_BOM_MISMATCH":"MANAGED_BOM_WARNING",phase:"dependencies",message:input2.abort?"Managed dependency policy blocked deployment.":"Managed dependency policy emitted a warning.",count:1};if(!RELEASE.test(input2.releaseId)||!input2.mismatches.length)return warning;const rows8=new Map;const names=new Set(input2.mismatches.map(row=>row.packageName));for(const row of[...input2.mismatches].sort((a,b2)=>a.packageName<b2.packageName?-1:a.packageName>b2.packageName?1:0)){if(rows8.size>=MAX_MANAGED_BOM_PACKAGES||rows8.has(row.packageName)||!isPackage(row.packageName)||!Object.hasOwn(input2.managedPackages,row.packageName)||input2.managedPackages[row.packageName]!==row.bomVersion||!isExactDependencyVersion(row.bomVersion)||!isMismatch(row.classification))continue;const safe=isSafeDependencyDeclaration(row.declared);rows8.set(row.packageName,{packageName:row.packageName,declared:safe?row.declared:REDACTED,declarationRedacted:!safe,bomVersion:row.bomVersion,...isExactDependencyVersion(row.lockedVersion)?{lockedVersion:row.lockedVersion}:{},classification:row.classification})}const managedBom={schemaVersion:1,releaseId:input2.releaseId,policy:input2.policy,decision:input2.abort?"block":"warn",packages:[...rows8.values()],totalPackages:names.size,omittedPackages:names.size-rows8.size};if(isManagedBomDiagnostic(managedBom))warning.managedBom=managedBom;return warning}function publicManagedBomWarning(value2){if(!object3(value2)||value2.code!=="MANAGED_BOM_WARNING"&&value2.code!=="MANAGED_BOM_MISMATCH")return null;const blocked2=value2.code==="MANAGED_BOM_MISMATCH";const result3={code:value2.code,phase:"dependencies",message:blocked2?"Managed dependency policy blocked deployment.":"Managed dependency policy emitted a warning.",count:Number.isSafeInteger(value2.count)&&value2.count>0?Math.min(1e3,value2.count):1};if(isManagedBomDiagnostic(value2.managedBom)&&value2.managedBom.decision===(blocked2?"block":"warn")){const d=value2.managedBom;result3.managedBom={schemaVersion:1,releaseId:d.releaseId,policy:d.policy,decision:d.decision,packages:d.packages.map(p2=>({packageName:p2.packageName,declared:p2.declared,declarationRedacted:p2.declarationRedacted,bomVersion:p2.bomVersion,...p2.lockedVersion!==void 0?{lockedVersion:p2.lockedVersion}:{},classification:p2.classification})),totalPackages:d.totalPackages,omittedPackages:d.omittedPackages}}return result3}var MAX_MANAGED_BOM_PACKAGES,MAX_MANAGED_BOM_DIAGNOSTIC_BYTES,RELEASE,PACKAGE,REDACTED,bytes;var init_managed_bom_diagnostic=__esm({"../shared/dist/src/managed-bom-diagnostic.js"(){"use strict";init_dependency_version_report();MAX_MANAGED_BOM_PACKAGES=128;MAX_MANAGED_BOM_DIAGNOSTIC_BYTES=128*1024;RELEASE=/^sha256:[a-f0-9]{64}$/u;PACKAGE=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u;REDACTED="[redacted declaration]";bytes=value2=>new TextEncoder().encode(value2).length}});function hasVerifiedDeploymentExecutorCompletion(operation){if(operation.executorState!=="completed"||!operation.receiptJson||!operation.receiptSha256){return false}try{const receipt=readVerifiedDeploymentExecutorReceipt(operation);return receipt?.phase==="completed"&&DEPLOYMENT_EXECUTOR_COMPLETED_RECEIPT_CODES.has(receipt.code)&&operation.executorState==="completed"}catch{return false}}function readVerifiedDeploymentExecutorReceipt(operation){if(!operation.receiptJson||!operation.receiptSha256)return null;try{const receipt=sanitizeDeploymentExecutorReceipt(JSON.parse(operation.receiptJson));return hashDeploymentExecutorReceipt(receipt)===operation.receiptSha256?receipt:null}catch{return null}}var POST_COMMIT_ROUTE_ACK_RECOVERED_CODE,RUNTIME_COMMITTED_ACTIVATION_ROUTE_REPAIRED_CODE,STALE_STATIC_LIVE_RELEASE_CONVERGED_CODE,DEPLOYMENT_EXECUTOR_COMPLETED_RECEIPT_CODES;var init_deployment_executor_completion_contract=__esm({"../platform/src/deployment-executor-completion-contract.ts"(){"use strict";init_deployment_executor_operation();POST_COMMIT_ROUTE_ACK_RECOVERED_CODE="PLATFORM_DEPLOYMENT_EXECUTOR_POST_COMMIT_ROUTE_ACK_RECOVERED";RUNTIME_COMMITTED_ACTIVATION_ROUTE_REPAIRED_CODE="RUNTIME_COMMITTED_ACTIVATION_ROUTE_REPAIRED";STALE_STATIC_LIVE_RELEASE_CONVERGED_CODE="PLATFORM_STALE_STATIC_LIVE_RELEASE_CONVERGED";DEPLOYMENT_EXECUTOR_COMPLETED_RECEIPT_CODES=new Set(["PLATFORM_DEPLOYMENT_EXECUTOR_COMPLETED",POST_COMMIT_ROUTE_ACK_RECOVERED_CODE,RUNTIME_COMMITTED_ACTIVATION_ROUTE_REPAIRED_CODE,STALE_STATIC_LIVE_RELEASE_CONVERGED_CODE])}});import{and as and16,eq as eq19}from"drizzle-orm";function mergeWarningSnapshot(old,warning){const conflict3=old?.managedBom&&warning.managedBom&&JSON.stringify(old.managedBom)!==JSON.stringify(warning.managedBom);if(old?.managedBomConflict||warning.managedBomConflict||conflict3){if(conflict3)console.warn("MANAGED_BOM_DIAGNOSTIC_INCOMPLETE");return{code:warning.code,phase:warning.phase,message:warning.message,count:Math.max(old?.count??0,warning.count),managedBomConflict:true}}return{...old?.managedBom?old:warning,count:Math.max(old?.count??0,warning.count)}}function normalizeWarningSnapshots(input2){if(!Array.isArray(input2)||input2.length>1e3)throw new Error("DEPLOYMENT_EXECUTOR_RECEIPT_WARNING_INVALID");const normalized=new Map;for(let offset=0;offset<input2.length;offset+=MAX_RECEIPT_WARNINGS){for(const warning of sanitizeDeploymentExecutorWarnings(input2.slice(offset,offset+MAX_RECEIPT_WARNINGS))){const key2=warningKey(warning);normalized.set(key2,{...warning,count:Math.min(1e3,warning.count+(normalized.get(key2)?.count??0))})}}const snapshots=new Map;for(const warning of input2){const key2=warningKey(warning);snapshots.set(key2,mergeWarningSnapshot(snapshots.get(key2),warning))}return[...normalized.values()].map(warning=>({...snapshots.get(warningKey(warning)),count:warning.count}))}function mergeDeploymentExecutorWarnings(prior=[],next=[]){const warnings=new Map;for(const warning of[...normalizeWarningSnapshots(prior),...normalizeWarningSnapshots(next)]){const key2=warningKey(warning);warnings.set(key2,mergeWarningSnapshot(warnings.get(key2),warning))}const incomplete=[...warnings.values()].some(w2=>w2.code===INCOMPLETE_WARNING.code);const retained=[...warnings.values()].filter(w2=>w2.code!==INCOMPLETE_WARNING.code);retained.sort((a,b2)=>Number(REQUIRED_WARNING_CODES.has(b2.code))-Number(REQUIRED_WARNING_CODES.has(a.code))||warningKey(a).localeCompare(warningKey(b2)));const overflow=incomplete||retained.length>MAX_RECEIPT_WARNINGS;return sanitizeDeploymentExecutorWarnings(overflow?[...retained.slice(0,MAX_RECEIPT_WARNINGS-1),{...INCOMPLETE_WARNING}]:retained)}async function readStoredDeploymentReceipt(input2){const rows8=await input2.db.select({receiptJson:deployments.executorReceiptJson,receiptSha256:deployments.executorReceiptSha256}).from(deployments).where(and16(eq19(deployments.id,input2.deploymentId),eq19(deployments.appId,input2.appId))).limit(1);return rows8[0]}function warningsFromStoredDeploymentReceipt(row){if(!row||row.receiptJson===null&&row.receiptSha256===null)return[];const verified=readVerifiedDeploymentExecutorReceipt(row);if(verified)return verified.warnings??[];if(row.receiptSha256===null&&row.receiptJson!==null){try{const legacy=sanitizeDeploymentExecutorReceipt(JSON.parse(row.receiptJson));if(!legacy.warnings?.length)return[]}catch{}}throw new Error("DEPLOYMENT_EXECUTOR_WARNING_RECEIPT_UNVERIFIED")}async function carryDeploymentExecutorWarnings(input2){let prior;let deferredSince;try{const row=await readStoredDeploymentReceipt(input2);prior=warningsFromStoredDeploymentReceipt(row);deferredSince=row?readVerifiedDeploymentExecutorReceipt(row)?.deferredSince:void 0}catch(error62){if(error62 instanceof Error&&error62.message==="DEPLOYMENT_EXECUTOR_WARNING_RECEIPT_UNVERIFIED"&&input2.receipt.phase==="recovery_required"&&input2.receipt.code==="DEPLOYMENT_EXECUTOR_LEASE_RECORD_INVALID")return input2.receipt;throw error62}const warnings=mergeDeploymentExecutorWarnings(prior,input2.receipt.warnings);const nonterminal=!["completed","failed","recovery_required"].includes(input2.receipt.phase);return{...input2.receipt,...nonterminal&&deferredSince&&!input2.receipt.deferredSince?{deferredSince}:{},...warnings.length?{warnings}:{}}}function publicDeploymentExecutorWarnings(warnings){return warnings.map(w2=>publicManagedBomWarning(w2)??{code:w2.code,phase:w2.phase,message:w2.message,count:w2.count})}var INCOMPLETE_WARNING,REQUIRED_WARNING_CODES,warningKey;var init_deployment_executor_warning_receipt=__esm({"../platform/src/deployment-executor-warning-receipt.ts"(){"use strict";init_schema();init_managed_bom_diagnostic();init_deployment_executor_completion_contract();init_deployment_executor_operation();INCOMPLETE_WARNING={code:"DEPLOYMENT_WARNINGS_INCOMPLETE",phase:"diagnostics",message:"Some deployment warnings were omitted because the receipt reached its capacity.",count:1};REQUIRED_WARNING_CODES=new Set(["MANAGED_BOM_WARNING","MANAGED_BOM_MISMATCH","ROUTE_CONVERGENCE_BLOCKED","PLATFORM_STALE_ROUTE_ONLY_RESUME","PLATFORM_STALE_PROJECTION_DEFERRED","PLATFORM_STALE_RELEASE_PROJECTION_SKIPPED"]);warningKey=warning=>`${warning.phase}:${warning.code}:${warning.message}`}});import{and as and17,asc as asc3,eq as eq20,gt as gt5,inArray as inArray9,lte as lte4,ne as ne9,notExists,or as or8,sql as sql99}from"drizzle-orm";import{alias as alias2}from"drizzle-orm/pg-core";async function findActiveAppDeploymentExecutor(input2){return(await input2.db.select({id:deployments.id,correlationId:deployments.correlationId}).from(deployments).where(and17(eq20(deployments.appId,input2.appId),eq20(deployments.status,"pending"),inArray9(deployments.executorState,[...NONTERMINAL_DEPLOYMENT_EXECUTOR_STATES]))).limit(1))[0]??null}function attemptConditions(attempt){return and17(eq20(deployments.id,attempt.deploymentId),eq20(deployments.appId,attempt.appId),eq20(deployments.env,attempt.env),eq20(deployments.attemptId,attempt.attemptId))}async function enqueueDeploymentExecutorOperation(input2){const targetOwnerIdentity=parseDeploymentExecutorOwnerId(input2.targetOwnerId);if(!/^deployment-payload-v1\.[a-zA-Z0-9_-]{8,160}\.[a-f0-9]{64}$/u.test(input2.payloadRef)||!/^[a-z0-9][a-z0-9-]{0,62}$/u.test(input2.targetNodeId)||!/^[a-z0-9][a-z0-9-]{0,31}$/u.test(input2.targetSlotId)||!/^[a-f0-9]{40}$/u.test(input2.targetRevision)||!targetOwnerIdentity||targetOwnerIdentity.nodeId!==input2.targetNodeId||targetOwnerIdentity.slotId!==input2.targetSlotId||targetOwnerIdentity.revision!==input2.targetRevision||!/^[a-f0-9]{64}$/u.test(input2.targetGenerationDigest)||!input2.appInstanceId||!input2.userId||input2.releaseAttemptId!==void 0&&input2.releaseAttemptId!==null&&!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u.test(input2.releaseAttemptId)||input2.localProjectDir!==void 0&&input2.localProjectDir!==null&&(input2.localProjectDir.length>4096||/[\0\r\n]/u.test(input2.localProjectDir)||input2.localProjectDir.normalize("NFC")!==input2.localProjectDir||!input2.localProjectDir.startsWith("/")&&!/^[A-Za-z]:[\\/]/u.test(input2.localProjectDir)||input2.localProjectDir.replaceAll("\\","/").split("/").includes(".."))||!Number.isSafeInteger(input2.payloadBytes)||input2.payloadBytes<=0||input2.payloadBytes>100*1024*1024){throw new Error("DEPLOYMENT_EXECUTOR_PAYLOAD_REF_INVALID")}const maxQueuedOperations=input2.maxQueuedOperations??DEFAULT_MAX_QUEUED_OPERATIONS;const maxQueuedBytes=input2.maxQueuedBytes??DEFAULT_MAX_QUEUED_BYTES;const maxUserOperations=input2.maxUserOperations??DEFAULT_MAX_USER_OPERATIONS;const maxUserBytes=input2.maxUserBytes??DEFAULT_MAX_USER_BYTES;if(!Number.isSafeInteger(maxQueuedOperations)||maxQueuedOperations<1||!Number.isSafeInteger(maxQueuedBytes)||maxQueuedBytes<input2.payloadBytes||!Number.isSafeInteger(maxUserOperations)||maxUserOperations<1||!Number.isSafeInteger(maxUserBytes)||maxUserBytes<input2.payloadBytes){throw new Error("DEPLOYMENT_EXECUTOR_CAPACITY_CONFIG_INVALID")}const[appBusy,capacityRows,userCapacityRows]=await Promise.all([findActiveAppDeploymentExecutor({db:input2.db,appId:input2.attempt.appId}),input2.db.select({count:sql99`count(*)::integer`,bytes:sql99`coalesce(sum(${deployments.executorPayloadBytes}), 0)::bigint`}).from(deployments).where(and17(eq20(deployments.status,"pending"),eq20(deployments.executorTargetNodeId,input2.targetNodeId),inArray9(deployments.executorState,[...NONTERMINAL_DEPLOYMENT_EXECUTOR_STATES]))),input2.db.select({count:sql99`count(*)::integer`,bytes:sql99`coalesce(sum(${deployments.executorPayloadBytes}), 0)::bigint`,blockingOperationId:sql99`min(${deployments.id})::integer`,blockingCorrelationId:sql99`(array_agg(${deployments.correlationId} ORDER BY ${deployments.id}))[1]`}).from(deployments).innerJoin(apps,eq20(apps.id,deployments.appId)).where(and17(eq20(deployments.status,"pending"),eq20(apps.userId,input2.userId),eq20(deployments.executorState,"queued")))]);if(appBusy){throw new DeploymentExecutorAdmissionError("DEPLOYMENT_EXECUTOR_APP_BUSY",409,appBusy.id,appBusy.correlationId)}const queuedCount=Number(capacityRows[0]?.count??0);const queuedBytes=Number(capacityRows[0]?.bytes??0);if(queuedCount>=maxQueuedOperations||queuedBytes+input2.payloadBytes>maxQueuedBytes){throw new DeploymentExecutorAdmissionError("DEPLOYMENT_EXECUTOR_QUEUE_FULL",429)}const userCount=Number(userCapacityRows[0]?.count??0);const userBytes=Number(userCapacityRows[0]?.bytes??0);if(userCount>=maxUserOperations||userBytes+input2.payloadBytes>maxUserBytes){const blockingOperationId=Number(userCapacityRows[0]?.blockingOperationId??0);const blockingCorrelationId=userCapacityRows[0]?.blockingCorrelationId??null;throw new DeploymentExecutorAdmissionError("DEPLOYMENT_EXECUTOR_USER_QUEUE_FULL",429,Number.isSafeInteger(blockingOperationId)&&blockingOperationId>0?blockingOperationId:void 0,typeof blockingCorrelationId==="string"?blockingCorrelationId:void 0)}const now=input2.now??new Date;const expectedControlPlaneState=input2.expectedControlPlaneState??"admitted";const rows8=await input2.db.update(deployments).set({executorState:"queued",executorTargetNodeId:input2.targetNodeId,executorTargetSlotId:input2.targetSlotId,executorTargetRevision:input2.targetRevision,executorTargetOwnerId:input2.targetOwnerId,executorTargetGenerationDigest:input2.targetGenerationDigest,executorAppInstanceId:input2.appInstanceId,executorPayloadBytes:input2.payloadBytes,executorPayloadRef:input2.payloadRef,executorReleaseAttemptId:input2.releaseAttemptId??null,executorLocalProjectDir:input2.localProjectDir??null,executorQueuedAt:now,executorUpdatedAt:now}).where(and17(attemptConditions(input2.attempt),eq20(deployments.status,"pending"),eq20(deployments.controlPlaneState,expectedControlPlaneState),eq20(deployments.executorState,"not_queued"))).returning({id:deployments.id});if(rows8.length!==1){const conflictRows=await input2.db.select({status:deployments.status,controlPlaneState:deployments.controlPlaneState,executorState:deployments.executorState}).from(deployments).where(attemptConditions(input2.attempt)).limit(1);const conflict3=conflictRows[0];const safeState=value2=>typeof value2==="string"&&/^[a-z_]{2,40}$/u.test(value2)?value2.toUpperCase():"UNKNOWN";throw new Error(conflict3?`DEPLOYMENT_EXECUTOR_ENQUEUE_CONFLICT_${safeState(conflict3.status)}_${safeState(conflict3.controlPlaneState)}_${safeState(conflict3.executorState)}`:"DEPLOYMENT_EXECUTOR_ENQUEUE_CONFLICT_ATTEMPT_ABSENT")}}async function finishDeploymentExecutorOperation(input2){assertDeploymentExecutorTransition(input2.operation.executorState,input2.state);const receipt=sanitizeDeploymentExecutorReceipt(await carryDeploymentExecutorWarnings({db:input2.db,...input2.operation,receipt:input2.receipt}));const receiptJson=JSON.stringify(receipt);const now=input2.now??new Date;const rows8=await input2.db.update(deployments).set({executorState:input2.state,...input2.state==="recovery_required"?{}:{executorPayloadRef:null},executorReceiptJson:receiptJson,executorReceiptSha256:hashDeploymentExecutorReceipt(receipt),executorUpdatedAt:now,...input2.activation?{bundleHash:input2.activation.bundleHash,status:"running",controlPlaneState:"active",callableBackend:input2.activation.callableBackend,failureStage:null,failureCode:null,errorMessage:null}:{},...input2.failure?{failureStage:input2.failure.stage,failureCode:input2.failure.code,candidateCleanupFailureCode:input2.failure.candidateCleanupFailureCode??null,errorMessage:input2.failure.legacyMessage.slice(0,300)}:{},...input2.state==="failed"?{status:"failed",controlPlaneState:"failed"}:{},...input2.clearLease===false?{}:{attemptOwnerId:null,attemptLeaseExpiresAt:null}}).where(and17(eq20(deployments.id,input2.operation.deploymentId),eq20(deployments.appId,input2.operation.appId),eq20(deployments.attemptId,input2.operation.attemptId),eq20(deployments.attemptOwnerId,input2.operation.ownerId),eq20(deployments.executorLeaseEpoch,input2.operation.leaseEpoch),input2.allowExpiredLease?lte4(deployments.attemptLeaseExpiresAt,now):gt5(deployments.attemptLeaseExpiresAt,now),eq20(deployments.executorState,input2.operation.executorState))).returning({id:deployments.id});if(rows8.length!==1)throw new Error("DEPLOYMENT_EXECUTOR_TERMINAL_CONFLICT");input2.operation.executorState=input2.state}async function getOwnedDeploymentExecutorStatus(input2){const rows8=await input2.db.select({deploymentId:deployments.id,appId:deployments.appId,appName:apps.name,appPort:apps.port,currentStaticDeployId:apps.currentStaticDeployId,currentStaticGenerationRef:apps.currentStaticGenerationRef,appInstanceId:apps.instanceId,executorAppInstanceId:deployments.executorAppInstanceId,releaseAttemptId:deployments.executorReleaseAttemptId,releaseEnvironment:appReleaseAttempts.environment,staticSize:apps.staticSize,bundleHash:deployments.bundleHash,status:deployments.status,controlPlaneState:deployments.controlPlaneState,executorState:deployments.executorState,environment:deployments.env,targetNodeId:deployments.executorTargetNodeId,targetSlotId:deployments.executorTargetSlotId,targetRevision:deployments.executorTargetRevision,targetOwnerId:deployments.executorTargetOwnerId,targetGenerationDigest:deployments.executorTargetGenerationDigest,correlationId:deployments.correlationId,failureStage:deployments.failureStage,failureCode:deployments.failureCode,candidateCleanupFailureCode:deployments.candidateCleanupFailureCode,receiptJson:deployments.executorReceiptJson,receiptSha256:deployments.executorReceiptSha256,queuedAt:deployments.executorQueuedAt}).from(deployments).innerJoin(apps,eq20(apps.id,deployments.appId)).leftJoin(appReleaseAttempts,and17(eq20(appReleaseAttempts.id,deployments.executorReleaseAttemptId),eq20(appReleaseAttempts.appId,deployments.appId))).where(and17(eq20(deployments.id,input2.deploymentId),eq20(apps.userId,input2.userId))).limit(1);return rows8[0]??null}var NONTERMINAL_DEPLOYMENT_EXECUTOR_STATES,DEFAULT_MAX_QUEUED_OPERATIONS,DEFAULT_MAX_QUEUED_BYTES,DEFAULT_MAX_USER_OPERATIONS,DEFAULT_MAX_USER_BYTES,DeploymentExecutorAdmissionError;var init_deployment_executor_store=__esm({"../platform/src/deployment-executor-store.ts"(){"use strict";init_deployment_executor_warning_receipt();init_schema();init_postgres_temporal2();init_deployment_failure_contract();init_deployment_release_scope();init_deployment_executor_operation();NONTERMINAL_DEPLOYMENT_EXECUTOR_STATES=["queued","claimed","database_preparing","schema_executing","runtime_preparing","candidate_attesting","committing","reconciling"];DEFAULT_MAX_QUEUED_OPERATIONS=128;DEFAULT_MAX_QUEUED_BYTES=512*1024*1024;DEFAULT_MAX_USER_OPERATIONS=8;DEFAULT_MAX_USER_BYTES=200*1024*1024;DeploymentExecutorAdmissionError=class extends Error{constructor(code,httpStatus,blockingOperationId,blockingCorrelationId,requestId){super(code);this.code=code;this.httpStatus=httpStatus;this.blockingOperationId=blockingOperationId;this.blockingCorrelationId=blockingCorrelationId;this.requestId=requestId}code;httpStatus;blockingOperationId;blockingCorrelationId;requestId}}});import{sql as sql100}from"drizzle-orm";function decodeAppDeleteErrorCode(stored){if(!stored?.startsWith(SEAL_PREFIX))return{code:stored,seal:null};const[failedState,cause,...extra]=stored.slice(SEAL_PREFIX.length).split(":");const stage=APP_DELETE_STAGE_BY_STATE[failedState??""];if(extra.length>0||!stage||!cause||cause!==NO_CAUSE&&!STABLE_CAUSE_PATTERN.test(cause)){return{code:APP_DELETE_RECOVERY_DEADLINE_CODE,seal:null}}return{code:APP_DELETE_RECOVERY_DEADLINE_CODE,seal:{failedState,stage,causeCode:cause===NO_CAUSE?null:cause}}}var APP_DELETE_RECOVERY_DEADLINE_CODE,SEAL_PREFIX,NO_CAUSE,STABLE_CAUSE_PATTERN,APP_DELETE_STAGE_BY_STATE;var init_app_delete_recovery_deadline=__esm({"../platform/src/app-delete-recovery-deadline.ts"(){"use strict";init_schema();APP_DELETE_RECOVERY_DEADLINE_CODE="APP_DELETE_RECOVERY_DEADLINE_EXCEEDED";SEAL_PREFIX=`${APP_DELETE_RECOVERY_DEADLINE_CODE}:`;NO_CAUSE="NONE";STABLE_CAUSE_PATTERN=/^[A-Z][A-Z0-9_]{2,127}$/u;APP_DELETE_STAGE_BY_STATE={accepted:"admission",stopping_children:"admission",draining_runtime:"runtime-stop",stop_dispatched:"runtime-stop",blocked_ownership_ambiguous:"runtime-stop",blocked_active_work:"runtime-stop",blocked_runtime_outcome_unknown:"runtime-stop",runtime_absent:"tenant-database",tenant_db_drop_pending:"tenant-database",failed_tenant_db_cleanup:"tenant-database",catalog_delete_pending:"catalog-finalize",failed_catalog_cleanup:"catalog-finalize",blocked_catalog_outcome_unknown:"catalog-finalize"}}});function recoveryDeadlineDiagnostic(operation,statusAction){const seal=operation.deadlineSeal;if(operation.state!=="failed_delete_recovery_required"||!seal)return{};return{error:`Delete stopped in the ${seal.stage} stage and passed its recovery deadline. Inspect the same operation with ${statusAction}.`,stage:seal.stage,failedState:seal.failedState,...seal.causeCode?{causeCode:seal.causeCode}:{},stateImpact:DEADLINE_STATE_IMPACT[seal.stage],retryPrecondition:"Run the app delete again; it reopens this same operation. If it stops at the same stage with the same cause code, Platform must clear that cause first.",retryClass:"retryable-infra",userAction:"RETRY"}}function runtimeAbsenceDiagnostic(operation,statusAction){if(operation.lastErrorCode!=="APP_DELETE_RUNTIME_EXTERNAL_ABSENCE_SCOPE_REQUIRED"&&operation.lastErrorCode!=="APP_DELETE_RUNTIME_EXTERNAL_ABSENCE_UNPROVEN"){return{}}const stage=operation.state==="blocked_runtime_outcome_unknown"?"runtime-absence":operation.state==="failed_catalog_cleanup"?"pre-catalog":void 0;if(!stage)return{};const scopeRequired=operation.lastErrorCode==="APP_DELETE_RUNTIME_EXTERNAL_ABSENCE_SCOPE_REQUIRED";return{error:scopeRequired?`Delete cleanup is waiting for Platform to restore exact app placement and ownership. Inspect the same operation with ${statusAction}.`:`Delete cleanup is waiting for Platform to complete exact runtime-absence observation. Inspect the same operation with ${statusAction}.`,stage,capability:"runtime-absence",stateImpact:stage==="pre-catalog"?"The tenant database cleanup step completed, but independent absence is not yet verified; catalog deletion was not recorded. Runtime may have changed.":"The same delete receipt remains active; this runtime proof did not delete the catalog. Runtime or tenant database cleanup may already have occurred.",retryable:false,retryPrecondition:scopeRequired?"Platform must restore exact app placement, current node ownership, and app incarnation; then recheck the same receipt.":"Platform must complete exact runtime absence observation; then recheck the same receipt.",retryClass:"platform-action",userAction:"VIEW_DELETE_STATUS",nextAction:"VIEW_DELETE_STATUS"}}function catalogOnlyEffectDiagnostic(operation,statusAction){return operation.state==="failed_catalog_cleanup"&&["APP_DELETE_CATALOG_ONLY_EFFECTS_PRESENT","APP_DELETE_CATALOG_ONLY_IDENTITY_CHANGED"].includes(operation.lastErrorCode??"")?{error:`Delete cleanup found a changed catalog identity or runtime, deployment, child, or serving-route effect after admission. Inspect the same operation with ${statusAction}.`,stage:"pre-catalog",capability:"catalog-effect-reconciliation",stateImpact:"Tenant database cleanup may have completed, but catalog deletion was not recorded; the same app and delete receipt remain authoritative.",retryable:false,retryPrecondition:"Platform must classify and safely clear the newly observed effect, then reconcile the same delete receipt.",retryClass:"platform-action",userAction:"VIEW_DELETE_STATUS",nextAction:"VIEW_DELETE_STATUS"}:{}}function platformOwnedStateDiagnostic(operation,statusAction){if(!(operation.state in PLATFORM_OWNED_STATE_TEXT))return{};const state2=operation.state;const text33=PLATFORM_OWNED_STATE_TEXT[state2];const childWait=state2==="stopping_children"&&operation.lastErrorCode===APP_DELETE_CHILD_NOT_CONVERGED_CODE;const causeCode=operation.lastErrorCode&&/^[A-Z][A-Z0-9_]{2,127}$/u.test(operation.lastErrorCode)?operation.lastErrorCode:null;return{error:childWait?`Delete is waiting for the child apps to finish deleting and is being retried automatically. Inspect the same operation with ${statusAction}.`:text33.error(statusAction),stage:APP_DELETE_STAGE_BY_STATE[state2],...causeCode?{causeCode}:{},stateImpact:childWait?CHILD_WAIT_STATE_IMPACT:text33.stateImpact,retryable:true,retryPrecondition:text33.retryPrecondition,retryClass:"platform-action",userAction:"VIEW_DELETE_STATUS",nextAction:"VIEW_DELETE_STATUS"}}function appDeleteStateDiagnostics(operation,statusAction){return{...platformOwnedStateDiagnostic(operation,statusAction),...runtimeAbsenceDiagnostic(operation,statusAction),...catalogOnlyEffectDiagnostic(operation,statusAction),...recoveryDeadlineDiagnostic(operation,statusAction)}}function blockedActiveWorkDiagnostic(operation,statusAction){if(operation.state!=="blocked_active_work")return{};return{error:`Delete is waiting for the app runtime to become idle and is being retried automatically. Inspect the same operation with ${statusAction}.`,stage:"runtime-stop",...operation.lastErrorCode?{causeCode:operation.lastErrorCode}:{},stateImpact:"The app is still running; its tenant data, routes, and catalog row were not changed by this delete.",retryable:true,retryPrecondition:"No action is needed first: the Platform retries this same operation about every 30 seconds until its recovery deadline. If it then reports failed_delete_recovery_required, run the app delete again.",retryClass:"platform-action",userAction:"VIEW_DELETE_STATUS",nextAction:"VIEW_DELETE_STATUS"}}var DEADLINE_STATE_IMPACT,APP_DELETE_CHILD_NOT_CONVERGED_CODE,CHILD_WAIT_STATE_IMPACT,PLATFORM_OWNED_STATE_TEXT;var init_app_delete_result_diagnostics=__esm({"../platform/src/app-delete-result-diagnostics.ts"(){"use strict";init_app_delete_recovery_deadline();DEADLINE_STATE_IMPACT={admission:"Deletion had not started any destructive step; the app, its routes, runtime, and tenant data are unchanged.","runtime-stop":"The app runtime stop did not finish. Tenant data and the app catalog row were not deleted.","tenant-database":"The runtime is stopped but tenant database cleanup did not finish. The app catalog row was not deleted.","catalog-finalize":"Runtime stop and tenant database cleanup may already be done, but the app catalog row was not deleted."};APP_DELETE_CHILD_NOT_CONVERGED_CODE="APP_DELETE_CHILD_NOT_CONVERGED";CHILD_WAIT_STATE_IMPACT="Child app deletions may already have changed child runtimes or data. This app is not deleted yet; its own runtime, tenant data and catalog row are unchanged.";PLATFORM_OWNED_STATE_TEXT={blocked_runtime_outcome_unknown:{error:statusAction=>`Delete is waiting for Platform to confirm the app runtime stop and is being retried automatically. Inspect the same operation with ${statusAction}.`,stateImpact:"The app runtime may already be stopped. Its tenant data and catalog row were not deleted.",retryPrecondition:"No action is needed first: Platform repeats the runtime stop on this same operation. Check its status before retrying. If it later reports a recovery required failure, run the app delete again."},stopping_children:{error:statusAction=>`Delete is waiting for earlier delete steps and is being retried automatically. Inspect the same operation with ${statusAction}.`,stateImpact:CHILD_WAIT_STATE_IMPACT,retryPrecondition:"No action is needed first: Platform retries the child deletes, then this same operation. Check its status before retrying. If it later reports a recovery required failure, run the app delete again."},failed_catalog_cleanup:{error:statusAction=>`Delete cleanup is waiting for Platform to finish catalog cleanup and is being retried automatically. Inspect the same operation with ${statusAction}.`,stateImpact:"Runtime stop and tenant database cleanup may already be done. The app catalog row may or may not be deleted yet.",retryPrecondition:"No action is needed first: Platform retries the catalog cleanup on this same operation. Check its status before retrying. If it later reports a recovery required failure, run the app delete again."}}}});import{sql as sql101}from"drizzle-orm";async function redriveRejectedServingRouteDeliveryInTransaction(input2){await input2.tx.execute(sql101`
|
|
8807
8807
|
SELECT set_config('app.current_user_id', '', true),
|
|
8808
8808
|
set_config('app.current_user_role', 'system', true),
|
|
8809
8809
|
set_config('app.internal_system', 'true', true)
|
|
@@ -9046,7 +9046,7 @@ ${argsDigest}`;const signature=sign3(null,Buffer.from(payload),scheduledJobDeliv
|
|
|
9046
9046
|
EXISTS (SELECT 1 FROM relation CROSS JOIN runtime_role WHERE has_table_privilege(runtime_role.rolname, relation.oid, 'INSERT')) AS app_can_insert,
|
|
9047
9047
|
EXISTS (SELECT 1 FROM relation CROSS JOIN runtime_role WHERE has_table_privilege(runtime_role.rolname, relation.oid, 'UPDATE')) AS app_can_update,
|
|
9048
9048
|
EXISTS (SELECT 1 FROM relation CROSS JOIN runtime_role WHERE has_table_privilege(runtime_role.rolname, relation.oid, 'DELETE')) AS app_can_delete
|
|
9049
|
-
`}});import{createHash as createHash51}from"node:crypto";function exactObject2(value2,fields,label){if(!value2||typeof value2!=="object"||Array.isArray(value2)){throw new TypeError(`${label} must be an object`)}const actual=Object.keys(value2).sort();const expected=[...fields].sort();if(actual.length!==expected.length||actual.some((key2,index27)=>key2!==expected[index27])){throw new TypeError(`${label} fields are invalid`)}return value2}function canonicalPath(value2){if(typeof value2!=="string"||value2.length===0||value2.length>512){throw new TypeError("codegen artifact path is invalid")}const normalized=value2.normalize("NFC").replaceAll("\\","/");if(normalized!==value2||normalized.startsWith("/")||normalized.split("/").some(part=>!part||part==="."||part==="..")){throw new TypeError("codegen artifact path is invalid")}return normalized}function hashGeneratedSchemaArtifacts(rows8){return createHash51("sha256").update(JSON.stringify(rows8)).digest("hex")}function compareCanonicalCodegenArtifactPaths(left,right){return left<right?-1:left>right?1:0}function canonicalizeCodegenArtifactProvenanceV1(value2){const record3=exactObject2(value2,["version","cliVersion","sourceRevision","generatedSchemaDigest","artifacts"],"codegen artifact provenance");if(record3.version!==1||typeof record3.cliVersion!=="string"||!VERSION3.test(record3.cliVersion)){throw new TypeError("codegen artifact provenance version is invalid")}if(typeof record3.sourceRevision!=="string"||!SHA2568.test(record3.sourceRevision)||typeof record3.generatedSchemaDigest!=="string"||!SHA2568.test(record3.generatedSchemaDigest)||!Array.isArray(record3.artifacts)||record3.artifacts.length>1e3){throw new TypeError("codegen artifact provenance digest is invalid")}const seen=new Set;const folded=new Set;const artifacts=record3.artifacts.map(candidate=>{const artifact=exactObject2(candidate,["path","size","sha256"],"codegen artifact");const path5=canonicalPath(artifact.path);const caseFolded=path5.toLocaleLowerCase("en-US");if(seen.has(path5)||folded.has(caseFolded)||!Number.isSafeInteger(artifact.size)||Number(artifact.size)<0||typeof artifact.sha256!=="string"||!SHA2568.test(artifact.sha256)){throw new TypeError("codegen artifact row is invalid")}seen.add(path5);folded.add(caseFolded);return{path:path5,size:Number(artifact.size),sha256:artifact.sha256}});const sorted=[...artifacts].sort((left,right)=>compareCanonicalCodegenArtifactPaths(left.path,right.path));if(JSON.stringify(sorted)!==JSON.stringify(artifacts)){throw new TypeError("codegen artifacts must be canonically sorted")}if(hashGeneratedSchemaArtifacts(artifacts)!==record3.generatedSchemaDigest){throw new TypeError("codegen artifact provenance digest mismatch")}return{version:1,cliVersion:record3.cliVersion,sourceRevision:record3.sourceRevision,generatedSchemaDigest:record3.generatedSchemaDigest,artifacts}}var SHA2568,VERSION3;var init_codegen_artifact_provenance=__esm({"../migration-contract/dist/codegen-artifact-provenance.js"(){"use strict";SHA2568=/^[a-f0-9]{64}$/u;VERSION3=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u}});import{createHash as createHash52}from"node:crypto";function assertExactObject(value2){if(!value2||typeof value2!=="object"||Array.isArray(value2)){throw new TypeError("deployment artifact identity must be an object")}const actual=Object.keys(value2).sort();const expected=[...IDENTITY_FIELDS,...Object.hasOwn(value2,"databaseCapability")?["databaseCapability"]:[]].sort();if(actual.length!==expected.length||actual.some((key2,index27)=>key2!==expected[index27])){throw new TypeError("deployment artifact identity fields are invalid")}}function assertVersion(value2,field){if(typeof value2!=="string"||!VERSION4.test(value2)||value2.length>128){throw new TypeError(`${field} is invalid`)}}function assertSha256(value2,field){if(typeof value2!=="string"||!SHA2569.test(value2)){throw new TypeError(`${field} must be a lowercase SHA-256`)}}function negotiateDeploymentArtifactIdentity(input2){if(input2.protocolVersion!==DEPLOYMENT_ARTIFACT_IDENTITY_PROTOCOL_VERSION){return{ok:false,code:"MIGRATION_BUNDLE_PROTOCOL_UNSUPPORTED"}}if(input2.filePlanVersion!==DEPLOYMENT_ARTIFACT_FILE_PLAN_VERSION){return{ok:false,code:"MIGRATION_BUNDLE_PLAN_VERSION_UNSUPPORTED"}}return{ok:true}}function canonicalizeDeploymentArtifactIdentityV2(value2){assertExactObject(value2);if(typeof value2.protocolVersion!=="number"||typeof value2.filePlanVersion!=="number"){throw new TypeError("deployment artifact identity versions are invalid")}const compatibility=negotiateDeploymentArtifactIdentity({protocolVersion:value2.protocolVersion,filePlanVersion:value2.filePlanVersion});if(!compatibility.ok)throw new TypeError(compatibility.code);assertVersion(value2.cliVersion,"cliVersion");assertVersion(value2.generatorVersion,"generatorVersion");assertSha256(value2.sourceRevision,"sourceRevision");assertSha256(value2.generatedSchemaDigest,"generatedSchemaDigest");if(Object.hasOwn(value2,"databaseCapability")&&value2.databaseCapability!==MIGRATION_DATABASE_CAPABILITY_EXPLICIT_DBLESS){throw new TypeError("databaseCapability is invalid")}assertSha256(value2.bundleSha256,"bundleSha256");assertSha256(value2.archiveSha256,"archiveSha256");return{protocolVersion:DEPLOYMENT_ARTIFACT_IDENTITY_PROTOCOL_VERSION,filePlanVersion:DEPLOYMENT_ARTIFACT_FILE_PLAN_VERSION,cliVersion:value2.cliVersion,generatorVersion:value2.generatorVersion,sourceRevision:value2.sourceRevision,generatedSchemaDigest:value2.generatedSchemaDigest,...Object.hasOwn(value2,"databaseCapability")?{databaseCapability:MIGRATION_DATABASE_CAPABILITY_EXPLICIT_DBLESS}:{},bundleSha256:value2.bundleSha256,archiveSha256:value2.archiveSha256}}function serializeDeploymentArtifactIdentityV2(value2){return JSON.stringify(canonicalizeDeploymentArtifactIdentityV2(value2))}function hashDeploymentArtifactIdentityV2(value2){return createHash52("sha256").update(serializeDeploymentArtifactIdentityV2(value2)).digest("hex")}var DEPLOYMENT_ARTIFACT_IDENTITY_PROTOCOL_VERSION,DEPLOYMENT_ARTIFACT_FILE_PLAN_VERSION,IDENTITY_FIELDS,SHA2569,VERSION4;var init_deployment_artifact_identity=__esm({"../migration-contract/dist/deployment-artifact-identity.js"(){"use strict";init_constants();DEPLOYMENT_ARTIFACT_IDENTITY_PROTOCOL_VERSION=2;DEPLOYMENT_ARTIFACT_FILE_PLAN_VERSION=1;IDENTITY_FIELDS=["protocolVersion","filePlanVersion","cliVersion","generatorVersion","sourceRevision","generatedSchemaDigest","bundleSha256","archiveSha256"];SHA2569=/^[a-f0-9]{64}$/u;VERSION4=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u}});var init_artifact_identity=__esm({"../migration-contract/dist/artifact-identity.js"(){"use strict";init_codegen_artifact_provenance();init_deployment_artifact_identity()}});import{createHash as createHash53}from"node:crypto";import{existsSync as existsSync25,lstatSync as lstatSync3,readFileSync as readFileSync21,readdirSync as readdirSync8}from"node:fs";import{relative as relative12,resolve as resolve61}from"node:path";function fail15(code){throw new MigrationBundleManifestError(code)}function sha2569(value2){return createHash53("sha256").update(value2).digest("hex")}function hasExactKeys(value2,keys2){if(!value2||typeof value2!=="object"||Array.isArray(value2))return false;const actual=Object.keys(value2).sort();const expected=[...keys2].sort();return actual.length===expected.length&&actual.every((key2,index27)=>key2===expected[index27])}function isSha256(value2){return typeof value2==="string"&&/^[a-f0-9]{64}$/u.test(value2)}function timestampFolderMillis(name){const millis=parseMigrationFolderMillis(name);if(millis===null)return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID");return millis}function readLegacyJournal(migrationsDir){const journalPath2=resolve61(migrationsDir,"meta","_journal.json");if(!existsSync25(journalPath2))return null;let parsed;try{parsed=JSON.parse(readFileSync21(journalPath2,"utf8"))}catch{return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const entries=parsed?.entries;if(!Array.isArray(entries))return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID");const journal=[...entries].sort((left,right)=>Number(left.idx)-Number(right.idx)).map(value2=>{const entry=value2;if(!Number.isSafeInteger(entry.idx)||!Number.isSafeInteger(entry.when)||Number(entry.when)<0||typeof entry.tag!=="string"||!entry.tag||entry.tag.includes("/")||entry.tag.includes("\\")){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return{index:Number(entry.idx),name:entry.tag,folderMillis:Number(entry.when)}});if(new Set(journal.map(entry=>entry.index)).size!==journal.length){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return journal.map(({name,folderMillis})=>({name,folderMillis}))}function currentMigrationSourceFiles(migrationsDir,entries){return entries.flatMap(name=>{const entryPath=resolve61(migrationsDir,name);const entryStats=lstatSync3(entryPath);const migrationSqlPath=resolve61(entryPath,"migration.sql");if(name==="meta"){if(!entryStats.isDirectory()||entryStats.isSymbolicLink()||existsSync25(migrationSqlPath)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return[]}if(!entryStats.isDirectory())return[];if(!existsSync25(migrationSqlPath))return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID");const sqlStats=lstatSync3(migrationSqlPath);if(!sqlStats.isFile()||sqlStats.isSymbolicLink()){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return[{name,folderMillis:timestampFolderMillis(name),path:migrationSqlPath}]})}function migrationSourceFiles(backendRoot){const migrationsDir=resolve61(backendRoot,"migrations");if(!existsSync25(migrationsDir))return[];const entries=readdirSync8(migrationsDir).sort();const journal=readLegacyJournal(migrationsDir);const legacyFiles=entries.filter(entry=>entry.endsWith(".sql"));const legacy=journal?journal.map(({name,folderMillis})=>({name,folderMillis,path:resolve61(migrationsDir,`${name}.sql`)})):legacyFiles.map(file2=>({name:file2.slice(0,-4),folderMillis:timestampFolderMillis(file2.slice(0,-4)),path:resolve61(migrationsDir,file2)}));if(legacy.some(migration=>!existsSync25(migration.path))||legacy.length!==legacyFiles.length){return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}const current=currentMigrationSourceFiles(migrationsDir,entries);const migrations=[...legacy,...current];if(new Set(migrations.map(migration=>migration.name)).size!==migrations.length){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return migrations.sort((left,right)=>left.folderMillis-right.folderMillis||left.name.localeCompare(right.name))}function bundleFileRows(backendRoot,directory=backendRoot){const rows8=[];for(const entry of readdirSync8(directory).sort()){const path5=resolve61(directory,entry);const stats=lstatSync3(path5);if(stats.isDirectory()){rows8.push(...bundleFileRows(backendRoot,path5));continue}if(!stats.isFile())return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH");const bytes2=readFileSync21(path5);rows8.push([relative12(backendRoot,path5).replaceAll("\\","/"),bytes2.length,sha2569(bytes2)])}return rows8}function archivePayloadRows(workspaceRoot,directory=workspaceRoot){const rows8=[];for(const entry of readdirSync8(directory).sort()){const path5=resolve61(directory,entry);const relativePath=relative12(workspaceRoot,path5).replaceAll("\\","/");if(relativePath===MIGRATION_BUNDLE_MANIFEST_PATH)continue;const stats=lstatSync3(path5);if(stats.isDirectory()){rows8.push(...archivePayloadRows(workspaceRoot,path5));continue}if(!stats.isFile()||stats.isSymbolicLink()){return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}const bytes2=readFileSync21(path5);rows8.push([relativePath.normalize("NFC"),bytes2.length,sha2569(bytes2)])}return rows8}function codegenProvenancePaths(directory){const paths=[];for(const entry of readdirSync8(directory).sort()){const path5=resolve61(directory,entry);const stats=lstatSync3(path5);if(stats.isDirectory())paths.push(...codegenProvenancePaths(path5));else if(stats.isFile()&&entry===CODEGEN_PROVENANCE_FILENAME)paths.push(path5)}return paths}function generatedArtifactRows(root2,directory=root2){const rows8=[];for(const entry of readdirSync8(directory).sort()){if(entry===CODEGEN_PROVENANCE_FILENAME)continue;const path5=resolve61(directory,entry);const stats=lstatSync3(path5);if(stats.isDirectory()){rows8.push(...generatedArtifactRows(root2,path5));continue}if(!stats.isFile()||stats.isSymbolicLink()){return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH")}const bytes2=readFileSync21(path5);rows8.push({path:relative12(root2,path5).replaceAll("\\","/").normalize("NFC"),size:bytes2.length,sha256:sha2569(bytes2)})}return rows8.sort((left,right)=>compareCanonicalCodegenArtifactPaths(left.path,right.path))}function deriveGeneratedSchemaDigest(backendRoot,expectedProvenance,fallbackDigest){const markers=codegenProvenancePaths(backendRoot);if(markers.length>1)return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH");if(markers.length===0)return fallbackDigest;let provenance;try{provenance=canonicalizeCodegenArtifactProvenanceV1(JSON.parse(readFileSync21(markers[0],"utf8")))}catch{return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH")}const rows8=generatedArtifactRows(resolve61(markers[0],".."));if(JSON.stringify(rows8)!==JSON.stringify(provenance.artifacts)||hashGeneratedSchemaArtifacts(rows8)!==provenance.generatedSchemaDigest||provenance.cliVersion!==expectedProvenance.cliVersion||expectedProvenance.sourceRevision!==void 0&&provenance.sourceRevision!==expectedProvenance.sourceRevision){return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH")}return provenance.generatedSchemaDigest}function tenantCapabilitySources(backendRoot,directory=backendRoot){const sources=[];for(const entry of readdirSync8(directory).sort()){const path5=resolve61(directory,entry);const stats=lstatSync3(path5);if(stats.isDirectory()){sources.push(...tenantCapabilitySources(backendRoot,path5));continue}const manifestPath=relative12(backendRoot,path5).replaceAll("\\","/");if(stats.isFile()&&isAuthSchemaSourcePath(manifestPath)){sources.push({path:manifestPath,source:readFileSync21(path5,"utf8")})}}return sources}function hasRateLimitCreationMigration(migrations){return migrations.some(({path:path5})=>/\bCREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:["']?public["']?\.)?["']?rate_limit["']?\b/iu.test(readFileSync21(path5,"utf8")))}function isForbiddenSecretFileName(name){if(name===".env")return true;if(!name.startsWith(".env."))return false;return name!==".env.example"&&name!==".env.sample"&&name!==".env.template"}function assertNoForbiddenSecretFiles(directory){for(const entry of readdirSync8(directory)){const path5=resolve61(directory,entry);const stats=lstatSync3(path5);if(stats.isDirectory()){assertNoForbiddenSecretFiles(path5)}else if(isForbiddenSecretFileName(entry)){return fail15("MIGRATION_BUNDLE_FORBIDDEN_SECRET_FILE")}}}function assertWorkspaceShape(workspaceRoot,allowDeploymentRootFiles){const rootEntries=readdirSync8(workspaceRoot).sort();if(!allowDeploymentRootFiles&&rootEntries.some(entry=>entry!=="gencow"&&entry!==".gencow")){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const backendRoot=resolve61(workspaceRoot,"gencow");const metadataDir=resolve61(workspaceRoot,".gencow");if(!existsSync25(backendRoot)||!lstatSync3(backendRoot).isDirectory()){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}assertNoForbiddenSecretFiles(backendRoot);if(!allowDeploymentRootFiles&&existsSync25(metadataDir)&&(!lstatSync3(metadataDir).isDirectory()||readdirSync8(metadataDir).some(entry=>entry!=="migration-bundle-manifest.json"))){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}}function isAuditMetadata(value2){return typeof value2==="string"&&value2.length>0&&value2.length<=128&&!/[\u0000-\u001f\u007f]/u.test(value2)}function parseManifest3(value2){const baseKeys=["protocolVersion","generator","generatorVersion","cliVersion","schemaSnapshotHash","migrations","bundleSha256"];const record3=value2&&typeof value2==="object"&&!Array.isArray(value2)?value2:null;const hasSourceMode=record3?Object.hasOwn(record3,"sourceMode"):false;const hasSchemaSources=record3?Object.hasOwn(record3,"schemaSources"):false;const hasDatabaseCapability=record3?Object.hasOwn(record3,"databaseCapability"):false;const hasRequiredTenantCapabilities=record3?Object.hasOwn(record3,"requiredTenantCapabilities"):false;const hasArtifactIdentity=record3?Object.hasOwn(record3,"artifactIdentity"):false;const hasArtifactIdentitySha256=record3?Object.hasOwn(record3,"artifactIdentitySha256"):false;const expectedKeys=[...baseKeys,...hasSourceMode?["sourceMode"]:[],...hasSchemaSources?["schemaSources"]:[],...hasDatabaseCapability?["databaseCapability"]:[],...hasRequiredTenantCapabilities?["requiredTenantCapabilities"]:[],...hasArtifactIdentity?["artifactIdentity"]:[],...hasArtifactIdentitySha256?["artifactIdentitySha256"]:[]];if(!hasExactKeys(value2,expectedKeys)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(value2.protocolVersion!==MIGRATION_BUNDLE_PROTOCOL_VERSION){return fail15("MIGRATION_BUNDLE_PROTOCOL_UNSUPPORTED")}const sourceMode=value2.sourceMode??"GENERATED";if(sourceMode!=="GENERATED"&&sourceMode!=="EXISTING_BUNDLE"){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(!isAuditMetadata(value2.generator)||!isAuditMetadata(value2.generatorVersion)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(typeof value2.cliVersion!=="string"||!/^\d+\.\d+\.\d+$/u.test(value2.cliVersion)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(!isSha256(value2.schemaSnapshotHash)||!isSha256(value2.bundleSha256)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(hasArtifactIdentity!==hasArtifactIdentitySha256){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}let artifactIdentity;if(hasArtifactIdentity){try{artifactIdentity=canonicalizeDeploymentArtifactIdentityV2(value2.artifactIdentity)}catch(error62){const message=error62 instanceof Error?error62.message:"";if(message==="MIGRATION_BUNDLE_PROTOCOL_UNSUPPORTED")return fail15(message);if(message==="MIGRATION_BUNDLE_PLAN_VERSION_UNSUPPORTED")return fail15(message);return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(!isSha256(value2.artifactIdentitySha256)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}}let requiredTenantCapabilities;if(hasRequiredTenantCapabilities){if(!Array.isArray(value2.requiredTenantCapabilities)||value2.requiredTenantCapabilities.length>32||value2.requiredTenantCapabilities.some(capability2=>typeof capability2!=="string"||!/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u.test(capability2))||new Set(value2.requiredTenantCapabilities).size!==value2.requiredTenantCapabilities.length){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(value2.requiredTenantCapabilities.some(capability2=>!MIGRATION_TENANT_CAPABILITIES_V1.includes(capability2))){return fail15("MIGRATION_BUNDLE_CAPABILITY_UNSUPPORTED")}requiredTenantCapabilities=[...value2.requiredTenantCapabilities]}let schemaSources;if(hasSchemaSources){if(!Array.isArray(value2.schemaSources)||value2.schemaSources.length>1e3){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const seen=new Set;const caseFolded=new Set;schemaSources=value2.schemaSources.map(source=>{if(!hasExactKeys(source,["path","sha256"])){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(typeof source.path!=="string"||source.path.length===0||source.path.length>512||source.path.startsWith("/")||source.path===".."||source.path.startsWith("../")||source.path.includes("\\")||source.path.split("/").some(part=>part===""||part==="."||part==="..")||!isSha256(source.sha256)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const folded=source.path.toLocaleLowerCase("en-US");if(seen.has(source.path)||caseFolded.has(folded)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}seen.add(source.path);caseFolded.add(folded);return{path:source.path,sha256:source.sha256}})}let databaseCapability;if(hasDatabaseCapability){if(value2.databaseCapability!==MIGRATION_DATABASE_CAPABILITY_EXPLICIT_DBLESS){return fail15("MIGRATION_BUNDLE_CAPABILITY_UNSUPPORTED")}databaseCapability=value2.databaseCapability}if(!Array.isArray(value2.migrations)||value2.migrations.length>1e4){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const migrations=value2.migrations.map(entry=>{if(!hasExactKeys(entry,["name","folderMillis","sqlSha256","requiredCapabilities"])){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(typeof entry.name!=="string"||entry.name.length===0||entry.name.length>255||entry.name.includes("/")||entry.name.includes("\\")||!Number.isSafeInteger(entry.folderMillis)||Number(entry.folderMillis)<0||!isSha256(entry.sqlSha256)||!Array.isArray(entry.requiredCapabilities)||entry.requiredCapabilities.some(capability2=>typeof capability2!=="string")){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(entry.requiredCapabilities.length!==1||entry.requiredCapabilities[0]!==MIGRATION_BUNDLE_CAPABILITY_V1){return fail15("MIGRATION_BUNDLE_CAPABILITY_UNSUPPORTED")}return entry});if(databaseCapability===MIGRATION_DATABASE_CAPABILITY_EXPLICIT_DBLESS&&(!hasSchemaSources||schemaSources?.length!==0||migrations.length!==0||requiredTenantCapabilities?.length)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return{...value2,...schemaSources?{schemaSources}:{},...databaseCapability?{databaseCapability}:{},...requiredTenantCapabilities?{requiredTenantCapabilities}:{},...artifactIdentity?{artifactIdentity,artifactIdentitySha256:value2.artifactIdentitySha256}:{},migrations}}function unsignedManifest(manifest,backendRoot){const schemaPath=resolve61(backendRoot,"schema.ts");if(!manifest.schemaSources&&!existsSync25(schemaPath)){return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}const schemaSources=manifest.schemaSources?.map(source=>{const sourcePath=resolve61(backendRoot,source.path);const stats=existsSync25(sourcePath)?lstatSync3(sourcePath):null;if(!stats?.isFile()||stats.isSymbolicLink()){return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}return{path:source.path,sha256:sha2569(readFileSync21(sourcePath))}});const migrations=migrationSourceFiles(backendRoot).map(migration=>({name:migration.name,folderMillis:migration.folderMillis,sqlSha256:sha2569(readFileSync21(migration.path)),requiredCapabilities:[MIGRATION_BUNDLE_CAPABILITY_V1]}));const derivedTenantCapabilities=deriveTenantCapabilities(tenantCapabilitySources(backendRoot));if(derivedTenantCapabilities.includes(MIGRATION_TENANT_CAPABILITY_AUTH_RATE_LIMIT_V1)&&!hasRateLimitCreationMigration(migrationSourceFiles(backendRoot))){return fail15("MIGRATION_BUNDLE_SCHEMA_CHANGE_WITHOUT_FORWARD_MIGRATION")}return{protocolVersion:MIGRATION_BUNDLE_PROTOCOL_VERSION,generator:manifest.generator,generatorVersion:manifest.generatorVersion,...manifest.sourceMode?{sourceMode:manifest.sourceMode}:{},cliVersion:manifest.cliVersion,...schemaSources?{schemaSources}:{},...manifest.databaseCapability?{databaseCapability:manifest.databaseCapability}:{},...manifest.requiredTenantCapabilities?{requiredTenantCapabilities:derivedTenantCapabilities}:{},schemaSnapshotHash:schemaSources?sha2569(JSON.stringify(schemaSources)):sha2569(readFileSync21(schemaPath)),migrations}}function verifyMigrationBundleManifest(workspaceRoot,requestCliVersion,allowDeploymentRootFiles=false,expectedArtifactIdentitySha256){assertWorkspaceShape(workspaceRoot,allowDeploymentRootFiles);const manifestPath=resolve61(workspaceRoot,MIGRATION_BUNDLE_MANIFEST_PATH);if(!existsSync25(manifestPath))return fail15("MIGRATION_BUNDLE_MANIFEST_REQUIRED");if(!lstatSync3(manifestPath).isFile())return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID");const raw2=readFileSync21(manifestPath);if(raw2.length===0||raw2.length>MAX_MANIFEST_BYTES){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}let parsed;try{parsed=JSON.parse(raw2.toString("utf8"))}catch{return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const manifest=parseManifest3(parsed);if(requestCliVersion!==void 0&&manifest.cliVersion!==requestCliVersion){return fail15("MIGRATION_BUNDLE_CLI_VERSION_MISMATCH")}const unsigned=unsignedManifest(manifest,resolve61(workspaceRoot,"gencow"));const derivedTenantCapabilities=deriveTenantCapabilities(tenantCapabilitySources(resolve61(workspaceRoot,"gencow")));if(manifest.schemaSnapshotHash!==unsigned.schemaSnapshotHash||JSON.stringify(manifest.schemaSources)!==JSON.stringify(unsigned.schemaSources)||manifest.databaseCapability!==unsigned.databaseCapability||JSON.stringify(manifest.migrations)!==JSON.stringify(unsigned.migrations)||manifest.requiredTenantCapabilities!==void 0&&JSON.stringify(manifest.requiredTenantCapabilities)!==JSON.stringify(derivedTenantCapabilities)||manifest.bundleSha256!==sha2569(JSON.stringify(bundleFileRows(resolve61(workspaceRoot,"gencow"))))){return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}let derivedArtifactIdentitySha256=null;if(manifest.artifactIdentity){const compatibility=negotiateDeploymentArtifactIdentity(manifest.artifactIdentity);if(!compatibility.ok)return fail15(compatibility.code);const derivedGeneratedSchemaDigest=deriveGeneratedSchemaDigest(resolve61(workspaceRoot,"gencow"),manifest.artifactIdentity,unsigned.schemaSnapshotHash);const derivedIdentity={...manifest.artifactIdentity,cliVersion:manifest.cliVersion,generatorVersion:manifest.generatorVersion,generatedSchemaDigest:derivedGeneratedSchemaDigest,bundleSha256:manifest.bundleSha256,archiveSha256:sha2569(JSON.stringify(archivePayloadRows(workspaceRoot)))};const derivedDigest=hashDeploymentArtifactIdentityV2(derivedIdentity);derivedArtifactIdentitySha256=derivedDigest;if(hashDeploymentArtifactIdentityV2(manifest.artifactIdentity)!==manifest.artifactIdentitySha256||derivedDigest!==manifest.artifactIdentitySha256||expectedArtifactIdentitySha256!==void 0&&expectedArtifactIdentitySha256!==manifest.artifactIdentitySha256){return fail15(expectedArtifactIdentitySha256?"PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH":"MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}}else{if(codegenProvenancePaths(resolve61(workspaceRoot,"gencow")).length>0){return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH")}if(expectedArtifactIdentitySha256!==void 0){return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH")}}const verifiedManifest=manifest.requiredTenantCapabilities===void 0&&derivedTenantCapabilities.length>0?{...manifest,requiredTenantCapabilities:derivedTenantCapabilities}:manifest;return{manifest:verifiedManifest,derivedArtifactIdentitySha256}}function assertDeploymentMigrationBundleManifest(workspaceRoot,requestCliVersion,expectedArtifactIdentitySha256){try{return verifyMigrationBundleManifest(workspaceRoot,requestCliVersion,true,expectedArtifactIdentitySha256).manifest}catch(error62){if(error62 instanceof MigrationBundleManifestError)throw error62;return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}}function verifyDeploymentMigrationBundleManifest(workspaceRoot,requestCliVersion,expectedArtifactIdentitySha256){try{return verifyMigrationBundleManifest(workspaceRoot,requestCliVersion,true,expectedArtifactIdentitySha256)}catch(error62){if(error62 instanceof MigrationBundleManifestError)throw error62;return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}}var MAX_MANIFEST_BYTES,MigrationBundleManifestError,CODEGEN_PROVENANCE_FILENAME;var init_migration_bundle_manifest=__esm({"../platform/src/migration-bundle-manifest.ts"(){"use strict";init_artifact_identity();init_dist();MAX_MANIFEST_BYTES=1024*1024;MigrationBundleManifestError=class extends Error{code;constructor(code){super(code);this.name="MigrationBundleManifestError";this.code=code}};CODEGEN_PROVENANCE_FILENAME=".gencow-codegen-provenance.json"}});function isKnownMigrationError(error62){return error62 instanceof LegacyMigrationSqlAuditError||error62 instanceof MigrationThinPolicyError||error62 instanceof MigrationExecutionPlanError||error62 instanceof MigrationTransactionRolledBackError||error62 instanceof MigrationJournalReadError||error62 instanceof MigrationSchemaLockError||error62 instanceof MigrationCheckCapabilityError||error62 instanceof MigrationFormatUnsupportedError||error62 instanceof MigrationGenerationFailedError||error62 instanceof MigrationHistoryRequiredError||error62 instanceof MigrationHistoryRecoveryRequiredError||error62 instanceof MigrationPrimaryFormatError||error62 instanceof MigrationProofInfrastructureError||error62 instanceof DrizzleMigrationStorePreflightError||error62 instanceof MigrationPushPreflightError||error62 instanceof TenantSchemaPostconditionError||error62 instanceof MigrationBundleManifestError||error62 instanceof Error&&error62.code==="PRE_DEPLOY_SAFETY_BACKUP_REQUIRED"}function safeText(value2,maxLength=200){if(typeof value2!=="string"||value2.length===0||value2.length>maxLength)return void 0;return/[\u0000-\u001f\u007f]/u.test(value2)?void 0:value2}function safeReasonCode(value2,fallback){return typeof value2==="string"&&/^[a-z0-9_:-]{1,80}$/u.test(value2)?value2:fallback}function safeMigration(error62){const migration=error62.migration;if(migration&&safeText(migration.name,240)&&/^[a-f0-9]{64}$/u.test(migration.sqlSha256)&&(migration.statementIndex===void 0||Number.isSafeInteger(migration.statementIndex)&&migration.statementIndex>0)&&(migration.lineStart===void 0||Number.isSafeInteger(migration.lineStart)&&migration.lineStart>0)&&(migration.lineEnd===void 0||Number.isSafeInteger(migration.lineEnd)&&migration.lineEnd>0&&(migration.lineStart===void 0||migration.lineEnd>=migration.lineStart))){return{...migration}}const name=safeText(error62.migrationName,240);const hash9=safeText(error62.migrationHash,64);return name&&hash9&&/^[a-f0-9]{64}$/u.test(hash9)?{name,sqlSha256:hash9}:void 0}function platformDiagnostic(code,reasonCode,correlationId,migration,operation){return retryableInfraDiagnostic({code,phase:code.startsWith("MIGRATION_SQL_")?"AUDIT":"PREFLIGHT",databaseState:"UNCHANGED",retryPolicy:"AFTER_DELAY",retryAfterSeconds:30,retryCondition:"Wait for the transient platform condition to clear, then retry the same immutable bundle.",correlationId,migration,operation,reason:{code:reasonCode,summary:"The migration runner is temporarily unavailable for this plan.",detail:"No tenant migration statement ran. Keep the source unchanged and retry after the indicated delay."},suggestedFixes:[],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}function migrationBundleManifestDiagnostic(error62,correlationId){const contract=MIGRATION_BUNDLE_ERROR_CONTRACT_V1[error62.code];const schemaChangeWithoutForwardMigration=error62.code==="MIGRATION_BUNDLE_SCHEMA_CHANGE_WITHOUT_FORWARD_MIGRATION";const common={code:error62.code,phase:"PREFLIGHT",databaseState:"UNCHANGED",correlationId,retryCondition:contract.failureClass==="USER_FIXABLE"?"Correct the project migration source, create a fresh immutable bundle, then retry the deployment.":contract.failureClass==="RETRYABLE_INFRA"?"Wait for the platform rollout to converge, then retry the same immutable bundle.":contract.nextAction==="UPDATE_CLI"?"Install a supported Gencow CLI and create a fresh migration bundle.":"Keep the source and operation identity unchanged while the platform state is inspected.",reason:{code:error62.code.toLowerCase(),summary:schemaChangeWithoutForwardMigration?"The migration bundle declares a schema change without its forward migration.":"The migration bundle failed manifest verification.",detail:schemaChangeWithoutForwardMigration?"The bundle was rejected before tenant database access or mutation. Add the missing forward migration in the project source and create a fresh bundle.":"The request was rejected after archive extraction and manifest verification, before tenant database access or mutation."},suggestedFixes:contract.failureClass==="USER_FIXABLE"?[{id:schemaChangeWithoutForwardMigration?"generate-forward-migration":"regenerate-bundle-from-trusted-source",title:schemaChangeWithoutForwardMigration?"Create the forward migration":"Regenerate the migration bundle",detail:schemaChangeWithoutForwardMigration?"Run gencow db:generate, review the forward migration, then create a fresh deployment bundle.":"Verify the project schema and migration files, then create a fresh bundle from trusted source files.",target:contract.fixTarget,confidence:"HIGH"}]:[],docsUrl:MIGRATION_CAPABILITY_MANIFEST_V1.docsUrl,supportedCliRange:MIGRATION_CAPABILITY_MANIFEST_V1.supportedCliRange,forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}};if(contract.failureClass==="USER_FIXABLE")return userFixableDiagnostic(common);if(contract.failureClass==="RETRYABLE_INFRA"){return retryableInfraDiagnostic({...common,retryPolicy:"AFTER_DELAY",retryAfterSeconds:15})}return platformActionDiagnostic({...common,nextAction:contract.nextAction==="UPDATE_CLI"?"UPDATE_CLI":"INSPECT_STATE"})}function recoveryDiagnostic(code,correlationId,context={}){const hasReceipt=typeof context.receiptId==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(context.receiptId);return recoveryRequiredDiagnostic({code:"MIGRATION_STATE_PROOF_UNAVAILABLE",phase:code==="MIGRATION_POSTCONDITION_FAILED"||code==="DB_MIGRATION_LOCK_RELEASE_FAILED"?"VERIFY":context.phase??"EXECUTE",retryCondition:"Retry only after Gencow verifies the migration journal and PostgreSQL catalog state.",correlationId,...hasReceipt?{receiptId:context.receiptId}:{},reason:{code:code.toLowerCase(),summary:"The final database state could not be proven automatically.",detail:"A blind retry could duplicate or conflict with an already committed change, so execution is blocked pending recovery verification."},suggestedFixes:[],nextAction:hasReceipt?"VIEW_STATUS":"INSPECT_STATE",forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}function buildActionableMigrationDiagnostic(error62,correlationId,context={}){const coded=isKnownMigrationError(error62)?error62:{};const planId=typeof coded.planId==="string"&&/^mig_[a-f0-9]{24}$/u.test(coded.planId)?coded.planId:void 0;const finalize2=diagnostic=>certifyActionableMigrationDiagnostic({...diagnostic,...planId?{planId}:{},docsUrl:MIGRATION_CAPABILITY_MANIFEST_V1.docsUrl,supportedCliRange:MIGRATION_CAPABILITY_MANIFEST_V1.supportedCliRange});const code=typeof coded.code==="string"&&KNOWN_CODES.has(coded.code)?coded.code:void 0;if(!code){if(context.executionStarted){return finalize2(recoveryDiagnostic("MIGRATION_EXECUTION_OUTCOME_UNKNOWN",correlationId,context))}return finalize2(platformDiagnostic("MIGRATION_PREFLIGHT_SERVICE_UNAVAILABLE","migration_platform_preflight_failed",correlationId))}if(error62 instanceof MigrationBundleManifestError){return finalize2(migrationBundleManifestDiagnostic(error62,correlationId))}const reasonCode=safeReasonCode(coded.reasonCode,code.toLowerCase());const migration=safeMigration(coded);const objectKind=safeText(coded.objectKind,80);const objectName=safeText(coded.objectName,240);const operation=objectKind?{kind:objectKind,objectKind,...objectName?{objectName}:{}}:void 0;if(error62 instanceof LegacyMigrationSqlAuditError){return finalize2(platformDiagnostic(code,"legacy_policy_slot",correlationId,migration,operation))}if(error62 instanceof MigrationTransactionRolledBackError){return finalize2(buildRolledBackDiagnostic({error:error62,correlationId,migration,forbiddenActions:FORBIDDEN_ACTIONS}))}if(error62 instanceof MigrationPushPreflightError){return finalize2(platformDiagnostic(code,reasonCode,correlationId,migration,{kind:"migration_preflight",objectKind:"SERVICE",objectName:reasonCode}))}if(error62 instanceof MigrationCheckCapabilityError){if(error62.reasonCode!=="migration_check_database_unavailable"){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Correct the project migration history, then run the read-only check again.",correlationId,reason:{code:reasonCode,summary:"The project cannot be checked as a Drizzle v1 migration bundle.",detail:"Restore schema.ts and generate one consistent directory-style migration history. Do not mix legacy and v1 migration formats."},suggestedFixes:[{id:"repair-check-project-history",title:"Use one Drizzle v1 migration history",detail:"Restore schema.ts and keep only the supported directory-style migration format before creating a fresh bundle.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}return finalize2(platformDiagnostic(code,reasonCode,correlationId,migration,{kind:"migration_check_capability"}))}if(error62 instanceof MigrationPrimaryFormatError){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Generate a Drizzle v1 migration history, then create a fresh immutable bundle.",correlationId,reason:{code:reasonCode,summary:"A legacy server slot rejected the migration history format.",detail:"This compatibility diagnostic came from the retired format-only admission path; it does not prove that an empty schema needs a migration."},suggestedFixes:[{id:"generate-drizzle-v1-history",title:"Generate a Drizzle v1 migration history",detail:"Keep applied history immutable and generate a supported directory-style migration bundle.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(error62 instanceof MigrationHistoryRequiredError){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Generate an initial Drizzle v1 migration, then create a fresh immutable bundle.",correlationId,reason:{code:reasonCode,summary:"Migration history is required before this backend can be deployed.",detail:"The canonical schema contains database objects, but the bundle has no Drizzle v1 migration history."},suggestedFixes:[{id:"generate-initial-drizzle-history",title:"Generate the initial migration",detail:"Run gencow codegen and gencow db:generate, then deploy the fresh bundle.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(error62 instanceof MigrationHistoryRecoveryRequiredError){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",correlationId,retryCondition:"Restore the exact applied migration files from trusted version control, then create a fresh bundle.",reason:{code:reasonCode,summary:"Applied migration history is missing from this deployment bundle.",detail:"No migration ran for this request. Restore the original applied files and put new changes in a forward migration."},suggestedFixes:[{id:"restore-applied-lineage",title:"Restore the applied migration lineage",detail:"Recover the exact applied files from trusted version control without editing the database journal.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(error62 instanceof MigrationProofInfrastructureError){return finalize2(buildProofInfrastructureDiagnostic({error:error62,code,reasonCode,correlationId,forbiddenActions:[...FORBIDDEN_ACTIONS]}))}if(error62 instanceof MigrationGenerationFailedError){return finalize2(userFixableDiagnostic({code,phase:"GENERATE",databaseState:"UNCHANGED",retryCondition:"Fix the schema import or generator configuration, then generate a fresh bundle.",correlationId,reason:{code:reasonCode,summary:"The database schema could not be inspected safely.",detail:"Canonical schema generation failed, so the server did not assume that an empty migration folder was DBless."},suggestedFixes:[{id:"fix-schema-generation",title:"Fix schema generation",detail:"Run gencow codegen and gencow db:generate locally and fix the reported import or config error.",target:"SCHEMA_SOURCE",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(error62 instanceof TenantSchemaPostconditionError){const shared={code,phase:"VERIFY",correlationId,operation:{kind:"tenant_schema_postcondition",objectKind:"rate_limit"},reason:{code:reasonCode,summary:"The tenant Auth schema is not ready for this runtime.",detail:"The declared durable Auth rate-limit capability is missing a required table, column, key, or runtime privilege. The candidate release remains inactive."},forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}};if(error62.databaseState==="RECOVERY_REQUIRED"){return finalize2(recoveryRequiredDiagnostic({...shared,retryCondition:"Inspect the canonical journal and schema state before changing source or starting another deployment.",suggestedFixes:[],nextAction:"INSPECT_STATE"}))}return finalize2(userFixableDiagnostic({...shared,databaseState:error62.databaseState,retryCondition:"Add or repair the forward migration for the declared tenant capability, then retry.",suggestedFixes:[{id:"repair-auth-rate-limit-migration",title:"Create a forward migration",detail:"Run gencow db:generate, review the rate_limit migration, then run gencow db:check and db:push for the same app and environment.",target:"PENDING_MIGRATION",confidence:"HIGH"}]}))}if(error62 instanceof MigrationFormatUnsupportedError){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Convert the project to a pure directory-style Drizzle v1 history.",correlationId,reason:{code:reasonCode,summary:"The migration history format is not supported.",detail:`The bundle contains ${error62.format} migration history. Managed deploy requires a pure Drizzle v1 history.`},suggestedFixes:[{id:"convert-drizzle-v1-history",title:"Convert to Drizzle v1 history",detail:"Follow the supported migration conversion procedure without editing applied journal rows.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(error62 instanceof MigrationThinPolicyError){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Remove the platform-boundary operation from the unapplied migration and run check again.",correlationId,migration,operation:{kind:"platform_policy_boundary",...objectName?{objectName}:{}},reason:{code:reasonCode,summary:"The pending migration crosses a Gencow-managed platform boundary.",detail:"Tenant migrations may change ordinary tenant objects, but not migration journals, protected system objects, roles, managed schemas, or platform-only capabilities."},suggestedFixes:[{id:"remove-platform-boundary-operation",title:"Keep the migration inside tenant scope",detail:"Edit only the unapplied migration so it changes ordinary tenant database objects.",target:"PENDING_MIGRATION",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"STRUCTURE_ONLY"}}))}if(code==="SCHEMA_PUSH_IN_PROGRESS"){return finalize2(retryableInfraDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryPolicy:"AFTER_DELAY",retryCondition:"Retry after the active schema push releases the database-scoped lock.",retryAfterSeconds:15,correlationId,reason:{code:"schema_push_in_progress",summary:"Another schema push currently owns the database migration lock.",detail:"No migration statement ran for this request. Wait for the active operation to finish and retry the same bundle."},suggestedFixes:[],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(code==="MIGRATION_LOCAL_PLAN_CHANGED"||code==="MIGRATION_PLAN_CHANGED"){return finalize2(retryableInfraDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryPolicy:"IMMEDIATE",retryCondition:"Regenerate a stable bundle and start a fresh plan from the beginning.",correlationId,migration,reason:{code:code.toLowerCase(),summary:"The local bundle or database journal changed while the plan was being checked.",detail:"The stale plan was discarded before execution; retry from a fresh immutable bundle."},suggestedFixes:[],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(MIGRATION_RUNTIME_TERMINAL_ERROR_CODES_V1.includes(code)){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Restore the exact applied migration artifact from trusted version control, then create a fresh plan.",correlationId,migration,reason:{code:code.toLowerCase(),summary:"The deployment bundle does not match immutable applied migration history.",detail:"Restore the original applied file byte-for-byte. Put any new schema change in a new forward migration."},suggestedFixes:[{id:"restore-applied-migration",title:"Restore the original migration artifact",detail:"Recover the exact file from trusted version control; do not rewrite history or edit the database journal.",target:"NONE",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(code==="MIGRATION_LOCAL_HISTORY_AMBIGUOUS"){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Regenerate a bundle with unique stable migration names without changing applied history.",correlationId,migration,reason:{code:"migration_local_history_ambiguous",summary:"The local migration bundle has missing or duplicate identity metadata.",detail:"Every migration must have one stable unique name before the server can derive a deterministic pending plan."},suggestedFixes:[{id:"regenerate-local-metadata",title:"Regenerate unique local migration metadata",detail:"Fix only unapplied duplicate or missing local identities and leave applied migration files unchanged.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(code==="MIGRATION_APPLIED_HISTORY_AMBIGUOUS"){return finalize2(platformActionDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",correlationId,retryCondition:"Retry after Gencow verifies the existing journal identity metadata.",nextAction:"INSPECT_STATE",reason:{code:code.toLowerCase(),summary:"Existing migration journal identity needs platform inspection.",detail:"No migration statement ran for this request. The existing journal cannot yet be matched to the immutable local plan."},suggestedFixes:[],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(code==="MIGRATION_POSTCONDITION_FAILED"){return finalize2(recoveryDiagnostic(code,correlationId,context))}if(error62 instanceof DrizzleMigrationStorePreflightError){return finalize2(platformActionDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",correlationId,retryCondition:"Retry after the platform migration-store status reports ready; no project edit is required.",nextAction:"INSPECT_STATE",reason:{code:reasonCode,summary:"The platform migration store needs preparation before migration can continue.",detail:"No tenant migration statement ran. Gencow must reconcile the classified store state before the same immutable bundle is retried."},suggestedFixes:[],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}return finalize2(platformDiagnostic(code,reasonCode,correlationId,migration,operation))}function migrationDiagnosticHttpStatus(diagnostic){if(diagnostic.code==="MIGRATION_APPLIED_HASH_DRIFT"||diagnostic.code==="MIGRATION_APPLIED_FILE_MISSING"||diagnostic.code==="MIGRATION_APPLIED_HISTORY_AMBIGUOUS"||diagnostic.code==="MIGRATION_LOCAL_HISTORY_AMBIGUOUS"){return 409}if(diagnostic.failureClass==="USER_FIXABLE")return 400;if(diagnostic.failureClass==="RETRYABLE_INFRA"){return diagnostic.code==="SCHEMA_PUSH_IN_PROGRESS"||diagnostic.code.endsWith("PLAN_CHANGED")?409:503}if(diagnostic.failureClass==="PLATFORM_ACTION_REQUIRED")return 503;return 500}var FORBIDDEN_ACTIONS,KNOWN_CODES;var init_migration_actionable_diagnostic=__esm({"../platform/src/migration-actionable-diagnostic.ts"(){"use strict";init_dist();init_drizzle_migration_store();init_migration_execution_plan();init_migration_execution_outcome();init_migration_rollback_diagnostic();init_provisioner_migration_journal();init_migration_legacy_audit_error();init_migration_capability();init_migration_thin_policy();init_migration_push_preflight_error();init_migration_proof_infrastructure_diagnostic();init_tenant_schema_postconditions();init_migration_bundle_manifest();FORBIDDEN_ACTIONS=["Do not use --force to bypass migration safety checks.","Do not edit or delete rows in drizzle.__drizzle_migrations.","Do not modify an already-applied migration; create a new forward migration instead."];KNOWN_CODES=new Set([...MIGRATION_ACTIONABLE_SERVER_ERROR_CODES_V1,...MIGRATION_RECOVERY_ALIAS_ERROR_CODES_V1])}});function isDeploymentSchemaError(error62){return error62 instanceof DeploymentSchemaError}var PUBLIC_MESSAGES,DeploymentSchemaError;var init_deployment_schema_error=__esm({"../platform/src/deployment-schema-error.ts"(){"use strict";PUBLIC_MESSAGES={SCHEMA_COMPATIBILITY_CONSTRAINT_UNAVAILABLE:"Deploy schema compatibility preflight requires platform repair",SCHEMA_REVISION_PLAN_FAILED:"Deploy schema preparation failed before tenant migration execution"};DeploymentSchemaError=class extends Error{code;databaseState;reasonCode;activeDeploymentState="UNCHANGED";publicMessage;constructor(input2){super(input2.code,{cause:input2.cause});this.name="DeploymentSchemaError";this.code=input2.code;this.databaseState=input2.databaseState;this.reasonCode=input2.reasonCode;this.publicMessage=PUBLIC_MESSAGES[input2.code]}}}});function localFix(error62){if(error62.code==="MIGRATION_BUNDLE_FORBIDDEN_SECRET_FILE"){return{summary:"The uploaded backend bundle contains a forbidden environment file.",title:"Remove secrets from the deployment artifact",detail:"Keep runtime secrets in Gencow environment configuration, remove environment files from the backend archive, then create a fresh bundle."}}if(error62.code==="MIGRATION_BUNDLE_CLI_VERSION_MISMATCH"){return{summary:"The migration bundle CLI version does not match the request header.",title:"Create one fresh request with the official CLI",detail:"Do not reuse or handcraft a migration archive or version header. Rerun db:check from the project."}}return{summary:"The migration bundle manifest does not match the uploaded schema and migrations.",title:"Regenerate the bundle",detail:"Do not edit the generated manifest. Verify local schema and migration files, then rerun db:check."}}function buildMigrationBundleFailureResponse(error62,correlationId,operation){const contract=MIGRATION_BUNDLE_ERROR_CONTRACT_V1[error62.code];if(error62.code==="MIGRATION_BUNDLE_GENERATOR_UNSUPPORTED"){const summary2="An older platform slot rejected audit-only generator metadata.";const diagnostic2=retryableInfraDiagnostic({code:error62.code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryPolicy:"AFTER_DELAY",retryAfterSeconds:15,retryCondition:"Retry the same immutable bundle after the platform rollout converges.",correlationId,reason:{code:"legacy_generator_policy_slot",summary:summary2,detail:"No tenant database access or mutation occurred. Current slots treat generator identity as audit metadata."},suggestedFixes:[],docsUrl:MIGRATION_CAPABILITY_MANIFEST_V1.docsUrl,supportedCliRange:MIGRATION_CAPABILITY_MANIFEST_V1.supportedCliRange,forbiddenActions:[],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}});return{status:contract.status,body:{error:`Schema ${operation} failed: ${summary2}`,...diagnostic2}}}const needsPlatformAction=contract.failureClass==="PLATFORM_ACTION_REQUIRED";const needsPlatformInspection=error62.code==="PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH";const needsUpgrade=needsPlatformAction&&!needsPlatformInspection;const fix=localFix(error62);const summary=needsPlatformInspection?"The platform could not prove the migration artifact identity.":needsUpgrade?"This migration bundle protocol requires a supported CLI.":fix.summary;const common={code:error62.code,phase:"PREFLIGHT",databaseState:"UNCHANGED",correlationId,retryCondition:needsPlatformInspection?"Keep the source and operation identity unchanged while the platform state is inspected.":needsUpgrade?"Install a CLI version in the supported range, then create a fresh migration bundle.":"Create a fresh bundle from unchanged trusted source files, then run db:check again.",reason:{code:error62.code.toLowerCase(),summary,detail:"The request was rejected after archive extraction and manifest verification, before tenant database access or mutation."},suggestedFixes:[{id:needsPlatformInspection?"inspect-platform-artifact-identity":needsUpgrade?"update-cli-and-regenerate-bundle":"regenerate-bundle-from-trusted-source",title:needsPlatformInspection?"Inspect platform artifact identity":needsUpgrade?"Update the CLI and regenerate the bundle":fix.title,detail:needsPlatformInspection?"Use the correlation ID to inspect the Platform verifier, source revision, and durable receipt.":needsUpgrade?`Install Gencow CLI ${MIGRATION_CAPABILITY_MANIFEST_V1.supportedCliRange} and rerun db:check.`:fix.detail,target:contract.fixTarget,confidence:"HIGH"}],docsUrl:MIGRATION_CAPABILITY_MANIFEST_V1.docsUrl,supportedCliRange:MIGRATION_CAPABILITY_MANIFEST_V1.supportedCliRange,forbiddenActions:["Do not use --force to bypass migration safety checks.","Do not edit or delete rows in drizzle.__drizzle_migrations."],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}};const diagnostic=needsPlatformAction?platformActionDiagnostic({...common,nextAction:needsPlatformInspection?"INSPECT_STATE":"UPDATE_CLI"}):userFixableDiagnostic(common);return{status:contract.status,body:{error:`Schema ${operation} failed: ${summary}`,...diagnostic}}}var init_apps_migration_bundle_errors=__esm({"../platform/gencow/apps-migration-bundle-errors.ts"(){"use strict";init_dist()}});function buildRestoreSourceRuntimeDiagnostic(input2){if(input2.code!=="RESTORE_SOURCE_RUNTIME_GENERATION_UNAVAILABLE"&&input2.code!=="RESTORE_SOURCE_RUNTIME_GENERATION_IDENTITY_MISMATCH")return null;const base2=buildPublicSelfServiceDiagnostic({code:input2.code,stage:"candidate",correlationId:input2.correlationId,operationId:input2.operationId,databaseState:"UNCHANGED",requestedAction:"VIEW_STATUS",reasonCode:"restore_source_runtime_unavailable",reasonSummary:"Recovery is blocked because the saved runtime could not be verified. The database and current serving deployment are preserved.",incumbentServing:"PRESERVED",operationState:"BLOCKED"});return{...base2,retry:{...base2.retry,condition:"Retry only after status reports the saved runtime is verified and recovery is ready."},action:{...base2.action,command:`gencow deploy status${input2.operationId?` --deployment ${input2.operationId}`:""}`}}}var init_restore_source_runtime_diagnostic=__esm({"../platform/src/restore-source-runtime-diagnostic.ts"(){"use strict";init_public_self_service_diagnostic()}});function buildNpmDependencyReplayDiagnostic(input2){if(input2.code!==NPM_DEPENDENCY_REPLAY_INVALID)return null;const base2=buildPublicSelfServiceDiagnostic({code:input2.code,stage:"candidate",correlationId:input2.correlationId,operationId:input2.operationId,databaseState:input2.databaseState??"UNKNOWN",requestedAction:"VIEW_STATUS",reasonCode:"saved_dependency_graph_unverified",reasonSummary:"Runtime recovery is blocked because the saved dependency graph could not be verified. Inspect recovery status; app source changes are not required.",incumbentServing:input2.incumbentServing??"PRESERVED",operationState:"BLOCKED"});return{...base2,stateImpact:{...base2.stateImpact,mutation:input2.databaseState===void 0||input2.databaseState==="UNKNOWN"?"UNKNOWN":base2.stateImpact.mutation},retry:{...base2.retry,condition:"Retry only after status confirms the saved dependency graph is verified and recovery is ready."},action:{...base2.action,command:`gencow deploy status${input2.operationId?` --deployment ${input2.operationId}`:""}`}}}var NPM_DEPENDENCY_REPLAY_INVALID,NpmDependencyReplayError;var init_npm_dependency_replay_diagnostic=__esm({"../platform/src/npm-dependency-replay-diagnostic.ts"(){"use strict";init_public_self_service_diagnostic();NPM_DEPENDENCY_REPLAY_INVALID="RUNTIME_RESTORE_SOURCE_DEPENDENCY_GRAPH_INVALID";NpmDependencyReplayError=class extends Error{code=NPM_DEPENDENCY_REPLAY_INVALID;constructor(){super(NPM_DEPENDENCY_REPLAY_INVALID)}}}});import{randomUUID as randomUUID36}from"node:crypto";function isMigrationDeployError(error62){const code=error62?.code;return typeof code==="string"&&MIGRATION_DEPLOY_CODES.has(code)&&!DEPLOY_RUNTIME_GUARDRAIL_CODES.has(code)}function compareStableVersions2(left,right){const leftParts=left.split("-")[0].split(".").map(Number);const rightParts=right.split("-")[0].split(".").map(Number);for(let index27=0;index27<3;index27+=1){if(leftParts[index27]!==rightParts[index27])return leftParts[index27]-rightParts[index27]}return 0}function requiresLegacyActionableDeployMessage(cliVersion){const version3=cliVersion??"";return/^\d+\.\d+\.\d+$/u.test(version3)&&compareStableVersions2(version3,LEGACY_ACTIONABLE_DEPLOY_CLI_MAX)<=0}function supportsAppDeleteStatusDiagnostic(cliVersion){return/^\d+\.\d+\.\d+$/u.test(cliVersion??"")&&compareStableVersions2(cliVersion,APP_DELETE_STATUS_DIAGNOSTIC_CLI_MIN)>=0}function legacyActionableDeployMessage(input2){if(!requiresLegacyActionableDeployMessage(input2.cliVersion))return input2.error;return[input2.error,`Code: ${input2.code}`,`Stage: ${input2.stage}`,`Next action: ${input2.userAction}`].join("\n")}function candidateBackendEvidenceBody(error62){const loadEvidence=error62.candidateLoadEvidence;if(loadEvidence!=="registry_empty_after_import"&&loadEvidence!=="minimal_mode")return{};const observedOperationCount=error62.observedOperationCount;return{candidateBackendEvidence:{loadEvidence,...Number.isSafeInteger(observedOperationCount)?{observedOperationCount}:{}}}}function getDeployRuntimeGuardrailCode(error62){const code=error62?.code;return typeof code==="string"&&DEPLOY_RUNTIME_GUARDRAIL_CODES.has(code)?code:null}function getDeploymentAttemptFailureCode(error62,stage,crashLogs){if(error62 instanceof AppDeploymentPlacementError)return error62.diagnosticCode;if(error62 instanceof DeploymentAdmissionError)return error62.code;if(isDeploymentSchemaError(error62))return error62.code;if(asControlPlaneSchemaUnavailableError(error62))return CONTROL_PLANE_SCHEMA_UNAVAILABLE;const guardrailCode=getDeployRuntimeGuardrailCode(error62);if(guardrailCode)return guardrailCode;if(isMigrationDeployError(error62))return String(error62.code);if(isDeployDependencyVersionError(error62)||isCronManifestDeployError(error62))return error62.code;const routePrepareCause=getDeploymentFailureCause(error62)==="DEPLOY_ARTIFACT_ROUTE_PREPARE_FAILED";if(stage==="route"&&routePrepareCause&&!isRoutePrepareConvergenceFailure(error62)){return getStableDeploymentFailureCode(error62)??"ACTIVATION_ROUTE_PREPARE_FAILED"}if(stage!=="route"&&getDeploymentFailureCause(error62)?.startsWith("DEPLOY_ARTIFACT_")){return"DEPLOY_ARTIFACT_MATERIALIZE_FAILED"}const stableCode=getStableDeploymentFailureCode(error62);if(stableCode)return stableCode;if(stage==="admission")return"DEPLOY_CONTRACT_INVALID";if(stage==="artifact")return"DEPLOY_ARTIFACT_MATERIALIZE_FAILED";if(stage==="schema")return"SCHEMA_APPLY_FAILED";if(stage==="activation"||stage==="route")return"ACTIVATION_ROUTE_ACK_PENDING";if(stage==="runtime")return"RUNTIME_OWNERSHIP_AMBIGUOUS";if(stage==="controller")return"CONTROL_PLANE_OBSERVATION_INCOMPLETE";return resolveGenericDeploymentFailurePolicy({stage,error:error62,crashLogs}).code}function getDeploymentAttemptFailureStage(error62,currentStage){return isMigrationDeployError(error62)||isDeploymentSchemaError(error62)?"schema":resolveDeploymentFailureStage(error62,currentStage)}function isAppBusyAdmissionError(error62){return error62 instanceof DeploymentExecutorAdmissionError&&error62.code===APP_BUSY_CODE}async function resolveAppBusyBlockingOperation(input2){if(!(input2.error instanceof DeploymentExecutorAdmissionError)||!isAppBusyAdmissionError(input2.error)){return void 0}if(input2.error.blockingOperationId){return{id:input2.error.blockingOperationId,correlationId:input2.error.blockingCorrelationId??null}}return readActiveDeploymentConflict({db:input2.db,appId:input2.appId,warn:input2.warn})}function buildAppBusyAdmissionResponse(input2){const ownBlocking=input2.error.blockingOperationId?{id:input2.error.blockingOperationId,correlationId:input2.error.blockingCorrelationId??null}:void 0;const blocking=ownBlocking??input2.blockingOperation;const blockingId=blocking&&Number.isSafeInteger(blocking.id)&&blocking.id>0?blocking.id:void 0;const blockingCorrelationId=blocking?.correlationId&&/^[A-Za-z0-9_-]{8,128}$/u.test(blocking.correlationId)?blocking.correlationId:void 0;const correlationId=input2.correlationId??`deploy_busy_${randomUUID36()}`;const statusCommand=blockingId===void 0?"gencow deploy status":`gencow deploy status --deployment ${blockingId}`;const baseSelfService=buildPublicSelfServiceDiagnostic({code:APP_BUSY_CODE,stage:input2.stage,correlationId,databaseState:"UNCHANGED",requestedAction:"VIEW_STATUS",reasonCode:"deployment_app_busy",reasonSummary:"Another deployment of this app is active. This request changed nothing.",incumbentServing:"PRESERVED",operationState:"BLOCKED"});const selfService={...baseSelfService,retry:{...baseSelfService.retry,condition:"Check the active deployment's status; retry this same deployment only after it reports a final result."},action:{...baseSelfService.action,command:statusCommand}};return{status:409,body:{error:"Another deployment of this app is active. This request changed nothing; check its status, then retry.",code:APP_BUSY_CODE,stage:input2.stage,retryClass:"retryable-infra",userAction:"VIEW_STATUS",databaseState:"UNCHANGED",...blockingId===void 0?{}:{retryReadinessReason:"ACTIVE_OWNER",blockingOperationId:blockingId},...blockingCorrelationId===void 0?{}:{blockingCorrelationId},correlationId,diagnostic:{selfService},nextAction:{kind:"VIEW_STATUS",command:statusCommand}}}}function buildDeployFailureResponse(error62,crashLogs,context={}){const correlationId=/^[A-Za-z0-9_-]{8,128}$/u.test(context.correlationId??"")?context.correlationId:void 0;const withCorrelation=correlationId?{correlationId}:{};const fallbackStage=context.stage??(error62 instanceof DeploymentAdmissionError?"admission":"candidate");const resolvedStage=getDeploymentAttemptFailureStage(error62,fallbackStage);const sourceRuntimeCode=getStableDeploymentFailureCode(error62);const stopConfigurationCorrelationId=correlationId??`stop_blocked_${randomUUID36()}`;const stopConfigurationDiagnostic=buildRuntimeStopConfigurationDiagnostic({code:sourceRuntimeCode??"",correlationId:stopConfigurationCorrelationId});if(stopConfigurationDiagnostic){return{status:503,body:{error:stopConfigurationDiagnostic.reason.summary,code:sourceRuntimeCode,stage:"runtime",retryClass:"platform-action",userAction:"VIEW_STATUS",databaseState:"UNCHANGED",activeDeploymentState:"PRESERVED",correlationId:stopConfigurationCorrelationId,nextAction:{kind:"VIEW_STATUS",command:stopConfigurationDiagnostic.action.command},diagnostic:{selfService:stopConfigurationDiagnostic}}}}if(sourceRuntimeCode===NPM_DEPENDENCY_REPLAY_INVALID){const responseCorrelationId=correlationId??`restore_blocked_${randomUUID36()}`;const selfService=buildNpmDependencyReplayDiagnostic({code:sourceRuntimeCode,correlationId:responseCorrelationId});return{status:503,body:{error:selfService.reason.summary,code:sourceRuntimeCode,stage:"candidate",retryClass:"platform-action",userAction:"VIEW_STATUS",databaseState:"UNKNOWN",activeDeploymentState:"PRESERVED",correlationId:responseCorrelationId,nextAction:{kind:"VIEW_STATUS",command:selfService.action.command},diagnostic:{selfService}}}}if(sourceRuntimeCode==="RESTORE_SOURCE_RUNTIME_GENERATION_UNAVAILABLE"||sourceRuntimeCode==="RESTORE_SOURCE_RUNTIME_GENERATION_IDENTITY_MISMATCH"){const responseCorrelationId=correlationId??`restore_blocked_${randomUUID36()}`;const selfService=buildRestoreSourceRuntimeDiagnostic({code:sourceRuntimeCode,correlationId:responseCorrelationId});const command=selfService.action.command;return{status:503,body:{error:selfService.reason.summary,code:sourceRuntimeCode,stage:"candidate",retryClass:"platform-action",userAction:"VIEW_STATUS",databaseState:"UNCHANGED",activeDeploymentState:"PRESERVED",correlationId:responseCorrelationId,nextAction:{kind:"VIEW_STATUS",command},diagnostic:{selfService}}}}if(isDeploymentSchemaError(error62)){return{status:503,body:{error:error62.publicMessage,code:error62.code,stage:"schema",retryClass:"platform-action",userAction:"OPERATOR_ACTION",databaseState:error62.databaseState,activeDeploymentState:error62.activeDeploymentState,...withCorrelation}}}if(error62 instanceof MigrationBundleManifestError){const response=buildMigrationBundleFailureResponse(error62,correlationId??"deploy_migration_unknown","check");const{error:publicError,...diagnostic}=response.body;return{status:response.status,body:{error:publicError,code:diagnostic.code,stage:"schema",retryClass:retryClassForMigrationFailureClass(diagnostic.failureClass),userAction:diagnostic.nextAction.kind,databaseState:diagnostic.databaseState,nextAction:{kind:diagnostic.nextAction.kind},diagnostic,...withCorrelation}}}if(isMigrationDeployError(error62)){const diagnostic=buildActionableMigrationDiagnostic(error62,correlationId??"deploy_migration_unknown");const retryClass=retryClassForMigrationFailureClass(diagnostic.failureClass);return{status:migrationDiagnosticHttpStatus(diagnostic),body:{error:diagnostic.reason.summary,code:diagnostic.code,stage:"schema",retryClass,userAction:diagnostic.nextAction.kind,databaseState:diagnostic.databaseState,nextAction:{kind:diagnostic.nextAction.kind},diagnostic,...withCorrelation}}}if(error62 instanceof DeploymentExecutorAdmissionError&&isAppBusyAdmissionError(error62)){return buildAppBusyAdmissionResponse({stage:resolvedStage,correlationId,error:error62,blockingOperation:context.blockingOperation})}if(error62 instanceof DeploymentExecutorAdmissionError&&error62.code===ADMISSION_UNAVAILABLE_CODE){return buildRetryableAdmissionUnavailableResponse({correlationId:context.correlationId??`deploy-admission-${randomUUID36()}`})}if(error62 instanceof DeploymentAdmissionError){if(error62.code==="DEPLOYMENT_EXECUTOR_RECOVERY_REQUIRED"){const blockingOperationId=error62.blockingOperationId;const blockingCorrelationId=error62.blockingCorrelationId;const responseCorrelationId=correlationId??`deploy_rejected_${randomUUID36()}`;const validBlockingOperationId=typeof blockingOperationId==="number"&&Number.isSafeInteger(blockingOperationId)&&blockingOperationId>0?blockingOperationId:void 0;const baseSelfService=buildPublicSelfServiceDiagnostic({code:error62.code,stage:"admission",correlationId:responseCorrelationId,...validBlockingOperationId===void 0?{}:{operationId:String(validBlockingOperationId)},databaseState:"UNCHANGED",requestedAction:"VIEW_STATUS",reasonCode:"deployment_executor_recovery_required",reasonSummary:"This request changed nothing. Platform owns the blocking deployment and retires eligible ones automatically; status changes when it is done. Some kinds are not retired automatically.",incumbentServing:"UNKNOWN",operationState:"BLOCKED"});const selfService={...baseSelfService,retry:{...baseSelfService.retry,condition:"Check the blocking deployment's status; retry only after it reports a final result and shows a retry command. Kinds Platform does not recover automatically stay blocked until a Platform operator acts; keep the correlation ID."},action:{...baseSelfService.action,...validBlockingOperationId===void 0?{}:{command:`gencow deploy status --deployment ${validBlockingOperationId}`}}};return{status:503,body:{error:"A previous deployment is blocking this deploy. Platform owns it and no gencow command can resolve it; Platform retires eligible ones automatically. This request changed nothing.",code:error62.code,stage:"admission",retryClass:"platform-action",userAction:"VIEW_STATUS",databaseState:"UNCHANGED",activeDeploymentState:"BLOCKED",retryReadinessReason:"RECOVERY_REQUIRED",...validBlockingOperationId===void 0?{}:{operationId:String(validBlockingOperationId),blockingOperationId:validBlockingOperationId},correlationId:responseCorrelationId,...typeof blockingCorrelationId==="string"&&/^[A-Za-z0-9_-]{8,128}$/u.test(blockingCorrelationId)?{blockingCorrelationId}:{},diagnostic:{selfService},nextAction:{kind:"VIEW_STATUS",...validBlockingOperationId!==void 0?{command:`gencow deploy status --deployment ${validBlockingOperationId}`}:{}}}}}if(error62.code==="RUNTIME_CANDIDATE_CLEANUP_INCOMPLETE"){return{status:503,body:{error:"Deploy candidate cleanup is incomplete; inspect platform state before retrying",code:error62.code,stage:"admission",retryClass:"platform-action",userAction:"INSPECT_STATE",...withCorrelation}}}if(resolvedStage==="artifact"||resolvedStage==="controller"){const failure3=resolveGenericDeploymentFailurePolicy({stage:resolvedStage,error:error62,crashLogs});return{status:failure3.status,body:{error:failure3.error,code:failure3.code,stage:resolvedStage,retryClass:failure3.retryClass,userAction:failure3.userAction,...withCorrelation}}}const updateCli=error62.code==="DEPLOY_CLI_UPGRADE_REQUIRED";const authAmbiguous=error62.code==="AUTH_SCHEMA_PROVENANCE_AMBIGUOUS";return{status:error62.status,body:{error:authAmbiguous?"Multiple Better Auth schema sources were found":updateCli?`Deploy requires Gencow CLI ${MIN_DEPLOY_CLI_VERSION} or newer`:"Deploy contract admission failed",code:error62.code,stage:"admission",retryClass:"terminal-client",userAction:updateCli?"UPDATE_CLI":"EDIT_AND_CHECK",...authAmbiguous?{databaseState:"UNCHANGED",activeDeploymentState:"UNCHANGED",files:error62.publicDetails?.files??[],remediation:["Keep exactly one Auth schema source.","Remove stale generated or legacy Auth schema files, then redeploy."]}:{},...withCorrelation}}}if(asControlPlaneSchemaUnavailableError(error62)){return{status:503,body:{error:"Deploy control-plane schema is unavailable",code:CONTROL_PLANE_SCHEMA_UNAVAILABLE,stage:"admission",retryClass:"platform-action",userAction:"OPERATOR_ACTION",...withCorrelation}}}if(error62?.code==="DEPLOYMENT_FAILURE_RECEIPT_UNAVAILABLE"){return{status:503,body:{error:"Deployment failure receipt could not be recorded. Please retry later.",code:"DEPLOYMENT_FAILURE_RECEIPT_UNAVAILABLE",stage:"admission",retryClass:"platform-action",userAction:"OPERATOR_ACTION",...withCorrelation}}}const placementCode=error62&&typeof error62==="object"&&["DEPLOYMENT_PLACEMENT_UNAVAILABLE","DEPLOYMENT_PLACEMENT_STATE_INVALID"].includes(String(error62.code??""))?String(error62.code):null;if(placementCode){const retryable=placementCode==="DEPLOYMENT_PLACEMENT_UNAVAILABLE";const diagnostic=error62 instanceof AppDeploymentPlacementError?{code:error62.diagnosticCode,scope:"placement"}:{code:"PLACEMENT_SYSTEM_UNAVAILABLE",scope:"placement"};return{status:503,body:{error:retryable?"App placement is being revalidated. Please retry shortly.":"App placement state requires platform reconciliation.",code:placementCode,stage:"admission",retryClass:retryable?"retryable-infra":"platform-action",userAction:retryable?"RETRY":"OPERATOR_ACTION",diagnostic,...withCorrelation}}}const guardrailCode=getDeployRuntimeGuardrailCode(error62);if(guardrailCode){if(guardrailCode==="APP_DELETE_ADMISSION_CLOSED"){const operationId2=error62.operationId;const deleteCorrelationId=error62.correlationId;if(typeof operationId2==="string"&&APP_DELETE_OPERATION_PATTERN2.test(operationId2)&&typeof deleteCorrelationId==="string"&&APP_DELETE_CORRELATION_PATTERN.test(deleteCorrelationId)){const typedStatus=supportsAppDeleteStatusDiagnostic(context.cliVersion);return{status:409,body:{error:typedStatus?"App deletion is in progress. Check deletion status before deploying.":"App deletion is in progress. Run the app delete command again to view status.",code:guardrailCode,stage:"admission",retryClass:"platform-action",userAction:typedStatus?"VIEW_DELETE_STATUS":"VIEW_STATUS",operationId:operationId2,correlationId:deleteCorrelationId}}}}const publicMessage=DEPLOY_RUNTIME_GUARDRAIL_MESSAGES[guardrailCode]??"deploy guardrail blocked this request";const retryable=guardrailCode==="DEPLOY_CAPACITY_LIMITED"||guardrailCode==="DEPLOY_RUNTIME_PORT_BUSY_MANAGED";const userAction=retryable?"RETRY":guardrailCode==="BACKEND_CAPABILITY_EMPTY"?"EDIT_AND_CHECK":"OPERATOR_ACTION";const errorMessage8=`Deploy failed: ${publicMessage}`;return{status:retryable?503:409,body:{error:guardrailCode==="BACKEND_CAPABILITY_EMPTY"?legacyActionableDeployMessage({error:errorMessage8,code:guardrailCode,stage:"candidate",userAction,cliVersion:context.cliVersion}):errorMessage8,code:guardrailCode,stage:"candidate",retryClass:retryable?"retryable-infra":guardrailCode==="BACKEND_CAPABILITY_EMPTY"?"terminal-client":"platform-action",userAction,...guardrailCode==="BACKEND_CAPABILITY_EMPTY"?candidateBackendEvidenceBody(error62):{},...withCorrelation}}}if(isDeployDependencyVersionError(error62)){return{status:400,body:{error:"Deploy dependency versions are incompatible with the hosted runtime",code:"DEPLOY_DEPENDENCY_VERSION_MISMATCH",stage:"admission",retryClass:"terminal-client",userAction:"EDIT_AND_CHECK",...withCorrelation}}}if(isCronManifestDeployError(error62)){return{status:400,body:{error:"Deploy cron manifest validation failed",code:"CRON_MANIFEST_INVALID",stage:"admission",retryClass:"terminal-client",userAction:"EDIT_AND_CHECK",...withCorrelation}}}const stage=resolvedStage;const candidateCleanupFailureCode=getCandidateCleanupFailureCode(error62);const withCandidateCleanup=candidateCleanupFailureCode?{candidateCleanupFailureCode}:{};if(stage==="schema"){return{status:503,body:{error:"Deploy schema outcome requires platform state inspection",code:getDeploymentAttemptFailureCode(error62,stage,crashLogs),stage,retryClass:"platform-action",userAction:"INSPECT_STATE",...withCorrelation}}}const failure2=resolveGenericDeploymentFailurePolicy({stage,error:error62,crashLogs});const provenance=readCandidateFailureProvenance(error62);return{status:failure2.status,body:{error:failure2.error,code:failure2.code,stage,retryClass:failure2.retryClass,userAction:failure2.userAction,...stage==="candidate"?{candidateProcessStarted:provenance?.processSpawned===true,candidateLogAvailable:provenance?.processSpawned===true&&Boolean(crashLogs?.length)}:{},...withCandidateCleanup,...withCorrelation}}}var MIGRATION_DEPLOY_CODES,DEPLOY_RUNTIME_GUARDRAIL_CODES,DEPLOY_RUNTIME_GUARDRAIL_MESSAGES,LEGACY_ACTIONABLE_DEPLOY_CLI_MAX,APP_DELETE_STATUS_DIAGNOSTIC_CLI_MIN,APP_DELETE_OPERATION_PATTERN2,APP_DELETE_CORRELATION_PATTERN,APP_BUSY_CODE;var init_apps_deploy_failures=__esm({"../platform/gencow/apps-deploy-failures.ts"(){"use strict";init_runtime_stop_configuration_diagnostic();init_deploy_dependency_compat();init_provisioner_cron_sync();init_deployment_request_admission();init_deployment_executor_store();init_deployment_admission_unavailable_response();init_deployment_busy_diagnostic();init_dist();init_migration_actionable_diagnostic();init_migration_bundle_manifest();init_deployment_schema_error();init_apps_migration_bundle_errors();init_deployment_control_plane_rollout();init_deployment_failure_contract();init_candidate_failure_provenance();init_app_deployment_placement();init_public_self_service_diagnostic();init_restore_source_runtime_diagnostic();init_npm_dependency_replay_diagnostic();MIGRATION_DEPLOY_CODES=new Set([...MIGRATION_ACTIONABLE_SERVER_ERROR_CODES_V1,...MIGRATION_RECOVERY_ALIAS_ERROR_CODES_V1]);DEPLOY_RUNTIME_GUARDRAIL_CODES=new Set(["DEPLOY_RUNTIME_PORT_BUSY_MANAGED","DEPLOY_RUNTIME_PORT_BUSY_FOREIGN","DEPLOY_RUNTIME_PORT_UNRECONCILED","DEPLOY_CAPACITY_LIMITED","BACKEND_CAPABILITY_EMPTY","APP_DELETE_ADMISSION_CLOSED","APP_DELETE_ADMISSION_IDENTITY_AMBIGUOUS"]);DEPLOY_RUNTIME_GUARDRAIL_MESSAGES={DEPLOY_RUNTIME_PORT_BUSY_MANAGED:"previous app runtime is still releasing its port",DEPLOY_RUNTIME_PORT_BUSY_FOREIGN:"app runtime port is occupied by a non-app process",DEPLOY_RUNTIME_PORT_UNRECONCILED:"current app runtime could not be safely identified",DEPLOY_CAPACITY_LIMITED:"deploy capacity is temporarily limited; the current app remains serving",BACKEND_CAPABILITY_EMPTY:"backend deploy did not expose any query, mutation, or procedure capability; use gencow static for frontend-only deployments",APP_DELETE_ADMISSION_CLOSED:"app deletion is already in progress",APP_DELETE_ADMISSION_IDENTITY_AMBIGUOUS:"app deletion identity is ambiguous; the current app remains unchanged"};LEGACY_ACTIONABLE_DEPLOY_CLI_MAX="0.1.184";APP_DELETE_STATUS_DIAGNOSTIC_CLI_MIN="0.1.190";APP_DELETE_OPERATION_PATTERN2=/^app_delete_(?:[a-f0-9]{32}|[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})$/u;APP_DELETE_CORRELATION_PATTERN=/^[A-Za-z0-9_-]{8,128}$/u;APP_BUSY_CODE="DEPLOYMENT_EXECUTOR_APP_BUSY"}});function deploymentExecutorDeferralDeadline(deferredSince){if(!(deferredSince instanceof Date)||!Number.isFinite(deferredSince.getTime()))return null;return new Date(deferredSince.getTime()+DEPLOYMENT_EXECUTOR_DEFER_BUDGET_MS)}var DEPLOYMENT_EXECUTOR_DEFER_BUDGET_MS;var init_deployment_executor_defer_budget=__esm({"../platform/src/deployment-executor-defer-budget.ts"(){"use strict";init_deployment_failure_contract();init_app_serving_route_target_rejection();init_deployment_executor_store();DEPLOYMENT_EXECUTOR_DEFER_BUDGET_MS=10*6e4}});function resolvePendingDeploymentPhase(input2){if(!SAFE_PHASE.test(input2.executorState))return null;if(input2.receipt?.phase!=="reconciling"||!SAFE_REASON_CODE.test(input2.receipt.code)){return{phase:input2.executorState}}const deferredSince=input2.receipt.deferredSince?new Date(input2.receipt.deferredSince):null;const staticAdmission=input2.environment==="static"?typeof input2.queuedAt==="string"?new Date(input2.queuedAt):input2.queuedAt:null;const deadline=deploymentExecutorDeferralDeadline(deferredSince??staticAdmission);return{phase:input2.executorState,phaseReasonCode:input2.receipt.code,...deferredSince?{deferredSince:deferredSince.toISOString()}:{},...deadline?{deadlineAt:deadline.toISOString()}:{}}}var SAFE_PHASE,SAFE_REASON_CODE;var init_deployment_executor_pending_phase=__esm({"../platform/src/deployment-executor-pending-phase.ts"(){"use strict";init_deployment_executor_defer_budget();SAFE_PHASE=/^[a-z][a-z_]{1,39}$/u;SAFE_REASON_CODE=/^[A-Z][A-Z0-9_]{2,99}$/u}});async function observeDeploymentExecutorProcess(input2){const targetGenerationBound=Boolean(input2.nodeId&&input2.slotId&&input2.revision&&input2.ownerId&&/^[a-f0-9]{64}$/u.test(input2.generationDigest??""));if(!targetGenerationBound){return{targetGenerationBound:false,executorAvailable:false,probeFailed:false}}try{return{targetGenerationBound:true,executorAvailable:await(input2.probeImpl??hasReadyDeploymentExecutorProcess)({db:input2.db,nodeId:input2.nodeId,slotId:input2.slotId,revision:input2.revision,ownerId:input2.ownerId,generationDigest:input2.generationDigest}),probeFailed:false}}catch{return{targetGenerationBound:true,executorAvailable:null,probeFailed:true}}}var init_deployment_executor_process_observation=__esm({"../platform/src/deployment-executor-process-observation.ts"(){"use strict";init_deployment_executor_worker_store()}});import{createHash as createHash54}from"node:crypto";function requiredIdentity(value2,code){const normalized=value2.trim();if(!normalized)throw new Error(code);return normalized}function positiveInteger2(value2,code){if(!Number.isSafeInteger(value2)||value2<1)throw new Error(code);return value2}function nonNegativeInteger(value2,code){if(!Number.isSafeInteger(value2)||value2<0)throw new Error(code);return value2}function canonicalPayload(binding){return[ROUTE_BINDING_VERSION,binding.appId,binding.appName,binding.environment,binding.deploymentId,binding.activationId,binding.instanceId,binding.artifactRef,binding.sourceGenerationRef,binding.runtimeGenerationRef,binding.activationEpoch,binding.nodeId,binding.nodeEpoch,binding.leaseEpoch,binding.port,binding.readyContractHash]}function canonicalTenantRouteBindingHash(binding){return createHash54("sha256").update(JSON.stringify(canonicalPayload(binding))).digest("hex")}function buildCanonicalTenantRouteBinding(input2){const binding={appId:positiveInteger2(input2.appId,"ROUTE_BINDING_SCOPE_INVALID"),appName:requiredIdentity(input2.appName,"ROUTE_BINDING_SCOPE_INVALID"),environment:requiredIdentity(input2.environment,"ROUTE_BINDING_SCOPE_INVALID"),deploymentId:positiveInteger2(input2.deploymentId,"ROUTE_BINDING_DEPLOYMENT_MISMATCH"),activationId:requiredIdentity(input2.activationId,"ROUTE_BINDING_ACTIVATION_MISMATCH"),instanceId:requiredIdentity(input2.instanceId,"ROUTE_BINDING_INSTANCE_AMBIGUOUS"),artifactRef:requiredIdentity(input2.artifactRef,"ROUTE_BINDING_GENERATION_MISMATCH"),sourceGenerationRef:requiredIdentity(input2.sourceGenerationRef,"ROUTE_BINDING_GENERATION_MISMATCH"),runtimeGenerationRef:requiredIdentity(input2.runtimeGenerationRef,"ROUTE_BINDING_GENERATION_MISMATCH"),activationEpoch:positiveInteger2(input2.activationEpoch,"ROUTE_BINDING_ACTIVATION_MISMATCH"),nodeId:requiredIdentity(input2.nodeId,"ROUTE_BINDING_NODE_FENCE_MISMATCH"),nodeEpoch:nonNegativeInteger(input2.nodeEpoch,"ROUTE_BINDING_NODE_FENCE_MISMATCH"),leaseEpoch:positiveInteger2(input2.leaseEpoch,"ROUTE_BINDING_NODE_FENCE_MISMATCH"),port:positiveInteger2(input2.port,"ROUTE_BINDING_INSTANCE_AMBIGUOUS"),readyContractHash:requiredIdentity(input2.readyContractHash,"ROUTE_BINDING_INSTANCE_AMBIGUOUS")};if(binding.port>65535)throw new Error("ROUTE_BINDING_INSTANCE_AMBIGUOUS");return{...binding,bindingHash:canonicalTenantRouteBindingHash(binding)}}var ROUTE_BINDING_VERSION;var init_runtime_route_binding_contract=__esm({"../platform/src/runtime-route-binding-contract.ts"(){"use strict";ROUTE_BINDING_VERSION=1}});var runtime_route_binding_reader_exports={};__export(runtime_route_binding_reader_exports,{ROUTE_BINDING_NOT_SERVING_CODE:()=>ROUTE_BINDING_NOT_SERVING_CODE,assertCanonicalTenantRouteFleetSnapshot:()=>assertCanonicalTenantRouteFleetSnapshot,loadCanonicalTenantRouteBinding:()=>loadCanonicalTenantRouteBinding,loadCanonicalTenantRouteBindings:()=>loadCanonicalTenantRouteBindings,loadCanonicalTenantRouteFleetSnapshot:()=>loadCanonicalTenantRouteFleetSnapshot,loadCanonicalTenantRouteProjectionProof:()=>loadCanonicalTenantRouteProjectionProof,loadCanonicalTenantRouteRemovalTargets:()=>loadCanonicalTenantRouteRemovalTargets});import{createHash as createHash55}from"node:crypto";import{and as and23,eq as eq26}from"drizzle-orm";function bindingFromRows(rows8){if(rows8.length!==1){throw new Error(rows8.length===0?ROUTE_BINDING_NOT_SERVING_CODE:"ROUTE_BINDING_INSTANCE_AMBIGUOUS")}const row=rows8[0];if(row.desiredActivationId!==row.activationId||row.activationState!=="serving"||row.instanceState!=="serving"||row.activationEpoch===null||row.routeAckEpoch!==row.activationEpoch||row.desiredActivationEpoch!==row.activationEpoch){throw new Error("ROUTE_BINDING_ACTIVATION_MISMATCH")}if(row.activationNodeId!==row.desiredNodeId||row.instanceNodeId!==row.desiredNodeId||row.nodeEpoch!==row.desiredNodeEpoch||row.instanceNodeEpoch!==row.desiredNodeEpoch){throw new Error("ROUTE_BINDING_NODE_FENCE_MISMATCH")}if(!row.artifactRef||!row.sourceGenerationRef||!row.runtimeGenerationRef||row.instanceArtifactRef!==row.artifactRef||row.instanceSourceGenerationRef!==row.sourceGenerationRef||row.instanceRuntimeGenerationRef!==row.runtimeGenerationRef){throw new Error("ROUTE_BINDING_GENERATION_MISMATCH")}if(!row.port||!row.readyContractHash){throw new Error("ROUTE_BINDING_INSTANCE_AMBIGUOUS")}return buildCanonicalTenantRouteBinding({appId:row.appId,appName:row.appName,environment:row.environment,deploymentId:row.deploymentId,activationId:row.activationId,instanceId:row.instanceId,artifactRef:row.artifactRef,sourceGenerationRef:row.sourceGenerationRef,runtimeGenerationRef:row.runtimeGenerationRef,activationEpoch:row.activationEpoch,nodeId:row.desiredNodeId,nodeEpoch:row.desiredNodeEpoch,leaseEpoch:row.leaseEpoch,port:row.port,readyContractHash:row.readyContractHash})}function bindingSelection(){return{appId:apps.id,appName:apps.name,environment:deployments.env,deploymentId:appDeploymentActivations.deploymentId,activationId:appDeploymentActivations.id,desiredActivationId:appRuntimeDesiredState.desiredActivationId,activationState:appDeploymentActivations.state,routeAckEpoch:appDeploymentActivations.routeAckEpoch,activationEpoch:appDeploymentActivations.activationEpoch,desiredActivationEpoch:appRuntimeDesiredState.activationEpoch,activationNodeId:appDeploymentActivations.nodeId,desiredNodeId:appRuntimeDesiredState.nodeId,instanceNodeId:appRuntimeInstances.nodeId,nodeEpoch:appDeploymentActivations.nodeEpoch,desiredNodeEpoch:appRuntimeDesiredState.nodeEpoch,instanceNodeEpoch:appRuntimeInstances.nodeEpoch,instanceId:appRuntimeInstances.instanceId,instanceState:appRuntimeInstances.state,artifactRef:appDeploymentActivations.artifactRef,instanceArtifactRef:appRuntimeInstances.artifactRef,sourceGenerationRef:appDeploymentActivations.sourceGenerationRef,instanceSourceGenerationRef:appRuntimeInstances.sourceGenerationRef,runtimeGenerationRef:appDeploymentActivations.runtimeGenerationRef,instanceRuntimeGenerationRef:appRuntimeInstances.runtimeGenerationRef,leaseEpoch:appRuntimeInstances.leaseEpoch,port:appRuntimeInstances.port,readyContractHash:appRuntimeInstances.readyContractHash}}function fleetSelection(){return{...bindingSelection(),authorityMode:appRuntimeDesiredState.authorityMode,desiredRuntimeState:appRuntimeDesiredState.desiredRuntimeState,hasBackend:apps.hasBackend,appStatus:apps.status}}function queryBindingRows(db){return db.select(bindingSelection()).from(appRuntimeDesiredState).innerJoin(apps,eq26(apps.id,appRuntimeDesiredState.appId)).innerJoin(appDeploymentActivations,and23(eq26(appDeploymentActivations.id,appRuntimeDesiredState.desiredActivationId),eq26(appDeploymentActivations.appId,appRuntimeDesiredState.appId))).innerJoin(deployments,and23(eq26(deployments.id,appDeploymentActivations.deploymentId),eq26(deployments.appId,appRuntimeDesiredState.appId))).innerJoin(appRuntimeInstances,and23(eq26(appRuntimeInstances.activationId,appDeploymentActivations.id),eq26(appRuntimeInstances.deploymentId,appDeploymentActivations.deploymentId),eq26(appRuntimeInstances.appId,appRuntimeDesiredState.appId),eq26(appRuntimeInstances.state,"serving")))}async function loadCanonicalTenantRouteBinding(input2){const rows8=await queryBindingRows(input2.db).where(and23(eq26(appRuntimeDesiredState.appId,input2.appId),eq26(appRuntimeDesiredState.authorityMode,"enforce"),eq26(appRuntimeDesiredState.desiredRuntimeState,"serving")));return bindingFromRows(rows8)}function projectionNumber(value2){const numberValue=typeof value2==="bigint"?Number(value2):Number(value2);return Number.isSafeInteger(numberValue)&&numberValue>0?numberValue:null}async function loadCanonicalTenantRouteProjectionProof(input2){const expectedSlots=[...new Set(input2.expectedPlatformSlots.map(slot=>slot.trim().toLowerCase()))].filter(Boolean);if(expectedSlots.length===0){throw new Error("ROUTE_BINDING_PROJECTION_ACTIVE_SLOTS_UNDECLARED")}const binding=await loadCanonicalTenantRouteBinding({db:input2.db,appId:input2.appId});if(binding.nodeId!==input2.nodeId){throw new Error("ROUTE_BINDING_NODE_FENCE_MISMATCH")}const rows8=await input2.db.select({appId:appRuntimeRouteProjections.appId,nodeId:appRuntimeRouteProjections.nodeId,platformSlot:appRuntimeRouteProjections.platformSlot,platformEpoch:appRuntimeRouteProjections.platformEpoch,platformRevision:appRuntimeRouteProjections.platformRevision,activationId:appRuntimeRouteProjections.activationId,activationEpoch:appRuntimeRouteProjections.activationEpoch,instanceId:appRuntimeRouteProjections.instanceId,leaseEpoch:appRuntimeRouteProjections.leaseEpoch,routePort:appRuntimeRouteProjections.routePort,readyContractHash:appRuntimeRouteProjections.readyContractHash,bindingHash:appRuntimeRouteProjections.bindingHash,state:appRuntimeRouteProjections.state,probedAt:appRuntimeRouteProjections.probedAt}).from(appRuntimeRouteProjections).where(and23(eq26(appRuntimeRouteProjections.appId,input2.appId),eq26(appRuntimeRouteProjections.nodeId,input2.nodeId)));const latestBySlot=new Map;for(const row of rows8){const slot=String(row.platformSlot??"").trim().toLowerCase();const epoch=projectionNumber(row.platformEpoch);if(!slot||epoch===null)throw new Error("ROUTE_BINDING_PROJECTION_MISMATCH");const previous=latestBySlot.get(slot);if(!previous||epoch>projectionNumber(previous.platformEpoch)){latestBySlot.set(slot,row)}}const expectedSet=new Set(expectedSlots);const requireExactSlotSet=input2.requireExactSlotSet??true;if(requireExactSlotSet&&latestBySlot.size!==expectedSet.size||requireExactSlotSet&&[...latestBySlot.keys()].some(slot=>!expectedSet.has(slot))||expectedSlots.some(slot=>!latestBySlot.has(slot))){throw new Error("ROUTE_BINDING_PROJECTION_SLOT_SET_MISMATCH")}const slots=expectedSlots.map(platformSlot=>{const row=latestBySlot.get(platformSlot);const platformEpoch=projectionNumber(row.platformEpoch);const activationEpoch=projectionNumber(row.activationEpoch);const leaseEpoch=projectionNumber(row.leaseEpoch);const routePort=projectionNumber(row.routePort);const platformRevision=String(row.platformRevision??"").trim();const activationId=String(row.activationId??"");const instanceId=String(row.instanceId??"");const readyContractHash=String(row.readyContractHash??"");const bindingHash=String(row.bindingHash??"");if(row.appId!==input2.appId||row.nodeId!==input2.nodeId||row.state!=="acknowledged"||row.probedAt===null||platformEpoch===null||activationEpoch===null||leaseEpoch===null||routePort===null||!platformRevision||!activationId||!instanceId||!readyContractHash||!bindingHash||activationId!==binding.activationId||activationEpoch!==binding.activationEpoch||instanceId!==binding.instanceId||leaseEpoch!==binding.leaseEpoch||routePort!==binding.port||readyContractHash!==binding.readyContractHash||bindingHash!==binding.bindingHash){throw new Error("ROUTE_BINDING_PROJECTION_MISMATCH")}return{platformSlot,platformEpoch,platformRevision,activationId,activationEpoch,instanceId,leaseEpoch,routePort,readyContractHash,bindingHash}});return{binding,nodeId:input2.nodeId,slots}}async function loadCanonicalTenantRouteBindings(input2){return(await loadCanonicalTenantRouteFleetSnapshot(input2)).bindings}function groupFleetRows(rows8){const grouped=new Map;for(const row of rows8){const group2=grouped.get(row.appId)??[];group2.push(row);grouped.set(row.appId,group2)}return grouped}function fleetAuthorityDigest(rows8){const evidence=rows8.map(row=>[row.appId,row.appName,row.authorityMode,row.hasBackend,row.desiredActivationId,row.desiredRuntimeState,row.desiredActivationEpoch,row.desiredNodeId,row.desiredNodeEpoch,row.environment,row.deploymentId,row.activationId,row.activationState,row.routeAckEpoch,row.activationEpoch,row.activationNodeId,row.nodeEpoch,row.artifactRef,row.sourceGenerationRef,row.runtimeGenerationRef,row.instanceId,row.instanceState,row.instanceNodeId,row.instanceNodeEpoch,row.instanceArtifactRef,row.instanceSourceGenerationRef,row.instanceRuntimeGenerationRef,row.leaseEpoch,row.port,row.readyContractHash]).sort((left,right)=>JSON.stringify(left).localeCompare(JSON.stringify(right)));return createHash55("sha256").update(JSON.stringify(evidence)).digest("hex")}async function queryFleetAuthorityRows(db){return await db.select(fleetSelection()).from(appRuntimeDesiredState).innerJoin(apps,eq26(apps.id,appRuntimeDesiredState.appId)).leftJoin(appDeploymentActivations,and23(eq26(appDeploymentActivations.id,appRuntimeDesiredState.desiredActivationId),eq26(appDeploymentActivations.appId,appRuntimeDesiredState.appId))).leftJoin(deployments,and23(eq26(deployments.id,appDeploymentActivations.deploymentId),eq26(deployments.appId,appRuntimeDesiredState.appId))).leftJoin(appRuntimeInstances,and23(eq26(appRuntimeInstances.activationId,appDeploymentActivations.id),eq26(appRuntimeInstances.deploymentId,appDeploymentActivations.deploymentId),eq26(appRuntimeInstances.appId,appRuntimeDesiredState.appId),eq26(appRuntimeInstances.state,"serving"))).where(eq26(appRuntimeDesiredState.authorityMode,"enforce"))}async function loadCanonicalTenantRouteFleetSnapshot(input2){const rows8=await queryFleetAuthorityRows(input2.db);const grouped=groupFleetRows(rows8);const bindings=[];const activationMismatchTargets=[];const blockedTargets=[];const removalTargets=[];for(const appRows of grouped.values()){const desired=appRows[0];if(desired.hasBackend&&desired.desiredRuntimeState==="serving"&&desired.desiredNodeId===input2.nodeId){const joinedRows=appRows.filter(row=>row.instanceId!==null);if(joinedRows.length===0){removalTargets.push({appId:desired.appId,appName:desired.appName});continue}try{bindings.push(bindingFromRows(joinedRows))}catch(error62){if(error62 instanceof Error&&error62.message==="ROUTE_BINDING_ACTIVATION_MISMATCH"){activationMismatchTargets.push({appId:desired.appId,appName:desired.appName});continue}blockedTargets.push({appId:desired.appId,appName:desired.appName,failureCode:error62 instanceof Error?error62.message:"RUNTIME_ROUTE_PROJECTION_STATE_AMBIGUOUS"});continue}}else{removalTargets.push({appId:desired.appId,appName:desired.appName})}}const appIds=[...grouped.keys()];const authorityDigestByAppId=Object.fromEntries(appIds.map(appId=>[String(appId),fleetAuthorityDigest(rows8.filter(row=>row.appId===appId))]));return{bindings,activationMismatchTargets,blockedTargets,removalTargets,authorityDigest:fleetAuthorityDigest(rows8),authorityDigestByAppId}}async function assertCanonicalTenantRouteFleetSnapshot(input2){const rows8=await queryFleetAuthorityRows(input2.db);if(input2.appIds&&input2.authorityDigestByAppId){for(const appId of[...new Set(input2.appIds)]){const expected=input2.authorityDigestByAppId[String(appId)];const current=fleetAuthorityDigest(rows8.filter(row=>row.appId===appId));if(expected!==current)throw new Error("RUNTIME_ROUTE_PROJECTION_AUTHORITY_CHANGED")}return}const currentDigest=fleetAuthorityDigest(rows8);if(currentDigest!==input2.authorityDigest){throw new Error("RUNTIME_ROUTE_PROJECTION_AUTHORITY_CHANGED")}}async function loadCanonicalTenantRouteRemovalTargets(input2){const rows8=await input2.db.select({appId:appRuntimeDesiredState.appId,appName:apps.name,desiredRuntimeState:appRuntimeDesiredState.desiredRuntimeState,nodeId:appRuntimeDesiredState.nodeId}).from(appRuntimeDesiredState).innerJoin(apps,eq26(apps.id,appRuntimeDesiredState.appId)).where(eq26(appRuntimeDesiredState.authorityMode,"enforce"));return rows8.filter(row=>row.desiredRuntimeState!=="serving"||row.nodeId!==input2.nodeId).map(({appId,appName})=>({appId,appName}))}var ROUTE_BINDING_NOT_SERVING_CODE;var init_runtime_route_binding_reader=__esm({"../platform/src/runtime-route-binding-reader.ts"(){"use strict";init_schema();init_runtime_route_binding_contract();ROUTE_BINDING_NOT_SERVING_CODE="ROUTE_BINDING_NOT_SERVING"}});async function observeBackendServing(input2){try{const binding=await(input2.loadRouteBindingImpl??loadCanonicalTenantRouteBinding)({db:input2.db,appId:input2.appId});return binding?{kind:"SERVING",binding}:{kind:"UNOBSERVABLE"}}catch(error62){const expectedAbsence=error62 instanceof Error&&error62.message===ROUTE_BINDING_NOT_SERVING_CODE;if(!expectedAbsence){console.warn(JSON.stringify({event:"backend_serving_lookup_unavailable",correlationId:input2.correlationId}))}return{kind:"UNOBSERVABLE"}}}function backendServingState(observation){return observation?.kind==="SERVING"?"PRESERVED":"UNKNOWN"}var init_deployment_backend_incumbent_serving=__esm({"../platform/src/deployment-backend-incumbent-serving.ts"(){"use strict";init_runtime_route_binding_reader()}});function isCrashedExecutorRetiredReceipt(receipt){return receipt?.warnings?.some(warning=>warning.code===CRASHED_EXECUTOR_RETIRED_WARNING_CODE)===true}function isActivationFenceRetiredReceipt(receipt){return receipt?.warnings?.some(warning=>warning.code===ACTIVATION_FENCE_RETIRED_WARNING_CODE)===true}function crashedExecutorInspectCommand(environment){return environment==="prod"?"gencow db:check --prod --inspect-state":"gencow db:check --inspect-state"}function crashedExecutorRecoveryGuidance(input2){const base2=input2.activation?"This deployment stopped before it was activated and was closed as failed. Nothing it started is still running, serving is unchanged, and new deployments are accepted.":"An earlier deployment crashed, so this one was closed as failed. The incumbent still serves this app, and new deployments are accepted.";const inspectCommand=crashedExecutorInspectCommand(input2.environment);const statusCommand=`gencow deploy status --deployment ${input2.operationId}`;if(input2.ambiguous){return{summary:`${base2} Database outcome is uncertain: check the migration state before relying on the schema.`,retryCondition:`Do not repeat this operation. Run "${inspectCommand}" to confirm the migration state, then start a new deployment only to change the app.`,nextAction:{kind:"INSPECT_STATE",command:inspectCommand}}}return{summary:base2,retryCondition:`Do not repeat this operation. Check its status with "${statusCommand}" if needed; a new deployment is accepted to change the app.`,nextAction:{kind:"VIEW_STATUS",command:statusCommand}}}function buildCrashedStaleDeploymentResponse(input2){const{operation,currentReceipt,fallbackDiagnostic}=input2;if(!fallbackDiagnostic||!currentReceipt||!(isCrashedExecutorRetiredReceipt(currentReceipt)||isActivationFenceRetiredReceipt(currentReceipt))||input2.failureCode!==STALE_DEPLOYMENT_RECOVERED_CODE||input2.failureStage!=="controller"||input2.recoveryRequired||operation.environment==="static"||operation.status!=="failed"||operation.controlPlaneState!=="failed"||operation.executorState!=="failed"||currentReceipt.phase!=="failed"||currentReceipt.code!==input2.failureCode){return null}const guidance=crashedExecutorRecoveryGuidance({environment:operation.environment,operationId:operation.deploymentId,ambiguous:currentReceipt.databaseState==="RECOVERY_REQUIRED",activation:isActivationFenceRetiredReceipt(currentReceipt)});return{status:409,body:{error:guidance.summary,code:input2.failureCode,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:input2.failureStage,databaseState:currentReceipt.databaseState,servingState:isActivationFenceRetiredReceipt(currentReceipt)?"UNCHANGED":"PRESERVED",retryClass:"platform-action",userAction:guidance.nextAction.kind,retryPrecondition:guidance.retryCondition,correlationId:operation.correlationId,appName:operation.appName,state:"failed",nextAction:guidance.nextAction,diagnostic:fallbackDiagnostic}}}var STALE_DEPLOYMENT_RECOVERED_CODE,CRASHED_EXECUTOR_RETIRED_WARNING_CODE,ACTIVATION_FENCE_RETIRED_WARNING_CODE;var init_deployment_stale_crashed_presentation=__esm({"../platform/src/deployment-stale-crashed-presentation.ts"(){"use strict";STALE_DEPLOYMENT_RECOVERED_CODE="PLATFORM_STALE_DEPLOYMENT_RECOVERED";CRASHED_EXECUTOR_RETIRED_WARNING_CODE="PLATFORM_STALE_CRASHED_EXECUTOR_RETIRED";ACTIVATION_FENCE_RETIRED_WARNING_CODE="PLATFORM_STALE_ACTIVATION_FENCE_RETIRED"}});function resolveStaleDeploymentNewDeploymentCommand(input2){if(input2.releaseBindingPresent===true&&input2.releaseEnvironment!=="dev"&&input2.releaseEnvironment!=="prod"){return null}const releaseEnvironment=resolveDeploymentReleaseEnvironment(input2);const component=input2.executionEnvironment==="static"?"static":input2.executionEnvironment==="dev"||input2.executionEnvironment==="prod"?"backend":null;if(component===null||!releaseBindingMatchesExecutionScope({component,executionEnvironment:input2.executionEnvironment,releaseEnvironment})){return null}if(releaseEnvironment==="prod")return"gencow deploy --prod";if(releaseEnvironment==="dev")return"gencow deploy";return null}function buildPublicDeploymentExecutorDiagnostic(input2){const policy=resolveStoredDeploymentFailurePolicy(input2.stage,input2.code);const rootCauseClass=publicRoutePrepareRootCauseClass({stage:input2.stage,code:input2.code,stored:input2.receipt.rootCauseClass});const candidateCauseCode=publicCandidateCauseCode({stage:input2.stage,code:input2.code,stored:input2.receipt.candidateCauseCode});const candidateHealthObservation=publicCandidateHealthObservation({code:input2.code,stored:input2.receipt.candidateHealthObservation});const routeTargetRejections=publicRouteTargetRejections({stage:input2.stage,code:input2.code,stored:input2.receipt.routeTargetRejections});const migrationDiagnostic=input2.code!=="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.receipt.diagnostic?.code===input2.code&&input2.receipt.diagnostic.correlationId===input2.correlationId?input2.receipt.diagnostic:void 0;const baseSelfService=buildPublicSelfServiceDiagnostic({code:input2.code,stage:input2.stage,correlationId:input2.correlationId,operationId:input2.operationId,databaseState:input2.receipt.databaseState,requestedAction:migrationDiagnostic?.nextAction.kind??(input2.recoveryRequired?"OPERATOR_ACTION":policy.userAction),reasonCode:migrationDiagnostic?.reason.code??input2.code.toLowerCase(),reasonSummary:input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.routeRetryReadiness?.reason==="READY"?"The failed static deployment remains terminal; route retry is now safe for this app.":input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.routeRetryReadiness?.reason==="ALREADY_RECOVERED"?"The failed static deployment remains terminal; a later static deployment now serves this app.":input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.routeRetryReadiness?.reason==="SERVING_CHANGED"?"The failed static deployment's content is live, but its record is closed as failed. No retry is needed.":migrationDiagnostic?.reason.summary??policy.error,incumbentServing:input2.incumbentServing,routeRetryReadiness:input2.routeRetryReadiness,operationState:input2.receipt.phase==="recovery_required"?"BLOCKED":input2.receipt.phase==="completed"?"COMPLETED":input2.receipt.phase==="failed"?"FAILED":"PENDING"});const sourceRuntimeDiagnostic=!input2.recoveryRequired&&(input2.receipt.databaseState==="NOT_ENTERED"||input2.receipt.databaseState==="UNCHANGED")?buildRestoreSourceRuntimeDiagnostic(input2):null;const stopConfigurationDiagnostic=!input2.recoveryRequired&&(input2.receipt.databaseState==="NOT_ENTERED"||input2.receipt.databaseState==="UNCHANGED")?buildRuntimeStopConfigurationDiagnostic(input2):null;const newDeploymentCommand=resolveStaleDeploymentNewDeploymentCommand({executionEnvironment:input2.environment,releaseEnvironment:input2.releaseEnvironment,releaseBindingPresent:input2.releaseBindingPresent});const crashedGuidance=!input2.recoveryRequired&&input2.environment!=="static"&&input2.code==="PLATFORM_STALE_DEPLOYMENT_RECOVERED"&&input2.stage==="controller"&&(isCrashedExecutorRetiredReceipt(input2.receipt)||isActivationFenceRetiredReceipt(input2.receipt))?crashedExecutorRecoveryGuidance({activation:isActivationFenceRetiredReceipt(input2.receipt),environment:input2.environment,operationId:input2.operationId,ambiguous:input2.receipt.databaseState==="RECOVERY_REQUIRED"}):null;const settledStaleDeployment=crashedGuidance===null&&newDeploymentCommand!==null&&input2.code==="PLATFORM_STALE_DEPLOYMENT_RECOVERED"&&input2.receipt.phase==="failed"&&input2.receipt.code==="PLATFORM_STALE_DEPLOYMENT_RECOVERED"&&(input2.receipt.databaseState==="APPLIED"||input2.receipt.databaseState==="UNCHANGED")&&!input2.recoveryRequired&&(input2.incumbentServing==="PRESERVED"||input2.incumbentServing==="NOT_APPLICABLE"&&input2.routeRetryReadiness?.incumbentServing==="NONE_TO_PRESERVE");const staleServingCondition=input2.incumbentServing==="NOT_APPLICABLE"?"no static site was live before this operation, so serving is unchanged":"the incumbent serving deployment is preserved";const staleServingSummary=input2.incumbentServing==="NOT_APPLICABLE"?"no static site was live before it, so your serving is unchanged":"the current serving deployment is preserved";const committedRouteBlocked=newDeploymentCommand!==null&&input2.environment!=="static"&&input2.recoveryRequired&&input2.stage==="route"&&input2.code===COMMITTED_ROUTE_BLOCKED_CODE&&isCommittedRouteBlockedReceipt(input2.receipt);const supersededByNewerCommit=!input2.recoveryRequired&&input2.environment!=="static"&&input2.code===SUPERSEDED_BY_NEWER_COMMIT_CODE&&isSupersededByNewerCommitReceipt(input2.receipt);const databaseOutcomeSummary=input2.receipt.databaseState==="APPLIED"?"applied database changes are preserved":"the database was left unchanged";const terminalDeferral=!input2.recoveryRequired&&input2.receipt.phase==="failed"&&isDeploymentExecutorDeferralTerminalCode(input2.code)&&(input2.receipt.databaseState==="APPLIED"||input2.receipt.databaseState==="UNCHANGED"||input2.receipt.databaseState==="NOT_ENTERED");const releaseAttemptClosed=input2.code===DEPLOYMENT_EXECUTOR_RELEASE_ATTEMPT_CLOSED;const releaseBindingTerminal=releaseAttemptClosed||input2.code===DEPLOYMENT_EXECUTOR_RELEASE_BINDING_INVALID;const platformToolchainUnavailable=migrationDiagnostic?.reason.code===PLATFORM_SCHEMA_TOOLCHAIN_UNAVAILABLE_REASON;const databaseTrustInvalid=input2.code==="RUNTIME_CANDIDATE_DATABASE_TRUST_INVALID"&&input2.stage==="candidate"&&!input2.recoveryRequired;const databaseTrustDiagnostic=databaseTrustInvalid?{...baseSelfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:"Retry only after the Platform restores the managed database trust file and sandbox profile binding, then confirms this operation is terminal."},action:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:["No app source, migration, or tenant database change is required; preserve the incumbent deployment."]},reason:{code:"runtime_candidate_database_trust_invalid",summary:"The Platform could not bind the managed database trust file to the candidate sandbox. The incumbent deployment and tenant data are preserved."}}:null;const candidateRouteEpochConflict=input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.stage==="candidate"&&!input2.recoveryRequired&&input2.receipt.phase==="failed";const candidateRouteEpochConflictDiagnostic=candidateRouteEpochConflict?{...baseSelfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:`This operation is terminal and was not activated, and ${databaseOutcomeSummary}. A previous route change for this app is still being settled by the Platform; check this operation, then start a new deployment.`},action:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:["No change to your source is needed; do not resume this failed operation."]},reason:{code:"app_serving_route_epoch_conflict",summary:"A previous route change for this app is still being settled by the Platform; your source is not the cause. Check the deployment status, then repeat the same deployment."}}:null;const selfService=supersededByNewerCommit?{...baseSelfService,responsibility:"TRANSIENT_DEPENDENCY",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:`A newer committed deployment already serves this app, and ${databaseOutcomeSummary}. No action is needed for this operation; start a new deployment only to change the app.`},action:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:[newDeploymentCommand?`Do not retry this operation; to change the app, start a new deployment with ${newDeploymentCommand}.`:"Do not retry this operation; a newer deployment already serves the app."]},reason:{code:"deployment_superseded_by_newer_commit",summary:"This deployment was superseded by a newer committed deployment, which serves the app. Serving and data are unchanged."}}:committedRouteBlocked?{...baseSelfService,responsibility:"TRANSIENT_DEPENDENCY",retry:{allowedNow:true,policy:"IMMEDIATE",condition:`This deployment is committed and keeps serving unchanged, and ${databaseOutcomeSummary}. Its route acknowledgement did not converge in the bounded window; a new deployment can start now and supersedes it.`},action:{kind:"RETRY",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:[`Do not resume or retry this operation; start a new deployment with ${newDeploymentCommand}.`]},reason:{code:"committed_route_convergence_blocked",summary:"The deployment is committed and serving is unchanged, but its route acknowledgement did not converge in time. Start a new deployment to supersede it."}}:terminalDeferral&&releaseBindingTerminal?{...baseSelfService,responsibility:releaseAttemptClosed?"TRANSIENT_DEPENDENCY":"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:`This operation is terminal and was never started, so no activation happened and ${databaseOutcomeSummary}. Retrying the same deployment cannot succeed; check this operation, then start a new deployment.`},action:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:[newDeploymentCommand?`Do not retry this operation; start a new deployment with ${newDeploymentCommand}.`:"Do not retry this operation; start a new deployment."]},reason:releaseAttemptClosed?{code:"release_attempt_closed_before_start",summary:`The release attempt was ended before the Platform started this deployment (for example the publisher stopped waiting while the executor was busy). Nothing was activated and ${databaseOutcomeSummary}.`}:{code:"release_binding_mismatch",summary:`The release this deployment belonged to does not match it, so the Platform stopped it before starting. Nothing was activated and ${databaseOutcomeSummary}.`}}:terminalDeferral?{...baseSelfService,retry:{allowedNow:false,policy:"AFTER_STATUS",condition:routeTargetRejections?`This operation is terminal and was not activated, and ${databaseOutcomeSummary}. A Platform route target rejected it (see the route target rejections); check this operation, then start a new deployment once app admission is open.`:`This operation is terminal and was not activated, and ${databaseOutcomeSummary}. Check this operation, then start a new deployment once app admission is open.`},action:{kind:baseSelfService.action.kind,command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:["Do not resume or retry this stopped operation; start a new deployment instead."]}}:crashedGuidance?{...baseSelfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:crashedGuidance.retryCondition},action:crashedGuidance.nextAction,reason:{code:isActivationFenceRetiredReceipt(input2.receipt)?"stale_activation_fence_retired":"stale_crashed_executor_retired",summary:crashedGuidance.summary}}:settledStaleDeployment?{...baseSelfService,responsibility:"TRANSIENT_DEPENDENCY",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:`This operation is terminal, ${staleServingCondition}, and ${databaseOutcomeSummary}. Check this operation, then start a new deployment only after app admission is open.`},action:{kind:"RETRY",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:["Do not resume or retry this failed operation; wait until app admission is open, then start a new deployment."]},reason:{code:"stale_deployment_recovered",summary:`The stale deployment is terminal, ${staleServingSummary}, and ${databaseOutcomeSummary}. A new deployment can start after app admission opens.`}}:databaseTrustDiagnostic??candidateRouteEpochConflictDiagnostic??stopConfigurationDiagnostic??buildNpmDependencyReplayDiagnostic({...input2,databaseState:input2.receipt.databaseState})??sourceRuntimeDiagnostic??(migrationDiagnostic?{...baseSelfService,retry:{allowedNow:migrationDiagnostic.safeToRetryNow,policy:migrationDiagnostic.retryPolicy==="IDEMPOTENT_NOOP"||platformToolchainUnavailable?"AFTER_STATUS":migrationDiagnostic.retryPolicy,condition:migrationDiagnostic.retryCondition??"Check the canonical migration state before starting another operation.",...migrationDiagnostic.retryAfterSeconds===void 0?{}:{afterSeconds:migrationDiagnostic.retryAfterSeconds}},action:{kind:baseSelfService.action.kind,...platformToolchainUnavailable?{command:`gencow deploy status --deployment ${input2.operationId}`}:baseSelfService.action.kind==="INSPECT_STATE"?{command:`gencow db:check${input2.environment==="prod"?" --prod":""} --inspect-state`}:migrationDiagnostic.nextAction.command?{command:migrationDiagnostic.nextAction.command}:{},...platformToolchainUnavailable?{prerequisites:["No edit to your schema or bundle is needed; run the same deploy again after the Platform restores its schema toolchain."]}:baseSelfService.action.prerequisites?{prerequisites:baseSelfService.action.prerequisites}:{}},reason:migrationDiagnostic.reason,forbiddenActions:migrationDiagnostic.forbiddenActions}:baseSelfService);const platformAction2=selfService.responsibility!=="USER_ACTION_REQUIRED";return{code:input2.code,databaseState:input2.receipt.databaseState,failureClass:platformAction2?"PLATFORM_ACTION_REQUIRED":"USER_FIXABLE",retryability:supersededByNewerCommit?"NOT_REQUIRED":committedRouteBlocked?"RETRY_NEW_DEPLOYMENT":settledStaleDeployment||terminalDeferral||crashedGuidance!==null?"NEW_DEPLOYMENT_AFTER_STATUS":input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.routeRetryReadiness?.reason==="ALREADY_RECOVERED"?"NOT_REQUIRED":input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.routeRetryReadiness?.reason==="SERVING_CHANGED"?"NOT_REQUIRED":input2.routeRetryReadiness?.retryReady===true&&input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"?"RETRY_NEW_DEPLOYMENT":input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&selfService.retry.policy==="AFTER_DELAY"?"AFTER_DELAY":!input2.recoveryRequired&&policy.retryClass==="retryable-infra"?"RETRY_SAME_DEPLOYMENT":platformAction2?"AFTER_PLATFORM_REPAIR":"AFTER_EDIT",action:selfService.action.kind,...(settledStaleDeployment||terminalDeferral||committedRouteBlocked)&&newDeploymentCommand?{newDeploymentCommand}:{},observedState:input2.receipt.phase,expectedState:"completed",reasonCode:input2.code.toLowerCase(),stage:input2.stage,selfService,...rootCauseClass?{rootCauseClass}:{},...candidateCauseCode?{candidateCauseCode}:{},...candidateHealthObservation?{candidateHealthObservation}:{},...routeTargetRejections?{routeTargetRejections}:{},...migrationDiagnostic?{migration:migrationDiagnostic}:{}}}var init_deployment_executor_public_diagnostic=__esm({"../platform/src/deployment-executor-public-diagnostic.ts"(){"use strict";init_deployment_candidate_health_observation();init_runtime_stop_configuration_diagnostic();init_restore_source_runtime_diagnostic();init_npm_dependency_replay_diagnostic();init_deployment_failure_contract();init_app_serving_route_target_rejection();init_deployment_candidate_cause();init_deployment_route_prepare_root_cause();init_canonical_schema_proof_missing_module();init_public_self_service_diagnostic();init_deployment_committed_route_contract();init_deployment_stale_crashed_presentation();init_deployment_release_scope()}});function buildPublicFailureChain(input2){const primaryFailure={code:SAFE_CODE3.test(input2.primaryCode)?input2.primaryCode:"DEPLOYMENT_FAILED",stage:input2.primaryStage,correlationId:input2.correlationId};const secondaryCode=input2.secondaryCode&&SAFE_CODE3.test(input2.secondaryCode)?input2.secondaryCode:null;return{primaryFailure,...secondaryCode?{cascade:{code:secondaryCode,causedBy:primaryFailure.code}}:{}}}var SAFE_CODE3;var init_deployment_failure_public_diagnostic=__esm({"../platform/src/deployment-failure-public-diagnostic.ts"(){"use strict";SAFE_CODE3=/^[A-Z][A-Z0-9_]{2,99}$/u}});function servingRouteEnvironment(env){const tier=optionalValue(env.GENCOW_DEPLOY_TIER);if(tier==="dev"||tier==="qc"||tier==="prod")return tier;return optionalValue(env.GENCOW_SERVING_ROUTE_PUBLICATION_ENVIRONMENT)}function optionalValue(value2){const normalized=value2?.trim()??"";return normalized||null}function positiveInteger3(value2){const parsed=Number(value2);return Number.isSafeInteger(parsed)&&parsed>0?parsed:null}function releaseMode(value2){const normalized=value2?.trim().toLowerCase();if(normalized==="1"||normalized==="true")return"all";return normalized==="allowlist"?"allowlist":"disabled"}function parseAppReleaseRuntimeConfig(env){return Object.freeze({executor:Object.freeze({appsDir:optionalValue(env.GENCOW_APPS_DIR),nodeId:optionalValue(env.GENCOW_NODE_ID)?.toLowerCase()??null,spoolDir:optionalValue(env.GENCOW_DEPLOYMENT_EXECUTOR_SPOOL_DIR)}),staticOrigin:Object.freeze({artifactRoot:optionalValue(env.GENCOW_STATIC_ORIGIN_ARTIFACT_ROOT),stageEnabled:env.GENCOW_STATIC_ORIGIN_STAGE_ENABLED==="true"}),release:Object.freeze({mode:releaseMode(env.GENCOW_RELEASE_VERSIONS_ENABLED),allowlist:Object.freeze((env.GENCOW_RELEASE_VERSIONS_ALLOWLIST??"").split(",").map(value2=>value2.trim()).filter(Boolean)),quotaBytes:positiveInteger3(env.GENCOW_RELEASE_STORAGE_QUOTA_BYTES),allowFilesystem:env.GENCOW_RELEASE_STORAGE_ALLOW_FILESYSTEM==="1",objectsDir:optionalValue(env.GENCOW_RELEASE_OBJECTS_DIR)}),storage:Object.freeze({azureAccountName:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_ACCOUNT_NAME),azureContainer:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_CONTAINER),azureEndpoint:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_ENDPOINT),azureAuth:env.GENCOW_PLATFORM_STORAGE_AZURE_AUTH==="client_secret"?"client_secret":"managed_identity",azureClientId:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_CLIENT_ID),azureTenantId:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_TENANT_ID),azurePrefix:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_PREFIX)?.replace(/\/+$/u,"")||null}),servingRoute:Object.freeze({publicationMode:optionalValue(env.GENCOW_SERVING_ROUTE_PUBLICATION_MODE)??"off",environment:servingRouteEnvironment(env),appAllowlist:optionalValue(env.GENCOW_SERVING_ROUTE_PUBLICATION_APP_ALLOWLIST),topologyRevision:optionalValue(env.GENCOW_SERVING_ROUTE_TOPOLOGY_REVISION),upsertTargetSetId:optionalValue(env.GENCOW_SERVING_ROUTE_UPSERT_TARGET_SET_ID),tombstoneTargetSetId:optionalValue(env.GENCOW_SERVING_ROUTE_TOMBSTONE_TARGET_SET_ID),artifactQuotaBytes:positiveInteger3(env.GENCOW_SERVING_ROUTE_ARTIFACT_QUOTA_BYTES),baseDomain:optionalValue(env.BASE_DOMAIN)})})}function parseAppReleaseProtectedSecrets(env){return Object.freeze({azureClientSecret:env.GENCOW_PLATFORM_STORAGE_AZURE_CLIENT_SECRET||null})}function isReleaseControlPlane(env){return env.IS_PLATFORM==="true"||env.GENCOW_DEPLOYMENT_EXECUTOR_ENABLED==="true"&&env.GENCOW_DEPLOYMENT_EXECUTOR_MODE==="dedicated"||env.GENCOW_BUILDER_WORKER_ENABLED==="true"&&env.GENCOW_BUILDER_WORKER_MODE==="dedicated"}function captureAppReleaseRuntimeEnv(env=process.env){const host=globalThis;if(host[SNAPSHOT_KEY])return host[SNAPSHOT_KEY];if(!isReleaseControlPlane(env))return null;const snapshot=Object.freeze({config:parseAppReleaseRuntimeConfig(env),protectedSecrets:parseAppReleaseProtectedSecrets(env)});host[SNAPSHOT_KEY]=snapshot;return snapshot}function appReleaseRuntimeConfig(explicit){if(explicit)return parseAppReleaseRuntimeConfig(explicit);return globalThis[SNAPSHOT_KEY]?.config??parseAppReleaseRuntimeConfig(process.env)}var SNAPSHOT_KEY,CAPTURE_SNAPSHOT_KEY;var init_app_release_runtime_env=__esm({"../platform/src/app-release-runtime-env.ts"(){"use strict";SNAPSHOT_KEY="__gencowAppReleaseRuntimeEnvSnapshot";CAPTURE_SNAPSHOT_KEY="__gencowCaptureAppReleaseRuntimeEnvSnapshot";globalThis[CAPTURE_SNAPSHOT_KEY]=captureAppReleaseRuntimeEnv}});import{createHash as createHash56}from"node:crypto";var RELEASE_OBJECT_TIERS,RELEASE_OBJECT_KINDS,RELEASE_OBJECT_REF;var init_release_object_store=__esm({"../platform/src/release-object-store.ts"(){"use strict";RELEASE_OBJECT_TIERS=["local","dev","qc","prod"];RELEASE_OBJECT_KINDS=["source","backend_artifact","static_artifact"];RELEASE_OBJECT_REF=new RegExp(`^release-object-v1\\.(${RELEASE_OBJECT_TIERS.join("|")})\\.([a-f0-9]{64})\\.([a-f0-9]{64})\\.([a-f0-9]{64})\\.(${RELEASE_OBJECT_KINDS.join("|")})\\.([a-f0-9]{64})$`,"u")}});import{createHash as createHash57,randomUUID as randomUUID37}from"node:crypto";import{createRequire as createRequire3}from"node:module";import{createReadStream as createReadStream2,createWriteStream}from"node:fs";import{chmod as chmod5,mkdir as mkdir8,rename as rename4,rm as rm4}from"node:fs/promises";import{dirname as dirname15,resolve as resolve62}from"node:path";import{Readable as Readable5}from"node:stream";import{pipeline as pipeline3}from"node:stream/promises";var init_release_object_store_azure=__esm({"../platform/src/release-object-store-azure.ts"(){"use strict";init_release_object_store()}});import{createHash as createHash58,randomUUID as randomUUID38}from"node:crypto";import{constants,createReadStream as createReadStream3}from"node:fs";import{chmod as chmod6,copyFile,link as link3,mkdir as mkdir9,open as open6,rename as rename5,rm as rm5,stat as stat8,writeFile as writeFile5}from"node:fs/promises";import{dirname as dirname16,join as join17,resolve as resolve63}from"node:path";import{Readable as Readable6}from"node:stream";var init_release_object_store_filesystem=__esm({"../platform/src/release-object-store-filesystem.ts"(){"use strict";init_release_object_store();init_release_object_store()}});import{resolve as resolve64}from"node:path";var init_release_object_store_factory=__esm({"../platform/src/release-object-store-factory.ts"(){"use strict";init_app_release_runtime_env();init_release_object_store_azure();init_release_object_store_filesystem()}});import{extname as extname8,isAbsolute as isAbsolute12,relative as relative13,resolve as resolve65}from"path";import{readFile as readFile6,stat as stat9}from"fs/promises";function isSafeSameOriginPath2(value2){if(!value2.startsWith("/")||value2.startsWith("//"))return false;if(/[\u0000-\u001f\u007f\\?#]/.test(value2))return false;try{const decoded=decodeURIComponent(value2);if(!decoded.startsWith("/")||decoded.startsWith("//")||/[\u0000-\u001f\u007f\\?#]/.test(decoded)){return false}return!decoded.split("/").some(segment=>segment==="."||segment==="..")}catch{return false}}function parseStaticRedirects2(source){const rules=[];for(const rawLine of source.split(/\r?\n/)){const line=rawLine.trim();if(!line||line.startsWith("#"))continue;const[from,to2,statusText,...extra]=line.split(/\s+/);const statusCode=Number(statusText);if(extra.length>0||!from||!to2||!ALLOWED_STATUSES2.has(statusCode)||!isSafeSameOriginPath2(from.replace(/\*$/,"safe"))||!isSafeSameOriginPath2(to2)){continue}const wildcard=from.endsWith("*");if(wildcard&&!from.endsWith("/*")||!wildcard&&from.includes("*"))continue;rules.push({from,to:to2,statusCode,wildcard})}return rules}var ALLOWED_STATUSES2;var init_static_redirects2=__esm({"../server/src/static-redirects.ts"(){"use strict";ALLOWED_STATUSES2=new Set([200,301,302,307,308,404])}});import{extname as extname9,isAbsolute as isAbsolute13,relative as relative14,resolve as resolve66}from"path";function hashLeafRule2(token){return`${HASH_LEAF_PREFIX2}${token}${HASH_LEAF_SUFFIX2}`}var STATIC_IMMUTABLE_EXTENSIONS2,STATIC_DOCUMENT_EXTENSIONS2,STATIC_NO_FALLBACK_EXTENSIONS2,IMMUTABLE_EXTENSION_ALTERNATION2,HASH_LEAF_PREFIX2,HASH_LEAF_SUFFIX2,STATIC_CONTENT_HASH_RULES2,staticContentHashRegexGroups2,staticNoFallbackExtensionSet2;var init_static_file_routing2=__esm({"../server/src/static-file-routing.ts"(){"use strict";init_static_redirects2();STATIC_IMMUTABLE_EXTENSIONS2=Object.freeze([".avif",".br",".css",".csv",".eot",".gif",".gz",".ico",".jpeg",".jpg",".js",".json",".m4a",".map",".mjs",".mov",".mp3",".mp4",".ogg",".pdf",".png",".svg",".tsv",".ttf",".txt",".wasm",".wav",".webm",".webmanifest",".webp",".woff",".woff2",".xml",".zip"]);STATIC_DOCUMENT_EXTENSIONS2=Object.freeze([".htm",".html"]);STATIC_NO_FALLBACK_EXTENSIONS2=Object.freeze([...STATIC_DOCUMENT_EXTENSIONS2,...STATIC_IMMUTABLE_EXTENSIONS2]);IMMUTABLE_EXTENSION_ALTERNATION2=STATIC_IMMUTABLE_EXTENSIONS2.map(extension=>extension.slice(1)).join("|");HASH_LEAF_PREFIX2="(?:^|/)[^/]+[-.]";HASH_LEAF_SUFFIX2=`\\.(?:${IMMUTABLE_EXTENSION_ALTERNATION2})$`;STATIC_CONTENT_HASH_RULES2=Object.freeze([{require:[hashLeafRule2("[0-9a-f]{10,}"),hashLeafRule2("(?:[0-9a-f]*[0-9]){2}[0-9a-f]*"),hashLeafRule2("(?:[0-9a-f]*[a-f]){2}[0-9a-f]*")],forbid:[]},{require:[hashLeafRule2("[A-Za-z0-9]{8}"),hashLeafRule2("(?:[A-Za-z0-9]*[0-9]){2}[A-Za-z0-9]*"),hashLeafRule2("(?:[A-Za-z0-9]*[A-Z]){2}[A-Za-z0-9]*"),hashLeafRule2("(?:[A-Za-z0-9]*[a-z]){2}[A-Za-z0-9]*")],forbid:[hashLeafRule2("[A-Za-z0-9]*[0-9]{4}[A-Za-z0-9]*")]},{require:[hashLeafRule2("[A-Z0-9]{8,}"),hashLeafRule2("[A-Z0-9]*[0-9][A-Z0-9]*"),hashLeafRule2("[A-Z0-9]*[A-Z][A-Z0-9]*")],forbid:[hashLeafRule2("[A-Z0-9]*[0-9]{4}[A-Z0-9]*")]}]);staticContentHashRegexGroups2=STATIC_CONTENT_HASH_RULES2.map(group2=>({require:group2.require.map(source=>new RegExp(source)),forbid:group2.forbid.map(source=>new RegExp(source))}));staticNoFallbackExtensionSet2=new Set(STATIC_NO_FALLBACK_EXTENSIONS2)}});import{createHash as createHash59}from"node:crypto";import{lstat as lstat3,readFile as readFile7,readdir as readdir5}from"node:fs/promises";import{isAbsolute as isAbsolute14,join as join18,relative as relative15,resolve as resolve67}from"node:path";function fail16(code){throw new Error(code)}function ownedByRootOrProcess(uid){const processUid=process.getuid?.();return uid===0||processUid===void 0||uid===processUid}function validateOriginRoot(input2){if(!isAbsolute14(input2)||input2.includes("\0"))fail16("STATIC_ORIGIN_ROOT_INVALID");const normalized=resolve67(input2);if(normalized==="/")fail16("STATIC_ORIGIN_ROOT_INVALID");return normalized}function validateLimits(input2){const limits={...DEFAULT_STATIC_ORIGIN_LIMITS,...input2};if(!Number.isSafeInteger(limits.maxFiles)||limits.maxFiles<1||limits.maxFiles>1e6||!Number.isSafeInteger(limits.maxBytes)||limits.maxBytes<1||limits.maxBytes>1024*1024*1024*1024||!Number.isSafeInteger(limits.maxFileBytes)||limits.maxFileBytes<1||limits.maxFileBytes>limits.maxBytes){fail16("STATIC_ORIGIN_LIMIT_INVALID")}return limits}function staticOriginAppScope(appInstanceId){if(!REFERENCE4.test(appInstanceId))fail16("STATIC_ORIGIN_APP_INSTANCE_INVALID");return createHash59("sha256").update(JSON.stringify(["app-instance",appInstanceId])).digest("hex")}function resolveStaticOriginGeneration(input2){const originRoot=validateOriginRoot(input2.originRoot);const parsed=STATIC_GENERATION_REF2.exec(input2.generationRef);if(!parsed)fail16("STATIC_ORIGIN_GENERATION_REF_INVALID");const generationSha256=parsed[5];if(!SHA25610.test(input2.integritySha256)||input2.integritySha256!==generationSha256){fail16("STATIC_ORIGIN_INTEGRITY_MISMATCH")}const scope=staticOriginAppScope(input2.appInstanceId);const scopeRoot=resolve67(originRoot,"generations",scope);const generationPath=resolve67(scopeRoot,generationSha256);const readyMarkerPath=resolve67(scopeRoot,`${generationSha256}.ready`);if(relative15(scopeRoot,generationPath)!==generationSha256||relative15(scopeRoot,readyMarkerPath)!==`${generationSha256}.ready`){fail16("STATIC_ORIGIN_GENERATION_PATH_INVALID")}return{originRoot,appScope:scope,generationSha256,generationPath,readyMarkerPath}}async function assertSafeParent(path5){const info2=await lstat3(path5).catch(()=>null);if(!info2||!info2.isDirectory()||info2.isSymbolicLink()||(info2.mode&18)!==0||!ownedByRootOrProcess(info2.uid)){fail16("STATIC_ORIGIN_ROOT_UNSAFE")}}async function assertSafeAppScope(path5){const info2=await lstat3(path5).catch(()=>null);if(!info2)fail16("STATIC_ORIGIN_GENERATION_UNAVAILABLE");if(!info2.isDirectory()||info2.isSymbolicLink()||(info2.mode&18)!==0||!ownedByRootOrProcess(info2.uid)){fail16("STATIC_ORIGIN_GENERATION_ENTRY_UNSAFE")}}function safeRelativeEntry(relativePath){const segments=relativePath.split("/");return segments.every((segment,index27)=>{if(!segment||/[\u0000-\u001f\u007f\\]/u.test(segment))return false;if(!segment.startsWith("."))return true;return index27===0&&segment===".well-known"})}async function inspectTree(generationPath,currentPath,limits,totals2){for(const entry of await readdir5(currentPath,{withFileTypes:true})){const entryPath=join18(currentPath,entry.name);const relativePath=relative15(generationPath,entryPath);if(!safeRelativeEntry(relativePath))fail16("STATIC_ORIGIN_GENERATION_ENTRY_UNSAFE");const info2=await lstat3(entryPath);if(info2.isSymbolicLink()||!ownedByRootOrProcess(info2.uid)){fail16("STATIC_ORIGIN_GENERATION_ENTRY_UNSAFE")}if(info2.isDirectory()){if((info2.mode&511)!==365)fail16("STATIC_ORIGIN_GENERATION_UNSEALED");await inspectTree(generationPath,entryPath,limits,totals2);continue}if(!info2.isFile()||info2.nlink!==1)fail16("STATIC_ORIGIN_GENERATION_ENTRY_UNSAFE");if((info2.mode&511)!==292)fail16("STATIC_ORIGIN_GENERATION_UNSEALED");totals2.fileCount+=1;totals2.bytes+=info2.size;if(info2.size>limits.maxFileBytes||totals2.fileCount>limits.maxFiles||totals2.bytes>limits.maxBytes){fail16("STATIC_ORIGIN_GENERATION_LIMIT_EXCEEDED")}}}async function sealedGenerationRootFingerprint(generation){await assertSafeParent(generation.originRoot);await assertSafeParent(join18(generation.originRoot,"generations"));await assertSafeAppScope(join18(generation.originRoot,"generations",generation.appScope));const generationInfo=await lstat3(generation.generationPath).catch(()=>null);if(!generationInfo||!generationInfo.isDirectory()||generationInfo.isSymbolicLink()||!ownedByRootOrProcess(generationInfo.uid)){fail16("STATIC_ORIGIN_GENERATION_UNAVAILABLE")}if((generationInfo.mode&511)!==365)fail16("STATIC_ORIGIN_GENERATION_UNSEALED");const readyInfo=await lstat3(generation.readyMarkerPath).catch(()=>null);if(!readyInfo||!readyInfo.isFile()||readyInfo.isSymbolicLink()||readyInfo.nlink!==1||(readyInfo.mode&511)!==292||!ownedByRootOrProcess(readyInfo.uid)){fail16("STATIC_ORIGIN_READY_MARKER_INVALID")}return[generationInfo,readyInfo].map(info2=>[info2.dev,info2.ino,info2.mode,info2.uid,info2.nlink,info2.mtimeMs,info2.ctimeMs].join(":")).join("|")}async function inspectSealedStaticOriginGenerationIdentity(input2){const generation=resolveStaticOriginGeneration(input2);return{generation,fingerprint:await sealedGenerationRootFingerprint(generation)}}async function verifySealedStaticOriginGenerationWithIdentity(input2){const generation=resolveStaticOriginGeneration(input2);const limits=validateLimits(input2.limits);const fingerprint4=await sealedGenerationRootFingerprint(generation);if(await readFile7(generation.readyMarkerPath,"utf8")!==generation.generationSha256){fail16("STATIC_ORIGIN_READY_MARKER_INVALID")}const totals2={fileCount:0,bytes:0};await inspectTree(generation.generationPath,generation.generationPath,limits,totals2);if(await sealedGenerationRootFingerprint(generation)!==fingerprint4){fail16("STATIC_ORIGIN_GENERATION_UNSEALED")}return{verified:{...generation,...totals2},fingerprint:fingerprint4}}async function verifySealedStaticOriginGeneration(input2){return(await verifySealedStaticOriginGenerationWithIdentity(input2)).verified}var SHA25610,REFERENCE4,STATIC_GENERATION_REF2,DEFAULT_STATIC_ORIGIN_LIMITS;var init_static_origin_layout=__esm({"../static-origin/src/static-origin-layout.ts"(){"use strict";SHA25610=/^[a-f0-9]{64}$/u;REFERENCE4=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;STATIC_GENERATION_REF2=/^release-object-v1\.(local|dev|qc|prod)\.([a-f0-9]{64})\.([a-f0-9]{64})\.([a-f0-9]{64})\.static_artifact\.([a-f0-9]{64})$/u;DEFAULT_STATIC_ORIGIN_LIMITS=Object.freeze({maxFiles:1e4,maxBytes:200*1024*1024,maxFileBytes:100*1024*1024})}});import{resolve as resolve68}from"node:path";function key(input2){return JSON.stringify([input2.appInstanceId,input2.generationRef,input2.integritySha256])}var StaticOriginVerifiedGenerationCache;var init_static_origin_generation_cache=__esm({"../static-origin/src/static-origin-generation-cache.ts"(){"use strict";init_static_origin_layout();StaticOriginVerifiedGenerationCache=class{entries=new Map;fullVerificationCount=0;identityCheckCount=0;originRoot;constructor(originRoot){this.originRoot=resolve68(originRoot)}get stats(){return{entries:this.entries.size,fullVerifications:this.fullVerificationCount,identityChecks:this.identityCheckCount}}async resolve(input2,derive){const request={originRoot:this.originRoot,...input2};const cacheKey=key(input2);const cached2=this.entries.get(cacheKey);if(cached2){this.identityCheckCount+=1;try{const identity2=await inspectSealedStaticOriginGenerationIdentity(request);if(identity2.fingerprint===cached2.fingerprint){return{verified:cached2.verified,derived:cached2.derived}}}catch(error62){this.entries.delete(cacheKey);throw error62}this.entries.delete(cacheKey)}this.fullVerificationCount+=1;const{verified,fingerprint:fingerprint4}=await verifySealedStaticOriginGenerationWithIdentity(request);const derived2=await derive(verified);this.entries.set(cacheKey,{fingerprint:fingerprint4,verified,derived:derived2});return{verified,derived:derived2}}retain(requests2){const live=new Set([...requests2].map(key));for(const cacheKey of this.entries.keys()){if(!live.has(cacheKey))this.entries.delete(cacheKey)}}}}});import{lstat as lstat4,readFile as readFile8}from"node:fs/promises";import{isIP as isIP2}from"node:net";import{extname as extname10,resolve as resolve69}from"node:path";function createStaticOriginCompileCache(originRoot){return new StaticOriginVerifiedGenerationCache(originRoot)}function fail17(code){throw new Error(code)}function validPort(input2){return Number.isSafeInteger(input2)&&input2>=1&&input2<=65535}function privateIpv4(input2){if(isIP2(input2)!==4)return false;const octets=input2.split(".").map(Number);return octets[0]===10||octets[0]===127||octets[0]===172&&octets[1]>=16&&octets[1]<=31||octets[0]===192&&octets[1]===168||octets[0]===100&&octets[1]>=64&&octets[1]<=127}function quote(input2){return JSON.stringify(input2)}function verbatimCaddyString(input2){if(/["\r\n]/u.test(input2))fail17("STATIC_ORIGIN_CONFIG_INVALID");return`"${input2}"`}function immutableExpression(){return STATIC_CONTENT_HASH_RULES2.map(group2=>{const required3=group2.require.map(source=>`{http.request.uri.path}.matches(r'${celRawString(source)}')`);const forbidden=group2.forbid.map(source=>`!{http.request.uri.path}.matches(r'${celRawString(source)}')`);return`(${[...required3,...forbidden].join(" && ")})`}).join(" || ")}function celRawString(input2){if(/['"\r\n]/u.test(input2))fail17("STATIC_ORIGIN_CONFIG_INVALID");return input2}async function usableRewriteRule(generationPath,rule){if(rule.statusCode!==200&&rule.statusCode!==404)return true;const targetPath=resolve69(generationPath,rule.to.replace(/^\/+/,""));if(!targetPath.startsWith(`${generationPath}/`))return false;const info2=await lstat4(targetPath).catch(()=>null);if(!info2?.isFile()||info2.isSymbolicLink())return false;return rule.statusCode!==404||DOCUMENT_EXTENSIONS.has(extname10(targetPath).toLowerCase())}async function loadRedirectRules(generationPath){const path5=resolve69(generationPath,"_redirects");const source=await readFile8(path5,"utf8").catch(()=>"");const parsed=parseStaticRedirects2(source);const accepted=[];for(const rule of parsed){if(await usableRewriteRule(generationPath,rule))accepted.push(rule)}return accepted}async function verifiedGenerationWithRules(originRoot,request,cache){const loadRules=generation=>loadRedirectRules(generation.generationPath);if(cache){if(cache.originRoot!==resolve69(originRoot))fail17("STATIC_ORIGIN_CONFIG_INVALID");const resolved=await cache.resolve(request,loadRules);return{verified:resolved.verified,rules:resolved.derived}}const verified=await verifySealedStaticOriginGeneration({originRoot,...request});return{verified,rules:await loadRules(verified)}}function redirectLines(site,wildcard){const output2=[];site.rules.filter(rule=>rule.wildcard===wildcard).forEach((rule,index27)=>{const name=`${wildcard?"wildcard":"redirect"}_${site.appId}_${index27}`;output2.push(` @${name} {`,` host ${site.hosts.map(quote).join(" ")}`,` path ${quote(rule.from)}`,` vars {vars.gencow_rw} ""`," }");if(rule.statusCode===301||rule.statusCode===302||rule.statusCode===307||rule.statusCode===308){output2.push(` redir @${name} ${quote(rule.to)} ${rule.statusCode}`);return}output2.push(` vars @${name} gencow_rw ${quote(name)}`,` vars @${name} gencow_rw_status ${quote(String(rule.statusCode))}`,` @${name}_rw vars {vars.gencow_rw} ${quote(name)}`,` rewrite @${name}_rw ${quote(rule.to)}`)});return output2}function sharedSiteLines(input2){const noFallbackPaths=["/assets","/assets/*",...STATIC_NO_FALLBACK_EXTENSIONS2.map(ext=>`*${ext}`)];const addresses=input2.sites.flatMap(site=>site.hosts).map(host=>`http://${host}:${input2.port}`);const mapRows=input2.sites.flatMap(site=>site.hosts.map(host=>` ${quote(host)} ${quote(site.generationPath)} ${quote(String(site.appId))} ${quote(String(site.routeEpoch))}`));return[`${addresses.join(", ")} {`,` bind ${input2.listenHost}`," encode gzip",` header X-Gencow-Edge ${quote("1")}`," log {",` output file ${quote(input2.meteringAccessLogFile)} {`," mode 0640"," roll_size 64MiB"," roll_keep 64"," roll_keep_for 168h"," roll_uncompressed"," }"," format json"," }"," log_append gencow_app_id {gencow_app_id}"," log_append gencow_route_epoch {gencow_route_epoch}",` @immutable expression ${verbatimCaddyString(immutableExpression())}`," route {"," map {host} {gencow_root} {gencow_app_id} {gencow_route_epoch} {",...mapRows,` default ${quote("/nonexistent")} "0" "0"`," }"," root * {gencow_root}",' vars gencow_rw ""',` vars gencow_cc ${quote("no-cache")}`,` vars @immutable gencow_cc ${quote(IMMUTABLE_CACHE)}`,' @unmapped vars {gencow_app_id} "0"'," skip_log @unmapped"," respond @unmapped 404"," @metadata path /_redirects"," respond @metadata 404"," @reserved path /api /api/* /platform /platform/* /internal /internal/* /_internal /_internal/* /ws /ws/* /_gencow/analytics.js /_gencow/analytics/event"," respond @reserved 404"," @hidden {"," path_regexp hidden (^|/)\\."," not path /.well-known /.well-known/*"," }"," respond @hidden 404",...input2.sites.flatMap(site=>redirectLines(site,false))," @exact {"," file {path}",' vars {vars.gencow_rw} ""'," }"," handle @exact {"," header Cache-Control {vars.gencow_cc}"," file_server {",` hide ${quote("_redirects")}`," }"," }"," @no_fallback {",` path ${noFallbackPaths.map(quote).join(" ")}`,' vars {vars.gencow_rw} ""'," }"," respond @no_fallback 404"," @document {"," file {path}.html {path}/index.html",' vars {vars.gencow_rw} ""'," }"," handle @document {"," try_files {path}.html {path}/index.html",` header Cache-Control ${quote("no-cache")}`," file_server {",` hide ${quote("_redirects")}`," }"," }",...input2.sites.flatMap(site=>redirectLines(site,true))," @spa {"," file /index.html",' vars {vars.gencow_rw} ""'," }"," handle @spa {",` rewrite * ${quote("/index.html")}`,` header Cache-Control ${quote("no-cache")}`," file_server {",` hide ${quote("_redirects")}`," }"," }",` vars gencow_cc ${quote("no-cache")}`,` vars @immutable gencow_cc ${quote(IMMUTABLE_CACHE)}`,' @rw_200 vars {vars.gencow_rw_status} "200"'," handle @rw_200 {"," header Cache-Control {vars.gencow_cc}"," file_server {",` hide ${quote("_redirects")}`," }"," }",' @rw_404 vars {vars.gencow_rw_status} "404"'," handle @rw_404 {"," header Cache-Control {vars.gencow_cc}"," file_server {",` hide ${quote("_redirects")}`," status 404"," }"," }"," respond 404"," }","}"]}function healthSite(listenHost,port){return[`http://:${port} {`,` bind ${listenHost}`," respond /health/live 200"," respond /health/core-ready 200"," respond 404","}"]}function validateProjection(projection){if(!Number.isSafeInteger(projection.appId)||projection.appId<1||projection.appId!==projection.entry.appId||projection.routeEpoch!==projection.entry.routeEpoch||!SHA25611.test(projection.routeHash)||projection.routeHash!==hashServingRouteManifestEntry(projection.entry)){fail17("STATIC_ORIGIN_PROJECTION_INVALID")}}async function compileStaticOriginCaddyfile(input2){if(!REFERENCE5.test(input2.nodeId)||!privateIpv4(input2.listenHost)||!input2.meteringAccessLogFile.startsWith("/")||!validPort(input2.listenPort)||!validPort(input2.adminPort)){fail17("STATIC_ORIGIN_CONFIG_INVALID")}const selected=input2.projections.filter(projection=>{validateProjection(projection);const entry=projection.entry;return entry.disposition==="upsert"&&(entry.mode==="static_only"||entry.mode==="fullstack")&&entry.static?.nodeId===input2.nodeId}).sort((left,right)=>left.appId-right.appId);const routes=[];const hosts=new Set;const sites=[];const unavailable3=[];for(const projection of selected){const entry=projection.entry;const staticRoute=entry.static;const routeHosts=entry.hostBindings.filter(binding=>binding.action==="serve").map(binding=>binding.host).sort();for(const host of routeHosts){if(hosts.has(host))fail17("STATIC_ORIGIN_HOST_COLLISION");hosts.add(host)}const generationRequest={appInstanceId:entry.appInstanceId,generationRef:staticRoute.generationRef,integritySha256:staticRoute.integritySha256};let generation;try{generation=await verifiedGenerationWithRules(input2.originRoot,generationRequest,input2.generationCache)}catch(error62){const code=error62 instanceof Error?error62.message:"";if(projection.appId===input2.candidateAppId||!APP_SCOPED_GENERATION_FAILURES.has(code))throw error62;unavailable3.push({appId:projection.appId,code});continue}const{verified,rules}=generation;if(routeHosts.length>0){sites.push({appId:projection.appId,routeEpoch:projection.routeEpoch,hosts:routeHosts,generationPath:verified.generationPath,rules})}routes.push({...verified,appId:projection.appId,routeEpoch:projection.routeEpoch,routeHash:projection.routeHash,hosts:routeHosts})}const lines=["{",` admin 127.0.0.1:${input2.adminPort}`," auto_https off","}","",...healthSite(input2.listenHost,input2.listenPort)];if(sites.length>0){lines.push("",...sharedSiteLines({listenHost:input2.listenHost,port:input2.listenPort,meteringAccessLogFile:input2.meteringAccessLogFile,sites}))}return{caddyfile:`${lines.join("\n")}
|
|
9049
|
+
`}});import{createHash as createHash51}from"node:crypto";function exactObject2(value2,fields,label){if(!value2||typeof value2!=="object"||Array.isArray(value2)){throw new TypeError(`${label} must be an object`)}const actual=Object.keys(value2).sort();const expected=[...fields].sort();if(actual.length!==expected.length||actual.some((key2,index27)=>key2!==expected[index27])){throw new TypeError(`${label} fields are invalid`)}return value2}function canonicalPath(value2){if(typeof value2!=="string"||value2.length===0||value2.length>512){throw new TypeError("codegen artifact path is invalid")}const normalized=value2.normalize("NFC").replaceAll("\\","/");if(normalized!==value2||normalized.startsWith("/")||normalized.split("/").some(part=>!part||part==="."||part==="..")){throw new TypeError("codegen artifact path is invalid")}return normalized}function hashGeneratedSchemaArtifacts(rows8){return createHash51("sha256").update(JSON.stringify(rows8)).digest("hex")}function compareCanonicalCodegenArtifactPaths(left,right){return left<right?-1:left>right?1:0}function canonicalizeCodegenArtifactProvenanceV1(value2){const record3=exactObject2(value2,["version","cliVersion","sourceRevision","generatedSchemaDigest","artifacts"],"codegen artifact provenance");if(record3.version!==1||typeof record3.cliVersion!=="string"||!VERSION3.test(record3.cliVersion)){throw new TypeError("codegen artifact provenance version is invalid")}if(typeof record3.sourceRevision!=="string"||!SHA2568.test(record3.sourceRevision)||typeof record3.generatedSchemaDigest!=="string"||!SHA2568.test(record3.generatedSchemaDigest)||!Array.isArray(record3.artifacts)||record3.artifacts.length>1e3){throw new TypeError("codegen artifact provenance digest is invalid")}const seen=new Set;const folded=new Set;const artifacts=record3.artifacts.map(candidate=>{const artifact=exactObject2(candidate,["path","size","sha256"],"codegen artifact");const path5=canonicalPath(artifact.path);const caseFolded=path5.toLocaleLowerCase("en-US");if(seen.has(path5)||folded.has(caseFolded)||!Number.isSafeInteger(artifact.size)||Number(artifact.size)<0||typeof artifact.sha256!=="string"||!SHA2568.test(artifact.sha256)){throw new TypeError("codegen artifact row is invalid")}seen.add(path5);folded.add(caseFolded);return{path:path5,size:Number(artifact.size),sha256:artifact.sha256}});const sorted=[...artifacts].sort((left,right)=>compareCanonicalCodegenArtifactPaths(left.path,right.path));if(JSON.stringify(sorted)!==JSON.stringify(artifacts)){throw new TypeError("codegen artifacts must be canonically sorted")}if(hashGeneratedSchemaArtifacts(artifacts)!==record3.generatedSchemaDigest){throw new TypeError("codegen artifact provenance digest mismatch")}return{version:1,cliVersion:record3.cliVersion,sourceRevision:record3.sourceRevision,generatedSchemaDigest:record3.generatedSchemaDigest,artifacts}}var SHA2568,VERSION3;var init_codegen_artifact_provenance=__esm({"../migration-contract/dist/codegen-artifact-provenance.js"(){"use strict";SHA2568=/^[a-f0-9]{64}$/u;VERSION3=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u}});import{createHash as createHash52}from"node:crypto";function assertExactObject(value2){if(!value2||typeof value2!=="object"||Array.isArray(value2)){throw new TypeError("deployment artifact identity must be an object")}const actual=Object.keys(value2).sort();const expected=[...IDENTITY_FIELDS,...Object.hasOwn(value2,"databaseCapability")?["databaseCapability"]:[]].sort();if(actual.length!==expected.length||actual.some((key2,index27)=>key2!==expected[index27])){throw new TypeError("deployment artifact identity fields are invalid")}}function assertVersion(value2,field){if(typeof value2!=="string"||!VERSION4.test(value2)||value2.length>128){throw new TypeError(`${field} is invalid`)}}function assertSha256(value2,field){if(typeof value2!=="string"||!SHA2569.test(value2)){throw new TypeError(`${field} must be a lowercase SHA-256`)}}function negotiateDeploymentArtifactIdentity(input2){if(input2.protocolVersion!==DEPLOYMENT_ARTIFACT_IDENTITY_PROTOCOL_VERSION){return{ok:false,code:"MIGRATION_BUNDLE_PROTOCOL_UNSUPPORTED"}}if(input2.filePlanVersion!==DEPLOYMENT_ARTIFACT_FILE_PLAN_VERSION){return{ok:false,code:"MIGRATION_BUNDLE_PLAN_VERSION_UNSUPPORTED"}}return{ok:true}}function canonicalizeDeploymentArtifactIdentityV2(value2){assertExactObject(value2);if(typeof value2.protocolVersion!=="number"||typeof value2.filePlanVersion!=="number"){throw new TypeError("deployment artifact identity versions are invalid")}const compatibility=negotiateDeploymentArtifactIdentity({protocolVersion:value2.protocolVersion,filePlanVersion:value2.filePlanVersion});if(!compatibility.ok)throw new TypeError(compatibility.code);assertVersion(value2.cliVersion,"cliVersion");assertVersion(value2.generatorVersion,"generatorVersion");assertSha256(value2.sourceRevision,"sourceRevision");assertSha256(value2.generatedSchemaDigest,"generatedSchemaDigest");if(Object.hasOwn(value2,"databaseCapability")&&value2.databaseCapability!==MIGRATION_DATABASE_CAPABILITY_EXPLICIT_DBLESS){throw new TypeError("databaseCapability is invalid")}assertSha256(value2.bundleSha256,"bundleSha256");assertSha256(value2.archiveSha256,"archiveSha256");return{protocolVersion:DEPLOYMENT_ARTIFACT_IDENTITY_PROTOCOL_VERSION,filePlanVersion:DEPLOYMENT_ARTIFACT_FILE_PLAN_VERSION,cliVersion:value2.cliVersion,generatorVersion:value2.generatorVersion,sourceRevision:value2.sourceRevision,generatedSchemaDigest:value2.generatedSchemaDigest,...Object.hasOwn(value2,"databaseCapability")?{databaseCapability:MIGRATION_DATABASE_CAPABILITY_EXPLICIT_DBLESS}:{},bundleSha256:value2.bundleSha256,archiveSha256:value2.archiveSha256}}function serializeDeploymentArtifactIdentityV2(value2){return JSON.stringify(canonicalizeDeploymentArtifactIdentityV2(value2))}function hashDeploymentArtifactIdentityV2(value2){return createHash52("sha256").update(serializeDeploymentArtifactIdentityV2(value2)).digest("hex")}var DEPLOYMENT_ARTIFACT_IDENTITY_PROTOCOL_VERSION,DEPLOYMENT_ARTIFACT_FILE_PLAN_VERSION,IDENTITY_FIELDS,SHA2569,VERSION4;var init_deployment_artifact_identity=__esm({"../migration-contract/dist/deployment-artifact-identity.js"(){"use strict";init_constants();DEPLOYMENT_ARTIFACT_IDENTITY_PROTOCOL_VERSION=2;DEPLOYMENT_ARTIFACT_FILE_PLAN_VERSION=1;IDENTITY_FIELDS=["protocolVersion","filePlanVersion","cliVersion","generatorVersion","sourceRevision","generatedSchemaDigest","bundleSha256","archiveSha256"];SHA2569=/^[a-f0-9]{64}$/u;VERSION4=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u}});var init_artifact_identity=__esm({"../migration-contract/dist/artifact-identity.js"(){"use strict";init_codegen_artifact_provenance();init_deployment_artifact_identity()}});import{createHash as createHash53}from"node:crypto";import{existsSync as existsSync25,lstatSync as lstatSync3,readFileSync as readFileSync21,readdirSync as readdirSync8}from"node:fs";import{relative as relative12,resolve as resolve61}from"node:path";function fail15(code){throw new MigrationBundleManifestError(code)}function sha2569(value2){return createHash53("sha256").update(value2).digest("hex")}function hasExactKeys(value2,keys2){if(!value2||typeof value2!=="object"||Array.isArray(value2))return false;const actual=Object.keys(value2).sort();const expected=[...keys2].sort();return actual.length===expected.length&&actual.every((key2,index27)=>key2===expected[index27])}function isSha256(value2){return typeof value2==="string"&&/^[a-f0-9]{64}$/u.test(value2)}function timestampFolderMillis(name){const millis=parseMigrationFolderMillis(name);if(millis===null)return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID");return millis}function readLegacyJournal(migrationsDir){const journalPath2=resolve61(migrationsDir,"meta","_journal.json");if(!existsSync25(journalPath2))return null;let parsed;try{parsed=JSON.parse(readFileSync21(journalPath2,"utf8"))}catch{return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const entries=parsed?.entries;if(!Array.isArray(entries))return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID");const journal=[...entries].sort((left,right)=>Number(left.idx)-Number(right.idx)).map(value2=>{const entry=value2;if(!Number.isSafeInteger(entry.idx)||!Number.isSafeInteger(entry.when)||Number(entry.when)<0||typeof entry.tag!=="string"||!entry.tag||entry.tag.includes("/")||entry.tag.includes("\\")){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return{index:Number(entry.idx),name:entry.tag,folderMillis:Number(entry.when)}});if(new Set(journal.map(entry=>entry.index)).size!==journal.length){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return journal.map(({name,folderMillis})=>({name,folderMillis}))}function currentMigrationSourceFiles(migrationsDir,entries){return entries.flatMap(name=>{const entryPath=resolve61(migrationsDir,name);const entryStats=lstatSync3(entryPath);const migrationSqlPath=resolve61(entryPath,"migration.sql");if(name==="meta"){if(!entryStats.isDirectory()||entryStats.isSymbolicLink()||existsSync25(migrationSqlPath)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return[]}if(!entryStats.isDirectory())return[];if(!existsSync25(migrationSqlPath))return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID");const sqlStats=lstatSync3(migrationSqlPath);if(!sqlStats.isFile()||sqlStats.isSymbolicLink()){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return[{name,folderMillis:timestampFolderMillis(name),path:migrationSqlPath}]})}function migrationSourceFiles(backendRoot){const migrationsDir=resolve61(backendRoot,"migrations");if(!existsSync25(migrationsDir))return[];const entries=readdirSync8(migrationsDir).sort();const journal=readLegacyJournal(migrationsDir);const legacyFiles=entries.filter(entry=>entry.endsWith(".sql"));const legacy=journal?journal.map(({name,folderMillis})=>({name,folderMillis,path:resolve61(migrationsDir,`${name}.sql`)})):legacyFiles.map(file2=>({name:file2.slice(0,-4),folderMillis:timestampFolderMillis(file2.slice(0,-4)),path:resolve61(migrationsDir,file2)}));if(legacy.some(migration=>!existsSync25(migration.path))||legacy.length!==legacyFiles.length){return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}const current=currentMigrationSourceFiles(migrationsDir,entries);const migrations=[...legacy,...current];if(new Set(migrations.map(migration=>migration.name)).size!==migrations.length){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return migrations.sort((left,right)=>left.folderMillis-right.folderMillis||left.name.localeCompare(right.name))}function bundleFileRows(backendRoot,directory=backendRoot){const rows8=[];for(const entry of readdirSync8(directory).sort()){const path5=resolve61(directory,entry);const stats=lstatSync3(path5);if(stats.isDirectory()){rows8.push(...bundleFileRows(backendRoot,path5));continue}if(!stats.isFile())return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH");const bytes2=readFileSync21(path5);rows8.push([relative12(backendRoot,path5).replaceAll("\\","/"),bytes2.length,sha2569(bytes2)])}return rows8}function archivePayloadRows(workspaceRoot,directory=workspaceRoot){const rows8=[];for(const entry of readdirSync8(directory).sort()){const path5=resolve61(directory,entry);const relativePath=relative12(workspaceRoot,path5).replaceAll("\\","/");if(relativePath===MIGRATION_BUNDLE_MANIFEST_PATH)continue;const stats=lstatSync3(path5);if(stats.isDirectory()){rows8.push(...archivePayloadRows(workspaceRoot,path5));continue}if(!stats.isFile()||stats.isSymbolicLink()){return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}const bytes2=readFileSync21(path5);rows8.push([relativePath.normalize("NFC"),bytes2.length,sha2569(bytes2)])}return rows8}function codegenProvenancePaths(directory){const paths=[];for(const entry of readdirSync8(directory).sort()){const path5=resolve61(directory,entry);const stats=lstatSync3(path5);if(stats.isDirectory())paths.push(...codegenProvenancePaths(path5));else if(stats.isFile()&&entry===CODEGEN_PROVENANCE_FILENAME)paths.push(path5)}return paths}function generatedArtifactRows(root2,directory=root2){const rows8=[];for(const entry of readdirSync8(directory).sort()){if(entry===CODEGEN_PROVENANCE_FILENAME)continue;const path5=resolve61(directory,entry);const stats=lstatSync3(path5);if(stats.isDirectory()){rows8.push(...generatedArtifactRows(root2,path5));continue}if(!stats.isFile()||stats.isSymbolicLink()){return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH")}const bytes2=readFileSync21(path5);rows8.push({path:relative12(root2,path5).replaceAll("\\","/").normalize("NFC"),size:bytes2.length,sha256:sha2569(bytes2)})}return rows8.sort((left,right)=>compareCanonicalCodegenArtifactPaths(left.path,right.path))}function deriveGeneratedSchemaDigest(backendRoot,expectedProvenance,fallbackDigest){const markers=codegenProvenancePaths(backendRoot);if(markers.length>1)return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH");if(markers.length===0)return fallbackDigest;let provenance;try{provenance=canonicalizeCodegenArtifactProvenanceV1(JSON.parse(readFileSync21(markers[0],"utf8")))}catch{return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH")}const rows8=generatedArtifactRows(resolve61(markers[0],".."));if(JSON.stringify(rows8)!==JSON.stringify(provenance.artifacts)||hashGeneratedSchemaArtifacts(rows8)!==provenance.generatedSchemaDigest||provenance.cliVersion!==expectedProvenance.cliVersion||expectedProvenance.sourceRevision!==void 0&&provenance.sourceRevision!==expectedProvenance.sourceRevision){return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH")}return provenance.generatedSchemaDigest}function tenantCapabilitySources(backendRoot,directory=backendRoot){const sources=[];for(const entry of readdirSync8(directory).sort()){const path5=resolve61(directory,entry);const stats=lstatSync3(path5);if(stats.isDirectory()){sources.push(...tenantCapabilitySources(backendRoot,path5));continue}const manifestPath=relative12(backendRoot,path5).replaceAll("\\","/");if(stats.isFile()&&isAuthSchemaSourcePath(manifestPath)){sources.push({path:manifestPath,source:readFileSync21(path5,"utf8")})}}return sources}function hasRateLimitCreationMigration(migrations){return migrations.some(({path:path5})=>/\bCREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:["']?public["']?\.)?["']?rate_limit["']?\b/iu.test(readFileSync21(path5,"utf8")))}function isForbiddenSecretFileName(name){if(name===".env")return true;if(!name.startsWith(".env."))return false;return name!==".env.example"&&name!==".env.sample"&&name!==".env.template"}function assertNoForbiddenSecretFiles(directory){for(const entry of readdirSync8(directory)){const path5=resolve61(directory,entry);const stats=lstatSync3(path5);if(stats.isDirectory()){assertNoForbiddenSecretFiles(path5)}else if(isForbiddenSecretFileName(entry)){return fail15("MIGRATION_BUNDLE_FORBIDDEN_SECRET_FILE")}}}function assertWorkspaceShape(workspaceRoot,allowDeploymentRootFiles){const rootEntries=readdirSync8(workspaceRoot).sort();if(!allowDeploymentRootFiles&&rootEntries.some(entry=>entry!=="gencow"&&entry!==".gencow")){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const backendRoot=resolve61(workspaceRoot,"gencow");const metadataDir=resolve61(workspaceRoot,".gencow");if(!existsSync25(backendRoot)||!lstatSync3(backendRoot).isDirectory()){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}assertNoForbiddenSecretFiles(backendRoot);if(!allowDeploymentRootFiles&&existsSync25(metadataDir)&&(!lstatSync3(metadataDir).isDirectory()||readdirSync8(metadataDir).some(entry=>entry!=="migration-bundle-manifest.json"))){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}}function isAuditMetadata(value2){return typeof value2==="string"&&value2.length>0&&value2.length<=128&&!/[\u0000-\u001f\u007f]/u.test(value2)}function parseManifest3(value2){const baseKeys=["protocolVersion","generator","generatorVersion","cliVersion","schemaSnapshotHash","migrations","bundleSha256"];const record3=value2&&typeof value2==="object"&&!Array.isArray(value2)?value2:null;const hasSourceMode=record3?Object.hasOwn(record3,"sourceMode"):false;const hasSchemaSources=record3?Object.hasOwn(record3,"schemaSources"):false;const hasDatabaseCapability=record3?Object.hasOwn(record3,"databaseCapability"):false;const hasRequiredTenantCapabilities=record3?Object.hasOwn(record3,"requiredTenantCapabilities"):false;const hasArtifactIdentity=record3?Object.hasOwn(record3,"artifactIdentity"):false;const hasArtifactIdentitySha256=record3?Object.hasOwn(record3,"artifactIdentitySha256"):false;const expectedKeys=[...baseKeys,...hasSourceMode?["sourceMode"]:[],...hasSchemaSources?["schemaSources"]:[],...hasDatabaseCapability?["databaseCapability"]:[],...hasRequiredTenantCapabilities?["requiredTenantCapabilities"]:[],...hasArtifactIdentity?["artifactIdentity"]:[],...hasArtifactIdentitySha256?["artifactIdentitySha256"]:[]];if(!hasExactKeys(value2,expectedKeys)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(value2.protocolVersion!==MIGRATION_BUNDLE_PROTOCOL_VERSION){return fail15("MIGRATION_BUNDLE_PROTOCOL_UNSUPPORTED")}const sourceMode=value2.sourceMode??"GENERATED";if(sourceMode!=="GENERATED"&&sourceMode!=="EXISTING_BUNDLE"){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(!isAuditMetadata(value2.generator)||!isAuditMetadata(value2.generatorVersion)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(typeof value2.cliVersion!=="string"||!/^\d+\.\d+\.\d+$/u.test(value2.cliVersion)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(!isSha256(value2.schemaSnapshotHash)||!isSha256(value2.bundleSha256)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(hasArtifactIdentity!==hasArtifactIdentitySha256){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}let artifactIdentity;if(hasArtifactIdentity){try{artifactIdentity=canonicalizeDeploymentArtifactIdentityV2(value2.artifactIdentity)}catch(error62){const message=error62 instanceof Error?error62.message:"";if(message==="MIGRATION_BUNDLE_PROTOCOL_UNSUPPORTED")return fail15(message);if(message==="MIGRATION_BUNDLE_PLAN_VERSION_UNSUPPORTED")return fail15(message);return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(!isSha256(value2.artifactIdentitySha256)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}}let requiredTenantCapabilities;if(hasRequiredTenantCapabilities){if(!Array.isArray(value2.requiredTenantCapabilities)||value2.requiredTenantCapabilities.length>32||value2.requiredTenantCapabilities.some(capability2=>typeof capability2!=="string"||!/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u.test(capability2))||new Set(value2.requiredTenantCapabilities).size!==value2.requiredTenantCapabilities.length){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(value2.requiredTenantCapabilities.some(capability2=>!MIGRATION_TENANT_CAPABILITIES_V1.includes(capability2))){return fail15("MIGRATION_BUNDLE_CAPABILITY_UNSUPPORTED")}requiredTenantCapabilities=[...value2.requiredTenantCapabilities]}let schemaSources;if(hasSchemaSources){if(!Array.isArray(value2.schemaSources)||value2.schemaSources.length>1e3){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const seen=new Set;const caseFolded=new Set;schemaSources=value2.schemaSources.map(source=>{if(!hasExactKeys(source,["path","sha256"])){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(typeof source.path!=="string"||source.path.length===0||source.path.length>512||source.path.startsWith("/")||source.path===".."||source.path.startsWith("../")||source.path.includes("\\")||source.path.split("/").some(part=>part===""||part==="."||part==="..")||!isSha256(source.sha256)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const folded=source.path.toLocaleLowerCase("en-US");if(seen.has(source.path)||caseFolded.has(folded)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}seen.add(source.path);caseFolded.add(folded);return{path:source.path,sha256:source.sha256}})}let databaseCapability;if(hasDatabaseCapability){if(value2.databaseCapability!==MIGRATION_DATABASE_CAPABILITY_EXPLICIT_DBLESS){return fail15("MIGRATION_BUNDLE_CAPABILITY_UNSUPPORTED")}databaseCapability=value2.databaseCapability}if(!Array.isArray(value2.migrations)||value2.migrations.length>1e4){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const migrations=value2.migrations.map(entry=>{if(!hasExactKeys(entry,["name","folderMillis","sqlSha256","requiredCapabilities"])){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(typeof entry.name!=="string"||entry.name.length===0||entry.name.length>255||entry.name.includes("/")||entry.name.includes("\\")||!Number.isSafeInteger(entry.folderMillis)||Number(entry.folderMillis)<0||!isSha256(entry.sqlSha256)||!Array.isArray(entry.requiredCapabilities)||entry.requiredCapabilities.some(capability2=>typeof capability2!=="string")){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}if(entry.requiredCapabilities.length!==1||entry.requiredCapabilities[0]!==MIGRATION_BUNDLE_CAPABILITY_V1){return fail15("MIGRATION_BUNDLE_CAPABILITY_UNSUPPORTED")}return entry});if(databaseCapability===MIGRATION_DATABASE_CAPABILITY_EXPLICIT_DBLESS&&(!hasSchemaSources||schemaSources?.length!==0||migrations.length!==0||requiredTenantCapabilities?.length)){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}return{...value2,...schemaSources?{schemaSources}:{},...databaseCapability?{databaseCapability}:{},...requiredTenantCapabilities?{requiredTenantCapabilities}:{},...artifactIdentity?{artifactIdentity,artifactIdentitySha256:value2.artifactIdentitySha256}:{},migrations}}function unsignedManifest(manifest,backendRoot){const schemaPath=resolve61(backendRoot,"schema.ts");if(!manifest.schemaSources&&!existsSync25(schemaPath)){return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}const schemaSources=manifest.schemaSources?.map(source=>{const sourcePath=resolve61(backendRoot,source.path);const stats=existsSync25(sourcePath)?lstatSync3(sourcePath):null;if(!stats?.isFile()||stats.isSymbolicLink()){return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}return{path:source.path,sha256:sha2569(readFileSync21(sourcePath))}});const migrations=migrationSourceFiles(backendRoot).map(migration=>({name:migration.name,folderMillis:migration.folderMillis,sqlSha256:sha2569(readFileSync21(migration.path)),requiredCapabilities:[MIGRATION_BUNDLE_CAPABILITY_V1]}));const derivedTenantCapabilities=deriveTenantCapabilities(tenantCapabilitySources(backendRoot));if(derivedTenantCapabilities.includes(MIGRATION_TENANT_CAPABILITY_AUTH_RATE_LIMIT_V1)&&!hasRateLimitCreationMigration(migrationSourceFiles(backendRoot))){return fail15("MIGRATION_BUNDLE_SCHEMA_CHANGE_WITHOUT_FORWARD_MIGRATION")}return{protocolVersion:MIGRATION_BUNDLE_PROTOCOL_VERSION,generator:manifest.generator,generatorVersion:manifest.generatorVersion,...manifest.sourceMode?{sourceMode:manifest.sourceMode}:{},cliVersion:manifest.cliVersion,...schemaSources?{schemaSources}:{},...manifest.databaseCapability?{databaseCapability:manifest.databaseCapability}:{},...manifest.requiredTenantCapabilities?{requiredTenantCapabilities:derivedTenantCapabilities}:{},schemaSnapshotHash:schemaSources?sha2569(JSON.stringify(schemaSources)):sha2569(readFileSync21(schemaPath)),migrations}}function verifyMigrationBundleManifest(workspaceRoot,requestCliVersion,allowDeploymentRootFiles=false,expectedArtifactIdentitySha256){assertWorkspaceShape(workspaceRoot,allowDeploymentRootFiles);const manifestPath=resolve61(workspaceRoot,MIGRATION_BUNDLE_MANIFEST_PATH);if(!existsSync25(manifestPath))return fail15("MIGRATION_BUNDLE_MANIFEST_REQUIRED");if(!lstatSync3(manifestPath).isFile())return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID");const raw2=readFileSync21(manifestPath);if(raw2.length===0||raw2.length>MAX_MANIFEST_BYTES){return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}let parsed;try{parsed=JSON.parse(raw2.toString("utf8"))}catch{return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}const manifest=parseManifest3(parsed);if(requestCliVersion!==void 0&&manifest.cliVersion!==requestCliVersion){return fail15("MIGRATION_BUNDLE_CLI_VERSION_MISMATCH")}const unsigned=unsignedManifest(manifest,resolve61(workspaceRoot,"gencow"));const derivedTenantCapabilities=deriveTenantCapabilities(tenantCapabilitySources(resolve61(workspaceRoot,"gencow")));if(manifest.schemaSnapshotHash!==unsigned.schemaSnapshotHash||JSON.stringify(manifest.schemaSources)!==JSON.stringify(unsigned.schemaSources)||manifest.databaseCapability!==unsigned.databaseCapability||JSON.stringify(manifest.migrations)!==JSON.stringify(unsigned.migrations)||manifest.requiredTenantCapabilities!==void 0&&JSON.stringify(manifest.requiredTenantCapabilities)!==JSON.stringify(derivedTenantCapabilities)||manifest.bundleSha256!==sha2569(JSON.stringify(bundleFileRows(resolve61(workspaceRoot,"gencow"))))){return fail15("MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}let derivedArtifactIdentitySha256=null;if(manifest.artifactIdentity){const compatibility=negotiateDeploymentArtifactIdentity(manifest.artifactIdentity);if(!compatibility.ok)return fail15(compatibility.code);const derivedGeneratedSchemaDigest=deriveGeneratedSchemaDigest(resolve61(workspaceRoot,"gencow"),manifest.artifactIdentity,unsigned.schemaSnapshotHash);const derivedIdentity={...manifest.artifactIdentity,cliVersion:manifest.cliVersion,generatorVersion:manifest.generatorVersion,generatedSchemaDigest:derivedGeneratedSchemaDigest,bundleSha256:manifest.bundleSha256,archiveSha256:sha2569(JSON.stringify(archivePayloadRows(workspaceRoot)))};const derivedDigest=hashDeploymentArtifactIdentityV2(derivedIdentity);derivedArtifactIdentitySha256=derivedDigest;if(hashDeploymentArtifactIdentityV2(manifest.artifactIdentity)!==manifest.artifactIdentitySha256||derivedDigest!==manifest.artifactIdentitySha256||expectedArtifactIdentitySha256!==void 0&&expectedArtifactIdentitySha256!==manifest.artifactIdentitySha256){return fail15(expectedArtifactIdentitySha256?"PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH":"MIGRATION_BUNDLE_INTEGRITY_MISMATCH")}}else{if(codegenProvenancePaths(resolve61(workspaceRoot,"gencow")).length>0){return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH")}if(expectedArtifactIdentitySha256!==void 0){return fail15("PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH")}}const verifiedManifest=manifest.requiredTenantCapabilities===void 0&&derivedTenantCapabilities.length>0?{...manifest,requiredTenantCapabilities:derivedTenantCapabilities}:manifest;return{manifest:verifiedManifest,derivedArtifactIdentitySha256}}function assertDeploymentMigrationBundleManifest(workspaceRoot,requestCliVersion,expectedArtifactIdentitySha256){try{return verifyMigrationBundleManifest(workspaceRoot,requestCliVersion,true,expectedArtifactIdentitySha256).manifest}catch(error62){if(error62 instanceof MigrationBundleManifestError)throw error62;return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}}function verifyDeploymentMigrationBundleManifest(workspaceRoot,requestCliVersion,expectedArtifactIdentitySha256){try{return verifyMigrationBundleManifest(workspaceRoot,requestCliVersion,true,expectedArtifactIdentitySha256)}catch(error62){if(error62 instanceof MigrationBundleManifestError)throw error62;return fail15("MIGRATION_BUNDLE_MANIFEST_INVALID")}}var MAX_MANIFEST_BYTES,MigrationBundleManifestError,CODEGEN_PROVENANCE_FILENAME;var init_migration_bundle_manifest=__esm({"../platform/src/migration-bundle-manifest.ts"(){"use strict";init_artifact_identity();init_dist();MAX_MANIFEST_BYTES=1024*1024;MigrationBundleManifestError=class extends Error{code;constructor(code){super(code);this.name="MigrationBundleManifestError";this.code=code}};CODEGEN_PROVENANCE_FILENAME=".gencow-codegen-provenance.json"}});function isKnownMigrationError(error62){return error62 instanceof LegacyMigrationSqlAuditError||error62 instanceof MigrationThinPolicyError||error62 instanceof MigrationExecutionPlanError||error62 instanceof MigrationTransactionRolledBackError||error62 instanceof MigrationJournalReadError||error62 instanceof MigrationSchemaLockError||error62 instanceof MigrationCheckCapabilityError||error62 instanceof MigrationFormatUnsupportedError||error62 instanceof MigrationGenerationFailedError||error62 instanceof MigrationHistoryRequiredError||error62 instanceof MigrationHistoryRecoveryRequiredError||error62 instanceof MigrationPrimaryFormatError||error62 instanceof MigrationProofInfrastructureError||error62 instanceof DrizzleMigrationStorePreflightError||error62 instanceof MigrationPushPreflightError||error62 instanceof TenantSchemaPostconditionError||error62 instanceof MigrationBundleManifestError||error62 instanceof Error&&error62.code==="PRE_DEPLOY_SAFETY_BACKUP_REQUIRED"}function safeText(value2,maxLength=200){if(typeof value2!=="string"||value2.length===0||value2.length>maxLength)return void 0;return/[\u0000-\u001f\u007f]/u.test(value2)?void 0:value2}function safeReasonCode(value2,fallback){return typeof value2==="string"&&/^[a-z0-9_:-]{1,80}$/u.test(value2)?value2:fallback}function safeMigration(error62){const migration=error62.migration;if(migration&&safeText(migration.name,240)&&/^[a-f0-9]{64}$/u.test(migration.sqlSha256)&&(migration.statementIndex===void 0||Number.isSafeInteger(migration.statementIndex)&&migration.statementIndex>0)&&(migration.lineStart===void 0||Number.isSafeInteger(migration.lineStart)&&migration.lineStart>0)&&(migration.lineEnd===void 0||Number.isSafeInteger(migration.lineEnd)&&migration.lineEnd>0&&(migration.lineStart===void 0||migration.lineEnd>=migration.lineStart))){return{...migration}}const name=safeText(error62.migrationName,240);const hash9=safeText(error62.migrationHash,64);return name&&hash9&&/^[a-f0-9]{64}$/u.test(hash9)?{name,sqlSha256:hash9}:void 0}function platformDiagnostic(code,reasonCode,correlationId,migration,operation){return retryableInfraDiagnostic({code,phase:code.startsWith("MIGRATION_SQL_")?"AUDIT":"PREFLIGHT",databaseState:"UNCHANGED",retryPolicy:"AFTER_DELAY",retryAfterSeconds:30,retryCondition:"Wait for the transient platform condition to clear, then retry the same immutable bundle.",correlationId,migration,operation,reason:{code:reasonCode,summary:"The migration runner is temporarily unavailable for this plan.",detail:"No tenant migration statement ran. Keep the source unchanged and retry after the indicated delay."},suggestedFixes:[],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}function migrationBundleManifestDiagnostic(error62,correlationId){const contract=MIGRATION_BUNDLE_ERROR_CONTRACT_V1[error62.code];const schemaChangeWithoutForwardMigration=error62.code==="MIGRATION_BUNDLE_SCHEMA_CHANGE_WITHOUT_FORWARD_MIGRATION";const common={code:error62.code,phase:"PREFLIGHT",databaseState:"UNCHANGED",correlationId,retryCondition:contract.failureClass==="USER_FIXABLE"?"Correct the project migration source, create a fresh immutable bundle, then retry the deployment.":contract.failureClass==="RETRYABLE_INFRA"?"Wait for the platform rollout to converge, then retry the same immutable bundle.":contract.nextAction==="UPDATE_CLI"?"Install a supported Gencow CLI and create a fresh migration bundle.":"Keep the source and operation identity unchanged while the platform state is inspected.",reason:{code:error62.code.toLowerCase(),summary:schemaChangeWithoutForwardMigration?"The migration bundle declares a schema change without its forward migration.":"The migration bundle failed manifest verification.",detail:schemaChangeWithoutForwardMigration?"The bundle was rejected before tenant database access or mutation. Add the missing forward migration in the project source and create a fresh bundle.":"The request was rejected after archive extraction and manifest verification, before tenant database access or mutation."},suggestedFixes:contract.failureClass==="USER_FIXABLE"?[{id:schemaChangeWithoutForwardMigration?"generate-forward-migration":"regenerate-bundle-from-trusted-source",title:schemaChangeWithoutForwardMigration?"Create the forward migration":"Regenerate the migration bundle",detail:schemaChangeWithoutForwardMigration?"Run gencow db:generate, review the forward migration, then create a fresh deployment bundle.":"Verify the project schema and migration files, then create a fresh bundle from trusted source files.",target:contract.fixTarget,confidence:"HIGH"}]:[],docsUrl:MIGRATION_CAPABILITY_MANIFEST_V1.docsUrl,supportedCliRange:MIGRATION_CAPABILITY_MANIFEST_V1.supportedCliRange,forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}};if(contract.failureClass==="USER_FIXABLE")return userFixableDiagnostic(common);if(contract.failureClass==="RETRYABLE_INFRA"){return retryableInfraDiagnostic({...common,retryPolicy:"AFTER_DELAY",retryAfterSeconds:15})}return platformActionDiagnostic({...common,nextAction:contract.nextAction==="UPDATE_CLI"?"UPDATE_CLI":"INSPECT_STATE"})}function recoveryDiagnostic(code,correlationId,context={}){const hasReceipt=typeof context.receiptId==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(context.receiptId);return recoveryRequiredDiagnostic({code:"MIGRATION_STATE_PROOF_UNAVAILABLE",phase:code==="MIGRATION_POSTCONDITION_FAILED"||code==="DB_MIGRATION_LOCK_RELEASE_FAILED"?"VERIFY":context.phase??"EXECUTE",retryCondition:"Retry only after Gencow verifies the migration journal and PostgreSQL catalog state.",correlationId,...hasReceipt?{receiptId:context.receiptId}:{},reason:{code:code.toLowerCase(),summary:"The final database state could not be proven automatically.",detail:"A blind retry could duplicate or conflict with an already committed change, so execution is blocked pending recovery verification."},suggestedFixes:[],nextAction:hasReceipt?"VIEW_STATUS":"INSPECT_STATE",forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}function buildActionableMigrationDiagnostic(error62,correlationId,context={}){const coded=isKnownMigrationError(error62)?error62:{};const planId=typeof coded.planId==="string"&&/^mig_[a-f0-9]{24}$/u.test(coded.planId)?coded.planId:void 0;const finalize2=diagnostic=>certifyActionableMigrationDiagnostic({...diagnostic,...planId?{planId}:{},docsUrl:MIGRATION_CAPABILITY_MANIFEST_V1.docsUrl,supportedCliRange:MIGRATION_CAPABILITY_MANIFEST_V1.supportedCliRange});const code=typeof coded.code==="string"&&KNOWN_CODES.has(coded.code)?coded.code:void 0;if(!code){if(context.executionStarted){return finalize2(recoveryDiagnostic("MIGRATION_EXECUTION_OUTCOME_UNKNOWN",correlationId,context))}return finalize2(platformDiagnostic("MIGRATION_PREFLIGHT_SERVICE_UNAVAILABLE","migration_platform_preflight_failed",correlationId))}if(error62 instanceof MigrationBundleManifestError){return finalize2(migrationBundleManifestDiagnostic(error62,correlationId))}const reasonCode=safeReasonCode(coded.reasonCode,code.toLowerCase());const migration=safeMigration(coded);const objectKind=safeText(coded.objectKind,80);const objectName=safeText(coded.objectName,240);const operation=objectKind?{kind:objectKind,objectKind,...objectName?{objectName}:{}}:void 0;if(error62 instanceof LegacyMigrationSqlAuditError){return finalize2(platformDiagnostic(code,"legacy_policy_slot",correlationId,migration,operation))}if(error62 instanceof MigrationTransactionRolledBackError){return finalize2(buildRolledBackDiagnostic({error:error62,correlationId,migration,forbiddenActions:FORBIDDEN_ACTIONS}))}if(error62 instanceof MigrationPushPreflightError){return finalize2(platformDiagnostic(code,reasonCode,correlationId,migration,{kind:"migration_preflight",objectKind:"SERVICE",objectName:reasonCode}))}if(error62 instanceof MigrationCheckCapabilityError){if(error62.reasonCode!=="migration_check_database_unavailable"){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Correct the project migration history, then run the read-only check again.",correlationId,reason:{code:reasonCode,summary:"The project cannot be checked as a Drizzle v1 migration bundle.",detail:"Restore schema.ts and generate one consistent directory-style migration history. Do not mix legacy and v1 migration formats."},suggestedFixes:[{id:"repair-check-project-history",title:"Use one Drizzle v1 migration history",detail:"Restore schema.ts and keep only the supported directory-style migration format before creating a fresh bundle.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}return finalize2(platformDiagnostic(code,reasonCode,correlationId,migration,{kind:"migration_check_capability"}))}if(error62 instanceof MigrationPrimaryFormatError){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Generate a Drizzle v1 migration history, then create a fresh immutable bundle.",correlationId,reason:{code:reasonCode,summary:"A legacy server slot rejected the migration history format.",detail:"This compatibility diagnostic came from the retired format-only admission path; it does not prove that an empty schema needs a migration."},suggestedFixes:[{id:"generate-drizzle-v1-history",title:"Generate a Drizzle v1 migration history",detail:"Keep applied history immutable and generate a supported directory-style migration bundle.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(error62 instanceof MigrationHistoryRequiredError){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Generate an initial Drizzle v1 migration, then create a fresh immutable bundle.",correlationId,reason:{code:reasonCode,summary:"Migration history is required before this backend can be deployed.",detail:"The canonical schema contains database objects, but the bundle has no Drizzle v1 migration history."},suggestedFixes:[{id:"generate-initial-drizzle-history",title:"Generate the initial migration",detail:"Run gencow codegen and gencow db:generate, then deploy the fresh bundle.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(error62 instanceof MigrationHistoryRecoveryRequiredError){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",correlationId,retryCondition:"Restore the exact applied migration files from trusted version control, then create a fresh bundle.",reason:{code:reasonCode,summary:"Applied migration history is missing from this deployment bundle.",detail:"No migration ran for this request. Restore the original applied files and put new changes in a forward migration."},suggestedFixes:[{id:"restore-applied-lineage",title:"Restore the applied migration lineage",detail:"Recover the exact applied files from trusted version control without editing the database journal.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(error62 instanceof MigrationProofInfrastructureError){return finalize2(buildProofInfrastructureDiagnostic({error:error62,code,reasonCode,correlationId,forbiddenActions:[...FORBIDDEN_ACTIONS]}))}if(error62 instanceof MigrationGenerationFailedError){return finalize2(userFixableDiagnostic({code,phase:"GENERATE",databaseState:"UNCHANGED",retryCondition:"Fix the schema import or generator configuration, then generate a fresh bundle.",correlationId,reason:{code:reasonCode,summary:"The database schema could not be inspected safely.",detail:"Canonical schema generation failed, so the server did not assume that an empty migration folder was DBless."},suggestedFixes:[{id:"fix-schema-generation",title:"Fix schema generation",detail:"Run gencow codegen and gencow db:generate locally and fix the reported import or config error.",target:"SCHEMA_SOURCE",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(error62 instanceof TenantSchemaPostconditionError){const shared={code,phase:"VERIFY",correlationId,operation:{kind:"tenant_schema_postcondition",objectKind:"rate_limit"},reason:{code:reasonCode,summary:"The tenant Auth schema is not ready for this runtime.",detail:"The declared durable Auth rate-limit capability is missing a required table, column, key, or runtime privilege. The candidate release remains inactive."},forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}};if(error62.databaseState==="RECOVERY_REQUIRED"){return finalize2(recoveryRequiredDiagnostic({...shared,retryCondition:"Inspect the canonical journal and schema state before changing source or starting another deployment.",suggestedFixes:[],nextAction:"INSPECT_STATE"}))}return finalize2(userFixableDiagnostic({...shared,databaseState:error62.databaseState,retryCondition:"Add or repair the forward migration for the declared tenant capability, then retry.",suggestedFixes:[{id:"repair-auth-rate-limit-migration",title:"Create a forward migration",detail:"Run gencow db:generate, review the rate_limit migration, then run gencow db:check and db:push for the same app and environment.",target:"PENDING_MIGRATION",confidence:"HIGH"}]}))}if(error62 instanceof MigrationFormatUnsupportedError){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Convert the project to a pure directory-style Drizzle v1 history.",correlationId,reason:{code:reasonCode,summary:"The migration history format is not supported.",detail:`The bundle contains ${error62.format} migration history. Managed deploy requires a pure Drizzle v1 history.`},suggestedFixes:[{id:"convert-drizzle-v1-history",title:"Convert to Drizzle v1 history",detail:"Follow the supported migration conversion procedure without editing applied journal rows.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(error62 instanceof MigrationThinPolicyError){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Remove the platform-boundary operation from the unapplied migration and run check again.",correlationId,migration,operation:{kind:"platform_policy_boundary",...objectName?{objectName}:{}},reason:{code:reasonCode,summary:"The pending migration crosses a Gencow-managed platform boundary.",detail:"Tenant migrations may change ordinary tenant objects, but not migration journals, protected system objects, roles, managed schemas, or platform-only capabilities."},suggestedFixes:[{id:"remove-platform-boundary-operation",title:"Keep the migration inside tenant scope",detail:"Edit only the unapplied migration so it changes ordinary tenant database objects.",target:"PENDING_MIGRATION",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"STRUCTURE_ONLY"}}))}if(code==="SCHEMA_PUSH_IN_PROGRESS"){return finalize2(retryableInfraDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryPolicy:"AFTER_DELAY",retryCondition:"Retry after the active schema push releases the database-scoped lock.",retryAfterSeconds:15,correlationId,reason:{code:"schema_push_in_progress",summary:"Another schema push currently owns the database migration lock.",detail:"No migration statement ran for this request. Wait for the active operation to finish and retry the same bundle."},suggestedFixes:[],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(code==="MIGRATION_LOCAL_PLAN_CHANGED"||code==="MIGRATION_PLAN_CHANGED"){return finalize2(retryableInfraDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryPolicy:"IMMEDIATE",retryCondition:"Regenerate a stable bundle and start a fresh plan from the beginning.",correlationId,migration,reason:{code:code.toLowerCase(),summary:"The local bundle or database journal changed while the plan was being checked.",detail:"The stale plan was discarded before execution; retry from a fresh immutable bundle."},suggestedFixes:[],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(MIGRATION_RUNTIME_TERMINAL_ERROR_CODES_V1.includes(code)){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Restore the exact applied migration artifact from trusted version control, then create a fresh plan.",correlationId,migration,reason:{code:code.toLowerCase(),summary:"The deployment bundle does not match immutable applied migration history.",detail:"Restore the original applied file byte-for-byte. Put any new schema change in a new forward migration."},suggestedFixes:[{id:"restore-applied-migration",title:"Restore the original migration artifact",detail:"Recover the exact file from trusted version control; do not rewrite history or edit the database journal.",target:"NONE",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(code==="MIGRATION_LOCAL_HISTORY_AMBIGUOUS"){return finalize2(userFixableDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryCondition:"Regenerate a bundle with unique stable migration names without changing applied history.",correlationId,migration,reason:{code:"migration_local_history_ambiguous",summary:"The local migration bundle has missing or duplicate identity metadata.",detail:"Every migration must have one stable unique name before the server can derive a deterministic pending plan."},suggestedFixes:[{id:"regenerate-local-metadata",title:"Regenerate unique local migration metadata",detail:"Fix only unapplied duplicate or missing local identities and leave applied migration files unchanged.",target:"PROJECT_CONFIG",confidence:"HIGH"}],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(code==="MIGRATION_APPLIED_HISTORY_AMBIGUOUS"){return finalize2(platformActionDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",correlationId,retryCondition:"Retry after Gencow verifies the existing journal identity metadata.",nextAction:"INSPECT_STATE",reason:{code:code.toLowerCase(),summary:"Existing migration journal identity needs platform inspection.",detail:"No migration statement ran for this request. The existing journal cannot yet be matched to the immutable local plan."},suggestedFixes:[],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}if(code==="MIGRATION_POSTCONDITION_FAILED"){return finalize2(recoveryDiagnostic(code,correlationId,context))}if(error62 instanceof DrizzleMigrationStorePreflightError){return finalize2(platformActionDiagnostic({code,phase:"PREFLIGHT",databaseState:"UNCHANGED",correlationId,retryCondition:"Retry after the platform migration-store status reports ready; no project edit is required.",nextAction:"INSPECT_STATE",reason:{code:reasonCode,summary:"The platform migration store needs preparation before migration can continue.",detail:"No tenant migration statement ran. Gencow must reconcile the classified store state before the same immutable bundle is retried."},suggestedFixes:[],forbiddenActions:[...FORBIDDEN_ACTIONS],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}}))}return finalize2(platformDiagnostic(code,reasonCode,correlationId,migration,operation))}function migrationDiagnosticHttpStatus(diagnostic){if(diagnostic.code==="MIGRATION_APPLIED_HASH_DRIFT"||diagnostic.code==="MIGRATION_APPLIED_FILE_MISSING"||diagnostic.code==="MIGRATION_APPLIED_HISTORY_AMBIGUOUS"||diagnostic.code==="MIGRATION_LOCAL_HISTORY_AMBIGUOUS"){return 409}if(diagnostic.failureClass==="USER_FIXABLE")return 400;if(diagnostic.failureClass==="RETRYABLE_INFRA"){return diagnostic.code==="SCHEMA_PUSH_IN_PROGRESS"||diagnostic.code.endsWith("PLAN_CHANGED")?409:503}if(diagnostic.failureClass==="PLATFORM_ACTION_REQUIRED")return 503;return 500}var FORBIDDEN_ACTIONS,KNOWN_CODES;var init_migration_actionable_diagnostic=__esm({"../platform/src/migration-actionable-diagnostic.ts"(){"use strict";init_dist();init_drizzle_migration_store();init_migration_execution_plan();init_migration_execution_outcome();init_migration_rollback_diagnostic();init_provisioner_migration_journal();init_migration_legacy_audit_error();init_migration_capability();init_migration_thin_policy();init_migration_push_preflight_error();init_migration_proof_infrastructure_diagnostic();init_tenant_schema_postconditions();init_migration_bundle_manifest();FORBIDDEN_ACTIONS=["Do not use --force to bypass migration safety checks.","Do not edit or delete rows in drizzle.__drizzle_migrations.","Do not modify an already-applied migration; create a new forward migration instead."];KNOWN_CODES=new Set([...MIGRATION_ACTIONABLE_SERVER_ERROR_CODES_V1,...MIGRATION_RECOVERY_ALIAS_ERROR_CODES_V1])}});function isDeploymentSchemaError(error62){return error62 instanceof DeploymentSchemaError}var PUBLIC_MESSAGES,DeploymentSchemaError;var init_deployment_schema_error=__esm({"../platform/src/deployment-schema-error.ts"(){"use strict";PUBLIC_MESSAGES={SCHEMA_COMPATIBILITY_CONSTRAINT_UNAVAILABLE:"Deploy schema compatibility preflight requires platform repair",SCHEMA_REVISION_PLAN_FAILED:"Deploy schema preparation failed before tenant migration execution"};DeploymentSchemaError=class extends Error{code;databaseState;reasonCode;activeDeploymentState="UNCHANGED";publicMessage;constructor(input2){super(input2.code,{cause:input2.cause});this.name="DeploymentSchemaError";this.code=input2.code;this.databaseState=input2.databaseState;this.reasonCode=input2.reasonCode;this.publicMessage=PUBLIC_MESSAGES[input2.code]}}}});function localFix(error62){if(error62.code==="MIGRATION_BUNDLE_FORBIDDEN_SECRET_FILE"){return{summary:"The uploaded backend bundle contains a forbidden environment file.",title:"Remove secrets from the deployment artifact",detail:"Keep runtime secrets in Gencow environment configuration, remove environment files from the backend archive, then create a fresh bundle."}}if(error62.code==="MIGRATION_BUNDLE_CLI_VERSION_MISMATCH"){return{summary:"The migration bundle CLI version does not match the request header.",title:"Create one fresh request with the official CLI",detail:"Do not reuse or handcraft a migration archive or version header. Rerun db:check from the project."}}return{summary:"The migration bundle manifest does not match the uploaded schema and migrations.",title:"Regenerate the bundle",detail:"Do not edit the generated manifest. Verify local schema and migration files, then rerun db:check."}}function buildMigrationBundleFailureResponse(error62,correlationId,operation){const contract=MIGRATION_BUNDLE_ERROR_CONTRACT_V1[error62.code];if(error62.code==="MIGRATION_BUNDLE_GENERATOR_UNSUPPORTED"){const summary2="An older platform slot rejected audit-only generator metadata.";const diagnostic2=retryableInfraDiagnostic({code:error62.code,phase:"PREFLIGHT",databaseState:"UNCHANGED",retryPolicy:"AFTER_DELAY",retryAfterSeconds:15,retryCondition:"Retry the same immutable bundle after the platform rollout converges.",correlationId,reason:{code:"legacy_generator_policy_slot",summary:summary2,detail:"No tenant database access or mutation occurred. Current slots treat generator identity as audit metadata."},suggestedFixes:[],docsUrl:MIGRATION_CAPABILITY_MANIFEST_V1.docsUrl,supportedCliRange:MIGRATION_CAPABILITY_MANIFEST_V1.supportedCliRange,forbiddenActions:[],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}});return{status:contract.status,body:{error:`Schema ${operation} failed: ${summary2}`,...diagnostic2}}}const needsPlatformAction=contract.failureClass==="PLATFORM_ACTION_REQUIRED";const needsPlatformInspection=error62.code==="PLATFORM_MIGRATION_ARTIFACT_CONTRACT_MISMATCH";const needsUpgrade=needsPlatformAction&&!needsPlatformInspection;const fix=localFix(error62);const summary=needsPlatformInspection?"The platform could not prove the migration artifact identity.":needsUpgrade?"This migration bundle protocol requires a supported CLI.":fix.summary;const common={code:error62.code,phase:"PREFLIGHT",databaseState:"UNCHANGED",correlationId,retryCondition:needsPlatformInspection?"Keep the source and operation identity unchanged while the platform state is inspected.":needsUpgrade?"Install a CLI version in the supported range, then create a fresh migration bundle.":"Create a fresh bundle from unchanged trusted source files, then run db:check again.",reason:{code:error62.code.toLowerCase(),summary,detail:"The request was rejected after archive extraction and manifest verification, before tenant database access or mutation."},suggestedFixes:[{id:needsPlatformInspection?"inspect-platform-artifact-identity":needsUpgrade?"update-cli-and-regenerate-bundle":"regenerate-bundle-from-trusted-source",title:needsPlatformInspection?"Inspect platform artifact identity":needsUpgrade?"Update the CLI and regenerate the bundle":fix.title,detail:needsPlatformInspection?"Use the correlation ID to inspect the Platform verifier, source revision, and durable receipt.":needsUpgrade?`Install Gencow CLI ${MIGRATION_CAPABILITY_MANIFEST_V1.supportedCliRange} and rerun db:check.`:fix.detail,target:contract.fixTarget,confidence:"HIGH"}],docsUrl:MIGRATION_CAPABILITY_MANIFEST_V1.docsUrl,supportedCliRange:MIGRATION_CAPABILITY_MANIFEST_V1.supportedCliRange,forbiddenActions:["Do not use --force to bypass migration safety checks.","Do not edit or delete rows in drizzle.__drizzle_migrations."],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}};const diagnostic=needsPlatformAction?platformActionDiagnostic({...common,nextAction:needsPlatformInspection?"INSPECT_STATE":"UPDATE_CLI"}):userFixableDiagnostic(common);return{status:contract.status,body:{error:`Schema ${operation} failed: ${summary}`,...diagnostic}}}var init_apps_migration_bundle_errors=__esm({"../platform/gencow/apps-migration-bundle-errors.ts"(){"use strict";init_dist()}});function buildRestoreSourceRuntimeDiagnostic(input2){if(input2.code!=="RESTORE_SOURCE_RUNTIME_GENERATION_UNAVAILABLE"&&input2.code!=="RESTORE_SOURCE_RUNTIME_GENERATION_IDENTITY_MISMATCH")return null;const base2=buildPublicSelfServiceDiagnostic({code:input2.code,stage:"candidate",correlationId:input2.correlationId,operationId:input2.operationId,databaseState:"UNCHANGED",requestedAction:"VIEW_STATUS",reasonCode:"restore_source_runtime_unavailable",reasonSummary:"Recovery is blocked because the saved runtime could not be verified. The database and current serving deployment are preserved.",incumbentServing:"PRESERVED",operationState:"BLOCKED"});return{...base2,retry:{...base2.retry,condition:"Retry only after status reports the saved runtime is verified and recovery is ready."},action:{...base2.action,command:`gencow deploy status${input2.operationId?` --deployment ${input2.operationId}`:""}`}}}var init_restore_source_runtime_diagnostic=__esm({"../platform/src/restore-source-runtime-diagnostic.ts"(){"use strict";init_public_self_service_diagnostic()}});function buildNpmDependencyReplayDiagnostic(input2){if(input2.code!==NPM_DEPENDENCY_REPLAY_INVALID)return null;const base2=buildPublicSelfServiceDiagnostic({code:input2.code,stage:"candidate",correlationId:input2.correlationId,operationId:input2.operationId,databaseState:input2.databaseState??"UNKNOWN",requestedAction:"VIEW_STATUS",reasonCode:"saved_dependency_graph_unverified",reasonSummary:"Runtime recovery is blocked because the saved dependency graph could not be verified. Inspect recovery status; app source changes are not required.",incumbentServing:input2.incumbentServing??"PRESERVED",operationState:"BLOCKED"});return{...base2,stateImpact:{...base2.stateImpact,mutation:input2.databaseState===void 0||input2.databaseState==="UNKNOWN"?"UNKNOWN":base2.stateImpact.mutation},retry:{...base2.retry,condition:"Retry only after status confirms the saved dependency graph is verified and recovery is ready."},action:{...base2.action,command:`gencow deploy status${input2.operationId?` --deployment ${input2.operationId}`:""}`}}}var NPM_DEPENDENCY_REPLAY_INVALID,NpmDependencyReplayError;var init_npm_dependency_replay_diagnostic=__esm({"../platform/src/npm-dependency-replay-diagnostic.ts"(){"use strict";init_public_self_service_diagnostic();NPM_DEPENDENCY_REPLAY_INVALID="RUNTIME_RESTORE_SOURCE_DEPENDENCY_GRAPH_INVALID";NpmDependencyReplayError=class extends Error{code=NPM_DEPENDENCY_REPLAY_INVALID;constructor(){super(NPM_DEPENDENCY_REPLAY_INVALID)}}}});import{randomUUID as randomUUID36}from"node:crypto";function isMigrationDeployError(error62){const code=error62?.code;return typeof code==="string"&&MIGRATION_DEPLOY_CODES.has(code)&&!DEPLOY_RUNTIME_GUARDRAIL_CODES.has(code)}function compareStableVersions2(left,right){const leftParts=left.split("-")[0].split(".").map(Number);const rightParts=right.split("-")[0].split(".").map(Number);for(let index27=0;index27<3;index27+=1){if(leftParts[index27]!==rightParts[index27])return leftParts[index27]-rightParts[index27]}return 0}function requiresLegacyActionableDeployMessage(cliVersion){const version3=cliVersion??"";return/^\d+\.\d+\.\d+$/u.test(version3)&&compareStableVersions2(version3,LEGACY_ACTIONABLE_DEPLOY_CLI_MAX)<=0}function supportsAppDeleteStatusDiagnostic(cliVersion){return/^\d+\.\d+\.\d+$/u.test(cliVersion??"")&&compareStableVersions2(cliVersion,APP_DELETE_STATUS_DIAGNOSTIC_CLI_MIN)>=0}function legacyActionableDeployMessage(input2){if(!requiresLegacyActionableDeployMessage(input2.cliVersion))return input2.error;return[input2.error,`Code: ${input2.code}`,`Stage: ${input2.stage}`,`Next action: ${input2.userAction}`].join("\n")}function candidateBackendEvidenceBody(error62){const loadEvidence=error62.candidateLoadEvidence;if(loadEvidence!=="registry_empty_after_import"&&loadEvidence!=="minimal_mode")return{};const observedOperationCount=error62.observedOperationCount;return{candidateBackendEvidence:{loadEvidence,...Number.isSafeInteger(observedOperationCount)?{observedOperationCount}:{}}}}function getDeployRuntimeGuardrailCode(error62){const code=error62?.code;return typeof code==="string"&&DEPLOY_RUNTIME_GUARDRAIL_CODES.has(code)?code:null}function getDeploymentAttemptFailureCode(error62,stage,crashLogs){if(error62 instanceof AppDeploymentPlacementError)return error62.diagnosticCode;if(error62 instanceof DeploymentAdmissionError)return error62.code;if(isDeploymentSchemaError(error62))return error62.code;if(asControlPlaneSchemaUnavailableError(error62))return CONTROL_PLANE_SCHEMA_UNAVAILABLE;const guardrailCode=getDeployRuntimeGuardrailCode(error62);if(guardrailCode)return guardrailCode;if(isMigrationDeployError(error62))return String(error62.code);if(isDeployDependencyVersionError(error62)||isCronManifestDeployError(error62))return error62.code;const routePrepareCause=getDeploymentFailureCause(error62)==="DEPLOY_ARTIFACT_ROUTE_PREPARE_FAILED";if(stage==="route"&&routePrepareCause&&!isRoutePrepareConvergenceFailure(error62)){return getStableDeploymentFailureCode(error62)??"ACTIVATION_ROUTE_PREPARE_FAILED"}if(stage!=="route"&&getDeploymentFailureCause(error62)?.startsWith("DEPLOY_ARTIFACT_")){return"DEPLOY_ARTIFACT_MATERIALIZE_FAILED"}const stableCode=getStableDeploymentFailureCode(error62);if(stableCode)return stableCode;if(stage==="admission")return"DEPLOY_CONTRACT_INVALID";if(stage==="artifact")return"DEPLOY_ARTIFACT_MATERIALIZE_FAILED";if(stage==="schema")return"SCHEMA_APPLY_FAILED";if(stage==="activation"||stage==="route")return"ACTIVATION_ROUTE_ACK_PENDING";if(stage==="runtime")return"RUNTIME_OWNERSHIP_AMBIGUOUS";if(stage==="controller")return"CONTROL_PLANE_OBSERVATION_INCOMPLETE";return resolveGenericDeploymentFailurePolicy({stage,error:error62,crashLogs}).code}function getDeploymentAttemptFailureStage(error62,currentStage){return isMigrationDeployError(error62)||isDeploymentSchemaError(error62)?"schema":resolveDeploymentFailureStage(error62,currentStage)}function isAppBusyAdmissionError(error62){return error62 instanceof DeploymentExecutorAdmissionError&&error62.code===APP_BUSY_CODE}async function resolveAppBusyBlockingOperation(input2){if(!(input2.error instanceof DeploymentExecutorAdmissionError)||!isAppBusyAdmissionError(input2.error)){return void 0}if(input2.error.blockingOperationId){return{id:input2.error.blockingOperationId,correlationId:input2.error.blockingCorrelationId??null}}return readActiveDeploymentConflict({db:input2.db,appId:input2.appId,warn:input2.warn})}function buildAppBusyAdmissionResponse(input2){const ownBlocking=input2.error.blockingOperationId?{id:input2.error.blockingOperationId,correlationId:input2.error.blockingCorrelationId??null}:void 0;const blocking=ownBlocking??input2.blockingOperation;const blockingId=blocking&&Number.isSafeInteger(blocking.id)&&blocking.id>0?blocking.id:void 0;const blockingCorrelationId=blocking?.correlationId&&/^[A-Za-z0-9_-]{8,128}$/u.test(blocking.correlationId)?blocking.correlationId:void 0;const correlationId=input2.correlationId??`deploy_busy_${randomUUID36()}`;const statusCommand=blockingId===void 0?"gencow deploy status":`gencow deploy status --deployment ${blockingId}`;const baseSelfService=buildPublicSelfServiceDiagnostic({code:APP_BUSY_CODE,stage:input2.stage,correlationId,databaseState:"UNCHANGED",requestedAction:"VIEW_STATUS",reasonCode:"deployment_app_busy",reasonSummary:"Another deployment of this app is active. This request changed nothing.",incumbentServing:"PRESERVED",operationState:"BLOCKED"});const selfService={...baseSelfService,retry:{...baseSelfService.retry,condition:"Check the active deployment's status; retry this same deployment only after it reports a final result."},action:{...baseSelfService.action,command:statusCommand}};return{status:409,body:{error:"Another deployment of this app is active. This request changed nothing; check its status, then retry.",code:APP_BUSY_CODE,stage:input2.stage,retryClass:"retryable-infra",userAction:"VIEW_STATUS",databaseState:"UNCHANGED",...blockingId===void 0?{}:{retryReadinessReason:"ACTIVE_OWNER",blockingOperationId:blockingId},...blockingCorrelationId===void 0?{}:{blockingCorrelationId},correlationId,diagnostic:{selfService},nextAction:{kind:"VIEW_STATUS",command:statusCommand}}}}function buildDeployFailureResponse(error62,crashLogs,context={}){const correlationId=/^[A-Za-z0-9_-]{8,128}$/u.test(context.correlationId??"")?context.correlationId:void 0;const withCorrelation=correlationId?{correlationId}:{};const fallbackStage=context.stage??(error62 instanceof DeploymentAdmissionError?"admission":"candidate");const resolvedStage=getDeploymentAttemptFailureStage(error62,fallbackStage);const sourceRuntimeCode=getStableDeploymentFailureCode(error62);const stopConfigurationCorrelationId=correlationId??`stop_blocked_${randomUUID36()}`;const stopConfigurationDiagnostic=buildRuntimeStopConfigurationDiagnostic({code:sourceRuntimeCode??"",correlationId:stopConfigurationCorrelationId});if(stopConfigurationDiagnostic){return{status:503,body:{error:stopConfigurationDiagnostic.reason.summary,code:sourceRuntimeCode,stage:"runtime",retryClass:"platform-action",userAction:"VIEW_STATUS",databaseState:"UNCHANGED",activeDeploymentState:"PRESERVED",correlationId:stopConfigurationCorrelationId,nextAction:{kind:"VIEW_STATUS",command:stopConfigurationDiagnostic.action.command},diagnostic:{selfService:stopConfigurationDiagnostic}}}}if(sourceRuntimeCode===NPM_DEPENDENCY_REPLAY_INVALID){const responseCorrelationId=correlationId??`restore_blocked_${randomUUID36()}`;const selfService=buildNpmDependencyReplayDiagnostic({code:sourceRuntimeCode,correlationId:responseCorrelationId});return{status:503,body:{error:selfService.reason.summary,code:sourceRuntimeCode,stage:"candidate",retryClass:"platform-action",userAction:"VIEW_STATUS",databaseState:"UNKNOWN",activeDeploymentState:"PRESERVED",correlationId:responseCorrelationId,nextAction:{kind:"VIEW_STATUS",command:selfService.action.command},diagnostic:{selfService}}}}if(sourceRuntimeCode==="RESTORE_SOURCE_RUNTIME_GENERATION_UNAVAILABLE"||sourceRuntimeCode==="RESTORE_SOURCE_RUNTIME_GENERATION_IDENTITY_MISMATCH"){const responseCorrelationId=correlationId??`restore_blocked_${randomUUID36()}`;const selfService=buildRestoreSourceRuntimeDiagnostic({code:sourceRuntimeCode,correlationId:responseCorrelationId});const command=selfService.action.command;return{status:503,body:{error:selfService.reason.summary,code:sourceRuntimeCode,stage:"candidate",retryClass:"platform-action",userAction:"VIEW_STATUS",databaseState:"UNCHANGED",activeDeploymentState:"PRESERVED",correlationId:responseCorrelationId,nextAction:{kind:"VIEW_STATUS",command},diagnostic:{selfService}}}}if(isDeploymentSchemaError(error62)){return{status:503,body:{error:error62.publicMessage,code:error62.code,stage:"schema",retryClass:"platform-action",userAction:"OPERATOR_ACTION",databaseState:error62.databaseState,activeDeploymentState:error62.activeDeploymentState,...withCorrelation}}}if(error62 instanceof MigrationBundleManifestError){const response=buildMigrationBundleFailureResponse(error62,correlationId??"deploy_migration_unknown","check");const{error:publicError,...diagnostic}=response.body;return{status:response.status,body:{error:publicError,code:diagnostic.code,stage:"schema",retryClass:retryClassForMigrationFailureClass(diagnostic.failureClass),userAction:diagnostic.nextAction.kind,databaseState:diagnostic.databaseState,nextAction:{kind:diagnostic.nextAction.kind},diagnostic,...withCorrelation}}}if(isMigrationDeployError(error62)){const diagnostic=buildActionableMigrationDiagnostic(error62,correlationId??"deploy_migration_unknown");const retryClass=retryClassForMigrationFailureClass(diagnostic.failureClass);return{status:migrationDiagnosticHttpStatus(diagnostic),body:{error:diagnostic.reason.summary,code:diagnostic.code,stage:"schema",retryClass,userAction:diagnostic.nextAction.kind,databaseState:diagnostic.databaseState,nextAction:{kind:diagnostic.nextAction.kind},diagnostic,...withCorrelation}}}if(error62 instanceof DeploymentExecutorAdmissionError&&isAppBusyAdmissionError(error62)){return buildAppBusyAdmissionResponse({stage:resolvedStage,correlationId,error:error62,blockingOperation:context.blockingOperation})}if(error62 instanceof DeploymentExecutorAdmissionError&&error62.code===ADMISSION_UNAVAILABLE_CODE){return buildRetryableAdmissionUnavailableResponse({correlationId:context.correlationId??`deploy-admission-${randomUUID36()}`})}if(error62 instanceof DeploymentAdmissionError){if(error62.code==="DEPLOYMENT_EXECUTOR_RECOVERY_REQUIRED"){const blockingOperationId=error62.blockingOperationId;const blockingCorrelationId=error62.blockingCorrelationId;const responseCorrelationId=correlationId??`deploy_rejected_${randomUUID36()}`;const validBlockingOperationId=typeof blockingOperationId==="number"&&Number.isSafeInteger(blockingOperationId)&&blockingOperationId>0?blockingOperationId:void 0;const baseSelfService=buildPublicSelfServiceDiagnostic({code:error62.code,stage:"admission",correlationId:responseCorrelationId,...validBlockingOperationId===void 0?{}:{operationId:String(validBlockingOperationId)},databaseState:"UNCHANGED",requestedAction:"VIEW_STATUS",reasonCode:"deployment_executor_recovery_required",reasonSummary:"This request changed nothing. Platform owns the blocking deployment and retires eligible ones automatically; status changes when it is done. Some kinds are not retired automatically.",incumbentServing:"UNKNOWN",operationState:"BLOCKED"});const selfService={...baseSelfService,retry:{...baseSelfService.retry,condition:"Check the blocking deployment's status; retry only after it reports a final result and shows a retry command. Kinds Platform does not recover automatically stay blocked until a Platform operator acts; keep the correlation ID."},action:{...baseSelfService.action,...validBlockingOperationId===void 0?{}:{command:`gencow deploy status --deployment ${validBlockingOperationId}`}}};return{status:503,body:{error:"A previous deployment is blocking this deploy. Platform owns it and no gencow command can resolve it; Platform retires eligible ones automatically. This request changed nothing.",code:error62.code,stage:"admission",retryClass:"platform-action",userAction:"VIEW_STATUS",databaseState:"UNCHANGED",activeDeploymentState:"BLOCKED",retryReadinessReason:"RECOVERY_REQUIRED",...validBlockingOperationId===void 0?{}:{operationId:String(validBlockingOperationId),blockingOperationId:validBlockingOperationId},correlationId:responseCorrelationId,...typeof blockingCorrelationId==="string"&&/^[A-Za-z0-9_-]{8,128}$/u.test(blockingCorrelationId)?{blockingCorrelationId}:{},diagnostic:{selfService},nextAction:{kind:"VIEW_STATUS",...validBlockingOperationId!==void 0?{command:`gencow deploy status --deployment ${validBlockingOperationId}`}:{}}}}}if(error62.code==="RUNTIME_CANDIDATE_CLEANUP_INCOMPLETE"){return{status:503,body:{error:"Deploy candidate cleanup is incomplete; inspect platform state before retrying",code:error62.code,stage:"admission",retryClass:"platform-action",userAction:"INSPECT_STATE",...withCorrelation}}}if(resolvedStage==="artifact"||resolvedStage==="controller"){const failure3=resolveGenericDeploymentFailurePolicy({stage:resolvedStage,error:error62,crashLogs});return{status:failure3.status,body:{error:failure3.error,code:failure3.code,stage:resolvedStage,retryClass:failure3.retryClass,userAction:failure3.userAction,...withCorrelation}}}const updateCli=error62.code==="DEPLOY_CLI_UPGRADE_REQUIRED";const authAmbiguous=error62.code==="AUTH_SCHEMA_PROVENANCE_AMBIGUOUS";return{status:error62.status,body:{error:authAmbiguous?"Multiple Better Auth schema sources were found":updateCli?`Deploy requires Gencow CLI ${MIN_DEPLOY_CLI_VERSION} or newer`:"Deploy contract admission failed",code:error62.code,stage:"admission",retryClass:"terminal-client",userAction:updateCli?"UPDATE_CLI":"EDIT_AND_CHECK",...authAmbiguous?{databaseState:"UNCHANGED",activeDeploymentState:"UNCHANGED",files:error62.publicDetails?.files??[],remediation:["Keep exactly one Auth schema source.","Remove stale generated or legacy Auth schema files, then redeploy."]}:{},...withCorrelation}}}if(asControlPlaneSchemaUnavailableError(error62)){return{status:503,body:{error:"Deploy control-plane schema is unavailable",code:CONTROL_PLANE_SCHEMA_UNAVAILABLE,stage:"admission",retryClass:"platform-action",userAction:"OPERATOR_ACTION",...withCorrelation}}}if(error62?.code==="DEPLOYMENT_FAILURE_RECEIPT_UNAVAILABLE"){return{status:503,body:{error:"Deployment failure receipt could not be recorded. Please retry later.",code:"DEPLOYMENT_FAILURE_RECEIPT_UNAVAILABLE",stage:"admission",retryClass:"platform-action",userAction:"OPERATOR_ACTION",...withCorrelation}}}const placementCode=error62&&typeof error62==="object"&&["DEPLOYMENT_PLACEMENT_UNAVAILABLE","DEPLOYMENT_PLACEMENT_STATE_INVALID"].includes(String(error62.code??""))?String(error62.code):null;if(placementCode){const retryable=placementCode==="DEPLOYMENT_PLACEMENT_UNAVAILABLE";const diagnostic=error62 instanceof AppDeploymentPlacementError?{code:error62.diagnosticCode,scope:"placement"}:{code:"PLACEMENT_SYSTEM_UNAVAILABLE",scope:"placement"};return{status:503,body:{error:retryable?"App placement is being revalidated. Please retry shortly.":"App placement state requires platform reconciliation.",code:placementCode,stage:"admission",retryClass:retryable?"retryable-infra":"platform-action",userAction:retryable?"RETRY":"OPERATOR_ACTION",diagnostic,...withCorrelation}}}const guardrailCode=getDeployRuntimeGuardrailCode(error62);if(guardrailCode){if(guardrailCode==="APP_DELETE_ADMISSION_CLOSED"){const operationId2=error62.operationId;const deleteCorrelationId=error62.correlationId;if(typeof operationId2==="string"&&APP_DELETE_OPERATION_PATTERN2.test(operationId2)&&typeof deleteCorrelationId==="string"&&APP_DELETE_CORRELATION_PATTERN.test(deleteCorrelationId)){const typedStatus=supportsAppDeleteStatusDiagnostic(context.cliVersion);return{status:409,body:{error:typedStatus?"App deletion is in progress. Check deletion status before deploying.":"App deletion is in progress. Run the app delete command again to view status.",code:guardrailCode,stage:"admission",retryClass:"platform-action",userAction:typedStatus?"VIEW_DELETE_STATUS":"VIEW_STATUS",operationId:operationId2,correlationId:deleteCorrelationId}}}}const publicMessage=DEPLOY_RUNTIME_GUARDRAIL_MESSAGES[guardrailCode]??"deploy guardrail blocked this request";const retryable=guardrailCode==="DEPLOY_CAPACITY_LIMITED"||guardrailCode==="DEPLOY_RUNTIME_PORT_BUSY_MANAGED";const userAction=retryable?"RETRY":guardrailCode==="BACKEND_CAPABILITY_EMPTY"?"EDIT_AND_CHECK":"OPERATOR_ACTION";const errorMessage8=`Deploy failed: ${publicMessage}`;return{status:retryable?503:409,body:{error:guardrailCode==="BACKEND_CAPABILITY_EMPTY"?legacyActionableDeployMessage({error:errorMessage8,code:guardrailCode,stage:"candidate",userAction,cliVersion:context.cliVersion}):errorMessage8,code:guardrailCode,stage:"candidate",retryClass:retryable?"retryable-infra":guardrailCode==="BACKEND_CAPABILITY_EMPTY"?"terminal-client":"platform-action",userAction,...guardrailCode==="BACKEND_CAPABILITY_EMPTY"?candidateBackendEvidenceBody(error62):{},...withCorrelation}}}if(isDeployDependencyVersionError(error62)){return{status:400,body:{error:"Deploy dependency versions are incompatible with the hosted runtime",code:"DEPLOY_DEPENDENCY_VERSION_MISMATCH",stage:"admission",retryClass:"terminal-client",userAction:"EDIT_AND_CHECK",...withCorrelation}}}if(isCronManifestDeployError(error62)){return{status:400,body:{error:"Deploy cron manifest validation failed",code:"CRON_MANIFEST_INVALID",stage:"admission",retryClass:"terminal-client",userAction:"EDIT_AND_CHECK",...withCorrelation}}}const stage=resolvedStage;const candidateCleanupFailureCode=getCandidateCleanupFailureCode(error62);const withCandidateCleanup=candidateCleanupFailureCode?{candidateCleanupFailureCode}:{};if(stage==="schema"){return{status:503,body:{error:"Deploy schema outcome requires platform state inspection",code:getDeploymentAttemptFailureCode(error62,stage,crashLogs),stage,retryClass:"platform-action",userAction:"INSPECT_STATE",...withCorrelation}}}const failure2=resolveGenericDeploymentFailurePolicy({stage,error:error62,crashLogs});const provenance=readCandidateFailureProvenance(error62);return{status:failure2.status,body:{error:failure2.error,code:failure2.code,stage,retryClass:failure2.retryClass,userAction:failure2.userAction,...stage==="candidate"?{candidateProcessStarted:provenance?.processSpawned===true,candidateLogAvailable:provenance?.processSpawned===true&&Boolean(crashLogs?.length)}:{},...withCandidateCleanup,...withCorrelation}}}var MIGRATION_DEPLOY_CODES,DEPLOY_RUNTIME_GUARDRAIL_CODES,DEPLOY_RUNTIME_GUARDRAIL_MESSAGES,LEGACY_ACTIONABLE_DEPLOY_CLI_MAX,APP_DELETE_STATUS_DIAGNOSTIC_CLI_MIN,APP_DELETE_OPERATION_PATTERN2,APP_DELETE_CORRELATION_PATTERN,APP_BUSY_CODE;var init_apps_deploy_failures=__esm({"../platform/gencow/apps-deploy-failures.ts"(){"use strict";init_runtime_stop_configuration_diagnostic();init_deploy_dependency_compat();init_provisioner_cron_sync();init_deployment_request_admission();init_deployment_executor_store();init_deployment_admission_unavailable_response();init_deployment_busy_diagnostic();init_dist();init_migration_actionable_diagnostic();init_migration_bundle_manifest();init_deployment_schema_error();init_apps_migration_bundle_errors();init_deployment_control_plane_rollout();init_deployment_failure_contract();init_candidate_failure_provenance();init_app_deployment_placement();init_public_self_service_diagnostic();init_restore_source_runtime_diagnostic();init_npm_dependency_replay_diagnostic();MIGRATION_DEPLOY_CODES=new Set([...MIGRATION_ACTIONABLE_SERVER_ERROR_CODES_V1,...MIGRATION_RECOVERY_ALIAS_ERROR_CODES_V1]);DEPLOY_RUNTIME_GUARDRAIL_CODES=new Set(["DEPLOY_RUNTIME_PORT_BUSY_MANAGED","DEPLOY_RUNTIME_PORT_BUSY_FOREIGN","DEPLOY_RUNTIME_PORT_UNRECONCILED","DEPLOY_CAPACITY_LIMITED","BACKEND_CAPABILITY_EMPTY","APP_DELETE_ADMISSION_CLOSED","APP_DELETE_ADMISSION_IDENTITY_AMBIGUOUS"]);DEPLOY_RUNTIME_GUARDRAIL_MESSAGES={DEPLOY_RUNTIME_PORT_BUSY_MANAGED:"previous app runtime is still releasing its port",DEPLOY_RUNTIME_PORT_BUSY_FOREIGN:"app runtime port is occupied by a non-app process",DEPLOY_RUNTIME_PORT_UNRECONCILED:"current app runtime could not be safely identified",DEPLOY_CAPACITY_LIMITED:"deploy capacity is temporarily limited; the current app remains serving",BACKEND_CAPABILITY_EMPTY:"backend deploy did not expose any query, mutation, or procedure capability; use gencow static for frontend-only deployments",APP_DELETE_ADMISSION_CLOSED:"app deletion is already in progress",APP_DELETE_ADMISSION_IDENTITY_AMBIGUOUS:"app deletion identity is ambiguous; the current app remains unchanged"};LEGACY_ACTIONABLE_DEPLOY_CLI_MAX="0.1.184";APP_DELETE_STATUS_DIAGNOSTIC_CLI_MIN="0.1.190";APP_DELETE_OPERATION_PATTERN2=/^app_delete_(?:[a-f0-9]{32}|[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})$/u;APP_DELETE_CORRELATION_PATTERN=/^[A-Za-z0-9_-]{8,128}$/u;APP_BUSY_CODE="DEPLOYMENT_EXECUTOR_APP_BUSY"}});function deploymentExecutorDeferralDeadline(deferredSince){if(!(deferredSince instanceof Date)||!Number.isFinite(deferredSince.getTime()))return null;return new Date(deferredSince.getTime()+DEPLOYMENT_EXECUTOR_DEFER_BUDGET_MS)}var DEPLOYMENT_EXECUTOR_DEFER_BUDGET_MS;var init_deployment_executor_defer_budget=__esm({"../platform/src/deployment-executor-defer-budget.ts"(){"use strict";init_deployment_failure_contract();init_app_serving_route_target_rejection();init_deployment_executor_store();DEPLOYMENT_EXECUTOR_DEFER_BUDGET_MS=10*6e4}});function resolvePendingDeploymentPhase(input2){if(!SAFE_PHASE.test(input2.executorState))return null;if(input2.receipt?.phase!=="reconciling"||!SAFE_REASON_CODE.test(input2.receipt.code)){return{phase:input2.executorState}}const deferredSince=input2.receipt.deferredSince?new Date(input2.receipt.deferredSince):null;const staticAdmission=input2.environment==="static"?typeof input2.queuedAt==="string"?new Date(input2.queuedAt):input2.queuedAt:null;const deadline=deploymentExecutorDeferralDeadline(deferredSince??staticAdmission);return{phase:input2.executorState,phaseReasonCode:input2.receipt.code,...deferredSince?{deferredSince:deferredSince.toISOString()}:{},...deadline?{deadlineAt:deadline.toISOString()}:{}}}var SAFE_PHASE,SAFE_REASON_CODE;var init_deployment_executor_pending_phase=__esm({"../platform/src/deployment-executor-pending-phase.ts"(){"use strict";init_deployment_executor_defer_budget();SAFE_PHASE=/^[a-z][a-z_]{1,39}$/u;SAFE_REASON_CODE=/^[A-Z][A-Z0-9_]{2,99}$/u}});async function observeDeploymentExecutorProcess(input2){const targetGenerationBound=Boolean(input2.nodeId&&input2.slotId&&input2.revision&&input2.ownerId&&/^[a-f0-9]{64}$/u.test(input2.generationDigest??""));if(!targetGenerationBound){return{targetGenerationBound:false,executorAvailable:false,probeFailed:false}}try{return{targetGenerationBound:true,executorAvailable:await(input2.probeImpl??hasReadyDeploymentExecutorProcess)({db:input2.db,nodeId:input2.nodeId,slotId:input2.slotId,revision:input2.revision,ownerId:input2.ownerId,generationDigest:input2.generationDigest}),probeFailed:false}}catch{return{targetGenerationBound:true,executorAvailable:null,probeFailed:true}}}var init_deployment_executor_process_observation=__esm({"../platform/src/deployment-executor-process-observation.ts"(){"use strict";init_deployment_executor_worker_store()}});import{createHash as createHash54}from"node:crypto";function requiredIdentity(value2,code){const normalized=value2.trim();if(!normalized)throw new Error(code);return normalized}function positiveInteger2(value2,code){if(!Number.isSafeInteger(value2)||value2<1)throw new Error(code);return value2}function nonNegativeInteger(value2,code){if(!Number.isSafeInteger(value2)||value2<0)throw new Error(code);return value2}function canonicalPayload(binding){return[ROUTE_BINDING_VERSION,binding.appId,binding.appName,binding.environment,binding.deploymentId,binding.activationId,binding.instanceId,binding.artifactRef,binding.sourceGenerationRef,binding.runtimeGenerationRef,binding.activationEpoch,binding.nodeId,binding.nodeEpoch,binding.leaseEpoch,binding.port,binding.readyContractHash]}function canonicalTenantRouteBindingHash(binding){return createHash54("sha256").update(JSON.stringify(canonicalPayload(binding))).digest("hex")}function buildCanonicalTenantRouteBinding(input2){const binding={appId:positiveInteger2(input2.appId,"ROUTE_BINDING_SCOPE_INVALID"),appName:requiredIdentity(input2.appName,"ROUTE_BINDING_SCOPE_INVALID"),environment:requiredIdentity(input2.environment,"ROUTE_BINDING_SCOPE_INVALID"),deploymentId:positiveInteger2(input2.deploymentId,"ROUTE_BINDING_DEPLOYMENT_MISMATCH"),activationId:requiredIdentity(input2.activationId,"ROUTE_BINDING_ACTIVATION_MISMATCH"),instanceId:requiredIdentity(input2.instanceId,"ROUTE_BINDING_INSTANCE_AMBIGUOUS"),artifactRef:requiredIdentity(input2.artifactRef,"ROUTE_BINDING_GENERATION_MISMATCH"),sourceGenerationRef:requiredIdentity(input2.sourceGenerationRef,"ROUTE_BINDING_GENERATION_MISMATCH"),runtimeGenerationRef:requiredIdentity(input2.runtimeGenerationRef,"ROUTE_BINDING_GENERATION_MISMATCH"),activationEpoch:positiveInteger2(input2.activationEpoch,"ROUTE_BINDING_ACTIVATION_MISMATCH"),nodeId:requiredIdentity(input2.nodeId,"ROUTE_BINDING_NODE_FENCE_MISMATCH"),nodeEpoch:nonNegativeInteger(input2.nodeEpoch,"ROUTE_BINDING_NODE_FENCE_MISMATCH"),leaseEpoch:positiveInteger2(input2.leaseEpoch,"ROUTE_BINDING_NODE_FENCE_MISMATCH"),port:positiveInteger2(input2.port,"ROUTE_BINDING_INSTANCE_AMBIGUOUS"),readyContractHash:requiredIdentity(input2.readyContractHash,"ROUTE_BINDING_INSTANCE_AMBIGUOUS")};if(binding.port>65535)throw new Error("ROUTE_BINDING_INSTANCE_AMBIGUOUS");return{...binding,bindingHash:canonicalTenantRouteBindingHash(binding)}}var ROUTE_BINDING_VERSION;var init_runtime_route_binding_contract=__esm({"../platform/src/runtime-route-binding-contract.ts"(){"use strict";ROUTE_BINDING_VERSION=1}});var runtime_route_binding_reader_exports={};__export(runtime_route_binding_reader_exports,{ROUTE_BINDING_NOT_SERVING_CODE:()=>ROUTE_BINDING_NOT_SERVING_CODE,assertCanonicalTenantRouteFleetSnapshot:()=>assertCanonicalTenantRouteFleetSnapshot,loadCanonicalTenantRouteBinding:()=>loadCanonicalTenantRouteBinding,loadCanonicalTenantRouteBindings:()=>loadCanonicalTenantRouteBindings,loadCanonicalTenantRouteFleetSnapshot:()=>loadCanonicalTenantRouteFleetSnapshot,loadCanonicalTenantRouteProjectionProof:()=>loadCanonicalTenantRouteProjectionProof,loadCanonicalTenantRouteRemovalTargets:()=>loadCanonicalTenantRouteRemovalTargets});import{createHash as createHash55}from"node:crypto";import{and as and23,eq as eq26}from"drizzle-orm";function bindingFromRows(rows8){if(rows8.length!==1){throw new Error(rows8.length===0?ROUTE_BINDING_NOT_SERVING_CODE:"ROUTE_BINDING_INSTANCE_AMBIGUOUS")}const row=rows8[0];if(row.desiredActivationId!==row.activationId||row.activationState!=="serving"||row.instanceState!=="serving"||row.activationEpoch===null||row.routeAckEpoch!==row.activationEpoch||row.desiredActivationEpoch!==row.activationEpoch){throw new Error("ROUTE_BINDING_ACTIVATION_MISMATCH")}if(row.activationNodeId!==row.desiredNodeId||row.instanceNodeId!==row.desiredNodeId||row.nodeEpoch!==row.desiredNodeEpoch||row.instanceNodeEpoch!==row.desiredNodeEpoch){throw new Error("ROUTE_BINDING_NODE_FENCE_MISMATCH")}if(!row.artifactRef||!row.sourceGenerationRef||!row.runtimeGenerationRef||row.instanceArtifactRef!==row.artifactRef||row.instanceSourceGenerationRef!==row.sourceGenerationRef||row.instanceRuntimeGenerationRef!==row.runtimeGenerationRef){throw new Error("ROUTE_BINDING_GENERATION_MISMATCH")}if(!row.port||!row.readyContractHash){throw new Error("ROUTE_BINDING_INSTANCE_AMBIGUOUS")}return buildCanonicalTenantRouteBinding({appId:row.appId,appName:row.appName,environment:row.environment,deploymentId:row.deploymentId,activationId:row.activationId,instanceId:row.instanceId,artifactRef:row.artifactRef,sourceGenerationRef:row.sourceGenerationRef,runtimeGenerationRef:row.runtimeGenerationRef,activationEpoch:row.activationEpoch,nodeId:row.desiredNodeId,nodeEpoch:row.desiredNodeEpoch,leaseEpoch:row.leaseEpoch,port:row.port,readyContractHash:row.readyContractHash})}function bindingSelection(){return{appId:apps.id,appName:apps.name,environment:deployments.env,deploymentId:appDeploymentActivations.deploymentId,activationId:appDeploymentActivations.id,desiredActivationId:appRuntimeDesiredState.desiredActivationId,activationState:appDeploymentActivations.state,routeAckEpoch:appDeploymentActivations.routeAckEpoch,activationEpoch:appDeploymentActivations.activationEpoch,desiredActivationEpoch:appRuntimeDesiredState.activationEpoch,activationNodeId:appDeploymentActivations.nodeId,desiredNodeId:appRuntimeDesiredState.nodeId,instanceNodeId:appRuntimeInstances.nodeId,nodeEpoch:appDeploymentActivations.nodeEpoch,desiredNodeEpoch:appRuntimeDesiredState.nodeEpoch,instanceNodeEpoch:appRuntimeInstances.nodeEpoch,instanceId:appRuntimeInstances.instanceId,instanceState:appRuntimeInstances.state,artifactRef:appDeploymentActivations.artifactRef,instanceArtifactRef:appRuntimeInstances.artifactRef,sourceGenerationRef:appDeploymentActivations.sourceGenerationRef,instanceSourceGenerationRef:appRuntimeInstances.sourceGenerationRef,runtimeGenerationRef:appDeploymentActivations.runtimeGenerationRef,instanceRuntimeGenerationRef:appRuntimeInstances.runtimeGenerationRef,leaseEpoch:appRuntimeInstances.leaseEpoch,port:appRuntimeInstances.port,readyContractHash:appRuntimeInstances.readyContractHash}}function fleetSelection(){return{...bindingSelection(),authorityMode:appRuntimeDesiredState.authorityMode,desiredRuntimeState:appRuntimeDesiredState.desiredRuntimeState,hasBackend:apps.hasBackend,appStatus:apps.status}}function queryBindingRows(db){return db.select(bindingSelection()).from(appRuntimeDesiredState).innerJoin(apps,eq26(apps.id,appRuntimeDesiredState.appId)).innerJoin(appDeploymentActivations,and23(eq26(appDeploymentActivations.id,appRuntimeDesiredState.desiredActivationId),eq26(appDeploymentActivations.appId,appRuntimeDesiredState.appId))).innerJoin(deployments,and23(eq26(deployments.id,appDeploymentActivations.deploymentId),eq26(deployments.appId,appRuntimeDesiredState.appId))).innerJoin(appRuntimeInstances,and23(eq26(appRuntimeInstances.activationId,appDeploymentActivations.id),eq26(appRuntimeInstances.deploymentId,appDeploymentActivations.deploymentId),eq26(appRuntimeInstances.appId,appRuntimeDesiredState.appId),eq26(appRuntimeInstances.state,"serving")))}async function loadCanonicalTenantRouteBinding(input2){const rows8=await queryBindingRows(input2.db).where(and23(eq26(appRuntimeDesiredState.appId,input2.appId),eq26(appRuntimeDesiredState.authorityMode,"enforce"),eq26(appRuntimeDesiredState.desiredRuntimeState,"serving")));return bindingFromRows(rows8)}function projectionNumber(value2){const numberValue=typeof value2==="bigint"?Number(value2):Number(value2);return Number.isSafeInteger(numberValue)&&numberValue>0?numberValue:null}async function loadCanonicalTenantRouteProjectionProof(input2){const expectedSlots=[...new Set(input2.expectedPlatformSlots.map(slot=>slot.trim().toLowerCase()))].filter(Boolean);if(expectedSlots.length===0){throw new Error("ROUTE_BINDING_PROJECTION_ACTIVE_SLOTS_UNDECLARED")}const binding=await loadCanonicalTenantRouteBinding({db:input2.db,appId:input2.appId});if(binding.nodeId!==input2.nodeId){throw new Error("ROUTE_BINDING_NODE_FENCE_MISMATCH")}const rows8=await input2.db.select({appId:appRuntimeRouteProjections.appId,nodeId:appRuntimeRouteProjections.nodeId,platformSlot:appRuntimeRouteProjections.platformSlot,platformEpoch:appRuntimeRouteProjections.platformEpoch,platformRevision:appRuntimeRouteProjections.platformRevision,activationId:appRuntimeRouteProjections.activationId,activationEpoch:appRuntimeRouteProjections.activationEpoch,instanceId:appRuntimeRouteProjections.instanceId,leaseEpoch:appRuntimeRouteProjections.leaseEpoch,routePort:appRuntimeRouteProjections.routePort,readyContractHash:appRuntimeRouteProjections.readyContractHash,bindingHash:appRuntimeRouteProjections.bindingHash,state:appRuntimeRouteProjections.state,probedAt:appRuntimeRouteProjections.probedAt}).from(appRuntimeRouteProjections).where(and23(eq26(appRuntimeRouteProjections.appId,input2.appId),eq26(appRuntimeRouteProjections.nodeId,input2.nodeId)));const latestBySlot=new Map;for(const row of rows8){const slot=String(row.platformSlot??"").trim().toLowerCase();const epoch=projectionNumber(row.platformEpoch);if(!slot||epoch===null)throw new Error("ROUTE_BINDING_PROJECTION_MISMATCH");const previous=latestBySlot.get(slot);if(!previous||epoch>projectionNumber(previous.platformEpoch)){latestBySlot.set(slot,row)}}const expectedSet=new Set(expectedSlots);const requireExactSlotSet=input2.requireExactSlotSet??true;if(requireExactSlotSet&&latestBySlot.size!==expectedSet.size||requireExactSlotSet&&[...latestBySlot.keys()].some(slot=>!expectedSet.has(slot))||expectedSlots.some(slot=>!latestBySlot.has(slot))){throw new Error("ROUTE_BINDING_PROJECTION_SLOT_SET_MISMATCH")}const slots=expectedSlots.map(platformSlot=>{const row=latestBySlot.get(platformSlot);const platformEpoch=projectionNumber(row.platformEpoch);const activationEpoch=projectionNumber(row.activationEpoch);const leaseEpoch=projectionNumber(row.leaseEpoch);const routePort=projectionNumber(row.routePort);const platformRevision=String(row.platformRevision??"").trim();const activationId=String(row.activationId??"");const instanceId=String(row.instanceId??"");const readyContractHash=String(row.readyContractHash??"");const bindingHash=String(row.bindingHash??"");if(row.appId!==input2.appId||row.nodeId!==input2.nodeId||row.state!=="acknowledged"||row.probedAt===null||platformEpoch===null||activationEpoch===null||leaseEpoch===null||routePort===null||!platformRevision||!activationId||!instanceId||!readyContractHash||!bindingHash||activationId!==binding.activationId||activationEpoch!==binding.activationEpoch||instanceId!==binding.instanceId||leaseEpoch!==binding.leaseEpoch||routePort!==binding.port||readyContractHash!==binding.readyContractHash||bindingHash!==binding.bindingHash){throw new Error("ROUTE_BINDING_PROJECTION_MISMATCH")}return{platformSlot,platformEpoch,platformRevision,activationId,activationEpoch,instanceId,leaseEpoch,routePort,readyContractHash,bindingHash}});return{binding,nodeId:input2.nodeId,slots}}async function loadCanonicalTenantRouteBindings(input2){return(await loadCanonicalTenantRouteFleetSnapshot(input2)).bindings}function groupFleetRows(rows8){const grouped=new Map;for(const row of rows8){const group2=grouped.get(row.appId)??[];group2.push(row);grouped.set(row.appId,group2)}return grouped}function fleetAuthorityDigest(rows8){const evidence=rows8.map(row=>[row.appId,row.appName,row.authorityMode,row.hasBackend,row.desiredActivationId,row.desiredRuntimeState,row.desiredActivationEpoch,row.desiredNodeId,row.desiredNodeEpoch,row.environment,row.deploymentId,row.activationId,row.activationState,row.routeAckEpoch,row.activationEpoch,row.activationNodeId,row.nodeEpoch,row.artifactRef,row.sourceGenerationRef,row.runtimeGenerationRef,row.instanceId,row.instanceState,row.instanceNodeId,row.instanceNodeEpoch,row.instanceArtifactRef,row.instanceSourceGenerationRef,row.instanceRuntimeGenerationRef,row.leaseEpoch,row.port,row.readyContractHash]).sort((left,right)=>JSON.stringify(left).localeCompare(JSON.stringify(right)));return createHash55("sha256").update(JSON.stringify(evidence)).digest("hex")}async function queryFleetAuthorityRows(db){return await db.select(fleetSelection()).from(appRuntimeDesiredState).innerJoin(apps,eq26(apps.id,appRuntimeDesiredState.appId)).leftJoin(appDeploymentActivations,and23(eq26(appDeploymentActivations.id,appRuntimeDesiredState.desiredActivationId),eq26(appDeploymentActivations.appId,appRuntimeDesiredState.appId))).leftJoin(deployments,and23(eq26(deployments.id,appDeploymentActivations.deploymentId),eq26(deployments.appId,appRuntimeDesiredState.appId))).leftJoin(appRuntimeInstances,and23(eq26(appRuntimeInstances.activationId,appDeploymentActivations.id),eq26(appRuntimeInstances.deploymentId,appDeploymentActivations.deploymentId),eq26(appRuntimeInstances.appId,appRuntimeDesiredState.appId),eq26(appRuntimeInstances.state,"serving"))).where(eq26(appRuntimeDesiredState.authorityMode,"enforce"))}async function loadCanonicalTenantRouteFleetSnapshot(input2){const rows8=await queryFleetAuthorityRows(input2.db);const grouped=groupFleetRows(rows8);const bindings=[];const activationMismatchTargets=[];const blockedTargets=[];const removalTargets=[];for(const appRows of grouped.values()){const desired=appRows[0];if(desired.hasBackend&&desired.desiredRuntimeState==="serving"&&desired.desiredNodeId===input2.nodeId){const joinedRows=appRows.filter(row=>row.instanceId!==null);if(joinedRows.length===0){removalTargets.push({appId:desired.appId,appName:desired.appName});continue}try{bindings.push(bindingFromRows(joinedRows))}catch(error62){if(error62 instanceof Error&&error62.message==="ROUTE_BINDING_ACTIVATION_MISMATCH"){activationMismatchTargets.push({appId:desired.appId,appName:desired.appName});continue}blockedTargets.push({appId:desired.appId,appName:desired.appName,failureCode:error62 instanceof Error?error62.message:"RUNTIME_ROUTE_PROJECTION_STATE_AMBIGUOUS"});continue}}else{removalTargets.push({appId:desired.appId,appName:desired.appName})}}const appIds=[...grouped.keys()];const authorityDigestByAppId=Object.fromEntries(appIds.map(appId=>[String(appId),fleetAuthorityDigest(rows8.filter(row=>row.appId===appId))]));return{bindings,activationMismatchTargets,blockedTargets,removalTargets,authorityDigest:fleetAuthorityDigest(rows8),authorityDigestByAppId}}async function assertCanonicalTenantRouteFleetSnapshot(input2){const rows8=await queryFleetAuthorityRows(input2.db);if(input2.appIds&&input2.authorityDigestByAppId){for(const appId of[...new Set(input2.appIds)]){const expected=input2.authorityDigestByAppId[String(appId)];const current=fleetAuthorityDigest(rows8.filter(row=>row.appId===appId));if(expected!==current)throw new Error("RUNTIME_ROUTE_PROJECTION_AUTHORITY_CHANGED")}return}const currentDigest=fleetAuthorityDigest(rows8);if(currentDigest!==input2.authorityDigest){throw new Error("RUNTIME_ROUTE_PROJECTION_AUTHORITY_CHANGED")}}async function loadCanonicalTenantRouteRemovalTargets(input2){const rows8=await input2.db.select({appId:appRuntimeDesiredState.appId,appName:apps.name,desiredRuntimeState:appRuntimeDesiredState.desiredRuntimeState,nodeId:appRuntimeDesiredState.nodeId}).from(appRuntimeDesiredState).innerJoin(apps,eq26(apps.id,appRuntimeDesiredState.appId)).where(eq26(appRuntimeDesiredState.authorityMode,"enforce"));return rows8.filter(row=>row.desiredRuntimeState!=="serving"||row.nodeId!==input2.nodeId).map(({appId,appName})=>({appId,appName}))}var ROUTE_BINDING_NOT_SERVING_CODE;var init_runtime_route_binding_reader=__esm({"../platform/src/runtime-route-binding-reader.ts"(){"use strict";init_schema();init_runtime_route_binding_contract();ROUTE_BINDING_NOT_SERVING_CODE="ROUTE_BINDING_NOT_SERVING"}});async function observeBackendServing(input2){try{const binding=await(input2.loadRouteBindingImpl??loadCanonicalTenantRouteBinding)({db:input2.db,appId:input2.appId});return binding?{kind:"SERVING",binding}:{kind:"UNOBSERVABLE"}}catch(error62){const expectedAbsence=error62 instanceof Error&&error62.message===ROUTE_BINDING_NOT_SERVING_CODE;if(!expectedAbsence){console.warn(JSON.stringify({event:"backend_serving_lookup_unavailable",correlationId:input2.correlationId}))}return{kind:"UNOBSERVABLE"}}}function backendServingState(observation){return observation?.kind==="SERVING"?"PRESERVED":"UNKNOWN"}var init_deployment_backend_incumbent_serving=__esm({"../platform/src/deployment-backend-incumbent-serving.ts"(){"use strict";init_runtime_route_binding_reader()}});function crashedIncumbentServingFact(receipt){const codes=new Set(receipt?.warnings?.map(warning=>warning.code)??[]);if(codes.has(CRASHED_EXECUTOR_NEVER_SERVED_WARNING_CODE))return"NO";if(codes.has(CRASHED_EXECUTOR_SERVING_UNVERIFIED_WARNING_CODE))return"UNKNOWN";return"YES"}function isCrashedExecutorRetiredReceipt(receipt){return receipt?.warnings?.some(warning=>CRASHED_EXECUTOR_RETIRED_WARNING_CODES.has(warning.code))===true}function isActivationFenceRetiredReceipt(receipt){return receipt?.warnings?.some(warning=>warning.code===ACTIVATION_FENCE_RETIRED_WARNING_CODE)===true}function crashedExecutorInspectCommand(environment){return environment==="prod"?"gencow db:check --prod --inspect-state":"gencow db:check --inspect-state"}function crashedExecutorBaseSummary(fact){if(fact==="NO"){return"An earlier deployment crashed, so this one was closed as failed. No deployment had served this app, so serving was not changed, and new deployments are accepted."}if(fact==="UNKNOWN"){return"An earlier deployment crashed, so this one was closed as failed. Serving was left unchanged, and new deployments are accepted."}return"An earlier deployment crashed, so this one was closed as failed. The incumbent still serves this app, and new deployments are accepted."}function crashedExecutorRecoveryGuidance(input2){const base2=input2.activation?"This deployment stopped before it was activated and was closed as failed. Nothing it started is still running, serving is unchanged, and new deployments are accepted.":crashedExecutorBaseSummary(input2.incumbentServing);const inspectCommand=crashedExecutorInspectCommand(input2.environment);const statusCommand=`gencow deploy status --deployment ${input2.operationId}`;if(input2.ambiguous){return{summary:`${base2} Database outcome is uncertain: check the migration state before relying on the schema.`,retryCondition:`Do not repeat this operation. Run "${inspectCommand}" to confirm the migration state, then start a new deployment only to change the app.`,nextAction:{kind:"INSPECT_STATE",command:inspectCommand}}}return{summary:base2,retryCondition:`Do not repeat this operation. Check its status with "${statusCommand}" if needed; a new deployment is accepted to change the app.`,nextAction:{kind:"VIEW_STATUS",command:statusCommand}}}function buildCrashedStaleDeploymentResponse(input2){const{operation,currentReceipt,fallbackDiagnostic}=input2;if(!fallbackDiagnostic||!currentReceipt||!(isCrashedExecutorRetiredReceipt(currentReceipt)||isActivationFenceRetiredReceipt(currentReceipt))||input2.failureCode!==STALE_DEPLOYMENT_RECOVERED_CODE||input2.failureStage!=="controller"||input2.recoveryRequired||operation.environment==="static"||operation.status!=="failed"||operation.controlPlaneState!=="failed"||operation.executorState!=="failed"||currentReceipt.phase!=="failed"||currentReceipt.code!==input2.failureCode){return null}const guidance=crashedExecutorRecoveryGuidance({environment:operation.environment,operationId:operation.deploymentId,ambiguous:currentReceipt.databaseState==="RECOVERY_REQUIRED",activation:isActivationFenceRetiredReceipt(currentReceipt),incumbentServing:crashedIncumbentServingFact(currentReceipt)});return{status:409,body:{error:guidance.summary,code:input2.failureCode,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:input2.failureStage,databaseState:currentReceipt.databaseState,servingState:isActivationFenceRetiredReceipt(currentReceipt)?"UNCHANGED":"PRESERVED",retryClass:"platform-action",userAction:guidance.nextAction.kind,retryPrecondition:guidance.retryCondition,correlationId:operation.correlationId,appName:operation.appName,state:"failed",nextAction:guidance.nextAction,diagnostic:fallbackDiagnostic}}}var STALE_DEPLOYMENT_RECOVERED_CODE,CRASHED_EXECUTOR_RETIRED_WARNING_CODE,CRASHED_EXECUTOR_NEVER_SERVED_WARNING_CODE,CRASHED_EXECUTOR_SERVING_UNVERIFIED_WARNING_CODE,CRASHED_EXECUTOR_RETIRED_WARNING_CODES,ACTIVATION_FENCE_RETIRED_WARNING_CODE;var init_deployment_stale_crashed_presentation=__esm({"../platform/src/deployment-stale-crashed-presentation.ts"(){"use strict";STALE_DEPLOYMENT_RECOVERED_CODE="PLATFORM_STALE_DEPLOYMENT_RECOVERED";CRASHED_EXECUTOR_RETIRED_WARNING_CODE="PLATFORM_STALE_CRASHED_EXECUTOR_RETIRED";CRASHED_EXECUTOR_NEVER_SERVED_WARNING_CODE="PLATFORM_STALE_CRASHED_EXECUTOR_NEVER_SERVED";CRASHED_EXECUTOR_SERVING_UNVERIFIED_WARNING_CODE="PLATFORM_STALE_CRASHED_EXECUTOR_SERVING_UNVERIFIED";CRASHED_EXECUTOR_RETIRED_WARNING_CODES=new Set([CRASHED_EXECUTOR_RETIRED_WARNING_CODE,CRASHED_EXECUTOR_NEVER_SERVED_WARNING_CODE,CRASHED_EXECUTOR_SERVING_UNVERIFIED_WARNING_CODE]);ACTIVATION_FENCE_RETIRED_WARNING_CODE="PLATFORM_STALE_ACTIVATION_FENCE_RETIRED"}});function resolveStaleDeploymentNewDeploymentCommand(input2){if(input2.releaseBindingPresent===true&&input2.releaseEnvironment!=="dev"&&input2.releaseEnvironment!=="prod"){return null}const releaseEnvironment=resolveDeploymentReleaseEnvironment(input2);const component=input2.executionEnvironment==="static"?"static":input2.executionEnvironment==="dev"||input2.executionEnvironment==="prod"?"backend":null;if(component===null||!releaseBindingMatchesExecutionScope({component,executionEnvironment:input2.executionEnvironment,releaseEnvironment})){return null}if(releaseEnvironment==="prod")return"gencow deploy --prod";if(releaseEnvironment==="dev")return"gencow deploy";return null}function buildPublicDeploymentExecutorDiagnostic(input2){const policy=resolveStoredDeploymentFailurePolicy(input2.stage,input2.code);const rootCauseClass=publicRoutePrepareRootCauseClass({stage:input2.stage,code:input2.code,stored:input2.receipt.rootCauseClass});const candidateCauseCode=publicCandidateCauseCode({stage:input2.stage,code:input2.code,stored:input2.receipt.candidateCauseCode});const candidateHealthObservation=publicCandidateHealthObservation({code:input2.code,stored:input2.receipt.candidateHealthObservation});const routeTargetRejections=publicRouteTargetRejections({stage:input2.stage,code:input2.code,stored:input2.receipt.routeTargetRejections});const migrationDiagnostic=input2.code!=="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.receipt.diagnostic?.code===input2.code&&input2.receipt.diagnostic.correlationId===input2.correlationId?input2.receipt.diagnostic:void 0;const baseSelfService=buildPublicSelfServiceDiagnostic({code:input2.code,stage:input2.stage,correlationId:input2.correlationId,operationId:input2.operationId,databaseState:input2.receipt.databaseState,requestedAction:migrationDiagnostic?.nextAction.kind??(input2.recoveryRequired?"OPERATOR_ACTION":policy.userAction),reasonCode:migrationDiagnostic?.reason.code??input2.code.toLowerCase(),reasonSummary:input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.routeRetryReadiness?.reason==="READY"?"The failed static deployment remains terminal; route retry is now safe for this app.":input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.routeRetryReadiness?.reason==="ALREADY_RECOVERED"?"The failed static deployment remains terminal; a later static deployment now serves this app.":input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.routeRetryReadiness?.reason==="SERVING_CHANGED"?"The failed static deployment's content is live, but its record is closed as failed. No retry is needed.":migrationDiagnostic?.reason.summary??policy.error,incumbentServing:input2.incumbentServing,routeRetryReadiness:input2.routeRetryReadiness,operationState:input2.receipt.phase==="recovery_required"?"BLOCKED":input2.receipt.phase==="completed"?"COMPLETED":input2.receipt.phase==="failed"?"FAILED":"PENDING"});const sourceRuntimeDiagnostic=!input2.recoveryRequired&&(input2.receipt.databaseState==="NOT_ENTERED"||input2.receipt.databaseState==="UNCHANGED")?buildRestoreSourceRuntimeDiagnostic(input2):null;const stopConfigurationDiagnostic=!input2.recoveryRequired&&(input2.receipt.databaseState==="NOT_ENTERED"||input2.receipt.databaseState==="UNCHANGED")?buildRuntimeStopConfigurationDiagnostic(input2):null;const newDeploymentCommand=resolveStaleDeploymentNewDeploymentCommand({executionEnvironment:input2.environment,releaseEnvironment:input2.releaseEnvironment,releaseBindingPresent:input2.releaseBindingPresent});const crashedGuidance=!input2.recoveryRequired&&input2.environment!=="static"&&input2.code==="PLATFORM_STALE_DEPLOYMENT_RECOVERED"&&input2.stage==="controller"&&(isCrashedExecutorRetiredReceipt(input2.receipt)||isActivationFenceRetiredReceipt(input2.receipt))?crashedExecutorRecoveryGuidance({activation:isActivationFenceRetiredReceipt(input2.receipt),environment:input2.environment,operationId:input2.operationId,ambiguous:input2.receipt.databaseState==="RECOVERY_REQUIRED",incumbentServing:crashedIncumbentServingFact(input2.receipt)}):null;const settledStaleDeployment=crashedGuidance===null&&newDeploymentCommand!==null&&input2.code==="PLATFORM_STALE_DEPLOYMENT_RECOVERED"&&input2.receipt.phase==="failed"&&input2.receipt.code==="PLATFORM_STALE_DEPLOYMENT_RECOVERED"&&(input2.receipt.databaseState==="APPLIED"||input2.receipt.databaseState==="UNCHANGED")&&!input2.recoveryRequired&&(input2.incumbentServing==="PRESERVED"||input2.incumbentServing==="NOT_APPLICABLE"&&input2.routeRetryReadiness?.incumbentServing==="NONE_TO_PRESERVE");const staleServingCondition=input2.incumbentServing==="NOT_APPLICABLE"?"no static site was live before this operation, so serving is unchanged":"the incumbent serving deployment is preserved";const staleServingSummary=input2.incumbentServing==="NOT_APPLICABLE"?"no static site was live before it, so your serving is unchanged":"the current serving deployment is preserved";const committedRouteBlocked=newDeploymentCommand!==null&&input2.environment!=="static"&&input2.recoveryRequired&&input2.stage==="route"&&input2.code===COMMITTED_ROUTE_BLOCKED_CODE&&isCommittedRouteBlockedReceipt(input2.receipt);const supersededByNewerCommit=!input2.recoveryRequired&&input2.environment!=="static"&&input2.code===SUPERSEDED_BY_NEWER_COMMIT_CODE&&isSupersededByNewerCommitReceipt(input2.receipt);const databaseOutcomeSummary=input2.receipt.databaseState==="APPLIED"?"applied database changes are preserved":"the database was left unchanged";const terminalDeferral=!input2.recoveryRequired&&input2.receipt.phase==="failed"&&isDeploymentExecutorDeferralTerminalCode(input2.code)&&(input2.receipt.databaseState==="APPLIED"||input2.receipt.databaseState==="UNCHANGED"||input2.receipt.databaseState==="NOT_ENTERED");const releaseAttemptClosed=input2.code===DEPLOYMENT_EXECUTOR_RELEASE_ATTEMPT_CLOSED;const releaseBindingTerminal=releaseAttemptClosed||input2.code===DEPLOYMENT_EXECUTOR_RELEASE_BINDING_INVALID;const platformToolchainUnavailable=migrationDiagnostic?.reason.code===PLATFORM_SCHEMA_TOOLCHAIN_UNAVAILABLE_REASON;const databaseTrustInvalid=input2.code==="RUNTIME_CANDIDATE_DATABASE_TRUST_INVALID"&&input2.stage==="candidate"&&!input2.recoveryRequired;const databaseTrustDiagnostic=databaseTrustInvalid?{...baseSelfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:"Retry only after the Platform restores the managed database trust file and sandbox profile binding, then confirms this operation is terminal."},action:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:["No app source, migration, or tenant database change is required; preserve the incumbent deployment."]},reason:{code:"runtime_candidate_database_trust_invalid",summary:"The Platform could not bind the managed database trust file to the candidate sandbox. The incumbent deployment and tenant data are preserved."}}:null;const candidateRouteEpochConflict=input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.stage==="candidate"&&!input2.recoveryRequired&&input2.receipt.phase==="failed";const candidateRouteEpochConflictDiagnostic=candidateRouteEpochConflict?{...baseSelfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:`This operation is terminal and was not activated, and ${databaseOutcomeSummary}. A previous route change for this app is still being settled by the Platform; check this operation, then start a new deployment.`},action:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:["No change to your source is needed; do not resume this failed operation."]},reason:{code:"app_serving_route_epoch_conflict",summary:"A previous route change for this app is still being settled by the Platform; your source is not the cause. Check the deployment status, then repeat the same deployment."}}:null;const selfService=supersededByNewerCommit?{...baseSelfService,responsibility:"TRANSIENT_DEPENDENCY",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:`A newer committed deployment already serves this app, and ${databaseOutcomeSummary}. No action is needed for this operation; start a new deployment only to change the app.`},action:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:[newDeploymentCommand?`Do not retry this operation; to change the app, start a new deployment with ${newDeploymentCommand}.`:"Do not retry this operation; a newer deployment already serves the app."]},reason:{code:"deployment_superseded_by_newer_commit",summary:"This deployment was superseded by a newer committed deployment, which serves the app. Serving and data are unchanged."}}:committedRouteBlocked?{...baseSelfService,responsibility:"TRANSIENT_DEPENDENCY",retry:{allowedNow:true,policy:"IMMEDIATE",condition:`This deployment is committed and keeps serving unchanged, and ${databaseOutcomeSummary}. Its route acknowledgement did not converge in the bounded window; a new deployment can start now and supersedes it.`},action:{kind:"RETRY",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:[`Do not resume or retry this operation; start a new deployment with ${newDeploymentCommand}.`]},reason:{code:"committed_route_convergence_blocked",summary:"The deployment is committed and serving is unchanged, but its route acknowledgement did not converge in time. Start a new deployment to supersede it."}}:terminalDeferral&&releaseBindingTerminal?{...baseSelfService,responsibility:releaseAttemptClosed?"TRANSIENT_DEPENDENCY":"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:`This operation is terminal and was never started, so no activation happened and ${databaseOutcomeSummary}. Retrying the same deployment cannot succeed; check this operation, then start a new deployment.`},action:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:[newDeploymentCommand?`Do not retry this operation; start a new deployment with ${newDeploymentCommand}.`:"Do not retry this operation; start a new deployment."]},reason:releaseAttemptClosed?{code:"release_attempt_closed_before_start",summary:`The release attempt was ended before the Platform started this deployment (for example the publisher stopped waiting while the executor was busy). Nothing was activated and ${databaseOutcomeSummary}.`}:{code:"release_binding_mismatch",summary:`The release this deployment belonged to does not match it, so the Platform stopped it before starting. Nothing was activated and ${databaseOutcomeSummary}.`}}:terminalDeferral?{...baseSelfService,retry:{allowedNow:false,policy:"AFTER_STATUS",condition:routeTargetRejections?`This operation is terminal and was not activated, and ${databaseOutcomeSummary}. A Platform route target rejected it (see the route target rejections); check this operation, then start a new deployment once app admission is open.`:`This operation is terminal and was not activated, and ${databaseOutcomeSummary}. Check this operation, then start a new deployment once app admission is open.`},action:{kind:baseSelfService.action.kind,command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:["Do not resume or retry this stopped operation; start a new deployment instead."]}}:crashedGuidance?{...baseSelfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:crashedGuidance.retryCondition},action:crashedGuidance.nextAction,reason:{code:isActivationFenceRetiredReceipt(input2.receipt)?"stale_activation_fence_retired":"stale_crashed_executor_retired",summary:crashedGuidance.summary}}:settledStaleDeployment?{...baseSelfService,responsibility:"TRANSIENT_DEPENDENCY",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:`This operation is terminal, ${staleServingCondition}, and ${databaseOutcomeSummary}. Check this operation, then start a new deployment only after app admission is open.`},action:{kind:"RETRY",command:`gencow deploy status --deployment ${input2.operationId}`,prerequisites:["Do not resume or retry this failed operation; wait until app admission is open, then start a new deployment."]},reason:{code:"stale_deployment_recovered",summary:`The stale deployment is terminal, ${staleServingSummary}, and ${databaseOutcomeSummary}. A new deployment can start after app admission opens.`}}:databaseTrustDiagnostic??candidateRouteEpochConflictDiagnostic??stopConfigurationDiagnostic??buildNpmDependencyReplayDiagnostic({...input2,databaseState:input2.receipt.databaseState})??sourceRuntimeDiagnostic??(migrationDiagnostic?{...baseSelfService,retry:{allowedNow:migrationDiagnostic.safeToRetryNow,policy:migrationDiagnostic.retryPolicy==="IDEMPOTENT_NOOP"||platformToolchainUnavailable?"AFTER_STATUS":migrationDiagnostic.retryPolicy,condition:migrationDiagnostic.retryCondition??"Check the canonical migration state before starting another operation.",...migrationDiagnostic.retryAfterSeconds===void 0?{}:{afterSeconds:migrationDiagnostic.retryAfterSeconds}},action:{kind:baseSelfService.action.kind,...platformToolchainUnavailable?{command:`gencow deploy status --deployment ${input2.operationId}`}:baseSelfService.action.kind==="INSPECT_STATE"?{command:`gencow db:check${input2.environment==="prod"?" --prod":""} --inspect-state`}:migrationDiagnostic.nextAction.command?{command:migrationDiagnostic.nextAction.command}:{},...platformToolchainUnavailable?{prerequisites:["No edit to your schema or bundle is needed; run the same deploy again after the Platform restores its schema toolchain."]}:baseSelfService.action.prerequisites?{prerequisites:baseSelfService.action.prerequisites}:{}},reason:migrationDiagnostic.reason,forbiddenActions:migrationDiagnostic.forbiddenActions}:baseSelfService);const platformAction2=selfService.responsibility!=="USER_ACTION_REQUIRED";return{code:input2.code,databaseState:input2.receipt.databaseState,failureClass:platformAction2?"PLATFORM_ACTION_REQUIRED":"USER_FIXABLE",retryability:supersededByNewerCommit?"NOT_REQUIRED":committedRouteBlocked?"RETRY_NEW_DEPLOYMENT":settledStaleDeployment||terminalDeferral||crashedGuidance!==null?"NEW_DEPLOYMENT_AFTER_STATUS":input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.routeRetryReadiness?.reason==="ALREADY_RECOVERED"?"NOT_REQUIRED":input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&input2.routeRetryReadiness?.reason==="SERVING_CHANGED"?"NOT_REQUIRED":input2.routeRetryReadiness?.retryReady===true&&input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"?"RETRY_NEW_DEPLOYMENT":input2.code==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&selfService.retry.policy==="AFTER_DELAY"?"AFTER_DELAY":!input2.recoveryRequired&&policy.retryClass==="retryable-infra"?"RETRY_SAME_DEPLOYMENT":platformAction2?"AFTER_PLATFORM_REPAIR":"AFTER_EDIT",action:selfService.action.kind,...(settledStaleDeployment||terminalDeferral||committedRouteBlocked)&&newDeploymentCommand?{newDeploymentCommand}:{},observedState:input2.receipt.phase,expectedState:"completed",reasonCode:input2.code.toLowerCase(),stage:input2.stage,selfService,...rootCauseClass?{rootCauseClass}:{},...candidateCauseCode?{candidateCauseCode}:{},...candidateHealthObservation?{candidateHealthObservation}:{},...routeTargetRejections?{routeTargetRejections}:{},...migrationDiagnostic?{migration:migrationDiagnostic}:{}}}var init_deployment_executor_public_diagnostic=__esm({"../platform/src/deployment-executor-public-diagnostic.ts"(){"use strict";init_deployment_candidate_health_observation();init_runtime_stop_configuration_diagnostic();init_restore_source_runtime_diagnostic();init_npm_dependency_replay_diagnostic();init_deployment_failure_contract();init_app_serving_route_target_rejection();init_deployment_candidate_cause();init_deployment_route_prepare_root_cause();init_canonical_schema_proof_missing_module();init_public_self_service_diagnostic();init_deployment_committed_route_contract();init_deployment_stale_crashed_presentation();init_deployment_release_scope()}});function buildPublicFailureChain(input2){const primaryFailure={code:SAFE_CODE3.test(input2.primaryCode)?input2.primaryCode:"DEPLOYMENT_FAILED",stage:input2.primaryStage,correlationId:input2.correlationId};const secondaryCode=input2.secondaryCode&&SAFE_CODE3.test(input2.secondaryCode)?input2.secondaryCode:null;return{primaryFailure,...secondaryCode?{cascade:{code:secondaryCode,causedBy:primaryFailure.code}}:{}}}var SAFE_CODE3;var init_deployment_failure_public_diagnostic=__esm({"../platform/src/deployment-failure-public-diagnostic.ts"(){"use strict";SAFE_CODE3=/^[A-Z][A-Z0-9_]{2,99}$/u}});function servingRouteEnvironment(env){const tier=optionalValue(env.GENCOW_DEPLOY_TIER);if(tier==="dev"||tier==="qc"||tier==="prod")return tier;return optionalValue(env.GENCOW_SERVING_ROUTE_PUBLICATION_ENVIRONMENT)}function optionalValue(value2){const normalized=value2?.trim()??"";return normalized||null}function positiveInteger3(value2){const parsed=Number(value2);return Number.isSafeInteger(parsed)&&parsed>0?parsed:null}function releaseMode(value2){const normalized=value2?.trim().toLowerCase();if(normalized==="1"||normalized==="true")return"all";return normalized==="allowlist"?"allowlist":"disabled"}function parseAppReleaseRuntimeConfig(env){return Object.freeze({executor:Object.freeze({appsDir:optionalValue(env.GENCOW_APPS_DIR),nodeId:optionalValue(env.GENCOW_NODE_ID)?.toLowerCase()??null,spoolDir:optionalValue(env.GENCOW_DEPLOYMENT_EXECUTOR_SPOOL_DIR)}),staticOrigin:Object.freeze({artifactRoot:optionalValue(env.GENCOW_STATIC_ORIGIN_ARTIFACT_ROOT),stageEnabled:env.GENCOW_STATIC_ORIGIN_STAGE_ENABLED==="true"}),release:Object.freeze({mode:releaseMode(env.GENCOW_RELEASE_VERSIONS_ENABLED),allowlist:Object.freeze((env.GENCOW_RELEASE_VERSIONS_ALLOWLIST??"").split(",").map(value2=>value2.trim()).filter(Boolean)),quotaBytes:positiveInteger3(env.GENCOW_RELEASE_STORAGE_QUOTA_BYTES),allowFilesystem:env.GENCOW_RELEASE_STORAGE_ALLOW_FILESYSTEM==="1",objectsDir:optionalValue(env.GENCOW_RELEASE_OBJECTS_DIR)}),storage:Object.freeze({azureAccountName:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_ACCOUNT_NAME),azureContainer:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_CONTAINER),azureEndpoint:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_ENDPOINT),azureAuth:env.GENCOW_PLATFORM_STORAGE_AZURE_AUTH==="client_secret"?"client_secret":"managed_identity",azureClientId:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_CLIENT_ID),azureTenantId:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_TENANT_ID),azurePrefix:optionalValue(env.GENCOW_PLATFORM_STORAGE_AZURE_PREFIX)?.replace(/\/+$/u,"")||null}),servingRoute:Object.freeze({publicationMode:optionalValue(env.GENCOW_SERVING_ROUTE_PUBLICATION_MODE)??"off",environment:servingRouteEnvironment(env),appAllowlist:optionalValue(env.GENCOW_SERVING_ROUTE_PUBLICATION_APP_ALLOWLIST),topologyRevision:optionalValue(env.GENCOW_SERVING_ROUTE_TOPOLOGY_REVISION),upsertTargetSetId:optionalValue(env.GENCOW_SERVING_ROUTE_UPSERT_TARGET_SET_ID),tombstoneTargetSetId:optionalValue(env.GENCOW_SERVING_ROUTE_TOMBSTONE_TARGET_SET_ID),artifactQuotaBytes:positiveInteger3(env.GENCOW_SERVING_ROUTE_ARTIFACT_QUOTA_BYTES),baseDomain:optionalValue(env.BASE_DOMAIN)})})}function parseAppReleaseProtectedSecrets(env){return Object.freeze({azureClientSecret:env.GENCOW_PLATFORM_STORAGE_AZURE_CLIENT_SECRET||null})}function isReleaseControlPlane(env){return env.IS_PLATFORM==="true"||env.GENCOW_DEPLOYMENT_EXECUTOR_ENABLED==="true"&&env.GENCOW_DEPLOYMENT_EXECUTOR_MODE==="dedicated"||env.GENCOW_BUILDER_WORKER_ENABLED==="true"&&env.GENCOW_BUILDER_WORKER_MODE==="dedicated"}function captureAppReleaseRuntimeEnv(env=process.env){const host=globalThis;if(host[SNAPSHOT_KEY])return host[SNAPSHOT_KEY];if(!isReleaseControlPlane(env))return null;const snapshot=Object.freeze({config:parseAppReleaseRuntimeConfig(env),protectedSecrets:parseAppReleaseProtectedSecrets(env)});host[SNAPSHOT_KEY]=snapshot;return snapshot}function appReleaseRuntimeConfig(explicit){if(explicit)return parseAppReleaseRuntimeConfig(explicit);return globalThis[SNAPSHOT_KEY]?.config??parseAppReleaseRuntimeConfig(process.env)}var SNAPSHOT_KEY,CAPTURE_SNAPSHOT_KEY;var init_app_release_runtime_env=__esm({"../platform/src/app-release-runtime-env.ts"(){"use strict";SNAPSHOT_KEY="__gencowAppReleaseRuntimeEnvSnapshot";CAPTURE_SNAPSHOT_KEY="__gencowCaptureAppReleaseRuntimeEnvSnapshot";globalThis[CAPTURE_SNAPSHOT_KEY]=captureAppReleaseRuntimeEnv}});import{createHash as createHash56}from"node:crypto";var RELEASE_OBJECT_TIERS,RELEASE_OBJECT_KINDS,RELEASE_OBJECT_REF;var init_release_object_store=__esm({"../platform/src/release-object-store.ts"(){"use strict";RELEASE_OBJECT_TIERS=["local","dev","qc","prod"];RELEASE_OBJECT_KINDS=["source","backend_artifact","static_artifact"];RELEASE_OBJECT_REF=new RegExp(`^release-object-v1\\.(${RELEASE_OBJECT_TIERS.join("|")})\\.([a-f0-9]{64})\\.([a-f0-9]{64})\\.([a-f0-9]{64})\\.(${RELEASE_OBJECT_KINDS.join("|")})\\.([a-f0-9]{64})$`,"u")}});import{createHash as createHash57,randomUUID as randomUUID37}from"node:crypto";import{createRequire as createRequire3}from"node:module";import{createReadStream as createReadStream2,createWriteStream}from"node:fs";import{chmod as chmod5,mkdir as mkdir8,rename as rename4,rm as rm4}from"node:fs/promises";import{dirname as dirname15,resolve as resolve62}from"node:path";import{Readable as Readable5}from"node:stream";import{pipeline as pipeline3}from"node:stream/promises";var init_release_object_store_azure=__esm({"../platform/src/release-object-store-azure.ts"(){"use strict";init_release_object_store()}});import{createHash as createHash58,randomUUID as randomUUID38}from"node:crypto";import{constants,createReadStream as createReadStream3}from"node:fs";import{chmod as chmod6,copyFile,link as link3,mkdir as mkdir9,open as open6,rename as rename5,rm as rm5,stat as stat8,writeFile as writeFile5}from"node:fs/promises";import{dirname as dirname16,join as join17,resolve as resolve63}from"node:path";import{Readable as Readable6}from"node:stream";var init_release_object_store_filesystem=__esm({"../platform/src/release-object-store-filesystem.ts"(){"use strict";init_release_object_store();init_release_object_store()}});import{resolve as resolve64}from"node:path";var init_release_object_store_factory=__esm({"../platform/src/release-object-store-factory.ts"(){"use strict";init_app_release_runtime_env();init_release_object_store_azure();init_release_object_store_filesystem()}});import{extname as extname8,isAbsolute as isAbsolute12,relative as relative13,resolve as resolve65}from"path";import{readFile as readFile6,stat as stat9}from"fs/promises";function isSafeSameOriginPath2(value2){if(!value2.startsWith("/")||value2.startsWith("//"))return false;if(/[\u0000-\u001f\u007f\\?#]/.test(value2))return false;try{const decoded=decodeURIComponent(value2);if(!decoded.startsWith("/")||decoded.startsWith("//")||/[\u0000-\u001f\u007f\\?#]/.test(decoded)){return false}return!decoded.split("/").some(segment=>segment==="."||segment==="..")}catch{return false}}function parseStaticRedirects2(source){const rules=[];for(const rawLine of source.split(/\r?\n/)){const line=rawLine.trim();if(!line||line.startsWith("#"))continue;const[from,to2,statusText,...extra]=line.split(/\s+/);const statusCode=Number(statusText);if(extra.length>0||!from||!to2||!ALLOWED_STATUSES2.has(statusCode)||!isSafeSameOriginPath2(from.replace(/\*$/,"safe"))||!isSafeSameOriginPath2(to2)){continue}const wildcard=from.endsWith("*");if(wildcard&&!from.endsWith("/*")||!wildcard&&from.includes("*"))continue;rules.push({from,to:to2,statusCode,wildcard})}return rules}var ALLOWED_STATUSES2;var init_static_redirects2=__esm({"../server/src/static-redirects.ts"(){"use strict";ALLOWED_STATUSES2=new Set([200,301,302,307,308,404])}});import{extname as extname9,isAbsolute as isAbsolute13,relative as relative14,resolve as resolve66}from"path";function hashLeafRule2(token){return`${HASH_LEAF_PREFIX2}${token}${HASH_LEAF_SUFFIX2}`}var STATIC_IMMUTABLE_EXTENSIONS2,STATIC_DOCUMENT_EXTENSIONS2,STATIC_NO_FALLBACK_EXTENSIONS2,IMMUTABLE_EXTENSION_ALTERNATION2,HASH_LEAF_PREFIX2,HASH_LEAF_SUFFIX2,STATIC_CONTENT_HASH_RULES2,staticContentHashRegexGroups2,staticNoFallbackExtensionSet2;var init_static_file_routing2=__esm({"../server/src/static-file-routing.ts"(){"use strict";init_static_redirects2();STATIC_IMMUTABLE_EXTENSIONS2=Object.freeze([".avif",".br",".css",".csv",".eot",".gif",".gz",".ico",".jpeg",".jpg",".js",".json",".m4a",".map",".mjs",".mov",".mp3",".mp4",".ogg",".pdf",".png",".svg",".tsv",".ttf",".txt",".wasm",".wav",".webm",".webmanifest",".webp",".woff",".woff2",".xml",".zip"]);STATIC_DOCUMENT_EXTENSIONS2=Object.freeze([".htm",".html"]);STATIC_NO_FALLBACK_EXTENSIONS2=Object.freeze([...STATIC_DOCUMENT_EXTENSIONS2,...STATIC_IMMUTABLE_EXTENSIONS2]);IMMUTABLE_EXTENSION_ALTERNATION2=STATIC_IMMUTABLE_EXTENSIONS2.map(extension=>extension.slice(1)).join("|");HASH_LEAF_PREFIX2="(?:^|/)[^/]+[-.]";HASH_LEAF_SUFFIX2=`\\.(?:${IMMUTABLE_EXTENSION_ALTERNATION2})$`;STATIC_CONTENT_HASH_RULES2=Object.freeze([{require:[hashLeafRule2("[0-9a-f]{10,}"),hashLeafRule2("(?:[0-9a-f]*[0-9]){2}[0-9a-f]*"),hashLeafRule2("(?:[0-9a-f]*[a-f]){2}[0-9a-f]*")],forbid:[]},{require:[hashLeafRule2("[A-Za-z0-9]{8}"),hashLeafRule2("(?:[A-Za-z0-9]*[0-9]){2}[A-Za-z0-9]*"),hashLeafRule2("(?:[A-Za-z0-9]*[A-Z]){2}[A-Za-z0-9]*"),hashLeafRule2("(?:[A-Za-z0-9]*[a-z]){2}[A-Za-z0-9]*")],forbid:[hashLeafRule2("[A-Za-z0-9]*[0-9]{4}[A-Za-z0-9]*")]},{require:[hashLeafRule2("[A-Z0-9]{8,}"),hashLeafRule2("[A-Z0-9]*[0-9][A-Z0-9]*"),hashLeafRule2("[A-Z0-9]*[A-Z][A-Z0-9]*")],forbid:[hashLeafRule2("[A-Z0-9]*[0-9]{4}[A-Z0-9]*")]}]);staticContentHashRegexGroups2=STATIC_CONTENT_HASH_RULES2.map(group2=>({require:group2.require.map(source=>new RegExp(source)),forbid:group2.forbid.map(source=>new RegExp(source))}));staticNoFallbackExtensionSet2=new Set(STATIC_NO_FALLBACK_EXTENSIONS2)}});import{createHash as createHash59}from"node:crypto";import{lstat as lstat3,readFile as readFile7,readdir as readdir5}from"node:fs/promises";import{isAbsolute as isAbsolute14,join as join18,relative as relative15,resolve as resolve67}from"node:path";function fail16(code){throw new Error(code)}function ownedByRootOrProcess(uid){const processUid=process.getuid?.();return uid===0||processUid===void 0||uid===processUid}function validateOriginRoot(input2){if(!isAbsolute14(input2)||input2.includes("\0"))fail16("STATIC_ORIGIN_ROOT_INVALID");const normalized=resolve67(input2);if(normalized==="/")fail16("STATIC_ORIGIN_ROOT_INVALID");return normalized}function validateLimits(input2){const limits={...DEFAULT_STATIC_ORIGIN_LIMITS,...input2};if(!Number.isSafeInteger(limits.maxFiles)||limits.maxFiles<1||limits.maxFiles>1e6||!Number.isSafeInteger(limits.maxBytes)||limits.maxBytes<1||limits.maxBytes>1024*1024*1024*1024||!Number.isSafeInteger(limits.maxFileBytes)||limits.maxFileBytes<1||limits.maxFileBytes>limits.maxBytes){fail16("STATIC_ORIGIN_LIMIT_INVALID")}return limits}function staticOriginAppScope(appInstanceId){if(!REFERENCE4.test(appInstanceId))fail16("STATIC_ORIGIN_APP_INSTANCE_INVALID");return createHash59("sha256").update(JSON.stringify(["app-instance",appInstanceId])).digest("hex")}function resolveStaticOriginGeneration(input2){const originRoot=validateOriginRoot(input2.originRoot);const parsed=STATIC_GENERATION_REF2.exec(input2.generationRef);if(!parsed)fail16("STATIC_ORIGIN_GENERATION_REF_INVALID");const generationSha256=parsed[5];if(!SHA25610.test(input2.integritySha256)||input2.integritySha256!==generationSha256){fail16("STATIC_ORIGIN_INTEGRITY_MISMATCH")}const scope=staticOriginAppScope(input2.appInstanceId);const scopeRoot=resolve67(originRoot,"generations",scope);const generationPath=resolve67(scopeRoot,generationSha256);const readyMarkerPath=resolve67(scopeRoot,`${generationSha256}.ready`);if(relative15(scopeRoot,generationPath)!==generationSha256||relative15(scopeRoot,readyMarkerPath)!==`${generationSha256}.ready`){fail16("STATIC_ORIGIN_GENERATION_PATH_INVALID")}return{originRoot,appScope:scope,generationSha256,generationPath,readyMarkerPath}}async function assertSafeParent(path5){const info2=await lstat3(path5).catch(()=>null);if(!info2||!info2.isDirectory()||info2.isSymbolicLink()||(info2.mode&18)!==0||!ownedByRootOrProcess(info2.uid)){fail16("STATIC_ORIGIN_ROOT_UNSAFE")}}async function assertSafeAppScope(path5){const info2=await lstat3(path5).catch(()=>null);if(!info2)fail16("STATIC_ORIGIN_GENERATION_UNAVAILABLE");if(!info2.isDirectory()||info2.isSymbolicLink()||(info2.mode&18)!==0||!ownedByRootOrProcess(info2.uid)){fail16("STATIC_ORIGIN_GENERATION_ENTRY_UNSAFE")}}function safeRelativeEntry(relativePath){const segments=relativePath.split("/");return segments.every((segment,index27)=>{if(!segment||/[\u0000-\u001f\u007f\\]/u.test(segment))return false;if(!segment.startsWith("."))return true;return index27===0&&segment===".well-known"})}async function inspectTree(generationPath,currentPath,limits,totals2){for(const entry of await readdir5(currentPath,{withFileTypes:true})){const entryPath=join18(currentPath,entry.name);const relativePath=relative15(generationPath,entryPath);if(!safeRelativeEntry(relativePath))fail16("STATIC_ORIGIN_GENERATION_ENTRY_UNSAFE");const info2=await lstat3(entryPath);if(info2.isSymbolicLink()||!ownedByRootOrProcess(info2.uid)){fail16("STATIC_ORIGIN_GENERATION_ENTRY_UNSAFE")}if(info2.isDirectory()){if((info2.mode&511)!==365)fail16("STATIC_ORIGIN_GENERATION_UNSEALED");await inspectTree(generationPath,entryPath,limits,totals2);continue}if(!info2.isFile()||info2.nlink!==1)fail16("STATIC_ORIGIN_GENERATION_ENTRY_UNSAFE");if((info2.mode&511)!==292)fail16("STATIC_ORIGIN_GENERATION_UNSEALED");totals2.fileCount+=1;totals2.bytes+=info2.size;if(info2.size>limits.maxFileBytes||totals2.fileCount>limits.maxFiles||totals2.bytes>limits.maxBytes){fail16("STATIC_ORIGIN_GENERATION_LIMIT_EXCEEDED")}}}async function sealedGenerationRootFingerprint(generation){await assertSafeParent(generation.originRoot);await assertSafeParent(join18(generation.originRoot,"generations"));await assertSafeAppScope(join18(generation.originRoot,"generations",generation.appScope));const generationInfo=await lstat3(generation.generationPath).catch(()=>null);if(!generationInfo||!generationInfo.isDirectory()||generationInfo.isSymbolicLink()||!ownedByRootOrProcess(generationInfo.uid)){fail16("STATIC_ORIGIN_GENERATION_UNAVAILABLE")}if((generationInfo.mode&511)!==365)fail16("STATIC_ORIGIN_GENERATION_UNSEALED");const readyInfo=await lstat3(generation.readyMarkerPath).catch(()=>null);if(!readyInfo||!readyInfo.isFile()||readyInfo.isSymbolicLink()||readyInfo.nlink!==1||(readyInfo.mode&511)!==292||!ownedByRootOrProcess(readyInfo.uid)){fail16("STATIC_ORIGIN_READY_MARKER_INVALID")}return[generationInfo,readyInfo].map(info2=>[info2.dev,info2.ino,info2.mode,info2.uid,info2.nlink,info2.mtimeMs,info2.ctimeMs].join(":")).join("|")}async function inspectSealedStaticOriginGenerationIdentity(input2){const generation=resolveStaticOriginGeneration(input2);return{generation,fingerprint:await sealedGenerationRootFingerprint(generation)}}async function verifySealedStaticOriginGenerationWithIdentity(input2){const generation=resolveStaticOriginGeneration(input2);const limits=validateLimits(input2.limits);const fingerprint4=await sealedGenerationRootFingerprint(generation);if(await readFile7(generation.readyMarkerPath,"utf8")!==generation.generationSha256){fail16("STATIC_ORIGIN_READY_MARKER_INVALID")}const totals2={fileCount:0,bytes:0};await inspectTree(generation.generationPath,generation.generationPath,limits,totals2);if(await sealedGenerationRootFingerprint(generation)!==fingerprint4){fail16("STATIC_ORIGIN_GENERATION_UNSEALED")}return{verified:{...generation,...totals2},fingerprint:fingerprint4}}async function verifySealedStaticOriginGeneration(input2){return(await verifySealedStaticOriginGenerationWithIdentity(input2)).verified}var SHA25610,REFERENCE4,STATIC_GENERATION_REF2,DEFAULT_STATIC_ORIGIN_LIMITS;var init_static_origin_layout=__esm({"../static-origin/src/static-origin-layout.ts"(){"use strict";SHA25610=/^[a-f0-9]{64}$/u;REFERENCE4=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;STATIC_GENERATION_REF2=/^release-object-v1\.(local|dev|qc|prod)\.([a-f0-9]{64})\.([a-f0-9]{64})\.([a-f0-9]{64})\.static_artifact\.([a-f0-9]{64})$/u;DEFAULT_STATIC_ORIGIN_LIMITS=Object.freeze({maxFiles:1e4,maxBytes:200*1024*1024,maxFileBytes:100*1024*1024})}});import{resolve as resolve68}from"node:path";function key(input2){return JSON.stringify([input2.appInstanceId,input2.generationRef,input2.integritySha256])}var StaticOriginVerifiedGenerationCache;var init_static_origin_generation_cache=__esm({"../static-origin/src/static-origin-generation-cache.ts"(){"use strict";init_static_origin_layout();StaticOriginVerifiedGenerationCache=class{entries=new Map;fullVerificationCount=0;identityCheckCount=0;originRoot;constructor(originRoot){this.originRoot=resolve68(originRoot)}get stats(){return{entries:this.entries.size,fullVerifications:this.fullVerificationCount,identityChecks:this.identityCheckCount}}async resolve(input2,derive){const request={originRoot:this.originRoot,...input2};const cacheKey=key(input2);const cached2=this.entries.get(cacheKey);if(cached2){this.identityCheckCount+=1;try{const identity2=await inspectSealedStaticOriginGenerationIdentity(request);if(identity2.fingerprint===cached2.fingerprint){return{verified:cached2.verified,derived:cached2.derived}}}catch(error62){this.entries.delete(cacheKey);throw error62}this.entries.delete(cacheKey)}this.fullVerificationCount+=1;const{verified,fingerprint:fingerprint4}=await verifySealedStaticOriginGenerationWithIdentity(request);const derived2=await derive(verified);this.entries.set(cacheKey,{fingerprint:fingerprint4,verified,derived:derived2});return{verified,derived:derived2}}retain(requests2){const live=new Set([...requests2].map(key));for(const cacheKey of this.entries.keys()){if(!live.has(cacheKey))this.entries.delete(cacheKey)}}}}});import{lstat as lstat4,readFile as readFile8}from"node:fs/promises";import{isIP as isIP2}from"node:net";import{extname as extname10,resolve as resolve69}from"node:path";function createStaticOriginCompileCache(originRoot){return new StaticOriginVerifiedGenerationCache(originRoot)}function fail17(code){throw new Error(code)}function validPort(input2){return Number.isSafeInteger(input2)&&input2>=1&&input2<=65535}function privateIpv4(input2){if(isIP2(input2)!==4)return false;const octets=input2.split(".").map(Number);return octets[0]===10||octets[0]===127||octets[0]===172&&octets[1]>=16&&octets[1]<=31||octets[0]===192&&octets[1]===168||octets[0]===100&&octets[1]>=64&&octets[1]<=127}function quote(input2){return JSON.stringify(input2)}function verbatimCaddyString(input2){if(/["\r\n]/u.test(input2))fail17("STATIC_ORIGIN_CONFIG_INVALID");return`"${input2}"`}function immutableExpression(){return STATIC_CONTENT_HASH_RULES2.map(group2=>{const required3=group2.require.map(source=>`{http.request.uri.path}.matches(r'${celRawString(source)}')`);const forbidden=group2.forbid.map(source=>`!{http.request.uri.path}.matches(r'${celRawString(source)}')`);return`(${[...required3,...forbidden].join(" && ")})`}).join(" || ")}function celRawString(input2){if(/['"\r\n]/u.test(input2))fail17("STATIC_ORIGIN_CONFIG_INVALID");return input2}async function usableRewriteRule(generationPath,rule){if(rule.statusCode!==200&&rule.statusCode!==404)return true;const targetPath=resolve69(generationPath,rule.to.replace(/^\/+/,""));if(!targetPath.startsWith(`${generationPath}/`))return false;const info2=await lstat4(targetPath).catch(()=>null);if(!info2?.isFile()||info2.isSymbolicLink())return false;return rule.statusCode!==404||DOCUMENT_EXTENSIONS.has(extname10(targetPath).toLowerCase())}async function loadRedirectRules(generationPath){const path5=resolve69(generationPath,"_redirects");const source=await readFile8(path5,"utf8").catch(()=>"");const parsed=parseStaticRedirects2(source);const accepted=[];for(const rule of parsed){if(await usableRewriteRule(generationPath,rule))accepted.push(rule)}return accepted}async function verifiedGenerationWithRules(originRoot,request,cache){const loadRules=generation=>loadRedirectRules(generation.generationPath);if(cache){if(cache.originRoot!==resolve69(originRoot))fail17("STATIC_ORIGIN_CONFIG_INVALID");const resolved=await cache.resolve(request,loadRules);return{verified:resolved.verified,rules:resolved.derived}}const verified=await verifySealedStaticOriginGeneration({originRoot,...request});return{verified,rules:await loadRules(verified)}}function redirectLines(site,wildcard){const output2=[];site.rules.filter(rule=>rule.wildcard===wildcard).forEach((rule,index27)=>{const name=`${wildcard?"wildcard":"redirect"}_${site.appId}_${index27}`;output2.push(` @${name} {`,` host ${site.hosts.map(quote).join(" ")}`,` path ${quote(rule.from)}`,` vars {vars.gencow_rw} ""`," }");if(rule.statusCode===301||rule.statusCode===302||rule.statusCode===307||rule.statusCode===308){output2.push(` redir @${name} ${quote(rule.to)} ${rule.statusCode}`);return}output2.push(` vars @${name} gencow_rw ${quote(name)}`,` vars @${name} gencow_rw_status ${quote(String(rule.statusCode))}`,` @${name}_rw vars {vars.gencow_rw} ${quote(name)}`,` rewrite @${name}_rw ${quote(rule.to)}`)});return output2}function sharedSiteLines(input2){const noFallbackPaths=["/assets","/assets/*",...STATIC_NO_FALLBACK_EXTENSIONS2.map(ext=>`*${ext}`)];const addresses=input2.sites.flatMap(site=>site.hosts).map(host=>`http://${host}:${input2.port}`);const mapRows=input2.sites.flatMap(site=>site.hosts.map(host=>` ${quote(host)} ${quote(site.generationPath)} ${quote(String(site.appId))} ${quote(String(site.routeEpoch))}`));return[`${addresses.join(", ")} {`,` bind ${input2.listenHost}`," encode gzip",` header X-Gencow-Edge ${quote("1")}`," log {",` output file ${quote(input2.meteringAccessLogFile)} {`," mode 0640"," roll_size 64MiB"," roll_keep 64"," roll_keep_for 168h"," roll_uncompressed"," }"," format json"," }"," log_append gencow_app_id {gencow_app_id}"," log_append gencow_route_epoch {gencow_route_epoch}",` @immutable expression ${verbatimCaddyString(immutableExpression())}`," route {"," map {host} {gencow_root} {gencow_app_id} {gencow_route_epoch} {",...mapRows,` default ${quote("/nonexistent")} "0" "0"`," }"," root * {gencow_root}",' vars gencow_rw ""',` vars gencow_cc ${quote("no-cache")}`,` vars @immutable gencow_cc ${quote(IMMUTABLE_CACHE)}`,' @unmapped vars {gencow_app_id} "0"'," skip_log @unmapped"," respond @unmapped 404"," @metadata path /_redirects"," respond @metadata 404"," @reserved path /api /api/* /platform /platform/* /internal /internal/* /_internal /_internal/* /ws /ws/* /_gencow/analytics.js /_gencow/analytics/event"," respond @reserved 404"," @hidden {"," path_regexp hidden (^|/)\\."," not path /.well-known /.well-known/*"," }"," respond @hidden 404",...input2.sites.flatMap(site=>redirectLines(site,false))," @exact {"," file {path}",' vars {vars.gencow_rw} ""'," }"," handle @exact {"," header Cache-Control {vars.gencow_cc}"," file_server {",` hide ${quote("_redirects")}`," }"," }"," @no_fallback {",` path ${noFallbackPaths.map(quote).join(" ")}`,' vars {vars.gencow_rw} ""'," }"," respond @no_fallback 404"," @document {"," file {path}.html {path}/index.html",' vars {vars.gencow_rw} ""'," }"," handle @document {"," try_files {path}.html {path}/index.html",` header Cache-Control ${quote("no-cache")}`," file_server {",` hide ${quote("_redirects")}`," }"," }",...input2.sites.flatMap(site=>redirectLines(site,true))," @spa {"," file /index.html",' vars {vars.gencow_rw} ""'," }"," handle @spa {",` rewrite * ${quote("/index.html")}`,` header Cache-Control ${quote("no-cache")}`," file_server {",` hide ${quote("_redirects")}`," }"," }",` vars gencow_cc ${quote("no-cache")}`,` vars @immutable gencow_cc ${quote(IMMUTABLE_CACHE)}`,' @rw_200 vars {vars.gencow_rw_status} "200"'," handle @rw_200 {"," header Cache-Control {vars.gencow_cc}"," file_server {",` hide ${quote("_redirects")}`," }"," }",' @rw_404 vars {vars.gencow_rw_status} "404"'," handle @rw_404 {"," header Cache-Control {vars.gencow_cc}"," file_server {",` hide ${quote("_redirects")}`," status 404"," }"," }"," respond 404"," }","}"]}function healthSite(listenHost,port){return[`http://:${port} {`,` bind ${listenHost}`," respond /health/live 200"," respond /health/core-ready 200"," respond 404","}"]}function validateProjection(projection){if(!Number.isSafeInteger(projection.appId)||projection.appId<1||projection.appId!==projection.entry.appId||projection.routeEpoch!==projection.entry.routeEpoch||!SHA25611.test(projection.routeHash)||projection.routeHash!==hashServingRouteManifestEntry(projection.entry)){fail17("STATIC_ORIGIN_PROJECTION_INVALID")}}async function compileStaticOriginCaddyfile(input2){if(!REFERENCE5.test(input2.nodeId)||!privateIpv4(input2.listenHost)||!input2.meteringAccessLogFile.startsWith("/")||!validPort(input2.listenPort)||!validPort(input2.adminPort)){fail17("STATIC_ORIGIN_CONFIG_INVALID")}const selected=input2.projections.filter(projection=>{validateProjection(projection);const entry=projection.entry;return entry.disposition==="upsert"&&(entry.mode==="static_only"||entry.mode==="fullstack")&&entry.static?.nodeId===input2.nodeId}).sort((left,right)=>left.appId-right.appId);const routes=[];const hosts=new Set;const sites=[];const unavailable3=[];for(const projection of selected){const entry=projection.entry;const staticRoute=entry.static;const routeHosts=entry.hostBindings.filter(binding=>binding.action==="serve").map(binding=>binding.host).sort();for(const host of routeHosts){if(hosts.has(host))fail17("STATIC_ORIGIN_HOST_COLLISION");hosts.add(host)}const generationRequest={appInstanceId:entry.appInstanceId,generationRef:staticRoute.generationRef,integritySha256:staticRoute.integritySha256};let generation;try{generation=await verifiedGenerationWithRules(input2.originRoot,generationRequest,input2.generationCache)}catch(error62){const code=error62 instanceof Error?error62.message:"";if(projection.appId===input2.candidateAppId||!APP_SCOPED_GENERATION_FAILURES.has(code))throw error62;unavailable3.push({appId:projection.appId,code});continue}const{verified,rules}=generation;if(routeHosts.length>0){sites.push({appId:projection.appId,routeEpoch:projection.routeEpoch,hosts:routeHosts,generationPath:verified.generationPath,rules})}routes.push({...verified,appId:projection.appId,routeEpoch:projection.routeEpoch,routeHash:projection.routeHash,hosts:routeHosts})}const lines=["{",` admin 127.0.0.1:${input2.adminPort}`," auto_https off","}","",...healthSite(input2.listenHost,input2.listenPort)];if(sites.length>0){lines.push("",...sharedSiteLines({listenHost:input2.listenHost,port:input2.listenPort,meteringAccessLogFile:input2.meteringAccessLogFile,sites}))}return{caddyfile:`${lines.join("\n")}
|
|
9050
9050
|
`,routes,unavailable:unavailable3}}var REFERENCE5,SHA25611,IMMUTABLE_CACHE,DOCUMENT_EXTENSIONS,APP_SCOPED_GENERATION_FAILURES;var init_static_origin_caddy_compiler=__esm({"../static-origin/src/static-origin-caddy-compiler.ts"(){"use strict";init_serving_route_manifest_contract();init_static_file_routing2();init_static_redirects2();init_static_origin_generation_cache();init_static_origin_layout();REFERENCE5=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;SHA25611=/^[a-f0-9]{64}$/u;IMMUTABLE_CACHE="public, max-age=31536000, immutable";DOCUMENT_EXTENSIONS=new Set([".htm",".html"]);APP_SCOPED_GENERATION_FAILURES=new Set(["STATIC_ORIGIN_GENERATION_UNAVAILABLE","STATIC_ORIGIN_GENERATION_UNSEALED","STATIC_ORIGIN_GENERATION_ENTRY_UNSAFE","STATIC_ORIGIN_GENERATION_LIMIT_EXCEEDED","STATIC_ORIGIN_READY_MARKER_INVALID","STATIC_ORIGIN_INTEGRITY_MISMATCH"])}});import{createHash as createHash60,randomUUID as randomUUID39}from"node:crypto";import{lstat as lstat5,mkdir as mkdir10,open as open7,readdir as readdir6,readFile as readFile9,rename as rename6,rm as rm6}from"node:fs/promises";import{dirname as dirname17,isAbsolute as isAbsolute15,join as join19,resolve as resolve70}from"node:path";function fail18(code){throw new Error(code)}function ownedByRootOrProcess2(uid){const processUid=process.getuid?.();return uid===0||processUid===void 0||uid===processUid}function canonicalValue2(input2){if(Array.isArray(input2))return input2.map(canonicalValue2);if(!input2||typeof input2!=="object")return input2;const record3=input2;return Object.fromEntries(Object.keys(record3).sort().map(key2=>[key2,canonicalValue2(record3[key2])]))}function canonicalJson2(input2){return JSON.stringify(canonicalValue2(input2))}function sha25610(input2){return createHash60("sha256").update(input2).digest("hex")}async function readStreamLimited(stream,maximumBytes){const reader=stream.getReader();const chunks=[];let bytes2=0;try{while(true){const result3=await reader.read();if(result3.done)break;bytes2+=result3.value.byteLength;if(bytes2>maximumBytes)fail18("STATIC_ORIGIN_CADDY_OUTPUT_TOO_LARGE");chunks.push(result3.value)}}finally{reader.releaseLock()}const joined=new Uint8Array(bytes2);let offset=0;for(const chunk2 of chunks){joined.set(chunk2,offset);offset+=chunk2.byteLength}return new TextDecoder().decode(joined)}async function atomicWrite(path5,body){const temp=join19(dirname17(path5),`.static-origin-${randomUUID39()}.tmp`);const handle=await open7(temp,"wx",384);try{await handle.writeFile(body,"utf8");await handle.sync()}catch(error62){await handle.close().catch(()=>void 0);await rm6(temp,{force:true}).catch(()=>void 0);throw error62}await handle.close();await rename6(temp,path5);const directory=await open7(dirname17(path5),"r");try{await directory.sync()}finally{await directory.close()}}async function ensurePrivateDirectory(path5){await mkdir10(path5,{recursive:true,mode:448});const info2=await lstat5(path5);if(!info2.isDirectory()||info2.isSymbolicLink()||(info2.mode&511)!==448||!ownedByRootOrProcess2(info2.uid)){fail18("STATIC_ORIGIN_CADDY_PATH_UNSAFE")}}async function assertPrivateFile(path5,maximumBytes){const info2=await lstat5(path5).catch(()=>null);if(!info2?.isFile()||info2.isSymbolicLink()||info2.size<1||info2.size>maximumBytes||(info2.mode&511)!==384||!ownedByRootOrProcess2(info2.uid)){fail18("STATIC_ORIGIN_CADDY_PREPARED_INVALID")}}var SHA25612,MAX_CADDYFILE_BYTES,MAX_CONFIG_BYTES,MAX_COMMAND_ERROR_BYTES,MAX_VALIDATED_CADDYFILES,CONFIG_HASH_DIRECTORY,DEFAULT_CONFIG_RETENTION,StaticOriginCaddyApplier;var init_static_origin_caddy_applier=__esm({"../static-origin/src/static-origin-caddy-applier.ts"(){"use strict";SHA25612=/^[a-f0-9]{64}$/u;MAX_CADDYFILE_BYTES=16*1024*1024;MAX_CONFIG_BYTES=32*1024*1024;MAX_COMMAND_ERROR_BYTES=1024*1024;MAX_VALIDATED_CADDYFILES=16;CONFIG_HASH_DIRECTORY=/^[0-9a-f]{64}$/u;DEFAULT_CONFIG_RETENTION=Object.freeze({keep:16,graceMs:10*6e4,maxRemovalsPerPass:256,minIntervalMs:3e4});StaticOriginCaddyApplier=class{stateRoot;caddyBinary;adminUrl;runCommandImpl;fetchImpl;validated=new Map;retention;nowImpl;lastPruneAt=Number.NEGATIVE_INFINITY;constructor(input2){this.retention={...DEFAULT_CONFIG_RETENTION,...input2.retention};this.nowImpl=input2.nowImpl??Date.now;if(!isAbsolute15(input2.stateRoot)||resolve70(input2.stateRoot)==="/"||!isAbsolute15(input2.caddyBinary)||!Number.isSafeInteger(input2.adminPort)||input2.adminPort<1||input2.adminPort>65535){fail18("STATIC_ORIGIN_CADDY_CONFIG_INVALID")}this.stateRoot=resolve70(input2.stateRoot);this.caddyBinary=resolve70(input2.caddyBinary);this.adminUrl=`http://127.0.0.1:${input2.adminPort}`;this.runCommandImpl=input2.runCommandImpl??((args,signal)=>this.runCommand(args,signal));this.fetchImpl=input2.fetchImpl??fetch}async ensureSafePaths(){await ensurePrivateDirectory(this.stateRoot);const binaryInfo=await lstat5(this.caddyBinary).catch(()=>null);if(!binaryInfo?.isFile()||binaryInfo.isSymbolicLink()||(binaryInfo.mode&18)!==0||(binaryInfo.mode&73)===0||!ownedByRootOrProcess2(binaryInfo.uid)){fail18("STATIC_ORIGIN_CADDY_PATH_UNSAFE")}}async runCommand(args,signal){if(signal?.aborted)fail18("STATIC_ORIGIN_CADDY_APPLY_ABORTED");const processHandle=Bun.spawn([this.caddyBinary,...args],{env:{PATH:"/usr/local/bin:/usr/bin:/bin",XDG_DATA_HOME:join19(this.stateRoot,"caddy-data"),XDG_CONFIG_HOME:join19(this.stateRoot,"caddy-config")},stdout:"pipe",stderr:"pipe"});const abort=()=>processHandle.kill("SIGKILL");signal?.addEventListener("abort",abort,{once:true});try{const[stdout,stderr,exitCode]=await Promise.all([readStreamLimited(processHandle.stdout,MAX_CONFIG_BYTES),readStreamLimited(processHandle.stderr,MAX_COMMAND_ERROR_BYTES),processHandle.exited]);if(signal?.aborted)fail18("STATIC_ORIGIN_CADDY_APPLY_ABORTED");return{exitCode,stdout,stderr}}finally{signal?.removeEventListener("abort",abort)}}async reuseValidated(caddyfile){const key2=sha25610(caddyfile);const prepared=this.validated.get(key2);if(!prepared)return null;try{await assertPrivateFile(prepared.configFile,MAX_CONFIG_BYTES);await assertPrivateFile(prepared.caddyfile,MAX_CADDYFILE_BYTES);if(await readFile9(prepared.caddyfile,"utf8")!==caddyfile||sha25610(await readFile9(prepared.configFile,"utf8"))!==prepared.configHash){fail18("STATIC_ORIGIN_CADDY_PREPARED_INVALID")}this.validated.delete(key2);this.validated.set(key2,prepared);return prepared}catch{this.validated.delete(key2);return null}}rememberValidated(caddyfile,prepared){const key2=sha25610(caddyfile);this.validated.delete(key2);this.validated.set(key2,prepared);while(this.validated.size>MAX_VALIDATED_CADDYFILES){this.validated.delete(this.validated.keys().next().value)}}async prepare(caddyfile,signal){if(Buffer.byteLength(caddyfile,"utf8")<1||Buffer.byteLength(caddyfile,"utf8")>MAX_CADDYFILE_BYTES){fail18("STATIC_ORIGIN_CADDYFILE_INVALID")}await this.ensureSafePaths();const reused=await this.reuseValidated(caddyfile);if(reused)return reused;const stagingRoot=join19(this.stateRoot,"staging");const configsRoot=join19(this.stateRoot,"configs");await ensurePrivateDirectory(stagingRoot);await ensurePrivateDirectory(configsRoot);const attemptRoot=join19(stagingRoot,randomUUID39());await mkdir10(attemptRoot,{mode:448});const caddyfilePath=join19(attemptRoot,"Caddyfile");const configPath=join19(attemptRoot,"config.json");try{await atomicWrite(caddyfilePath,caddyfile);const adapted=await this.runCommandImpl(["adapt","--config",caddyfilePath,"--adapter","caddyfile"],signal);if(adapted.exitCode!==0)fail18("STATIC_ORIGIN_CADDY_ADAPT_FAILED");let decoded;try{decoded=JSON.parse(adapted.stdout)}catch{return fail18("STATIC_ORIGIN_CADDY_ADAPT_FAILED")}const config2=canonicalJson2(decoded);if(Buffer.byteLength(config2,"utf8")>MAX_CONFIG_BYTES)fail18("STATIC_ORIGIN_CADDY_OUTPUT_TOO_LARGE");await atomicWrite(configPath,config2);const validated=await this.runCommandImpl(["validate","--config",configPath],signal);if(validated.exitCode!==0)fail18("STATIC_ORIGIN_CADDY_VALIDATE_FAILED");const configHash=sha25610(config2);const targetRoot=join19(configsRoot,configHash);try{await rename6(attemptRoot,targetRoot)}catch(error62){const code=error62.code;if(code!=="EEXIST"&&code!=="ENOTEMPTY")throw error62;await rm6(attemptRoot,{recursive:true,force:true});if(await readFile9(join19(targetRoot,"config.json"),"utf8").catch(()=>"")!==config2||await readFile9(join19(targetRoot,"Caddyfile"),"utf8").catch(()=>"")!==caddyfile){fail18("STATIC_ORIGIN_CADDY_CONFIG_CONFLICT")}}const prepared={configHash,configFile:join19(targetRoot,"config.json"),caddyfile:join19(targetRoot,"Caddyfile")};this.rememberValidated(caddyfile,prepared);return prepared}catch(error62){await rm6(attemptRoot,{recursive:true,force:true}).catch(()=>void 0);throw error62}}async commit(prepared,signal){if(!SHA25612.test(prepared.configHash))fail18("STATIC_ORIGIN_CADDY_PREPARED_INVALID");const expectedRoot=join19(this.stateRoot,"configs",prepared.configHash);if(prepared.configFile!==join19(expectedRoot,"config.json")||prepared.caddyfile!==join19(expectedRoot,"Caddyfile")){fail18("STATIC_ORIGIN_CADDY_PREPARED_INVALID")}await ensurePrivateDirectory(expectedRoot);await assertPrivateFile(prepared.configFile,MAX_CONFIG_BYTES);await assertPrivateFile(prepared.caddyfile,MAX_CADDYFILE_BYTES);const config2=await readFile9(prepared.configFile,"utf8").catch(()=>fail18("STATIC_ORIGIN_CADDY_PREPARED_INVALID"));if(sha25610(config2)!==prepared.configHash)fail18("STATIC_ORIGIN_CADDY_PREPARED_INVALID");const loaded=await this.fetchImpl(new Request(`${this.adminUrl}/load`,{method:"POST",headers:{"content-type":"application/json"},body:config2,signal})).catch(()=>fail18("STATIC_ORIGIN_CADDY_LOAD_FAILED"));if(!loaded.ok)fail18("STATIC_ORIGIN_CADDY_LOAD_FAILED");const readBack=await this.fetchImpl(new Request(`${this.adminUrl}/config/`,{signal})).catch(()=>fail18("STATIC_ORIGIN_CADDY_READ_BACK_FAILED"));if(!readBack.ok)fail18("STATIC_ORIGIN_CADDY_READ_BACK_FAILED");if(!readBack.body)fail18("STATIC_ORIGIN_CADDY_READ_BACK_FAILED");const readBackBody=await readStreamLimited(readBack.body,MAX_CONFIG_BYTES);let decoded;try{decoded=JSON.parse(readBackBody)}catch{return fail18("STATIC_ORIGIN_CADDY_READ_BACK_FAILED")}if(sha25610(canonicalJson2(decoded))!==prepared.configHash){fail18("STATIC_ORIGIN_CADDY_READ_BACK_MISMATCH")}await atomicWrite(join19(this.stateRoot,"current"),prepared.configHash);await this.pruneConfigs(prepared.configHash);return{configHash:prepared.configHash}}async pruneConfigs(currentHash){const now=this.nowImpl();if(now-this.lastPruneAt<this.retention.minIntervalMs)return;this.lastPruneAt=now;try{const configsRoot=join19(this.stateRoot,"configs");const protectedHashes=new Set([currentHash]);for(const prepared of this.validated.values())protectedHashes.add(prepared.configHash);const candidates=[];for(const entry of await readdir6(configsRoot,{withFileTypes:true})){if(!entry.isDirectory()||!CONFIG_HASH_DIRECTORY.test(entry.name))continue;const info2=await lstat5(join19(configsRoot,entry.name)).catch(()=>null);if(!info2?.isDirectory()||info2.isSymbolicLink())continue;candidates.push({hash:entry.name,mtimeMs:info2.mtimeMs})}candidates.sort((left,right)=>right.mtimeMs-left.mtimeMs);const removable=candidates.slice(this.retention.keep).filter(entry=>!protectedHashes.has(entry.hash)&&now-entry.mtimeMs>=this.retention.graceMs).reverse().slice(0,this.retention.maxRemovalsPerPass);for(const entry of removable){await rm6(join19(configsRoot,entry.hash),{recursive:true,force:true}).catch(()=>void 0)}}catch{}}async load(caddyfile,signal){return this.commit(await this.prepare(caddyfile,signal),signal)}}}});import{lstat as lstat6,readFile as readFile10}from"node:fs/promises";import{isIP as isIP3}from"node:net";import{isAbsolute as isAbsolute16,relative as relative16,resolve as resolve71}from"node:path";function fail19(code){throw new Error(code)}function ownedByRootOrProcess3(uid){const processUid=process.getuid?.();return uid===0||processUid===0||processUid===void 0||uid===processUid}function exactRecord(input2){if(!input2||typeof input2!=="object"||Array.isArray(input2))fail19("STATIC_ORIGIN_CONFIG_INVALID");const record3=input2;if(Object.keys(record3).sort().join(",")!==[...CONFIG_KEYS].sort().join(",")){fail19("STATIC_ORIGIN_CONFIG_INVALID")}return record3}function validPort2(value2){return typeof value2==="number"&&Number.isSafeInteger(value2)&&value2>=1&&value2<=65535}function privateIpv42(value2){if(typeof value2!=="string"||isIP3(value2)!==4)return false;const octets=value2.split(".").map(Number);return octets[0]===10||octets[0]===127||octets[0]===172&&octets[1]>=16&&octets[1]<=31||octets[0]===192&&octets[1]===168||octets[0]===100&&octets[1]>=64&&octets[1]<=127}function safeAbsolutePath(value2){return typeof value2==="string"&&isAbsolute16(value2)&&resolve71(value2)!=="/"&&!value2.includes("\0")}function overlaps(left,right){const relation2=relative16(left,right);return relation2===""||!relation2.startsWith("..")&&!isAbsolute16(relation2)}async function loadStaticOriginConfig(configFile){if(!isAbsolute16(configFile))fail19("STATIC_ORIGIN_CONFIG_FILE_UNSAFE");const info2=await lstat6(configFile).catch(()=>null);if(!info2?.isFile()||info2.isSymbolicLink()||info2.size<1||info2.size>64*1024||(info2.mode&511)!==384||!ownedByRootOrProcess3(info2.uid)){fail19("STATIC_ORIGIN_CONFIG_FILE_UNSAFE")}let decoded;try{decoded=JSON.parse(await readFile10(configFile,"utf8"))}catch{return fail19("STATIC_ORIGIN_CONFIG_INVALID")}const record3=exactRecord(decoded);if(record3.protocolVersion!==1||typeof record3.configGeneration!=="string"||!REFERENCE6.test(record3.configGeneration)||typeof record3.nodeId!=="string"||!REFERENCE6.test(record3.nodeId)||!privateIpv42(record3.listenHost)||!safeAbsolutePath(record3.originRoot)||!safeAbsolutePath(record3.stateRoot)||!safeAbsolutePath(record3.meteringAccessLogFile)||!safeAbsolutePath(record3.caddyBinary)||!validPort2(record3.listenPort)||!validPort2(record3.adminPort)||record3.listenPort===record3.adminPort){fail19("STATIC_ORIGIN_CONFIG_INVALID")}const originRoot=resolve71(record3.originRoot);const stateRoot=resolve71(record3.stateRoot);const meteringAccessLogFile=resolve71(record3.meteringAccessLogFile);if(overlaps(originRoot,stateRoot)||overlaps(stateRoot,originRoot)||overlaps(originRoot,meteringAccessLogFile)||overlaps(stateRoot,meteringAccessLogFile)){fail19("STATIC_ORIGIN_CONFIG_INVALID")}return{configGeneration:record3.configGeneration,nodeId:record3.nodeId,listenHost:record3.listenHost,originRoot,stateRoot,meteringAccessLogFile,caddyBinary:resolve71(record3.caddyBinary),listenPort:record3.listenPort,adminPort:record3.adminPort}}var REFERENCE6,CONFIG_KEYS;var init_static_origin_config=__esm({"../static-origin/src/static-origin-config.ts"(){"use strict";REFERENCE6=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;CONFIG_KEYS=["protocolVersion","configGeneration","nodeId","listenHost","originRoot","stateRoot","meteringAccessLogFile","caddyBinary","listenPort","adminPort"]}});import{createPublicKey as createPublicKey3}from"node:crypto";import{lstat as lstat7,readFile as readFile11}from"node:fs/promises";import{isAbsolute as isAbsolute17,resolve as resolve72}from"node:path";function fail20(code){throw new Error(code)}function exactRecord2(input2,keys2){if(!input2||typeof input2!=="object"||Array.isArray(input2))fail20("ROUTE_PROJECTOR_CONFIG_INVALID");const record3=input2;if(Object.keys(record3).sort().join(",")!==[...keys2].sort().join(",")){fail20("ROUTE_PROJECTOR_CONFIG_INVALID")}return record3}function ownedByRootOrProcess4(uid){const processUid=process.getuid?.();return uid===0||processUid===void 0||uid===processUid}async function readSafeFile(path5,options){if(!isAbsolute17(path5))fail20(options.code);let info2;try{info2=await lstat7(path5)}catch{return fail20(options.code)}const mode=info2.mode&511;if(info2.isSymbolicLink()||!info2.isFile()||info2.size<1||info2.size>options.maxBytes||!ownedByRootOrProcess4(info2.uid)||options.exactMode!==void 0&&mode!==options.exactMode||options.forbidWritableByOthers===true&&(mode&18)!==0){fail20(options.code)}return readFile11(path5,"utf8")}function parseToken(body){const token=body.endsWith("\n")?body.slice(0,-1):body;if(!TOKEN.test(token)||token.includes("\r")||token.includes("\n")){fail20("ROUTE_PROJECTOR_TOKEN_FILE_INVALID")}return token}async function loadTrustKeys(input2){if(!Array.isArray(input2)||input2.length<1||input2.length>2){fail20("ROUTE_PROJECTOR_CONFIG_INVALID")}const trusted=new Map;for(const item of input2){const record3=exactRecord2(item,["keyId","publicKeyFile"]);if(typeof record3.keyId!=="string"||!REFERENCE7.test(record3.keyId)||typeof record3.publicKeyFile!=="string"||trusted.has(record3.keyId)){fail20("ROUTE_PROJECTOR_CONFIG_INVALID")}const keyBody=await readSafeFile(record3.publicKeyFile,{code:"ROUTE_PROJECTOR_PUBLIC_KEY_FILE_UNSAFE",maxBytes:16*1024,forbidWritableByOthers:true});let publicKey;try{publicKey=createPublicKey3(keyBody)}catch{return fail20("ROUTE_PROJECTOR_PUBLIC_KEY_INVALID")}if(publicKey.asymmetricKeyType!=="ed25519")fail20("ROUTE_PROJECTOR_PUBLIC_KEY_INVALID");trusted.set(record3.keyId,publicKey)}return trusted}async function loadServingRouteProjectorConfig(configFile){const configBody=await readSafeFile(configFile,{code:"ROUTE_PROJECTOR_CONFIG_FILE_UNSAFE",maxBytes:64*1024,exactMode:384});let decoded;try{decoded=JSON.parse(configBody)}catch{return fail20("ROUTE_PROJECTOR_CONFIG_INVALID")}const record3=exactRecord2(decoded,CONFIG_KEYS2);if(record3.protocolVersion!==1||typeof record3.environment!=="string"||!ENVIRONMENTS3.has(record3.environment)||typeof record3.projectorId!=="string"||!REFERENCE7.test(record3.projectorId)||typeof record3.configGeneration!=="string"||!REFERENCE7.test(record3.configGeneration)||record3.listenHost!=="127.0.0.1"&&record3.listenHost!=="::1"||typeof record3.listenPort!=="number"||!Number.isSafeInteger(record3.listenPort)||record3.listenPort<1||record3.listenPort>65535||typeof record3.lkgRoot!=="string"||!isAbsolute17(record3.lkgRoot)||typeof record3.authorizationTokenFile!=="string"){fail20("ROUTE_PROJECTOR_CONFIG_INVALID")}const authorizationToken=parseToken(await readSafeFile(record3.authorizationTokenFile,{code:"ROUTE_PROJECTOR_TOKEN_FILE_UNSAFE",maxBytes:1024,exactMode:384}));return{environment:record3.environment,projectorId:record3.projectorId,configGeneration:record3.configGeneration,listenHost:record3.listenHost,listenPort:record3.listenPort,lkgRoot:resolve72(record3.lkgRoot),authorizationToken,trustedPublicKeys:await loadTrustKeys(record3.trustedKeys)}}var REFERENCE7,TOKEN,ENVIRONMENTS3,CONFIG_KEYS2;var init_serving_route_projector_config=__esm({"../server/src/serving-route-projector-config.ts"(){"use strict";REFERENCE7=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;TOKEN=/^[A-Za-z0-9._~+/-]{32,510}={0,2}$/u;ENVIRONMENTS3=new Set(["local","dev","qc","prod"]);CONFIG_KEYS2=["protocolVersion","environment","projectorId","configGeneration","listenHost","listenPort","lkgRoot","authorizationTokenFile","trustedKeys"]}});import{randomUUID as randomUUID40}from"node:crypto";import{lstat as lstat8,mkdir as mkdir11,open as open8,readFile as readFile12,readdir as readdir7,rename as rename7,stat as stat10,unlink as unlink4}from"node:fs/promises";import{dirname as dirname18,isAbsolute as isAbsolute18,join as join20,resolve as resolve73}from"node:path";function quarantineServingRouteIdentityCollisions(routes){const owners=new Map;for(const route of routes.values()){const key2=route.entry.appName.trim().toLocaleLowerCase();const ids=owners.get(key2)??[];ids.push(route.appId);owners.set(key2,ids)}const rejected=[...owners.values()].filter(ids=>ids.length>1).flat();for(const appId of rejected)routes.delete(appId);return rejected}function fail21(code){throw new Error(code)}function ownedByRootOrProcess5(uid){const processUid=process.getuid?.();return uid===0||processUid===void 0||uid===processUid}function exactStoredRoute(input2){if(!input2||typeof input2!=="object"||Array.isArray(input2)){return fail21("ROUTE_PROJECTOR_LKG_CORRUPT")}const record3=input2;if(Object.keys(record3).sort().join(",")!=="envelope,storageVersion"||record3.storageVersion!==1){return fail21("ROUTE_PROJECTOR_LKG_CORRUPT")}return record3}async function ensurePrivateRoot(root2){if(!isAbsolute18(root2))fail21("ROUTE_PROJECTOR_ROOT_INVALID");const expected=resolve73(root2);await mkdir11(expected,{recursive:true,mode:448});const rootStat=await lstat8(expected);if(!rootStat.isDirectory()||rootStat.isSymbolicLink()||(rootStat.mode&511)!==448||!ownedByRootOrProcess5(rootStat.uid)){fail21("ROUTE_PROJECTOR_ROOT_INVALID")}const appsRoot=join20(expected,"apps");await mkdir11(appsRoot,{recursive:true,mode:448});const appsStat=await lstat8(appsRoot);if(!appsStat.isDirectory()||appsStat.isSymbolicLink()||(appsStat.mode&511)!==448||!ownedByRootOrProcess5(appsStat.uid)){fail21("ROUTE_PROJECTOR_ROOT_INVALID")}return appsRoot}async function ensurePrivateStagedRoot(root2){await ensurePrivateRoot(root2);const stagedRoot=join20(resolve73(root2),"staged");await mkdir11(stagedRoot,{recursive:true,mode:448});const stagedStat=await lstat8(stagedRoot);if(!stagedStat.isDirectory()||stagedStat.isSymbolicLink()||(stagedStat.mode&511)!==448||!ownedByRootOrProcess5(stagedStat.uid)){fail21("ROUTE_PROJECTOR_ROOT_INVALID")}return stagedRoot}async function withAppLock(key2,operation){const previous=appLocks.get(key2)??Promise.resolve();let release;const current=new Promise(resolveLock=>{release=resolveLock});const queued=previous.then(()=>current);appLocks.set(key2,queued);await previous;try{return await operation()}finally{release();if(appLocks.get(key2)===queued)appLocks.delete(key2)}}function verifySingleRoute(envelope,options){const verified=verifySignedServingRouteManifest(envelope,options);if(verified.manifest.entries.length!==1)fail21("ROUTE_PROJECTOR_DELTA_CARDINALITY_INVALID");const entry=verified.manifest.entries[0];return{appId:entry.appId,routeEpoch:entry.routeEpoch,routeHash:hashServingRouteManifestEntry(entry),manifestEpoch:verified.manifest.manifestEpoch,manifestHash:verified.manifestHash,keyId:verified.keyId,entry}}async function readStoredRoute(path5,options){let fileStat;try{fileStat=await lstat8(path5)}catch(error62){if(error62.code==="ENOENT")return null;throw error62}if(fileStat.isSymbolicLink()||!fileStat.isFile()||fileStat.size<1||fileStat.size>MAX_STORED_ENVELOPE_BYTES||(fileStat.mode&511)!==384||!ownedByRootOrProcess5(fileStat.uid)){fail21("ROUTE_PROJECTOR_LKG_CORRUPT")}let decoded;try{decoded=JSON.parse(await readFile12(path5,"utf8"))}catch{return fail21("ROUTE_PROJECTOR_LKG_CORRUPT")}return verifySingleRoute(exactStoredRoute(decoded).envelope,options)}async function atomicWrite2(path5,body){const directory=dirname18(path5);const tempPath=join20(directory,`.route-${randomUUID40()}.tmp`);const handle=await open8(tempPath,"wx",384);try{await handle.writeFile(body,"utf8");await handle.sync()}catch(error62){await handle.close().catch(()=>void 0);await unlink4(tempPath).catch(()=>void 0);throw error62}await handle.close();try{await rename7(tempPath,path5);const directoryHandle=await open8(directory,"r");try{await directoryHandle.sync()}finally{await directoryHandle.close()}}catch(error62){await unlink4(tempPath).catch(()=>void 0);throw error62}}async function removeAndSync(path5){try{await unlink4(path5)}catch(error62){if(error62.code==="ENOENT")return;throw error62}const directoryHandle=await open8(dirname18(path5),"r");try{await directoryHandle.sync()}finally{await directoryHandle.close()}}function rejectedPreparation(candidate,decision){return{...candidate,decision:decision==="reject_stale"?"rejected_stale":"rejected_conflict",readBackVerified:false}}function storedBody(envelope){const body=JSON.stringify({storageVersion:STORAGE_VERSION,envelope});if(Buffer.byteLength(body,"utf8")>MAX_STORED_ENVELOPE_BYTES){fail21("ROUTE_PROJECTOR_LKG_TOO_LARGE")}return body}async function prepareSignedServingRouteProjection(options){const candidate=verifySingleRoute(options.envelope,options);const appsRoot=await ensurePrivateRoot(options.root);const stagedRoot=await ensurePrivateStagedRoot(options.root);const currentPath=join20(appsRoot,`${candidate.appId}.json`);const stagedPath=join20(stagedRoot,`${candidate.appId}.json`);return withAppLock(currentPath,async()=>{const current=await readStoredRoute(currentPath,options);const currentDecision=decideServingRouteEntryApply(current?{routeEpoch:current.routeEpoch,routeHash:current.routeHash}:null,candidate.entry);if(currentDecision.decision==="reject_stale"||currentDecision.decision==="reject_conflict"){return rejectedPreparation(candidate,currentDecision.decision)}if(currentDecision.decision==="duplicate"){return{...current,decision:"duplicate",readBackVerified:true}}if(current&&candidate.manifestEpoch<=current.manifestEpoch){fail21("ROUTE_PROJECTOR_MANIFEST_EPOCH_STALE")}const staged=await readStoredRoute(stagedPath,options);const stagedDecision=decideServingRouteEntryApply(staged?{routeEpoch:staged.routeEpoch,routeHash:staged.routeHash}:null,candidate.entry);if(stagedDecision.decision==="reject_stale"||stagedDecision.decision==="reject_conflict"){return rejectedPreparation(candidate,stagedDecision.decision)}if(stagedDecision.decision==="duplicate"){if(!staged||staged.manifestHash!==candidate.manifestHash){fail21("ROUTE_PROJECTOR_MANIFEST_EQUIVOCATION")}return{...staged,decision:"duplicate",readBackVerified:true}}await atomicWrite2(stagedPath,storedBody(options.envelope));const readBack=await readStoredRoute(stagedPath,options);if(!readBack||readBack.appId!==candidate.appId||readBack.routeEpoch!==candidate.routeEpoch||readBack.routeHash!==candidate.routeHash||readBack.manifestHash!==candidate.manifestHash){fail21("ROUTE_PROJECTOR_READ_BACK_FAILED")}return{...readBack,decision:"prepared",readBackVerified:true}})}async function commitPreparedServingRouteProjection(options){const candidate=verifySingleRoute(options.envelope,options);const appsRoot=await ensurePrivateRoot(options.root);const stagedRoot=await ensurePrivateStagedRoot(options.root);const currentPath=join20(appsRoot,`${candidate.appId}.json`);const stagedPath=join20(stagedRoot,`${candidate.appId}.json`);return withAppLock(currentPath,async()=>{const current=await readStoredRoute(currentPath,options);const apply=decideServingRouteEntryApply(current?{routeEpoch:current.routeEpoch,routeHash:current.routeHash}:null,candidate.entry);if(apply.decision==="reject_stale"||apply.decision==="reject_conflict"){return{...candidate,decision:apply.decision==="reject_stale"?"rejected_stale":"rejected_conflict",readBackVerified:false}}if(apply.decision==="duplicate"){if(!current||current.manifestHash!==candidate.manifestHash){fail21("ROUTE_PROJECTOR_MANIFEST_EQUIVOCATION")}await removeAndSync(stagedPath).catch(()=>void 0);return{...current,decision:"duplicate",readBackVerified:true}}const staged=await readStoredRoute(stagedPath,options);if(!staged||staged.appId!==candidate.appId||staged.entry.appInstanceId!==candidate.entry.appInstanceId||staged.routeEpoch!==candidate.routeEpoch||staged.routeHash!==candidate.routeHash){fail21("ROUTE_PROJECTOR_PREPARE_REQUIRED")}if(current&&candidate.manifestEpoch<=current.manifestEpoch){fail21("ROUTE_PROJECTOR_MANIFEST_EPOCH_STALE")}await atomicWrite2(currentPath,storedBody(options.envelope));const readBack=await readStoredRoute(currentPath,options);if(!readBack||readBack.appId!==candidate.appId||readBack.routeEpoch!==candidate.routeEpoch||readBack.routeHash!==candidate.routeHash||readBack.manifestHash!==candidate.manifestHash){fail21("ROUTE_PROJECTOR_READ_BACK_FAILED")}await removeAndSync(stagedPath).catch(()=>void 0);return{...readBack,decision:"applied",readBackVerified:true}})}async function applySignedServingRouteProjection(options){const candidate=verifySingleRoute(options.envelope,options);const appsRoot=await ensurePrivateRoot(options.root);const path5=join20(appsRoot,`${candidate.appId}.json`);return withAppLock(path5,async()=>{const current=await readStoredRoute(path5,options);const apply=decideServingRouteEntryApply(current?{routeEpoch:current.routeEpoch,routeHash:current.routeHash}:null,candidate.entry);if(apply.decision==="reject_stale"||apply.decision==="reject_conflict"){return{...candidate,decision:apply.decision==="reject_stale"?"rejected_stale":"rejected_conflict",readBackVerified:false}}if(apply.decision==="duplicate"){if(!current||current.manifestHash!==candidate.manifestHash){fail21("ROUTE_PROJECTOR_MANIFEST_EQUIVOCATION")}return{...current,decision:"duplicate",readBackVerified:true}}if(current&&candidate.manifestEpoch<=current.manifestEpoch){fail21("ROUTE_PROJECTOR_MANIFEST_EPOCH_STALE")}await atomicWrite2(path5,storedBody(options.envelope));const readBack=await readStoredRoute(path5,options);if(!readBack||readBack.appId!==candidate.appId||readBack.routeEpoch!==candidate.routeEpoch||readBack.routeHash!==candidate.routeHash||readBack.manifestHash!==candidate.manifestHash){fail21("ROUTE_PROJECTOR_READ_BACK_FAILED")}return{...readBack,decision:"applied",readBackVerified:true}})}async function loadServingRouteProjectionLkg(options){return createServingRouteProjectionLkgReader(options).load()}function createServingRouteProjectionLkgReader(options){const now=options.now??Date.now;const files=new Map;const stats={loads:0,directoryScans:0,fileReads:0};let last2;const load=async()=>{stats.loads+=1;const appsRoot=await ensurePrivateRoot(options.root);const startedAt=now();const directory=await stat10(appsRoot,{bigint:true});const directorySignature=`${directory.ino}:${directory.mtimeNs}:${directory.ctimeNs}`;if(last2?.trusted&&last2.directorySignature===directorySignature&&startedAt-last2.scannedAt<FULL_REVALIDATION_INTERVAL_MS){return last2.snapshot}stats.directoryScans+=1;const routes=new Map;const rejectedAppIds=[];const seen=new Set;for(const filename of(await readdir7(appsRoot)).sort()){const match2=filename.match(APP_FILE);if(!match2)continue;const appId=Number(match2[1]);if(!Number.isSafeInteger(appId)||appId<1)continue;const path5=join20(appsRoot,filename);seen.add(path5);let signature;try{const fileStat=await lstat8(path5,{bigint:true});signature=`${fileStat.ino}:${fileStat.size}:${fileStat.mode}:${fileStat.uid}:${fileStat.mtimeNs}:${fileStat.ctimeNs}`}catch{signature=void 0}let cached2=signature?files.get(path5):void 0;if(!cached2||cached2.signature!==signature){stats.fileReads+=1;let route=null;try{route=await readStoredRoute(path5,options);if(!route||route.appId!==appId)route=null}catch{route=null}cached2={signature:signature??"",route};if(signature)files.set(path5,cached2)}if(cached2.route)routes.set(appId,cached2.route);else rejectedAppIds.push(appId)}for(const path5 of files.keys())if(!seen.has(path5))files.delete(path5);rejectedAppIds.push(...quarantineServingRouteIdentityCollisions(routes));const snapshot={routes,rejectedAppIds:[...new Set(rejectedAppIds)].sort((a,b2)=>a-b2)};last2={directorySignature,trusted:startedAt-Number(directory.mtimeNs/1000000n)>DIRECTORY_MTIME_SETTLE_MS,scannedAt:startedAt,snapshot};return snapshot};return{load,stats}}var STORAGE_VERSION,MAX_STORED_ENVELOPE_BYTES,APP_FILE,appLocks,DIRECTORY_MTIME_SETTLE_MS,FULL_REVALIDATION_INTERVAL_MS;var init_serving_route_projector_lkg=__esm({"../server/src/serving-route-projector-lkg.ts"(){"use strict";init_serving_route_manifest_contract();STORAGE_VERSION=1;MAX_STORED_ENVELOPE_BYTES=5*1024*1024;APP_FILE=/^(\d+)\.json$/u;appLocks=new Map;DIRECTORY_MTIME_SETTLE_MS=1e3;FULL_REVALIDATION_INTERVAL_MS=3e4}});import{timingSafeEqual as timingSafeEqual14}from"node:crypto";function fail22(code){throw new Error(code)}function exactRecord3(input2,keys2,code){if(!input2||typeof input2!=="object"||Array.isArray(input2))fail22(code);const record3=input2;if(Object.keys(record3).sort().join(",")!==[...keys2].sort().join(","))fail22(code);return record3}function validPositive(value2){return typeof value2==="number"&&Number.isSafeInteger(value2)&&value2>0}function parseServingRouteProjectorDeliveryRequest(input2){const record3=exactRecord3(input2,["protocolVersion","eventId","phase","appId","appInstanceId","routeEpoch","entryHash","manifestHash","topologyRevision","envelope"],"ROUTE_PROJECTOR_REQUEST_INVALID");if(record3.protocolVersion!==1||typeof record3.eventId!=="string"||!EVENT_ID2.test(record3.eventId)||record3.phase!=="prepare"&&record3.phase!=="commit"&&record3.phase!=="tombstone"||!validPositive(record3.appId)||typeof record3.appInstanceId!=="string"||!REFERENCE8.test(record3.appInstanceId)||!validPositive(record3.routeEpoch)||typeof record3.entryHash!=="string"||!SHA25613.test(record3.entryHash)||typeof record3.manifestHash!=="string"||!SHA25613.test(record3.manifestHash)||typeof record3.topologyRevision!=="string"||!REFERENCE8.test(record3.topologyRevision)){fail22("ROUTE_PROJECTOR_REQUEST_INVALID")}return record3}function rejectionCode(error62){const code=error62 instanceof Error?error62.message:"";return FAILURE_CODE.test(code)?code:"ROUTE_PROJECTOR_APPLY_FAILED"}async function applyTargetAndReadBack(options,phase,projection){if(!options.applyTarget)return projection.routeHash;const timeoutMs=options.targetApplyTimeoutMs??2e3;if(!Number.isSafeInteger(timeoutMs)||timeoutMs<100||timeoutMs>3e4){fail22("ROUTE_PROJECTOR_CONFIG_INVALID")}const controller=new AbortController;const timeout=setTimeout(()=>controller.abort("ROUTE_PROJECTOR_TARGET_TIMEOUT"),timeoutMs);try{const readBackHash=await options.applyTarget({phase,projection,signal:controller.signal});if(readBackHash!==projection.routeHash){fail22("ROUTE_PROJECTOR_TARGET_READ_BACK_MISMATCH")}return readBackHash}catch(error62){if(controller.signal.aborted)fail22("ROUTE_PROJECTOR_TARGET_TIMEOUT");throw error62}finally{clearTimeout(timeout)}}function receiptBase(request,options){return{protocolVersion:1,eventId:request.eventId,phase:request.phase,projectorId:options.projectorId,appId:request.appId,appInstanceId:request.appInstanceId,routeEpoch:request.routeEpoch,entryHash:request.entryHash,manifestHash:request.manifestHash,topologyRevision:request.topologyRevision,processInvocation:options.processInvocation,configGeneration:options.configGeneration}}async function applyServingRouteProjectorDelivery(input2,options){if(!REFERENCE8.test(options.projectorId)||!REFERENCE8.test(options.processInvocation)||!REFERENCE8.test(options.configGeneration)){fail22("ROUTE_PROJECTOR_CONFIG_INVALID")}const request=parseServingRouteProjectorDeliveryRequest(input2);const base2=receiptBase(request,options);try{const verified=verifySignedServingRouteManifest(request.envelope,{expectedEnvironment:options.expectedEnvironment,trustedPublicKeys:options.trustedPublicKeys});const verifiedEntry=verified.manifest.entries[0];if(verified.manifest.entries.length!==1||!verifiedEntry||verifiedEntry.appId!==request.appId||verifiedEntry.appInstanceId!==request.appInstanceId||verifiedEntry.routeEpoch!==request.routeEpoch||hashServingRouteManifestEntry(verifiedEntry)!==request.entryHash||verified.manifestHash!==request.manifestHash||request.phase==="tombstone"!==(verifiedEntry.disposition==="tombstone")){fail22("ROUTE_PROJECTOR_DELIVERY_IDENTITY_MISMATCH")}const projectionOptions={root:options.root,expectedEnvironment:options.expectedEnvironment,trustedPublicKeys:options.trustedPublicKeys,envelope:request.envelope};const projection=request.phase==="prepare"?await prepareSignedServingRouteProjection(projectionOptions):request.phase==="commit"?await commitPreparedServingRouteProjection(projectionOptions):await applySignedServingRouteProjection(projectionOptions);if(projection.appId!==request.appId||projection.entry.appInstanceId!==request.appInstanceId||projection.routeEpoch!==request.routeEpoch||projection.routeHash!==request.entryHash||projection.manifestHash!==request.manifestHash||request.phase==="tombstone"!==(projection.entry.disposition==="tombstone")){fail22("ROUTE_PROJECTOR_DELIVERY_IDENTITY_MISMATCH")}if(projection.decision==="rejected_stale"||projection.decision==="rejected_conflict"){return{...base2,result:"rejected",readBackHash:null,failureCode:projection.decision==="rejected_stale"?"ROUTE_PROJECTOR_ROUTE_EPOCH_STALE":"ROUTE_PROJECTOR_ROUTE_EPOCH_CONFLICT"}}if(!projection.readBackVerified)fail22("ROUTE_PROJECTOR_READ_BACK_FAILED");const targetReadBackHash=await applyTargetAndReadBack(options,request.phase,projection);return{...base2,result:request.phase==="prepare"?"prepared":"applied",readBackHash:targetReadBackHash,failureCode:null}}catch(error62){return{...base2,result:"rejected",readBackHash:null,failureCode:rejectionCode(error62)}}}function authorized(header,token){const expected=`Bearer ${token}`;if(header===null)return false;const left=Buffer.from(header);const right=Buffer.from(expected);return left.length===right.length&&timingSafeEqual14(left,right)}function json2(body,status){return Response.json(body,{status,headers:{"cache-control":"no-store","x-content-type-options":"nosniff"}})}function createServingRouteProjectorRequestHandler(options){if(options.authorizationToken.length<32||options.authorizationToken.length>512){fail22("ROUTE_PROJECTOR_CONFIG_INVALID")}return async request=>{const url2=new URL(request.url);if(request.method!=="POST"||url2.pathname!=="/v1/routes/apply"){return json2({error:"not_found"},404)}if(!authorized(request.headers.get("authorization"),options.authorizationToken)){return json2({error:"forbidden"},403)}const declaredLength=Number(request.headers.get("content-length")??"0");if(Number.isFinite(declaredLength)&&declaredLength>MAX_REQUEST_BYTES){return json2({error:"payload_too_large"},413)}let text33;try{text33=await request.text()}catch{return json2({error:"invalid_request"},400)}if(Buffer.byteLength(text33,"utf8")>MAX_REQUEST_BYTES){return json2({error:"payload_too_large"},413)}let decoded;try{decoded=JSON.parse(text33)}catch{return json2({error:"invalid_request"},400)}try{return json2(await applyServingRouteProjectorDelivery(decoded,options),200)}catch{return json2({error:"invalid_request"},400)}}}var EVENT_ID2,REFERENCE8,SHA25613,FAILURE_CODE,MAX_REQUEST_BYTES;var init_serving_route_projector_protocol=__esm({"../server/src/serving-route-projector-protocol.ts"(){"use strict";init_serving_route_manifest_contract();init_serving_route_projector_lkg();EVENT_ID2=/^serving_route_[a-f0-9]{64}$/u;REFERENCE8=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;SHA25613=/^[a-f0-9]{64}$/u;FAILURE_CODE=/^[A-Z][A-Z0-9_]{2,127}$/u;MAX_REQUEST_BYTES=5*1024*1024}});function sameServingRouteProjection(left,right){return left.appId===right.appId&&left.entry.appInstanceId===right.entry.appInstanceId&&left.routeEpoch===right.routeEpoch&&left.routeHash===right.routeHash}function isStrictlyNewerServingRouteProjection(candidate,current){return candidate.routeEpoch>current.routeEpoch}function assertForwardServingRouteProjection(input2){if(!input2.current||isStrictlyNewerServingRouteProjection(input2.candidate,input2.current)||sameServingRouteProjection(input2.current,input2.candidate)){return}throw new Error(input2.candidate.routeEpoch===input2.current.routeEpoch?input2.epochConflictCode:input2.epochStaleCode)}var init_serving_route_projection_order=__esm({"../server/src/serving-route-projection-order.ts"(){"use strict"}});function fail23(code){throw new Error(code)}var StaticOriginTargetState;var init_static_origin_target_state=__esm({"../static-origin/src/static-origin-target-state.ts"(){"use strict";init_serving_route_projection_order();init_static_origin_caddy_compiler();StaticOriginTargetState=class{activeRoutes;unavailable=new Map;preparedRoutes=new Map;transitionTail=Promise.resolve();originRoot;meteringAccessLogFile;nodeId;listenHost;listenPort;adminPort;caddy;generationCache;constructor(input2){this.originRoot=input2.originRoot;this.meteringAccessLogFile=input2.meteringAccessLogFile;this.nodeId=input2.nodeId;this.listenHost=input2.listenHost;this.listenPort=input2.listenPort;this.adminPort=input2.adminPort;this.activeRoutes=new Map([...input2.activeRoutes].map(route=>[route.appId,route]));this.caddy=input2.caddy;this.generationCache=createStaticOriginCompileCache(input2.originRoot)}get generationVerificationStats(){return this.generationCache.stats}retainLiveGenerations(){const live=[...this.activeRoutes.values(),...this.preparedRoutes.values()].flatMap(route=>route.entry.static?[{appInstanceId:route.entry.appInstanceId,generationRef:route.entry.static.generationRef,integritySha256:route.entry.static.integritySha256}]:[]);this.generationCache.retain(live)}activeRouteHash(appId){return this.activeRoutes.get(appId)?.routeHash??null}get activeRouteCount(){return this.activeRoutes.size}async compile(routes,candidateAppId){return compileStaticOriginCaddyfile({originRoot:this.originRoot,meteringAccessLogFile:this.meteringAccessLogFile,nodeId:this.nodeId,listenHost:this.listenHost,listenPort:this.listenPort,adminPort:this.adminPort,projections:[...routes],generationCache:this.generationCache,candidateAppId})}async compileAndLoad(routes,candidateAppId,signal){const compiled=await this.compile(routes,candidateAppId);await this.caddy.load(compiled.caddyfile,signal);this.unavailable=new Map(compiled.unavailable.map(({appId,code})=>[appId,code]))}get unavailableApps(){return this.unavailable}async initialize(signal){await this.compileAndLoad(this.activeRoutes.values(),void 0,signal);this.retainLiveGenerations()}async applyTarget(input2){const previous=this.transitionTail;let release;this.transitionTail=new Promise(resolve159=>{release=resolve159});await previous;try{if(input2.signal?.aborted)fail23("STATIC_ORIGIN_TARGET_APPLY_ABORTED");return await this.applyLocked(input2)}finally{this.retainLiveGenerations();release()}}async applyLocked(input2){const candidate=input2.projection;const current=this.activeRoutes.get(candidate.appId);assertForwardServingRouteProjection({current,candidate,epochConflictCode:"STATIC_ORIGIN_TARGET_EPOCH_CONFLICT",epochStaleCode:"STATIC_ORIGIN_TARGET_EPOCH_STALE"});if(current&&sameServingRouteProjection(current,candidate))return candidate.routeHash;if(input2.phase==="prepare"){if(candidate.entry.disposition!=="upsert")fail23("STATIC_ORIGIN_TARGET_PHASE_INVALID");const staged=this.preparedRoutes.get(candidate.appId);if(staged&&!sameServingRouteProjection(staged,candidate)){if(!isStrictlyNewerServingRouteProjection(candidate,staged)){fail23("STATIC_ORIGIN_TARGET_PREPARE_CONFLICT")}this.preparedRoutes.delete(candidate.appId)}const prospective=new Map(this.activeRoutes);for(const prepared of this.preparedRoutes.values())prospective.set(prepared.appId,prepared);prospective.set(candidate.appId,candidate);const validation=await this.compile(prospective.values(),candidate.appId);await this.caddy.validate(validation.caddyfile,input2.signal);this.preparedRoutes.set(candidate.appId,candidate);return candidate.routeHash}if(input2.phase==="commit"){const prepared=this.preparedRoutes.get(candidate.appId);if(prepared&&!sameServingRouteProjection(prepared,candidate)){fail23("STATIC_ORIGIN_TARGET_PREPARE_CONFLICT")}if(!prepared){const recovered=new Map(this.activeRoutes);recovered.set(candidate.appId,candidate);const validation=await this.compile(recovered.values(),candidate.appId);await this.caddy.validate(validation.caddyfile,input2.signal)}}else if(candidate.entry.disposition!=="tombstone"){fail23("STATIC_ORIGIN_TARGET_PHASE_INVALID")}const next=new Map(this.activeRoutes);next.set(candidate.appId,candidate);await this.compileAndLoad(next.values(),candidate.appId,input2.signal);this.activeRoutes=next;this.preparedRoutes.delete(candidate.appId);return candidate.routeHash}}}});function resolveStaticOriginTargetApplyTimeoutMs(env){const raw2=env.GENCOW_STATIC_ORIGIN_TARGET_APPLY_TIMEOUT_MS?.trim()??"";if(!raw2)return STATIC_ORIGIN_TARGET_APPLY_TIMEOUT_MS;const value2=/^[0-9]{1,6}$/u.test(raw2)?Number(raw2):Number.NaN;if(!Number.isSafeInteger(value2)||value2<MIN_TARGET_APPLY_TIMEOUT_MS||value2>MAX_TARGET_APPLY_TIMEOUT_MS){fail24("STATIC_ORIGIN_TARGET_APPLY_TIMEOUT_INVALID")}return value2}function fail24(code){throw new Error(code)}function waitForShutdownSignal(){return new Promise(resolveShutdown=>{const shutdown=()=>{process.off("SIGTERM",shutdown);process.off("SIGINT",shutdown);resolveShutdown()};process.once("SIGTERM",shutdown);process.once("SIGINT",shutdown)})}function processInvocation(env){const invocation=env.INVOCATION_ID?.trim().toLowerCase()??"";if(!/^[a-f0-9]{32}$/u.test(invocation))fail24("STATIC_ORIGIN_INVOCATION_REQUIRED");return invocation}function json3(body,status=200){return Response.json(body,{status,headers:{"cache-control":"no-store","x-content-type-options":"nosniff"}})}function defaultCaddyTarget(config2){const applier=new StaticOriginCaddyApplier({stateRoot:config2.stateRoot,caddyBinary:config2.caddyBinary,adminPort:config2.adminPort});return{validate:async(caddyfile,signal)=>void await applier.prepare(caddyfile,signal),load:async(caddyfile,signal)=>void await applier.load(caddyfile,signal)}}async function runStaticOriginEntry(options={}){const env=options.env??process.env;const logger3=options.logger??console;if(env.GENCOW_STATIC_ORIGIN_ENABLED!=="true"){logger3.log("[static-origin] disabled");return false}if(DATABASE_ENV_KEYS.some(key2=>Boolean(env[key2]?.trim()))){fail24("STATIC_ORIGIN_DATABASE_CREDENTIAL_FORBIDDEN")}const invocation=processInvocation(env);const targetApplyTimeoutMs=resolveStaticOriginTargetApplyTimeoutMs(env);const staticConfigFile=env.GENCOW_STATIC_ORIGIN_CONFIG_FILE?.trim()??"";const projectorConfigFile=env.GENCOW_ROUTE_PROJECTOR_CONFIG_FILE?.trim()??"";if(!staticConfigFile||!projectorConfigFile)fail24("STATIC_ORIGIN_CONFIG_FILE_REQUIRED");const[staticConfig,projectorConfig]=await Promise.all([(options.loadStaticConfigImpl??loadStaticOriginConfig)(staticConfigFile),(options.loadProjectorConfigImpl??loadServingRouteProjectorConfig)(projectorConfigFile)]);if(staticConfig.configGeneration!==projectorConfig.configGeneration){fail24("STATIC_ORIGIN_CONFIG_GENERATION_MISMATCH")}if(projectorConfig.listenPort===staticConfig.listenPort||projectorConfig.listenPort===staticConfig.adminPort){fail24("STATIC_ORIGIN_LISTENER_COLLISION")}const lkg=await(options.loadLkgImpl??loadServingRouteProjectionLkg)({root:projectorConfig.lkgRoot,expectedEnvironment:projectorConfig.environment,trustedPublicKeys:projectorConfig.trustedPublicKeys});const state2=new StaticOriginTargetState({...staticConfig,activeRoutes:lkg.routes.values(),caddy:(options.createCaddyTargetImpl??defaultCaddyTarget)(staticConfig)});await state2.initialize();for(const[appId,code]of state2.unavailableApps){logger3.warn(`[static-origin] generation unavailable app=${appId} code=${code}`)}const projector=(options.createProjectorHandlerImpl??createServingRouteProjectorRequestHandler)({root:projectorConfig.lkgRoot,expectedEnvironment:projectorConfig.environment,trustedPublicKeys:projectorConfig.trustedPublicKeys,projectorId:projectorConfig.projectorId,processInvocation:invocation,configGeneration:projectorConfig.configGeneration,authorizationToken:projectorConfig.authorizationToken,applyTarget:input2=>state2.applyTarget(input2),targetApplyTimeoutMs});const handler=async request=>{const pathname=new URL(request.url).pathname;if(pathname==="/v1/routes/apply")return projector(request);if(request.method==="GET"&&pathname==="/health/live")return json3({ok:true});if(request.method==="GET"&&pathname==="/health/core-ready"){return json3({ok:true,projectorId:projectorConfig.projectorId,configGeneration:projectorConfig.configGeneration,activeRouteCount:state2.activeRouteCount,quarantinedRouteCount:lkg.rejectedAppIds.length,unavailableRouteCount:state2.unavailableApps.size})}return json3({error:"Not found"},404)};const server2=(options.serveImpl??Bun.serve)({hostname:projectorConfig.listenHost,port:projectorConfig.listenPort,fetch:handler});logger3.log(`[static-origin] ready projector=${projectorConfig.projectorId} routes=${state2.activeRouteCount} quarantined=${lkg.rejectedAppIds.length} unavailable=${state2.unavailableApps.size}`);try{await(options.waitForShutdownImpl??waitForShutdownSignal)()}finally{await server2.stop?.(true)}return true}var DATABASE_ENV_KEYS,STATIC_ORIGIN_TARGET_APPLY_TIMEOUT_MS,MIN_TARGET_APPLY_TIMEOUT_MS,MAX_TARGET_APPLY_TIMEOUT_MS;var init_static_origin_entry=__esm({"../static-origin/src/static-origin-entry.ts"(){"use strict";init_serving_route_projector_config();init_serving_route_projector_lkg();init_serving_route_projector_protocol();init_static_origin_caddy_applier();init_static_origin_config();init_static_origin_target_state();DATABASE_ENV_KEYS=["DATABASE_URL","PLATFORM_DATABASE_URL","GENCOW_PLATFORM_DB","GENCOW_DIRECT_DATABASE_URL","GENCOW_DIRECT_DDL_DATABASE_URL","GENCOW_CATALOG_READ_DATABASE_URL","GENCOW_DEPLOYMENT_EXECUTOR_DATABASE_URL","GENCOW_ROUTE_PUBLISHER_DATABASE_URL"];STATIC_ORIGIN_TARGET_APPLY_TIMEOUT_MS=25e3;MIN_TARGET_APPLY_TIMEOUT_MS=2e3;MAX_TARGET_APPLY_TIMEOUT_MS=25e3;if(import.meta.main){runStaticOriginEntry().then(()=>process.exit(0)).catch(error62=>{console.error("[static-origin] fatal:",error62 instanceof Error?error62.message:String(error62));process.exit(1)})}}});import{chmod as chmod7,lstat as lstat9,readdir as readdir8,rm as rm7,rmdir}from"node:fs/promises";import{join as join21}from"node:path";var init_static_origin_generation_removal=__esm({"../static-origin/src/static-origin-generation-removal.ts"(){"use strict";init_static_origin_layout()}});import{randomUUID as randomUUID41}from"node:crypto";import{chmod as chmod8,cp as cp2,lstat as lstat10,mkdir as mkdir12,open as open9,readFile as readFile13,readdir as readdir9,rename as rename8,rm as rm8}from"node:fs/promises";import{dirname as dirname19,join as join22,relative as relative17,resolve as resolve74}from"node:path";var init_static_origin_generation_store=__esm({"../static-origin/src/static-origin-generation-store.ts"(){"use strict";init_static_origin_layout()}});import{createHash as createHash61,randomUUID as randomUUID42}from"node:crypto";import{constants as constants2}from"node:fs";import{lstat as lstat11,mkdir as mkdir13,open as open10,readFile as readFile14,readdir as readdir10,rename as rename9,rm as rm9}from"node:fs/promises";import{basename as basename9,dirname as dirname20,extname as extname11,isAbsolute as isAbsolute19,join as join23,resolve as resolve75}from"node:path";function fail25(code){throw Object.assign(new Error(code),{code})}function sha25611(value2){return createHash61("sha256").update(value2).digest("hex")}function safeInteger(value2,minimum=0){return typeof value2==="number"&&Number.isSafeInteger(value2)&&value2>=minimum}function accessLogName(file2,entry){const extension=extname11(file2);const stem=basename9(file2,extension);return entry===basename9(file2)||entry.startsWith(`${stem}-`)&&entry.endsWith(extension)}function exactCheckpoint(value2){if(!value2||typeof value2!=="object"||Array.isArray(value2)){return fail25("STATIC_METERING_CHECKPOINT_INVALID")}const record3=value2;if(Object.keys(record3).sort().join(",")!=="sources,version"||record3.version!==1&&record3.version!==2){return fail25("STATIC_METERING_CHECKPOINT_INVALID")}if(!record3.sources||typeof record3.sources!=="object"||Array.isArray(record3.sources)){return fail25("STATIC_METERING_CHECKPOINT_INVALID")}const sources=record3.sources;if(Object.keys(sources).length>MAX_CHECKPOINT_SOURCES){return fail25("STATIC_METERING_CHECKPOINT_INVALID")}const decoded={};for(const[identity2,source]of Object.entries(sources)){if(!/^[a-f0-9]{64}$/u.test(identity2)||!source||typeof source!=="object"){return fail25("STATIC_METERING_CHECKPOINT_INVALID")}const fields=source;const legacy=record3.version===1;if(Object.keys(fields).sort().join(",")!==(legacy?"offset,updatedAt":"observedSize,offset,updatedAt")||!safeInteger(fields.offset)||!legacy&&(!safeInteger(fields.observedSize)||fields.observedSize<fields.offset)||typeof fields.updatedAt!=="string"||!Number.isFinite(Date.parse(fields.updatedAt))){return fail25("STATIC_METERING_CHECKPOINT_INVALID")}decoded[identity2]={offset:fields.offset,observedSize:legacy?fields.offset:fields.observedSize,updatedAt:fields.updatedAt}}return{version:2,sources:decoded}}async function loadCheckpoint(path5){const info2=await lstat11(path5).catch(()=>null);if(!info2)return{version:2,sources:{}};const processUid=process.getuid?.();if(!info2.isFile()||info2.isSymbolicLink()||info2.size<1||info2.size>256*1024||(info2.mode&511)!==384||processUid!==void 0&&info2.uid!==0&&info2.uid!==processUid){return fail25("STATIC_METERING_CHECKPOINT_UNSAFE")}try{return exactCheckpoint(JSON.parse(await readFile14(path5,"utf8")))}catch(error62){if(error62.message.startsWith("STATIC_METERING_"))throw error62;return fail25("STATIC_METERING_CHECKPOINT_INVALID")}}async function syncDirectory2(path5){const handle=await open10(path5,"r");try{await handle.sync()}finally{await handle.close()}}async function persistCheckpoint(path5,checkpoint){const parent=dirname20(path5);await mkdir13(parent,{recursive:true,mode:448});const parentInfo=await lstat11(parent);const processUid=process.getuid?.();if(!parentInfo.isDirectory()||parentInfo.isSymbolicLink()||(parentInfo.mode&511)!==448||processUid!==void 0&&parentInfo.uid!==0&&parentInfo.uid!==processUid){return fail25("STATIC_METERING_CHECKPOINT_UNSAFE")}const temp=join23(parent,`.static-metering-${randomUUID42()}.tmp`);const handle=await open10(temp,"wx",384);try{await handle.writeFile(JSON.stringify(checkpoint),"utf8");await handle.sync()}catch(error62){await handle.close().catch(()=>void 0);await rm9(temp,{force:true}).catch(()=>void 0);throw error62}await handle.close();await rename9(temp,path5);await syncDirectory2(parent)}function parseAccessRecord(input2,nodeId,sourceIdentity,sequence){let decoded;try{decoded=JSON.parse(input2)}catch{return fail25("STATIC_METERING_ACCESS_RECORD_INVALID")}if(!decoded||typeof decoded!=="object"||Array.isArray(decoded)){return fail25("STATIC_METERING_ACCESS_RECORD_INVALID")}const record3=decoded;const appId=Number(record3.gencow_app_id);const routeEpoch=Number(record3.gencow_route_epoch);if(!safeInteger(appId,1)||!safeInteger(routeEpoch)||!safeInteger(record3.status,100)||record3.status>599||!safeInteger(record3.size)||typeof record3.ts!=="number"||!Number.isFinite(record3.ts)){return fail25("STATIC_METERING_ACCESS_RECORD_INVALID")}const observedAt=new Date(record3.ts*1e3);if(!Number.isFinite(observedAt.getTime()))return fail25("STATIC_METERING_ACCESS_RECORD_INVALID");const gatewayId=`static:${sha25611(nodeId).slice(0,24)}`;const invocationId=sha25611(`${nodeId}\0${sourceIdentity}`).slice(0,32);return{version:1,eventId:sha25611(`${gatewayId}\0${invocationId}\0${sequence}`),gatewayId,invocationId,sequence,observedAt:observedAt.toISOString(),appId,routeEpoch,requestCount:1,responseBytes:record3.size,status:record3.status}}function pruneCheckpoint(checkpoint,active){const entries=Object.entries(checkpoint.sources);if(entries.length<MAX_CHECKPOINT_SOURCES)return;entries.filter(([identity2,source])=>!active.has(identity2)&&source.offset===source.observedSize).sort((left,right)=>Date.parse(left[1].updatedAt)-Date.parse(right[1].updatedAt)).slice(0,entries.length-MAX_CHECKPOINT_SOURCES+1).forEach(([identity2])=>delete checkpoint.sources[identity2])}async function collectStaticOriginAccessLogsOnce(input2){if(!isAbsolute19(input2.accessLogFile)||!isAbsolute19(input2.checkpointFile)||!NODE_ID2.test(input2.nodeId)){return fail25("STATIC_METERING_COLLECTOR_CONFIG_INVALID")}const accessLogFile=resolve75(input2.accessLogFile);const checkpointFile=resolve75(input2.checkpointFile);const directory=dirname20(accessLogFile);const directoryInfo=await lstat11(directory).catch(()=>null);if(!directoryInfo?.isDirectory()||directoryInfo.isSymbolicLink()||(directoryInfo.mode&488)!==488||(directoryInfo.mode&23)!==0){return fail25("STATIC_METERING_ACCESS_LOG_UNSAFE")}const entries=(await readdir10(directory,{withFileTypes:true}).catch(()=>[])).filter(entry=>accessLogName(accessLogFile,entry.name)).sort((left,right)=>left.name.localeCompare(right.name));const checkpoint=await loadCheckpoint(checkpointFile);const activeIdentities=new Set;let files=0;let records=0;let bytes2=0;for(const entry of entries){const path5=join23(directory,entry.name);const info2=await lstat11(path5,{bigint:true});if(!entry.isFile()||entry.isSymbolicLink()||!info2.isFile()||info2.isSymbolicLink()||(info2.mode&0o600n)!==0o600n||(info2.mode&0o027n)!==0n){return fail25("STATIC_METERING_ACCESS_LOG_UNSAFE")}if(info2.size>BigInt(MAX_LOG_BYTES))return fail25("STATIC_METERING_ACCESS_LOG_TOO_LARGE");const sourceIdentity=sha25611(`${info2.dev}:${info2.ino}:${info2.birthtimeNs}`);activeIdentities.add(sourceIdentity);const sourceCheckpoint=checkpoint.sources[sourceIdentity];const start2=sourceCheckpoint?.offset??0;if(BigInt(start2)>info2.size||sourceCheckpoint&&BigInt(sourceCheckpoint.observedSize)>info2.size){return fail25("STATIC_METERING_ACCESS_LOG_TRUNCATED")}const handle=await open10(path5,constants2.O_RDONLY|constants2.O_NOFOLLOW);const opened=await handle.stat({bigint:true});if(opened.dev!==info2.dev||opened.ino!==info2.ino){await handle.close();return fail25("STATIC_METERING_ACCESS_LOG_UNSAFE")}let offset=start2;let pending=Buffer.alloc(0);try{while(BigInt(offset)<info2.size){const remaining=Number(info2.size-BigInt(offset));const chunk2=Buffer.alloc(Math.min(1024*1024,remaining));const read=await handle.read(chunk2,0,chunk2.length,offset);if(read.bytesRead<1)break;const combined=Buffer.concat([pending,chunk2.subarray(0,read.bytesRead)]);let cursor=0;while(true){const newline=combined.indexOf(10,cursor);if(newline<0)break;const line=combined.subarray(cursor,newline).toString("utf8");const sequence=offset-pending.length+cursor+1;if(!line)return fail25("STATIC_METERING_ACCESS_RECORD_INVALID");await input2.spool.appendDurableRecord(parseAccessRecord(line,input2.nodeId,sourceIdentity,sequence));records+=1;cursor=newline+1}offset+=read.bytesRead;pending=combined.subarray(cursor)}}finally{await handle.close()}const durableOffset=offset-pending.length;const observedSize=Number(info2.size);if(durableOffset>start2||sourceCheckpoint?.observedSize!==observedSize){checkpoint.sources[sourceIdentity]={offset:durableOffset,observedSize,updatedAt:(input2.now??(()=>new Date))().toISOString()};pruneCheckpoint(checkpoint,activeIdentities);await persistCheckpoint(checkpointFile,checkpoint);bytes2+=durableOffset-start2}files+=1}if(Object.entries(checkpoint.sources).some(([identity2,source])=>!activeIdentities.has(identity2)&&source.offset<source.observedSize)){return fail25("STATIC_METERING_ACCESS_LOG_GAP")}return{files,records,bytes:bytes2}}var NODE_ID2,MAX_LOG_BYTES,MAX_CHECKPOINT_SOURCES;var init_static_origin_metering_collector=__esm({"../static-origin/src/static-origin-metering-collector.ts"(){"use strict";NODE_ID2=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;MAX_LOG_BYTES=128*1024*1024;MAX_CHECKPOINT_SOURCES=512}});import{createHash as createHash62}from"node:crypto";import{chmod as chmod9,lstat as lstat12,mkdir as mkdir14,open as open11,readFile as readFile15,readdir as readdir11,rename as rename10,truncate,unlink as unlink5}from"node:fs/promises";import{isAbsolute as isAbsolute20,resolve as resolve76}from"node:path";function fail26(code){throw Object.assign(new Error(code),{code})}function sha25612(value2){return createHash62("sha256").update(value2).digest("hex")}function integer35(value2,minimum,maximum){return typeof value2==="number"&&Number.isSafeInteger(value2)&&value2>=minimum&&value2<=maximum}function assertInput(input2){if(!integer35(input2.appId,1,Number.MAX_SAFE_INTEGER)||!integer35(input2.routeEpoch,0,Number.MAX_SAFE_INTEGER)||!integer35(input2.responseBytes,0,Number.MAX_SAFE_INTEGER)||!integer35(input2.status,100,599)){fail26("ROUTE_GATEWAY_METERING_EVENT_INVALID")}}function canonicalRecord(record3){return JSON.stringify({version:record3.version,eventId:record3.eventId,gatewayId:record3.gatewayId,invocationId:record3.invocationId,sequence:record3.sequence,observedAt:record3.observedAt,appId:record3.appId,routeEpoch:record3.routeEpoch,requestCount:record3.requestCount,responseBytes:record3.responseBytes,status:record3.status})}function encodeRecord(record3){return`${JSON.stringify({...record3,checksumSha256:sha25612(canonicalRecord(record3))})}
|
|
9051
9051
|
`}function assertPreparedRecord(record3){if(record3.version!==1||!IDENTITY.test(record3.gatewayId)||!INVOCATION.test(record3.invocationId)||!integer35(record3.sequence,1,Number.MAX_SAFE_INTEGER)||!Number.isFinite(Date.parse(record3.observedAt))||record3.requestCount!==1||record3.eventId!==sha25612(`${record3.gatewayId}\0${record3.invocationId}\0${record3.sequence}`)){fail26("ROUTE_GATEWAY_METERING_EVENT_INVALID")}assertInput(record3)}function decodeRouteGatewayMeteringRecord(line){let decoded;try{decoded=JSON.parse(line)}catch{return fail26("ROUTE_GATEWAY_METERING_RECORD_CORRUPT")}const record3=decoded;const exactKeys2=["appId","checksumSha256","eventId","gatewayId","invocationId","observedAt","requestCount","responseBytes","routeEpoch","sequence","status","version"];if(!decoded||typeof decoded!=="object"||Array.isArray(decoded)||Object.keys(decoded).sort().join(",")!==exactKeys2.sort().join(",")||record3.version!==1||typeof record3.eventId!=="string"||!/^[a-f0-9]{64}$/u.test(record3.eventId)||typeof record3.gatewayId!=="string"||!IDENTITY.test(record3.gatewayId)||typeof record3.invocationId!=="string"||!INVOCATION.test(record3.invocationId)||!integer35(record3.sequence,1,Number.MAX_SAFE_INTEGER)||typeof record3.observedAt!=="string"||!Number.isFinite(Date.parse(record3.observedAt))||record3.requestCount!==1||typeof record3.checksumSha256!=="string"){return fail26("ROUTE_GATEWAY_METERING_RECORD_CORRUPT")}assertInput(record3);if(record3.eventId!==sha25612(`${record3.gatewayId}\0${record3.invocationId}\0${record3.sequence}`)||record3.checksumSha256!==sha25612(canonicalRecord(record3))){return fail26("ROUTE_GATEWAY_METERING_RECORD_CORRUPT")}return record3}async function syncDirectory3(root2){const handle=await open11(root2,"r");try{await handle.sync()}finally{await handle.close()}}async function prepareRoot(root2){if(!isAbsolute20(root2))fail26("ROUTE_GATEWAY_METERING_ROOT_UNSAFE");await mkdir14(root2,{recursive:true,mode:448});const info2=await lstat12(root2);const processUid=process.getuid?.();if(info2.isSymbolicLink()||!info2.isDirectory()||(info2.mode&63)!==0||processUid!==void 0&&info2.uid!==0&&info2.uid!==processUid){fail26("ROUTE_GATEWAY_METERING_ROOT_UNSAFE")}await chmod9(root2,448)}async function recoverOpenSegments(root2){for(const entry of await readdir11(root2,{withFileTypes:true})){const match2=SEGMENT.exec(entry.name);if(!match2||match2[3]!=="open"||!entry.isFile())continue;const path5=resolve76(root2,entry.name);const bytes2=await readFile15(path5);const lastNewline=bytes2.lastIndexOf(10);const durableLength=lastNewline<0?0:lastNewline+1;if(durableLength!==bytes2.byteLength)await truncate(path5,durableLength);const text33=bytes2.subarray(0,durableLength).toString("utf8");for(const line of text33.split("\n").filter(Boolean))decodeRouteGatewayMeteringRecord(line);const sealed=path5.replace(/\.open$/u,".sealed");try{await lstat12(sealed);fail26("ROUTE_GATEWAY_METERING_SEGMENT_COLLISION")}catch(error62){if(error62.code!=="ENOENT")throw error62}await rename10(path5,sealed)}await syncDirectory3(root2)}async function assertInvocationUnused(root2,invocationId){for(const entry of await readdir11(root2,{withFileTypes:true})){const match2=SEGMENT.exec(entry.name);if(entry.isFile()&&match2?.[1]===invocationId){fail26("ROUTE_GATEWAY_METERING_INVOCATION_REUSED")}}}async function mapConcurrent(values2,concurrency,mapper){const results=new Array(values2.length);let next=0;async function worker(){while(next<values2.length){const index27=next++;results[index27]=await mapper(values2[index27])}}await Promise.all(Array.from({length:Math.min(concurrency,values2.length)},()=>worker()));return results}async function spoolSnapshot(root2){const entries=(await readdir11(root2,{withFileTypes:true})).filter(entry=>entry.isFile()&&SEGMENT.test(entry.name));const snapshots=await mapConcurrent(entries,32,async entry=>{const path5=resolve76(root2,entry.name);const info2=await lstat12(path5);if(!info2.isFile()||info2.isSymbolicLink())fail26("ROUTE_GATEWAY_METERING_RECORD_CORRUPT");const content=await readFile15(path5);if(content.byteLength!==info2.size)fail26("ROUTE_GATEWAY_METERING_RECORD_CORRUPT");if(entry.name.endsWith(".sealed")&&content.length>0&&content[content.length-1]!==10){fail26("ROUTE_GATEWAY_METERING_RECORD_CORRUPT")}let backlogEvents=0;let oldestObservedAtMs=null;let oldestSequence=null;for(const line of content.toString("utf8").split("\n").filter(Boolean)){const record3=decodeRouteGatewayMeteringRecord(line);const observedAtMs=Date.parse(record3.observedAt);backlogEvents+=1;if(oldestObservedAtMs===null||observedAtMs<oldestObservedAtMs){oldestObservedAtMs=observedAtMs;oldestSequence=record3.sequence}}return{logicalBytes:content.byteLength,backlogEvents,oldestObservedAtMs,oldestSequence}});return snapshots.reduce((total,snapshot)=>({logicalBytes:total.logicalBytes+snapshot.logicalBytes,backlogEvents:total.backlogEvents+snapshot.backlogEvents,oldestObservedAtMs:total.oldestObservedAtMs===null||snapshot.oldestObservedAtMs!==null&&snapshot.oldestObservedAtMs<total.oldestObservedAtMs?snapshot.oldestObservedAtMs:total.oldestObservedAtMs,oldestSequence:total.oldestObservedAtMs===null||snapshot.oldestObservedAtMs!==null&&snapshot.oldestObservedAtMs<total.oldestObservedAtMs?snapshot.oldestSequence:total.oldestSequence}),{logicalBytes:0,backlogEvents:0,oldestObservedAtMs:null,oldestSequence:null})}var IDENTITY,INVOCATION,SEGMENT,RouteGatewayMeteringSpool;var init_route_gateway_metering_spool=__esm({"../route-gateway/src/route-gateway-metering-spool.ts"(){"use strict";IDENTITY=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;INVOCATION=/^[a-f0-9]{32}$/u;SEGMENT=/^meter-v1\.([a-f0-9]{32})\.(\d{16})\.(open|sealed)$/u;RouteGatewayMeteringSpool=class _RouteGatewayMeteringSpool{root;gatewayId;invocationId;maxSpoolBytes;maxSegmentBytes;maxSegmentEvents;maxPendingEvents;nowMs;sequence=0;segmentPath=null;segmentBytes=0;segmentEvents=0;totalBytes=0;backlogEvents=0;oldestObservedAtMs=null;oldestSequence=null;acceptedEvents=0;durableEvents=0;droppedEvents=0;pendingEvents=0;lastErrorCode=null;closed=false;operations=Promise.resolve();constructor(options){this.root=resolve76(options.root);this.gatewayId=options.gatewayId;this.invocationId=options.invocationId;this.maxSpoolBytes=options.maxSpoolBytes;this.maxSegmentBytes=options.maxSegmentBytes;this.maxSegmentEvents=options.maxSegmentEvents;this.maxPendingEvents=options.maxPendingEvents;this.nowMs=options.nowMs}static async open(options){if(!isAbsolute20(options.root))fail26("ROUTE_GATEWAY_METERING_ROOT_UNSAFE");if(!IDENTITY.test(options.gatewayId)||!INVOCATION.test(options.invocationId)){fail26("ROUTE_GATEWAY_METERING_IDENTITY_INVALID")}const maxSpoolBytes=options.maxSpoolBytes??512*1024*1024;const maxSegmentBytes=options.maxSegmentBytes??8*1024*1024;const maxSegmentEvents=options.maxSegmentEvents??100;const maxPendingEvents=options.maxPendingEvents??1e4;if(!integer35(maxSpoolBytes,1024,64*1024*1024*1024)||!integer35(maxSegmentBytes,256,maxSpoolBytes)||!integer35(maxSegmentEvents,1,1e5)||!integer35(maxPendingEvents,1,1e6)){fail26("ROUTE_GATEWAY_METERING_LIMIT_INVALID")}const root2=resolve76(options.root);await prepareRoot(root2);await recoverOpenSegments(root2);await assertInvocationUnused(root2,options.invocationId);const spool=new _RouteGatewayMeteringSpool({...options,root:root2,maxSpoolBytes,maxSegmentBytes,maxSegmentEvents,maxPendingEvents,nowMs:options.nowMs??Date.now});const snapshot=await spoolSnapshot(root2);spool.totalBytes=snapshot.logicalBytes;spool.backlogEvents=snapshot.backlogEvents;spool.oldestObservedAtMs=snapshot.oldestObservedAtMs;spool.oldestSequence=snapshot.oldestSequence;return spool}record(input2){assertInput(input2);if(this.closed||this.pendingEvents>=this.maxPendingEvents){this.droppedEvents+=1;this.lastErrorCode=this.closed?"ROUTE_GATEWAY_METERING_CLOSED":"ROUTE_GATEWAY_METERING_QUEUE_FULL";return false}const sequence=++this.sequence;const observedAt=new Date(this.nowMs()).toISOString();const record3={version:1,eventId:sha25612(`${this.gatewayId}\0${this.invocationId}\0${sequence}`),gatewayId:this.gatewayId,invocationId:this.invocationId,sequence,observedAt,appId:input2.appId,routeEpoch:input2.routeEpoch,requestCount:1,responseBytes:input2.responseBytes,status:input2.status};this.acceptedEvents+=1;this.pendingEvents+=1;const storageSequence=sequence;void this.runExclusive(()=>this.append(record3,storageSequence)).catch(error62=>{this.droppedEvents+=1;this.lastErrorCode=error62&&typeof error62==="object"&&typeof error62.code==="string"?error62.code:"ROUTE_GATEWAY_METERING_WRITE_FAILED"}).finally(()=>{this.pendingEvents-=1});return true}runExclusive(operation){const result3=this.operations.then(operation);this.operations=result3.then(()=>void 0,()=>void 0);return result3}async appendDurableRecord(record3){assertPreparedRecord(record3);if(this.closed||this.pendingEvents>=this.maxPendingEvents){fail26(this.closed?"ROUTE_GATEWAY_METERING_CLOSED":"ROUTE_GATEWAY_METERING_QUEUE_FULL")}const storageSequence=++this.sequence;this.acceptedEvents+=1;this.pendingEvents+=1;try{await this.runExclusive(()=>this.append(record3,storageSequence))}catch(error62){this.droppedEvents+=1;this.lastErrorCode=error62&&typeof error62==="object"&&typeof error62.code==="string"?error62.code:"ROUTE_GATEWAY_METERING_WRITE_FAILED";throw error62}finally{this.pendingEvents-=1}}async append(record3,storageSequence){const encoded=encodeRecord(record3);const bytes2=Buffer.byteLength(encoded);if(this.totalBytes+bytes2>this.maxSpoolBytes)fail26("ROUTE_GATEWAY_METERING_SPOOL_FULL");if(!this.segmentPath||this.segmentBytes+bytes2>this.maxSegmentBytes||this.segmentEvents>=this.maxSegmentEvents){await this.sealSegment();this.segmentPath=resolve76(this.root,`meter-v1.${this.invocationId}.${String(storageSequence).padStart(16,"0")}.open`);this.segmentBytes=0;this.segmentEvents=0}const handle=await open11(this.segmentPath,"a",384);try{await handle.write(encoded);await handle.sync()}finally{await handle.close()}this.segmentBytes+=bytes2;this.segmentEvents+=1;this.totalBytes+=bytes2;this.backlogEvents+=1;const observedAtMs=Date.parse(record3.observedAt);if(this.oldestObservedAtMs===null||observedAtMs<this.oldestObservedAtMs){this.oldestObservedAtMs=observedAtMs;this.oldestSequence=record3.sequence}this.durableEvents+=1}async sealSegment(){if(!this.segmentPath)return;const sealed=this.segmentPath.replace(/\.open$/u,".sealed");await rename10(this.segmentPath,sealed);await syncDirectory3(this.root);this.segmentPath=null;this.segmentBytes=0;this.segmentEvents=0}diagnostics(){const oldestAgeMs=this.oldestObservedAtMs===null?null:Math.max(0,this.nowMs()-this.oldestObservedAtMs);return{acceptedEvents:this.acceptedEvents,durableEvents:this.durableEvents,droppedEvents:this.droppedEvents,pendingEvents:this.pendingEvents,backlogEvents:this.backlogEvents,logicalBytes:this.totalBytes,oldestSequence:this.oldestSequence,oldestObservedAt:this.oldestObservedAtMs===null?null:new Date(this.oldestObservedAtMs).toISOString(),oldestAgeMs,lastErrorCode:this.lastErrorCode}}async flush(){await this.operations}async prepareIngestBatch(input2={}){const maxEvents=input2.maxEvents??1e3;const maxBytes=input2.maxBytes??16*1024*1024;if(!integer35(maxEvents,1,1e5)||!integer35(maxBytes,this.maxSegmentBytes,512*1024*1024)){fail26("ROUTE_GATEWAY_METERING_BATCH_LIMIT_INVALID")}return this.runExclusive(async()=>{await this.sealSegment();const segments=[];let eventCount=0;let bytes2=0;const entries=(await readdir11(this.root,{withFileTypes:true})).filter(entry=>entry.isFile()&&SEGMENT.test(entry.name)&&entry.name.endsWith(".sealed")).sort((left,right)=>left.name.localeCompare(right.name));for(const entry of entries){const path5=resolve76(this.root,entry.name);const content=await readFile15(path5);const records=content.toString("utf8").split("\n").filter(Boolean).map(decodeRouteGatewayMeteringRecord);if(records.length===0)continue;if(segments.length>0&&(eventCount+records.length>maxEvents||bytes2+content.byteLength>maxBytes)){break}segments.push({name:entry.name,sha256:createHash62("sha256").update(content).digest("hex"),bytes:content.byteLength,records});eventCount+=records.length;bytes2+=content.byteLength;if(eventCount>=maxEvents||bytes2>=maxBytes)break}return segments.length===0?null:{batchId:sha25612(segments.map(segment=>`${segment.name}:${segment.sha256}`).join("\n")),segments,eventCount,bytes:bytes2}})}async acknowledgeIngestBatch(batch){if(!/^[a-f0-9]{64}$/u.test(batch.batchId)||batch.segments.length<1||batch.batchId!==sha25612(batch.segments.map(segment=>`${segment.name}:${segment.sha256}`).join("\n"))){fail26("ROUTE_GATEWAY_METERING_ACK_INVALID")}await this.runExclusive(async()=>{for(const segment of batch.segments){if(!SEGMENT.test(segment.name)||!segment.name.endsWith(".sealed")||!/^[a-f0-9]{64}$/u.test(segment.sha256)){fail26("ROUTE_GATEWAY_METERING_ACK_INVALID")}const path5=resolve76(this.root,segment.name);const info2=await lstat12(path5).catch(()=>fail26("ROUTE_GATEWAY_METERING_ACK_SEGMENT_MISSING"));if(!info2.isFile()||info2.isSymbolicLink()||info2.size!==segment.bytes){fail26("ROUTE_GATEWAY_METERING_ACK_SEGMENT_DRIFT")}const content=await readFile15(path5);if(createHash62("sha256").update(content).digest("hex")!==segment.sha256){fail26("ROUTE_GATEWAY_METERING_ACK_SEGMENT_DRIFT")}await unlink5(path5)}await syncDirectory3(this.root);const snapshot=await spoolSnapshot(this.root);this.totalBytes=snapshot.logicalBytes;this.backlogEvents=snapshot.backlogEvents;this.oldestObservedAtMs=snapshot.oldestObservedAtMs;this.oldestSequence=snapshot.oldestSequence})}async close(){if(this.closed)return;this.closed=true;await this.runExclusive(()=>this.sealSegment())}}}});import{createHash as createHash63}from"node:crypto";function fail27(code){throw Object.assign(new Error(code),{code})}function exactKeys(value2,expected){return Boolean(value2)&&typeof value2==="object"&&!Array.isArray(value2)&&Object.keys(value2).sort().join(",")===[...expected].sort().join(",")}function positiveInteger4(value2,maximum){return typeof value2==="number"&&Number.isSafeInteger(value2)&&value2>0&&value2<=maximum}function expectedBatchId(segments){return createHash63("sha256").update(segments.map(segment=>`${segment.name}:${segment.sha256}`).join("\n")).digest("hex")}function parseJson(body,code){try{return JSON.parse(body)}catch{return fail27(code)}}function decodeRouteGatewayMeteringIngestBatch(body){const decoded=parseJson(body,"ROUTE_GATEWAY_METERING_INGEST_BATCH_INVALID");if(!exactKeys(decoded,BATCH_KEYS))fail27("ROUTE_GATEWAY_METERING_INGEST_BATCH_INVALID");if(decoded.version!==1||typeof decoded.batchId!=="string"||!HASH.test(decoded.batchId)||!positiveInteger4(decoded.eventCount,1e5)||!Array.isArray(decoded.segments)||decoded.segments.length<1||decoded.segments.length>1e3){fail27("ROUTE_GATEWAY_METERING_INGEST_BATCH_INVALID")}const names=new Set;let eventCount=0;const segments=decoded.segments.map(value2=>{if(!exactKeys(value2,SEGMENT_KEYS))fail27("ROUTE_GATEWAY_METERING_INGEST_BATCH_INVALID");if(typeof value2.name!=="string"||!SEGMENT2.test(value2.name)||names.has(value2.name)||typeof value2.sha256!=="string"||!HASH.test(value2.sha256)||!positiveInteger4(value2.bytes,512*1024*1024)||!Array.isArray(value2.records)||value2.records.length<1||value2.records.length>1e5){fail27("ROUTE_GATEWAY_METERING_INGEST_BATCH_INVALID")}names.add(value2.name);const records=value2.records.map(record3=>{try{return decodeRouteGatewayMeteringRecord(JSON.stringify(record3))}catch{return fail27("ROUTE_GATEWAY_METERING_INGEST_BATCH_INVALID")}});eventCount+=records.length;return{name:value2.name,sha256:value2.sha256,bytes:value2.bytes,records}});if(eventCount!==decoded.eventCount||expectedBatchId(segments)!==decoded.batchId){fail27("ROUTE_GATEWAY_METERING_INGEST_BATCH_INVALID")}return{version:1,batchId:decoded.batchId,eventCount,segments}}function encodeRouteGatewayMeteringIngestBatch(batch){return JSON.stringify(decodeRouteGatewayMeteringIngestBatch(JSON.stringify({version:1,batchId:batch.batchId,eventCount:batch.eventCount,segments:batch.segments})))}function decodeRouteGatewayMeteringIngestAck(body,expected){const decoded=parseJson(body,"ROUTE_GATEWAY_METERING_INGEST_ACK_INVALID");if(!exactKeys(decoded,["batchId","eventCount","version"])||decoded.version!==1||decoded.batchId!==expected.batchId||decoded.eventCount!==expected.eventCount){fail27("ROUTE_GATEWAY_METERING_INGEST_ACK_INVALID")}return{version:1,batchId:decoded.batchId,eventCount:decoded.eventCount}}var HASH,SEGMENT2,BATCH_KEYS,SEGMENT_KEYS;var init_route_gateway_metering_ingest_protocol=__esm({"../route-gateway/src/route-gateway-metering-ingest-protocol.ts"(){"use strict";init_route_gateway_metering_spool();HASH=/^[a-f0-9]{64}$/u;SEGMENT2=/^meter-v1\.[a-f0-9]{32}\.\d{16}\.sealed$/u;BATCH_KEYS=["batchId","eventCount","segments","version"];SEGMENT_KEYS=["bytes","name","records","sha256"]}});import{lstat as lstat13,readFile as readFile16}from"node:fs/promises";import{isAbsolute as isAbsolute21}from"node:path";function fail28(code){throw Object.assign(new Error(code),{code})}function errorCode2(error62){return error62&&typeof error62==="object"&&typeof error62.code==="string"?error62.code:"ROUTE_GATEWAY_METERING_UPLOAD_FAILED"}function boundedInteger2(raw2,fallback,min2,max2){if(!raw2?.trim())return fallback;const value2=Number(raw2);if(!Number.isSafeInteger(value2)||value2<min2||value2>max2){fail28("ROUTE_GATEWAY_METERING_UPLOADER_CONFIG_INVALID")}return value2}function assertIngestUrl(value2){let url2;try{url2=new URL(value2)}catch{return fail28("ROUTE_GATEWAY_METERING_INGEST_URL_INVALID")}const loopbackHttp=url2.protocol==="http:"&&(url2.hostname==="127.0.0.1"||url2.hostname==="[::1]")&&url2.port!=="";if(url2.protocol!=="https:"&&!loopbackHttp||url2.username||url2.password||url2.search||url2.hash||url2.pathname!=="/v1/metering/ingest"){fail28("ROUTE_GATEWAY_METERING_INGEST_URL_INVALID")}}async function readProtectedToken(path5){if(!isAbsolute21(path5))fail28("ROUTE_GATEWAY_METERING_TOKEN_FILE_UNSAFE");const info2=await lstat13(path5).catch(()=>fail28("ROUTE_GATEWAY_METERING_TOKEN_FILE_UNSAFE"));const processUid=process.getuid?.();if(info2.isSymbolicLink()||!info2.isFile()||info2.size<32||info2.size>1024||(info2.mode&511)!==384||processUid!==void 0&&info2.uid!==0&&info2.uid!==processUid){fail28("ROUTE_GATEWAY_METERING_TOKEN_FILE_UNSAFE")}const body=await readFile16(path5,"utf8");const token=body.endsWith("\n")?body.slice(0,-1):body;if(!/^[A-Za-z0-9._~+/-]{32,510}={0,2}$/u.test(token)||token.includes("\n")||token.includes("\r")){fail28("ROUTE_GATEWAY_METERING_TOKEN_FILE_INVALID")}return token}async function loadRouteGatewayMeteringUploaderConfig(env){const ingestUrl=env.GENCOW_ROUTE_METERING_INGEST_URL?.trim()??"";const tokenFile=env.GENCOW_ROUTE_METERING_INGEST_TOKEN_FILE?.trim()??"";if(!ingestUrl||!tokenFile)fail28("ROUTE_GATEWAY_METERING_UPLOADER_CONFIG_REQUIRED");assertIngestUrl(ingestUrl);const intervalMs=boundedInteger2(env.GENCOW_ROUTE_METERING_UPLOAD_INTERVAL_MS,1e3,100,6e4);const maxRetryIntervalMs=boundedInteger2(env.GENCOW_ROUTE_METERING_UPLOAD_MAX_RETRY_INTERVAL_MS,6e4,100,15*6e4);if(maxRetryIntervalMs<intervalMs)fail28("ROUTE_GATEWAY_METERING_UPLOADER_CONFIG_INVALID");return{ingestUrl,authorizationToken:await readProtectedToken(tokenFile),intervalMs,maxRetryIntervalMs,requestTimeoutMs:boundedInteger2(env.GENCOW_ROUTE_METERING_UPLOAD_TIMEOUT_MS,45e3,100,6e4),maxEvents:boundedInteger2(env.GENCOW_ROUTE_METERING_UPLOAD_MAX_EVENTS,100,1,1e5),maxBytes:boundedInteger2(env.GENCOW_ROUTE_METERING_UPLOAD_MAX_BYTES,8*1024*1024,256,512*1024*1024)}}async function boundedResponseBody(response){const declared=Number(response.headers.get("content-length"));if(Number.isFinite(declared)&&declared>4096)fail28("ROUTE_GATEWAY_METERING_INGEST_ACK_INVALID");const body=await response.text();if(Buffer.byteLength(body)>4096)fail28("ROUTE_GATEWAY_METERING_INGEST_ACK_INVALID");return body}async function runRouteGatewayMeteringUploadCycle(options){let batch=null;try{assertIngestUrl(options.ingestUrl);batch=await options.spool.prepareIngestBatch({maxEvents:options.maxEvents,maxBytes:options.maxBytes});if(!batch)return{status:"empty",eventCount:0,errorCode:null};const response=await(options.fetchImpl??fetch)(options.ingestUrl,{method:"POST",headers:{authorization:`Bearer ${options.authorizationToken}`,"content-type":"application/json"},body:encodeRouteGatewayMeteringIngestBatch(batch),signal:AbortSignal.timeout(options.requestTimeoutMs)});if(response.status!==200)fail28(`METERING_INGEST_HTTP_${response.status}`);decodeRouteGatewayMeteringIngestAck(await boundedResponseBody(response),batch);await options.spool.acknowledgeIngestBatch(batch);return{status:"uploaded",eventCount:batch.eventCount,errorCode:null}}catch(error62){return{status:"deferred",eventCount:batch?.eventCount??0,errorCode:errorCode2(error62)}}}function waitForInterval(signal,intervalMs){return new Promise(resolveWait=>{if(signal.aborted)return resolveWait();const timer2=setTimeout(done,intervalMs);function done(){clearTimeout(timer2);signal.removeEventListener("abort",done);resolveWait()}signal.addEventListener("abort",done,{once:true})})}function routeGatewayMeteringRetryDelayMs(input2){if(input2.consecutiveFailures<=0)return input2.intervalMs;const exponent=Math.min(30,input2.consecutiveFailures);const ceiling=Math.min(input2.maxRetryIntervalMs,input2.intervalMs*2**exponent);const random2=Math.min(1,Math.max(0,input2.random));return Math.floor(input2.intervalMs+(ceiling-input2.intervalMs)*random2)}function startRouteGatewayMeteringUploader(options){const controller=new AbortController;const diagnostics={uploadedEvents:0,failedCycles:0,consecutiveFailures:0,retryDelayMs:options.intervalMs,lastErrorCode:null};const runCycle=options.runCycleImpl??runRouteGatewayMeteringUploadCycle;const wait2=options.waitForIntervalImpl??waitForInterval;const random2=options.randomImpl??Math.random;const polling=(async()=>{while(!controller.signal.aborted){const result3=await runCycle(options);if(result3.status==="uploaded"){diagnostics.uploadedEvents+=result3.eventCount;diagnostics.consecutiveFailures=0;diagnostics.lastErrorCode=null}else if(result3.status==="deferred"){diagnostics.failedCycles+=1;diagnostics.consecutiveFailures+=1;diagnostics.lastErrorCode=result3.errorCode;options.logger.warn(`[route-gateway] metering upload deferred code=${result3.errorCode}`)}else{diagnostics.consecutiveFailures=0;diagnostics.lastErrorCode=null}diagnostics.retryDelayMs=routeGatewayMeteringRetryDelayMs({intervalMs:options.intervalMs,maxRetryIntervalMs:options.maxRetryIntervalMs,consecutiveFailures:diagnostics.consecutiveFailures,random:random2()});await wait2(controller.signal,diagnostics.retryDelayMs)}})();return{diagnostics:()=>({...diagnostics}),async stop(){controller.abort();await polling}}}var init_route_gateway_metering_uploader=__esm({"../route-gateway/src/route-gateway-metering-uploader.ts"(){"use strict";init_route_gateway_metering_ingest_protocol()}});import{randomBytes as randomBytes9,createHash as createHash64}from"node:crypto";function fail29(code){throw new Error(code)}function boundedInteger3(raw2,fallback,minimum,maximum){if(!raw2?.trim())return fallback;const parsed=Number(raw2);if(!Number.isSafeInteger(parsed)||parsed<minimum||parsed>maximum){fail29("STATIC_METERING_CONFIG_INVALID")}return parsed}function required2(env,key2){const value2=env[key2]?.trim()??"";if(!value2)fail29("STATIC_METERING_CONFIG_REQUIRED");return value2}function errorCode3(error62){const message=error62 instanceof Error?error62.message:"";return/^STATIC_METERING_[A-Z0-9_]+$/u.test(message)?message:"STATIC_METERING_COLLECT_FAILED"}function json4(body,status=200){return Response.json(body,{status,headers:{"cache-control":"no-store","x-content-type-options":"nosniff"}})}function waitForShutdownSignal2(){return new Promise(resolveShutdown=>{const shutdown=()=>{process.off("SIGTERM",shutdown);process.off("SIGINT",shutdown);resolveShutdown()};process.once("SIGTERM",shutdown);process.once("SIGINT",shutdown)})}function waitForInterval2(signal,intervalMs){return new Promise(resolveWait=>{if(signal.aborted)return resolveWait();const timer2=setTimeout(done,intervalMs);function done(){clearTimeout(timer2);signal.removeEventListener("abort",done);resolveWait()}signal.addEventListener("abort",done,{once:true})})}async function runStaticOriginMeteringEntry(options={}){const env=options.env??process.env;const logger3=options.logger??console;if(env.GENCOW_STATIC_METERING_ENABLED!=="true"){logger3.log("[static-metering] disabled");return false}if(DATABASE_ENV_KEYS2.some(key2=>Boolean(env[key2]?.trim()))){fail29("STATIC_METERING_DATABASE_CREDENTIAL_FORBIDDEN")}const nodeId=required2(env,"GENCOW_STATIC_METERING_NODE_ID");const accessLogFile=required2(env,"GENCOW_STATIC_METERING_ACCESS_LOG_FILE");const checkpointFile=required2(env,"GENCOW_STATIC_METERING_CHECKPOINT_FILE");const spoolRoot2=required2(env,"GENCOW_STATIC_METERING_SPOOL_DIR");const collectIntervalMs=boundedInteger3(env.GENCOW_STATIC_METERING_COLLECT_INTERVAL_MS,250,100,6e4);const healthPort=boundedInteger3(env.GENCOW_STATIC_METERING_HEALTH_PORT,4533,1024,65535);const maxSpoolBytes=boundedInteger3(env.GENCOW_STATIC_METERING_MAX_SPOOL_BYTES,512*1024*1024,1024,64*1024*1024*1024);const maxSegmentBytes=boundedInteger3(env.GENCOW_STATIC_METERING_MAX_SEGMENT_BYTES,8*1024*1024,256,512*1024*1024);const spoolInvocation=randomBytes9(16).toString("hex");const gatewayId=`static-spool:${createHash64("sha256").update(nodeId).digest("hex").slice(0,20)}`;const uploaderConfig=await(options.loadUploaderConfigImpl??loadRouteGatewayMeteringUploaderConfig)({GENCOW_ROUTE_METERING_INGEST_URL:env.GENCOW_STATIC_METERING_INGEST_URL,GENCOW_ROUTE_METERING_INGEST_TOKEN_FILE:env.GENCOW_STATIC_METERING_INGEST_TOKEN_FILE,GENCOW_ROUTE_METERING_UPLOAD_INTERVAL_MS:env.GENCOW_STATIC_METERING_UPLOAD_INTERVAL_MS,GENCOW_ROUTE_METERING_UPLOAD_MAX_RETRY_INTERVAL_MS:env.GENCOW_STATIC_METERING_UPLOAD_MAX_RETRY_INTERVAL_MS,GENCOW_ROUTE_METERING_UPLOAD_TIMEOUT_MS:env.GENCOW_STATIC_METERING_UPLOAD_TIMEOUT_MS,GENCOW_ROUTE_METERING_UPLOAD_MAX_EVENTS:env.GENCOW_STATIC_METERING_UPLOAD_MAX_EVENTS,GENCOW_ROUTE_METERING_UPLOAD_MAX_BYTES:env.GENCOW_STATIC_METERING_UPLOAD_MAX_BYTES});const spool=await(options.openSpoolImpl??RouteGatewayMeteringSpool.open)({root:spoolRoot2,gatewayId,invocationId:spoolInvocation,maxSpoolBytes,maxSegmentBytes,maxPendingEvents:1});let uploader;try{uploader=(options.startUploaderImpl??startRouteGatewayMeteringUploader)({...uploaderConfig,spool,logger:logger3})}catch(error62){await spool.close();throw error62}const controller=new AbortController;const collect=options.collectOnceImpl??collectStaticOriginAccessLogsOnce;const diagnostics={collectedRecords:0,collectedBytes:0,collectFailedCycles:0,lastCollectAt:null,lastCollectErrorCode:null};const polling=(async()=>{while(!controller.signal.aborted){try{const result3=await collect({accessLogFile,checkpointFile,nodeId,spool});diagnostics.collectedRecords+=result3.records;diagnostics.collectedBytes+=result3.bytes;diagnostics.lastCollectAt=new Date().toISOString();diagnostics.lastCollectErrorCode=null}catch(error62){const code=errorCode3(error62);diagnostics.collectFailedCycles+=1;diagnostics.lastCollectErrorCode=code;logger3.warn(`[static-metering] collect deferred code=${code}`)}await waitForInterval2(controller.signal,collectIntervalMs)}})();const handler=async request=>{const path5=new URL(request.url).pathname;if(request.method==="GET"&&path5==="/health/live")return json4({ok:true});if(request.method==="GET"&&path5==="/health/core-ready"){const spoolState=spool.diagnostics();const uploadState=uploader.diagnostics();const utilization=Math.min(100,Math.round(spoolState.logicalBytes/maxSpoolBytes*1e4)/100);const ok=diagnostics.lastCollectAt!==null&&diagnostics.lastCollectErrorCode===null&&uploadState.lastErrorCode===null&&spoolState.lastErrorCode===null&&utilization<90;return json4({ok,nodeId,collectedRecords:diagnostics.collectedRecords,collectedBytes:diagnostics.collectedBytes,collectFailedCycles:diagnostics.collectFailedCycles,lastCollectAt:diagnostics.lastCollectAt,collectErrorCode:diagnostics.lastCollectErrorCode,spoolLogicalBytes:spoolState.logicalBytes,spoolUtilizationPercent:utilization,spoolDroppedEvents:spoolState.droppedEvents,spoolBacklogEvents:spoolState.backlogEvents??0,spoolOldestSequence:spoolState.oldestSequence??null,spoolOldestObservedAt:spoolState.oldestObservedAt??null,spoolOldestAgeMs:spoolState.oldestAgeMs??null,spoolErrorCode:spoolState.lastErrorCode,uploadedEvents:uploadState.uploadedEvents,uploadFailedCycles:uploadState.failedCycles,uploadConsecutiveFailures:uploadState.consecutiveFailures??0,uploadRetryDelayMs:uploadState.retryDelayMs??uploaderConfig.intervalMs,uploadErrorCode:uploadState.lastErrorCode},ok?200:503)}return json4({error:"not_found"},404)};const serve=options.serveImpl??(input2=>Bun.serve(input2));let server2;try{server2=serve({hostname:"127.0.0.1",port:healthPort,fetch:handler})}catch(error62){controller.abort();await polling;await uploader.stop();await spool.close();throw error62}logger3.log(`[static-metering] ready node=${nodeId} healthPort=${healthPort}`);try{await(options.waitForShutdownImpl??waitForShutdownSignal2)()}finally{controller.abort();await polling;await server2.stop(true);await uploader.stop();await spool.close()}return true}var DATABASE_ENV_KEYS2;var init_static_origin_metering_entry=__esm({"../static-origin/src/static-origin-metering-entry.ts"(){"use strict";init_route_gateway_metering_spool();init_route_gateway_metering_uploader();init_static_origin_metering_collector();DATABASE_ENV_KEYS2=["DATABASE_URL","PLATFORM_DATABASE_URL","GENCOW_PLATFORM_DB","GENCOW_DIRECT_DATABASE_URL","GENCOW_DIRECT_DDL_DATABASE_URL","GENCOW_CATALOG_READ_DATABASE_URL","GENCOW_DEPLOYMENT_EXECUTOR_DATABASE_URL","GENCOW_ROUTE_PUBLISHER_DATABASE_URL","GENCOW_SERVING_METERING_INGESTOR_DATABASE_URL"];if(import.meta.main){runStaticOriginMeteringEntry().then(()=>process.exit(0)).catch(error62=>{const code=errorCode3(error62);console.error(`[static-metering] fatal code=${code}`);process.exit(1)})}}});var init_src=__esm({"../static-origin/src/index.ts"(){"use strict";init_static_origin_caddy_compiler();init_static_origin_caddy_applier();init_static_origin_config();init_static_origin_entry();init_static_origin_generation_removal();init_static_origin_generation_store();init_static_origin_layout();init_static_origin_metering_collector();init_static_origin_metering_entry();init_static_origin_target_state()}});import{resolve as resolve77}from"node:path";import{and as and24,eq as eq27}from"drizzle-orm";function getAppReleaseBackendArtifactStore(){const appsRoot=process.env.GENCOW_APPS_DIR||resolve77(process.cwd(),".gencow/apps-data");return createAppDeploymentArtifactStore({artifactRoot:process.env.GENCOW_APP_ARTIFACTS_DIR||resolve77(appsRoot,".control-plane","artifacts"),cacheRoot:process.env.GENCOW_APP_ARTIFACT_CACHE_DIR||resolve77(appsRoot,".control-plane","artifact-cache")})}var init_app_release_backend_artifact=__esm({"../platform/src/app-release-backend-artifact.ts"(){"use strict";init_schema();init_app_deployment_artifact_store()}});import{randomUUID as randomUUID43}from"node:crypto";import{cp as cp3,mkdir as mkdir15,readFile as readFile17,readdir as readdir12,rename as rename11,rm as rm10,stat as stat11,writeFile as writeFile6,chmod as chmod10}from"node:fs/promises";import{join as join24,resolve as resolve78}from"node:path";var init_static_generation_store=__esm({"../platform/src/static-generation-store.ts"(){"use strict";init_release_object_store()}});import{and as and25,eq as eq28,sql as sql105}from"drizzle-orm";var init_static_origin_serving_orphan_authority=__esm({"../platform/src/static-origin-serving-orphan-authority.ts"(){"use strict";init_runtime_activity_contract();init_src();init_schema()}});import{and as and26,eq as eq29,inArray as inArray14,sql as sql106}from"drizzle-orm";var init_app_release_gc=__esm({"../platform/src/app-release-gc.ts"(){"use strict";init_runtime_activity_contract();init_src();init_schema();init_app_release_retention();init_release_object_store_factory();init_app_release_backend_artifact();init_static_generation_store();init_static_origin_serving_orphan_authority()}});import{and as and27,eq as eq30,inArray as inArray15,sql as sql107}from"drizzle-orm";var init_app_release_quota=__esm({"../platform/src/app-release-quota.ts"(){"use strict";init_schema();init_app_release_unbound_attempt_lease()}});var init_app_release_binding_requirement=__esm({"../platform/src/app-release-binding-requirement.ts"(){"use strict"}});function fail30(){throw new Error("APP_SERVING_ROUTE_ROLLOUT_CONFIG_INVALID")}function parseAllowlist(raw2){if(raw2?.trim()==="*")return"all";let decoded;try{decoded=JSON.parse(raw2??"")}catch{return fail30()}if(!Array.isArray(decoded)||decoded.length<1||decoded.length>1e4||decoded.some(value2=>!Number.isSafeInteger(value2)||Number(value2)<1)){return fail30()}return new Set(decoded)}function loadAppServingRouteRolloutConfig(input2){const config2=input2.runtimeConfig??appReleaseRuntimeConfig(input2.env);const route=config2.servingRoute;const mode=route.publicationMode;if(mode==="off")return null;if(mode!=="enforce"||!Number.isSafeInteger(input2.appId)||input2.appId<1)return fail30();const deploymentEnvironment2=input2.deploymentEnvironment;const configuredEnvironment=route.environment??void 0;const topologyRevision=route.topologyRevision??"";const upsertTargetSetId=route.upsertTargetSetId??"";const tombstoneTargetSetId=route.tombstoneTargetSetId??"";const allowlist2=parseAllowlist(route.appAllowlist??void 0);let baseDomain;try{baseDomain=normalizeServingRouteHost(route.baseDomain??"")}catch{return fail30()}if(!ENVIRONMENTS4.has(deploymentEnvironment2)||!ENVIRONMENTS4.has(configuredEnvironment)){return fail30()}const servingEnvironment=configuredEnvironment;if(!REFERENCE9.test(topologyRevision)||!REFERENCE9.test(upsertTargetSetId)||!REFERENCE9.test(tombstoneTargetSetId)){return fail30()}if(allowlist2!=="all"&&!allowlist2.has(input2.appId))return null;return{activation:{environment:servingEnvironment,baseDomain,topologyRevision,targetSetId:upsertTargetSetId,backendRoutePrefixes:MANAGED_BACKEND_ROUTE_PREFIXES},deletion:{environment:servingEnvironment,baseDomain,topologyRevision,tombstoneTargetSetId}}}var REFERENCE9,ENVIRONMENTS4,MANAGED_BACKEND_ROUTE_PREFIXES;var init_app_serving_route_rollout_config=__esm({"../platform/src/app-serving-route-rollout-config.ts"(){"use strict";init_serving_route_manifest_contract();init_app_release_runtime_env();REFERENCE9=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;ENVIRONMENTS4=new Set(["local","dev","qc","prod"]);MANAGED_BACKEND_ROUTE_PREFIXES=["/api","/internal","/_internal","/platform","/ws"]}});var init_app_release_rollout=__esm({"../platform/src/app-release-rollout.ts"(){"use strict";init_app_release_runtime_env();init_app_release_binding_requirement();init_app_serving_route_rollout_config()}});import{createHash as createHash65}from"node:crypto";async function completeBackendReleaseDeployBinding(input2){if(!input2.binding)return;await(input2.recordComponent??recordAppReleaseComponent)({db:input2.db,appId:input2.appId,attemptId:input2.binding.attemptId,environment:input2.binding.environment,component:"backend",deploymentId:input2.deploymentId})}async function projectFailedReleaseDeployBinding(input2){if(!input2.binding)return;await failAppReleaseAttemptInTransaction({tx:input2.tx,attemptId:input2.binding.attemptId,appId:input2.appId,environment:input2.binding.environment,failureStage:input2.failureStage,failureCode:input2.failureCode})}var init_apps_release_deploy_binding=__esm({"../platform/gencow/apps-release-deploy-binding.ts"(){"use strict";init_app_release_store();init_release_object_store_factory();init_release_object_store();init_app_release_gc();init_app_release_attempt_failure_store();init_app_release_quota();init_app_release_rollout();init_deployment_failure_contract()}});import{createHash as createHash66}from"node:crypto";import{and as and28,eq as eq31,inArray as inArray16,isNull as isNull8,or as or10}from"drizzle-orm";function fail31(code){throw Object.assign(new Error(code),{code})}function sha25613(value2){return createHash66("sha256").update(value2).digest("hex")}function revisionSelection(){return{id:appSchemaRevisions.id,appId:appSchemaRevisions.appId,deploymentId:appSchemaRevisions.deploymentId,bundleManifestSha256:appSchemaRevisions.bundleManifestSha256,artifactIdentityClaimedSha256:appSchemaRevisions.artifactIdentityClaimedSha256,artifactIdentityDerivedSha256:appSchemaRevisions.artifactIdentityDerivedSha256,platformSourceRevision:appSchemaRevisions.platformSourceRevision,compatibilityClass:appSchemaRevisions.compatibilityClass,state:appSchemaRevisions.state,preJournalFingerprint:appSchemaRevisions.preJournalFingerprint,postJournalFingerprint:appSchemaRevisions.postJournalFingerprint,appliedNamesHash:appSchemaRevisions.appliedNamesHash,failureCode:appSchemaRevisions.failureCode,inheritedFromRevisionId:appSchemaRevisions.inheritedFromRevisionId,appliedAt:appSchemaRevisions.appliedAt,reconciledAt:appSchemaRevisions.reconciledAt}}async function inheritReadySchemaRevision(input2){if(!Number.isSafeInteger(input2.appId)||input2.appId<=0||!Number.isSafeInteger(input2.sourceDeploymentId)||input2.sourceDeploymentId<=0||!Number.isSafeInteger(input2.targetDeploymentId)||input2.targetDeploymentId<=0||input2.sourceDeploymentId===input2.targetDeploymentId||!input2.sourceRevisionId||!input2.correlationId){return fail31("SCHEMA_REVISION_INHERITANCE_INPUT_INVALID")}return input2.db.transaction(async tx=>{const source=await assertReadySchemaRevisionForInheritance({db:tx,appId:input2.appId,sourceDeploymentId:input2.sourceDeploymentId,sourceRevisionId:input2.sourceRevisionId});const id=`schema_${sha25613(JSON.stringify([input2.appId,input2.targetDeploymentId,input2.sourceRevisionId,source.bundleManifestSha256])).slice(0,32)}`;const targetDeployments=await tx.select({id:deployments.id,schemaRevisionId:deployments.schemaRevisionId}).from(deployments).where(and28(eq31(deployments.id,input2.targetDeploymentId),eq31(deployments.appId,input2.appId)));const targetDeployment=targetDeployments[0];if(!targetDeployment)return fail31("SCHEMA_REVISION_INHERITANCE_TARGET_NOT_FOUND");if(targetDeployment.schemaRevisionId!==null&&targetDeployment.schemaRevisionId!==id){return fail31("SCHEMA_REVISION_INHERITANCE_TARGET_CONFLICT")}const reconciledAt=new Date;await tx.insert(appSchemaRevisions).values({id,appId:input2.appId,deploymentId:input2.targetDeploymentId,bundleManifestSha256:source.bundleManifestSha256,artifactIdentityClaimedSha256:source.artifactIdentityClaimedSha256,artifactIdentityDerivedSha256:source.artifactIdentityDerivedSha256,platformSourceRevision:source.platformSourceRevision,compatibilityClass:source.compatibilityClass,state:source.state,preJournalFingerprint:source.preJournalFingerprint,postJournalFingerprint:source.postJournalFingerprint,appliedNamesHash:source.appliedNamesHash,failureCode:null,inheritedFromRevisionId:source.id,correlationId:input2.correlationId,appliedAt:source.appliedAt,reconciledAt}).onConflictDoNothing({target:appSchemaRevisions.deploymentId});const inheritedRows=await tx.select(revisionSelection()).from(appSchemaRevisions).where(eq31(appSchemaRevisions.deploymentId,input2.targetDeploymentId));const inherited=inheritedRows[0];assertInheritedRevisionIdentity({source,inherited,appId:input2.appId,targetDeploymentId:input2.targetDeploymentId,targetRevisionId:id});const deploymentsUpdated=await tx.update(deployments).set({schemaRevisionId:id}).where(and28(eq31(deployments.id,input2.targetDeploymentId),eq31(deployments.appId,input2.appId),or10(isNull8(deployments.schemaRevisionId),eq31(deployments.schemaRevisionId,id)))).returning({id:deployments.id});if(!deploymentsUpdated[0])return fail31("SCHEMA_REVISION_INHERITANCE_BINDING_FAILED");return inherited})}function assertInheritedRevisionIdentity(input2){const{source,inherited}=input2;const id=`schema_${sha25613(JSON.stringify([input2.appId,input2.targetDeploymentId,source.id,source.bundleManifestSha256])).slice(0,32)}`;const fields=["bundleManifestSha256","artifactIdentityClaimedSha256","artifactIdentityDerivedSha256","platformSourceRevision","compatibilityClass","state","preJournalFingerprint","postJournalFingerprint","appliedNamesHash"];if(!inherited||input2.targetRevisionId!==id||inherited.id!==id||inherited.appId!==input2.appId||inherited.deploymentId!==input2.targetDeploymentId||inherited.inheritedFromRevisionId!==source.id||fields.some(field=>inherited[field]!==source[field])||inherited.failureCode!==null||!(inherited.reconciledAt instanceof Date)||(inherited.appliedAt?.getTime()??null)!==(source.appliedAt?.getTime()??null)){fail31("SCHEMA_REVISION_INHERITANCE_IDENTITY_MISMATCH")}}async function assertInheritedReadySchemaRevision(input2){const source=await assertReadySchemaRevisionForInheritance(input2);const inherited=await loadRevision(input2.db,input2.targetRevisionId);assertInheritedRevisionIdentity({...input2,source,inherited});return inherited}async function loadRevision(db,revisionId){const rows8=await db.select(revisionSelection()).from(appSchemaRevisions).where(eq31(appSchemaRevisions.id,revisionId));const row=rows8[0];if(!row)return fail31("SCHEMA_REVISION_NOT_FOUND");return row}async function assertReadySchemaRevisionForInheritance(input2){const source=await loadRevision(input2.db,input2.sourceRevisionId);if(source.appId!==input2.appId||source.deploymentId!==input2.sourceDeploymentId){return fail31("SCHEMA_REVISION_INHERITANCE_SOURCE_MISMATCH")}if(source.state!=="not_required"&&source.state!=="applied"){return fail31("SCHEMA_REVISION_INHERITANCE_SOURCE_NOT_READY")}if(source.state==="applied"&&(!SHA25614.test(source.postJournalFingerprint??"")||!SHA25614.test(source.appliedNamesHash??"")||!(source.appliedAt instanceof Date))){return fail31("SCHEMA_REVISION_INHERITANCE_PROOF_INVALID")}return source}async function planDeploymentSchemaRevision(input2){const artifactIdentityClaimedSha256=input2.artifactIdentityClaimedSha256??null;const artifactIdentityDerivedSha256=input2.artifactIdentityDerivedSha256??null;const platformSourceRevision=input2.platformSourceRevision??null;if(!Number.isSafeInteger(input2.appId)||input2.appId<=0||!Number.isSafeInteger(input2.deploymentId)||input2.deploymentId<=0||input2.bundleManifestSha256!==null&&!SHA25614.test(input2.bundleManifestSha256)||artifactIdentityClaimedSha256!==null&&!SHA25614.test(artifactIdentityClaimedSha256)||artifactIdentityDerivedSha256!==artifactIdentityClaimedSha256||artifactIdentityClaimedSha256===null!==(platformSourceRevision===null)||platformSourceRevision!==null&&!/^[a-f0-9]{40,64}$/u.test(platformSourceRevision)||!input2.correlationId){return fail31("SCHEMA_REVISION_INPUT_INVALID")}if(input2.bundleManifestSha256===null&&input2.compatibilityClass!=="none"){return fail31("SCHEMA_REVISION_CLASSIFICATION_INVALID")}const id=`schema_${sha25613(JSON.stringify([input2.appId,input2.deploymentId,input2.bundleManifestSha256])).slice(0,32)}`;const state2=input2.compatibilityClass==="none"?"not_required":"planned";await input2.db.insert(appSchemaRevisions).values({id,appId:input2.appId,deploymentId:input2.deploymentId,bundleManifestSha256:input2.bundleManifestSha256,artifactIdentityClaimedSha256,artifactIdentityDerivedSha256,platformSourceRevision,compatibilityClass:input2.compatibilityClass,state:state2,correlationId:input2.correlationId}).onConflictDoNothing({target:appSchemaRevisions.deploymentId});const revision=await loadRevision(input2.db,id);if(revision.appId!==input2.appId||revision.deploymentId!==input2.deploymentId||revision.bundleManifestSha256!==input2.bundleManifestSha256||revision.artifactIdentityClaimedSha256!==artifactIdentityClaimedSha256||revision.artifactIdentityDerivedSha256!==artifactIdentityDerivedSha256||revision.platformSourceRevision!==platformSourceRevision||revision.compatibilityClass!==input2.compatibilityClass){return fail31("SCHEMA_REVISION_IDENTITY_MISMATCH")}const deploymentsUpdated=await input2.db.update(deployments).set({schemaRevisionId:id}).where(and28(eq31(deployments.id,input2.deploymentId),eq31(deployments.appId,input2.appId))).returning({id:deployments.id});if(!deploymentsUpdated[0])return fail31("SCHEMA_REVISION_DEPLOYMENT_BINDING_FAILED");return revision}async function terminalizePlannedDeploymentSchemaRevision(input2){if(!Number.isSafeInteger(input2.appId)||input2.appId<=0||!Number.isSafeInteger(input2.deploymentId)||input2.deploymentId<=0||!/^[A-Z][A-Z0-9_]{2,99}$/u.test(input2.failureCode)){return fail31("SCHEMA_REVISION_FAILURE_INPUT_INVALID")}const states=input2.terminalState==="recovery_required"?["planned","applying","outcome_uncertain"]:["planned"];await input2.db.update(appSchemaRevisions).set({state:input2.terminalState,failureCode:input2.failureCode,updatedAt:new Date}).where(and28(eq31(appSchemaRevisions.appId,input2.appId),eq31(appSchemaRevisions.deploymentId,input2.deploymentId),inArray16(appSchemaRevisions.state,states)))}function assertProof(proof){if(!SHA25614.test(proof.journalFingerprint)||!SHA25614.test(proof.appliedNamesHash)){return fail31("SCHEMA_REVISION_PROOF_INVALID")}}async function executeSchemaRevision(input2){const revision=await loadRevision(input2.db,input2.revisionId);if(revision.state==="not_required"||revision.state==="applied")return revision;if(revision.state!=="planned")return fail31("SCHEMA_REVISION_NOT_RETRYABLE");if(revision.compatibilityClass!=="versioned_v1"&&revision.compatibilityClass!=="expand_compatible"){return fail31("SCHEMA_MANUAL_MIGRATION_REQUIRED")}if(!SHA25614.test(input2.expectedAppliedNamesHash))return fail31("SCHEMA_REVISION_PROOF_INVALID");await input2.prepareProofSource?.();const pre=await input2.readProof();assertProof(pre);const acquired=await input2.db.update(appSchemaRevisions).set({state:"applying",preJournalFingerprint:pre.journalFingerprint,updatedAt:new Date}).where(and28(eq31(appSchemaRevisions.id,input2.revisionId),eq31(appSchemaRevisions.state,"planned"))).returning({id:appSchemaRevisions.id});if(!acquired[0])return fail31("SCHEMA_REVISION_NOT_RETRYABLE");try{await input2.apply();const post=await input2.readProof();assertProof(post);if(post.appliedNamesHash!==input2.expectedAppliedNamesHash){throw new Error("SCHEMA_POSTCONDITION_MISMATCH")}const completed=await input2.db.update(appSchemaRevisions).set({state:"applied",postJournalFingerprint:post.journalFingerprint,appliedNamesHash:post.appliedNamesHash,appliedAt:new Date,failureCode:null,updatedAt:new Date}).where(and28(eq31(appSchemaRevisions.id,input2.revisionId),eq31(appSchemaRevisions.state,"applying"))).returning({id:appSchemaRevisions.id});if(!completed[0])return fail31("SCHEMA_REVISION_POSTCONDITION_FAILED");return loadRevision(input2.db,input2.revisionId)}catch(error62){let state2="outcome_uncertain";let code="SCHEMA_APPLY_OUTCOME_UNCERTAIN";const errorCode4=error62?.code;const explicitPostconditionFailure=errorCode4==="MIGRATION_POSTCONDITION_FAILED"||errorCode4==="MIGRATION_TENANT_SCHEMA_POSTCONDITION_FAILED";let verifiedPost=null;let preserveRolledBackError=false;try{const post=await input2.readProof();assertProof(post);if(post.appliedNamesHash===input2.expectedAppliedNamesHash&&!explicitPostconditionFailure){verifiedPost=post;state2="applied";code=""}else if(explicitPostconditionFailure){code=errorCode4}else if(post.journalFingerprint===pre.journalFingerprint&&post.appliedNamesHash===pre.appliedNamesHash){preserveRolledBackError=error62 instanceof MigrationTransactionRolledBackError;state2=preserveRolledBackError&&error62.failureClass==="RETRYABLE_INFRA"?"planned":"failed";code="SCHEMA_APPLY_FAILED"}}catch{}const completed=await input2.db.update(appSchemaRevisions).set({state:state2,failureCode:code||null,...verifiedPost?{postJournalFingerprint:verifiedPost.journalFingerprint,appliedNamesHash:verifiedPost.appliedNamesHash,appliedAt:new Date}:{},updatedAt:new Date}).where(and28(eq31(appSchemaRevisions.id,input2.revisionId),eq31(appSchemaRevisions.state,"applying"))).returning({id:appSchemaRevisions.id});if(!completed[0])return fail31("SCHEMA_REVISION_POSTCONDITION_FAILED");if(state2==="applied")return loadRevision(input2.db,input2.revisionId);if(explicitPostconditionFailure||preserveRolledBackError)throw error62;return fail31(code)}}async function hasPriorAppliedVersionedLineage(input2){const rows8=await input2.db.select({compatibilityClass:appSchemaRevisions.compatibilityClass,bundleManifestSha256:appSchemaRevisions.bundleManifestSha256}).from(appSchemaRevisions).where(and28(eq31(appSchemaRevisions.appId,input2.appId),eq31(appSchemaRevisions.state,"applied")));return rows8.some(row=>(row.compatibilityClass==="versioned_v1"||row.compatibilityClass==="expand_compatible")&&typeof row.bundleManifestSha256==="string"&&SHA25614.test(row.bundleManifestSha256))}async function assertSchemaRevisionAllowsCandidate(input2){const revision=await loadRevision(input2.db,input2.revisionId);if(revision.state!=="not_required"&&revision.state!=="applied"){return fail31("SCHEMA_REVISION_BLOCKS_CANDIDATE")}return revision.state}var SHA25614;var init_deployment_schema_revision=__esm({"../platform/src/deployment-schema-revision.ts"(){"use strict";init_schema();init_migration_execution_outcome();SHA25614=/^[a-f0-9]{64}$/u}});import{and as and29,eq as eq32,isNull as isNull9}from"drizzle-orm";async function projectFailedDeploymentExecutorOperation(input2){await(input2.projectReleaseFailureImpl??projectFailedReleaseDeployBinding)({tx:input2.db,appId:input2.appId,binding:input2.binding,failureStage:input2.failure.stage,failureCode:input2.failure.code});await(input2.terminalizePlannedSchemaRevisionImpl??terminalizePlannedDeploymentSchemaRevision)({db:input2.db,appId:input2.appId,deploymentId:input2.deploymentId,terminalState:input2.state,failureCode:input2.failure.code})}async function sealFailedDeploymentExecutorOperation(input2){if("cleanupOwner"in input2)return sealCandidateCleanupOwner(input2.cleanupOwner);await input2.db.transaction(async tx=>{await projectFailedDeploymentExecutorOperation({db:tx,appId:input2.operation.appId,deploymentId:input2.operation.deploymentId,binding:input2.binding,state:input2.state,failure:input2.failure,projectReleaseFailureImpl:input2.projectReleaseFailureImpl,terminalizePlannedSchemaRevisionImpl:input2.terminalizePlannedSchemaRevisionImpl});await(input2.finishOperationImpl??finishDeploymentExecutorOperation)({db:tx,operation:input2.operation,state:input2.state,receipt:input2.receipt,allowExpiredLease:input2.allowExpiredLease,failure:input2.failure});if(input2.state==="failed")await releaseTerminalOwnerServingRoutePrepares(tx,{appId:input2.operation.appId})})}async function sealCandidateCleanupOwner(input2){const{tx,appId,deploymentId}=input2;const now=input2.now??new Date;const schemaRows=await tx.select({state:appSchemaRevisions.state}).from(appSchemaRevisions).where(and29(eq32(appSchemaRevisions.appId,appId),eq32(appSchemaRevisions.deploymentId,deploymentId))).limit(1);const databaseState=schemaRows[0]?.state==="applied"?"APPLIED":"UNCHANGED";const receipt=sanitizeDeploymentExecutorReceipt(await carryDeploymentExecutorWarnings({db:tx,appId,deploymentId,receipt:{phase:"failed",code:CANDIDATE_CLEANUP_COMPLETED_FAILURE_CODE,databaseState,detail:"candidate cleanup proved no committed activation or serving pointer; deployment closed"}}));const rows8=await tx.update(deployments).set({status:"failed",controlPlaneState:"failed",executorState:"failed",failureCode:CANDIDATE_CLEANUP_COMPLETED_FAILURE_CODE,executorReceiptJson:JSON.stringify(receipt),executorReceiptSha256:hashDeploymentExecutorReceipt(receipt),executorUpdatedAt:now}).where(and29(eq32(deployments.id,deploymentId),eq32(deployments.appId,appId),eq32(deployments.status,"pending"),eq32(deployments.executorState,"recovery_required"),eq32(deployments.candidateCleanupFailureCode,"CANDIDATE_CLEANUP_PENDING"),isNull9(deployments.attemptOwnerId),eq32(deployments.executorLeaseEpoch,input2.expectedExecutorLeaseEpoch))).returning({releaseAttemptId:deployments.executorReleaseAttemptId});if(rows8.length!==1)throw new Error("RUNTIME_CANDIDATE_CLEANUP_FINALIZE_CONFLICT");const releaseAttemptId=rows8[0].releaseAttemptId;const releaseRows=releaseAttemptId?await tx.select({environment:appReleaseAttempts.environment,state:appReleaseAttempts.state}).from(appReleaseAttempts).where(and29(eq32(appReleaseAttempts.id,releaseAttemptId),eq32(appReleaseAttempts.appId,appId))).limit(1):[];const release=releaseRows[0];const binding=release&&release.state!=="succeeded"&&release.state!=="superseded"?{attemptId:releaseAttemptId,environment:release.environment}:null;await projectFailedDeploymentExecutorOperation({db:tx,appId,deploymentId,binding,state:"failed",failure:{stage:"candidate",code:CANDIDATE_CLEANUP_COMPLETED_FAILURE_CODE}});await releaseTerminalOwnerServingRoutePrepares(tx,{appId})}var init_deployment_executor_terminal=__esm({"../platform/src/deployment-executor-terminal.ts"(){"use strict";init_deployment_executor_warning_receipt();init_schema();init_apps_release_deploy_binding();init_deployment_executor_operation();init_app_serving_route_owner_release();init_deployment_failure_contract();init_deployment_schema_revision();init_deployment_executor_store()}});import{createHash as createHash67}from"node:crypto";import{readFileSync as readFileSync22}from"node:fs";function isTerminalRuntimeInstanceState(state2){return state2==="stopped"||state2==="exited"}function hasExactRuntimeProcessBinding(runnerRefExact,live,identityExact,instance){return runnerRefExact&&(live?identityExact:isCompleteRuntimeProcessIdentity(instance)||isTerminalRuntimeInstanceState(instance.state))}function parseLinuxProcStatRecord(source){const open12=source.indexOf("(");const close=source.lastIndexOf(")");if(open12<=0||close<=open12)return null;const pid=safePositiveInteger2(source.slice(0,open12).trim());const fields=source.slice(close+1).trim().split(/\s+/u);const processState2=fields[0]??"";const processGroupId=safePositiveInteger2(fields[2]??"");const startTicks=safePositiveInteger2(fields[19]??"");if(!pid||!/^[A-Z]$/u.test(processState2)||!processGroupId||!startTicks)return null;return{pid,processGroupId,startTicks,processState:processState2}}function safePositiveInteger2(value2){const parsed=Number(value2);return Number.isSafeInteger(parsed)&&parsed>1?parsed:null}function parseLinuxProcStat(source){const parsed=parseLinuxProcStatRecord(source);return parsed?{pid:parsed.pid,processGroupId:parsed.processGroupId,startTicks:parsed.startTicks}:null}function parseLinuxProcessState(source){return parseLinuxProcStatRecord(source)?.processState??null}function readLinuxProcessState(pid,readFile23=path5=>readFileSync22(path5,"utf8"),platform=process.platform){if(platform!=="linux"||!Number.isSafeInteger(pid)||pid<=1)return null;try{return parseLinuxProcessState(readFile23(`/proc/${pid}/stat`))}catch{return null}}function canonicalCgroupRefHash(source){const canonical=source.split(/\r?\n/u).map(line=>line.trim()).filter(Boolean).sort().join("\n");if(!canonical)return null;return createHash67("sha256").update(canonical).digest("hex")}function observeLinuxProcessIdentity(pid,runnerSessionId,readFile23=path5=>readFileSync22(path5,"utf8"),platform=process.platform){if(platform!=="linux"||!Number.isSafeInteger(pid)||pid<=1||!runnerSessionId.trim()){return null}try{const processRecord=parseLinuxProcStatRecord(readFile23(`/proc/${pid}/stat`));if(!processRecord||processRecord.pid!==pid||processRecord.processState.startsWith("Z"))return null;const processStat=processRecord;const groupStat=parseLinuxProcStat(readFile23(`/proc/${processStat.processGroupId}/stat`));const cgroupRefHash=canonicalCgroupRefHash(readFile23(`/proc/${pid}/cgroup`));if(!groupStat||groupStat.pid!==processStat.processGroupId||groupStat.processGroupId!==processStat.processGroupId||!cgroupRefHash){return null}return{pid,pidStartTicks:processStat.startTicks,processGroupId:processStat.processGroupId,processGroupStartTicks:groupStat.startTicks,cgroupRefHash,runnerSessionId}}catch{return null}}function observeLinuxKernelProcessIdentity(pid,readFile23=path5=>readFileSync22(path5,"utf8"),platform=process.platform){const observed2=observeLinuxProcessIdentity(pid,"kernel-observation",readFile23,platform);if(!observed2)return null;const{runnerSessionId:_runnerSessionId,...kernelIdentity}=observed2;return kernelIdentity}function runtimeKernelProcessIdentityMatches(observed2,expected){return Boolean(observed2&&observed2.pid===expected.pid&&observed2.pidStartTicks===expected.pidStartTicks&&observed2.processGroupId===expected.processGroupId&&observed2.processGroupStartTicks===expected.processGroupStartTicks&&observed2.cgroupRefHash===expected.cgroupRefHash)}function runtimeProcessIdentityMatches(observed2,expected){return Boolean(observed2&&observed2.pid===expected.pid&&observed2.pidStartTicks===expected.pidStartTicks&&observed2.processGroupId===expected.processGroupId&&observed2.processGroupStartTicks===expected.processGroupStartTicks&&observed2.cgroupRefHash===expected.cgroupRefHash&&observed2.runnerSessionId===expected.runnerSessionId)}function isCompleteRuntimeProcessIdentity(value2){return Boolean(value2&&Number.isSafeInteger(value2.pid)&&Number(value2.pid)>1&&Number.isSafeInteger(value2.pidStartTicks)&&Number(value2.pidStartTicks)>1&&Number.isSafeInteger(value2.processGroupId)&&Number(value2.processGroupId)>1&&Number.isSafeInteger(value2.processGroupStartTicks)&&Number(value2.processGroupStartTicks)>1&&typeof value2.cgroupRefHash==="string"&&/^[a-f0-9]{64}$/u.test(value2.cgroupRefHash)&&typeof value2.runnerSessionId==="string"&&value2.runnerSessionId.length>0)}var init_runtime_process_identity=__esm({"../platform/src/runtime-process-identity.ts"(){"use strict"}});import{and as and30,eq as eq33,inArray as inArray17,isNotNull as isNotNull2,isNull as isNull10,ne as ne10,or as or11,sql as sql108}from"drizzle-orm";import{readFile as readFile18}from"node:fs/promises";import{createConnection as createConnection2}from"node:net";function incompleteCandidatePredicate(){return or11(and30(inArray17(appRuntimeInstances.state,[...CANDIDATE_INSTANCE_STATES]),inArray17(appDeploymentActivations.state,[...CANDIDATE_ACTIVATION_STATES])),and30(eq33(appRuntimeInstances.state,"stopped"),inArray17(appDeploymentActivations.state,["prepared","candidate_ready"])))}function terminalSupersededServingPredicate(){return and30(eq33(appRuntimeInstances.state,"serving"),inArray17(appDeploymentActivations.state,["draining","superseded"]),inArray17(deployments.controlPlaneState,["failed","superseded"]),isNull10(deployments.attemptOwnerId))}function terminalStoppedCandidateMissingCleanupProofPredicate(recoveryAttempt){return and30(eq33(appRuntimeInstances.state,"stopped"),inArray17(appDeploymentActivations.state,["failed","superseded"]),isNull10(appRuntimeInstances.candidateCleanupCompletedAt),recoveryAttempt?or11(isNull10(deployments.attemptOwnerId),and30(eq33(deployments.id,recoveryAttempt.deploymentId),eq33(deployments.attemptOwnerId,recoveryAttempt.attemptOwnerId),eq33(deployments.status,"pending"),eq33(deployments.controlPlaneState,"candidate"),sql108`${deployments.attemptLeaseExpiresAt} > NOW()`)):isNull10(deployments.attemptOwnerId))}function supersededNeverServedStartingPredicate(){return and30(eq33(appRuntimeInstances.state,"starting"),inArray17(appDeploymentActivations.state,["draining","superseded"]),isNull10(deployments.attemptOwnerId))}function runtimeCandidateCleanupRequiredPredicate(input2){return and30(or11(incompleteCandidatePredicate(),terminalSupersededServingPredicate(),supersededNeverServedStartingPredicate(),terminalStoppedCandidateMissingCleanupProofPredicate(input2?.recoveryAttempt)),sql108`NOT EXISTS (
|
|
9052
9052
|
SELECT 1
|
|
@@ -10151,7 +10151,7 @@ ${fingerprintReleaseOwnedNodeModulesRoots(repoRoot2)}
|
|
|
10151
10151
|
throw new Error("composed Core import registered " + name);
|
|
10152
10152
|
}
|
|
10153
10153
|
}
|
|
10154
|
-
`;const result3=spawnSync(process.execPath,["--no-install","--eval",script],{cwd:resolve87(runtimeDir,"server"),encoding:"utf8",timeout:15e3,maxBuffer:64*1024});if(!result3.error&&result3.status===0)return;const failure2=result3.error?.message??`Bun exited with status ${result3.status??result3.signal??"unknown"}`;const detail=(result3.stderr||result3.stdout||"").trim().slice(-2048);throw new Error(`[runtime-layout] Runtime Core facade import validation failed: ${failure2}${detail?`: ${detail}`:""}`)}var RUNTIME_CORE_FACADE_RECIPE;var init_runtime_core_facade_composer=__esm({"../platform/src/runtime-core-facade-composer.ts"(){"use strict";RUNTIME_CORE_FACADE_RECIPE={version:1,backingCoreSpecifier:"./dist/index.js",compatibilitySpecifier:"../server/legacy-core/index.js",compatibilityFactory:"createLegacyCoreCompatibility",bindings:[["httpAction","legacy.httpAction"],["crud","legacy.crud"],["gencowCrud","legacy.crud"],["getRegisteredHttpActions","legacy.getRegisteredHttpActions"],["getRegisteredCrudCodegenMeta","legacy.getRegisteredCrudCodegenMeta"],["getOwnerRlsTables","legacy.getOwnerRlsTables"]]}}});import{mkdirSync as mkdirSync5,realpathSync as realpathSync5,rmSync as rmSync6,symlinkSync}from"node:fs";import{relative as relative22,resolve as resolve88}from"node:path";function safeRealpath3(path5){try{return realpathSync5(path5)}catch{return path5}}function symlinkRelativeEntry(targetPath,destinationPath,type="dir",options={}){rmSync6(destinationPath,{recursive:true,force:true});const destinationParent=resolve88(destinationPath,"..");mkdirSync5(destinationParent,{recursive:true});const fromPath=options.preserveLogicalPath?destinationParent:realpathSync5(destinationParent);const toPath3=options.preserveLogicalPath?resolve88(targetPath):safeRealpath3(targetPath);const relativeTarget=relative22(fromPath,toPath3)||".";symlinkSync(relativeTarget,destinationPath,type)}var init_runtime_generation_staging=__esm({"../platform/src/runtime-generation-staging.ts"(){"use strict"}});import{createHash as createHash75,randomUUID as randomUUID46}from"crypto";import{chmodSync,closeSync,constants as constants3,copyFileSync as copyFileSync2,existsSync as existsSync34,fsyncSync,lstatSync as lstatSync7,mkdirSync as mkdirSync6,mkdtempSync as mkdtempSync5,openSync,readFileSync as readFileSync31,readdirSync as readdirSync12,realpathSync as realpathSync6,renameSync,rmSync as rmSync7,statSync as statSync6,symlinkSync as symlinkSync2}from"fs";import{basename as basename10,dirname as dirname24,isAbsolute as isAbsolute25,join as join26,relative as relative23,resolve as resolve89,sep as sep3}from"path";function resolveRuntimeClosureNativePlanBudget(budget){const resolved={maxRecords:budget?.maxRecords??NATIVE_PLAN_MAX_RECORDS,maxEncodedBytes:budget?.maxEncodedBytes??NATIVE_PLAN_MAX_BYTES,maxPathBytes:budget?.maxPathBytes??NATIVE_PLAN_MAX_PATH_BYTES};if(!Number.isSafeInteger(resolved.maxRecords)||resolved.maxRecords<0||resolved.maxRecords>NATIVE_PLAN_MAX_RECORDS||!Number.isSafeInteger(resolved.maxEncodedBytes)||resolved.maxEncodedBytes<1||resolved.maxEncodedBytes>NATIVE_PLAN_MAX_BYTES||!Number.isSafeInteger(resolved.maxPathBytes)||resolved.maxPathBytes<1||resolved.maxPathBytes>NATIVE_PLAN_MAX_PATH_BYTES){throw new Error("runtime native closure plan budget invalid")}return resolved}function canonicalSealedRuntimeFileMode(mode){return mode&73?365:292}function packageManagerNodeModulesRoot(sourceRoot,targetPath){const targetRelativePath=ensureContainedPath(sourceRoot,targetPath,"package manager package");const parts=targetRelativePath.split(sep3);const pnpmIndex=parts.indexOf(".pnpm");if(pnpmIndex>=1&&parts[pnpmIndex-1]==="node_modules"&&parts[pnpmIndex+2]==="node_modules"){return parts.slice(0,pnpmIndex+3).join(sep3)}const bunIndex=parts.indexOf(".bun");if(bunIndex>=1&&parts[bunIndex-1]==="node_modules"&&parts[bunIndex+2]==="node_modules"){return parts.slice(0,bunIndex+3).join(sep3)}return null}function ensureContainedPath(root2,path5,label){const rel=relative23(root2,path5);if(!rel||rel===".")return".";if(isAbsolute25(rel)||rel===".."||rel.startsWith(`..${sep3}`)){throw new Error(`${label} escapes runtime root: ${path5}`)}return rel}function shouldExclude(path5,directory){const name=basename10(path5);if(name===".env"||name.startsWith(".env."))return true;if(!directory&&SECRET_FILE_PATTERN.test(name))return true;if(directory&&EXCLUDED_DIRECTORY_NAMES.has(name))return true;return!directory&&TEST_FILE_PATTERN.test(name)}function planFence(path5){const value2=lstatSync7(path5,{bigint:true});return{dev:value2.dev.toString(),ino:value2.ino.toString(),mode:value2.mode.toString(),size:value2.size.toString(),nlink:value2.nlink.toString(),mtimeNs:value2.mtimeNs.toString(),ctimeNs:value2.ctimeNs.toString()}}function planPath(path5,budget){const normalized=path5.replaceAll("\\","/");if(!normalized||normalized.startsWith("/")||normalized.includes("\0")||normalized.split("/").includes("..")){throw new Error("runtime generation plan path invalid")}if(Buffer.byteLength(normalized,"utf8")>budget.maxPathBytes){throw new RuntimeClosureNativePlanUnsupportedError}return normalized}function recordPlan(context,record3){if(!context.planRecords)return;if(context.planRecords.length>=context.planBudget.maxRecords){throw new RuntimeClosureNativePlanUnsupportedError}const encodedBytes=Buffer.byteLength(JSON.stringify(record3),"utf8")+1;const nextBytes=(context.planEncodedBytes??0)+encodedBytes;if(nextBytes>context.planBudget.maxEncodedBytes)throw new RuntimeClosureNativePlanUnsupportedError;context.planEncodedBytes=nextBytes;context.planRecords.push(record3)}function updateHash(context,value2){context.hash?.update(value2)}function copyFileWithClone(sourcePath,destinationPath){mkdirSync6(dirname24(destinationPath),{recursive:true,mode:493});copyFileSync2(sourcePath,destinationPath,constants3.COPYFILE_FICLONE);chmodSync(destinationPath,statSync6(sourcePath).mode&511)}function copyRelativeRuntimePath(context,relativePath){const sourcePath=resolve89(context.sourceRoot,relativePath);const safeRelativePath=ensureContainedPath(context.sourceRoot,sourcePath,"runtime snapshot path");if(context.visited.has(safeRelativePath)||!existsSync34(sourcePath))return;context.visited.add(safeRelativePath);const sourceStat=lstatSync7(sourcePath);if(shouldExclude(sourcePath,sourceStat.isDirectory()))return;const destinationPath=resolve89(context.stagingRoot,safeRelativePath);if(sourceStat.isSymbolicLink()){const targetPath=realpathSync6(sourcePath);const targetRelativePath=ensureContainedPath(context.sourceRoot,targetPath,"runtime symlink");const destinationTarget=resolve89(context.stagingRoot,targetRelativePath);mkdirSync6(dirname24(destinationPath),{recursive:true,mode:493});const linkTarget=relative23(dirname24(destinationPath),destinationTarget)||".";symlinkSync2(linkTarget,destinationPath,statSync6(targetPath).isDirectory()?"dir":"file");copyRelativeRuntimePath(context,targetRelativePath);const dependencyRoot=packageManagerNodeModulesRoot(context.sourceRoot,targetPath);if(dependencyRoot)copyRelativeRuntimePath(context,dependencyRoot);return}if(sourceStat.isDirectory()){mkdirSync6(destinationPath,{recursive:true,mode:sourceStat.mode&511|448});for(const entry of readdirSync12(sourcePath).sort()){copyRelativeRuntimePath(context,join26(safeRelativePath,entry))}return}if(sourceStat.isFile())copyFileWithClone(sourcePath,destinationPath)}function hashRelativeRuntimePath(context,relativePath){const sourcePath=resolve89(context.sourceRoot,relativePath);const safeRelativePath=ensureContainedPath(context.sourceRoot,sourcePath,"runtime hash path");if(context.visited.has(safeRelativePath)||!existsSync34(sourcePath))return;context.visited.add(safeRelativePath);const sourceStat=lstatSync7(sourcePath);if(shouldExclude(sourcePath,sourceStat.isDirectory()))return;if(sourceStat.isSymbolicLink()){const targetPath=realpathSync6(sourcePath);const targetRelativePath=ensureContainedPath(context.sourceRoot,targetPath,"runtime hash symlink");if(context.planRecords){recordPlan(context,{kind:"L",path:planPath(safeRelativePath,context.planBudget),target:planPath(targetRelativePath,context.planBudget),fence:planFence(sourcePath)})}updateHash(context,`L\0${safeRelativePath}\0${targetRelativePath}\0`);hashRelativeRuntimePath(context,targetRelativePath);const dependencyRoot=packageManagerNodeModulesRoot(context.sourceRoot,targetPath);if(dependencyRoot)hashRelativeRuntimePath(context,dependencyRoot);return}if(sourceStat.isDirectory()){if(context.planRecords){recordPlan(context,{kind:"D",path:planPath(safeRelativePath,context.planBudget),fence:planFence(sourcePath)})}updateHash(context,`D\0${safeRelativePath}\0`);for(const entry of readdirSync12(sourcePath).sort()){hashRelativeRuntimePath(context,join26(safeRelativePath,entry))}return}if(sourceStat.isFile()){if(context.planRecords){recordPlan(context,{kind:"F",path:planPath(safeRelativePath,context.planBudget),fence:planFence(sourcePath)})}const executeBits=canonicalSealedRuntimeFileMode(sourceStat.mode)&73;updateHash(context,`F\0${safeRelativePath}\0${executeBits}\0`);if(context.hash){context.hash.update(readFileSync31(sourcePath));context.hash.update("\0")}}}function createRuntimeClosureNativePlan(params){const sourceRoot=realpathSync6(params.runtimeRoot);const budget=resolveRuntimeClosureNativePlanBudget(params.budget);if(Buffer.byteLength(sourceRoot,"utf8")>budget.maxPathBytes){throw new RuntimeClosureNativePlanUnsupportedError}const root2={path:sourceRoot,...planFence(sourceRoot)};const initialPlanEncodedBytes=Buffer.byteLength(JSON.stringify({version:1,root:root2,records:[]}),"utf8");if(initialPlanEncodedBytes>budget.maxEncodedBytes){throw new RuntimeClosureNativePlanUnsupportedError}const context={sourceRoot,visited:new Set,planRecords:[],planEncodedBytes:initialPlanEncodedBytes,planBudget:budget};for(const seed of params.closureSeeds)hashRelativeRuntimePath(context,seed);return{version:1,root:root2,records:context.planRecords}}function createRuntimeClosureNativePlanForManifest(manifest){const sourceRoot=runtimeSnapshotSourceRoot(manifest);return createRuntimeClosureNativePlan({runtimeRoot:sourceRoot,closureSeeds:runtimeSnapshotSeeds(manifest,sourceRoot)})}function mapRuntimePath(sourceRoot,finalRoot,path5,label){const sourcePath=realpathSync6(path5);const relativePath=ensureContainedPath(sourceRoot,sourcePath,label);return resolve89(finalRoot,relativePath)}function copyBinarySnapshot(params){if(params.snapshot.status!=="present"||!params.snapshot.path)return params.snapshot;const sourcePath=realpathSync6(params.snapshot.path);const extension=process.platform==="win32"?".exe":"";const relativePath=params.layoutVersion===3?join26("runtime","bin",`${params.name}${extension}`):join26("bin",`${params.name}${extension}`);copyFileWithClone(sourcePath,resolve89(params.stagingRoot,relativePath));return{...params.snapshot,path:resolve89(params.finalRoot,relativePath)}}function runtimeSnapshotSourceRoot(manifest){const runtimeRoot=realpathSync6(manifest.runtimeRoot);return manifest.layoutVersion===3?realpathSync6(resolve89(runtimeRoot,"..")):runtimeRoot}function runtimeSnapshotSeeds(manifest,sourceRoot){const layout=detectRuntimeManifestLayout(manifest.runtimeRoot,manifest.serverEntry.path);const seeds=new Set(layout==="managed-release"?manifest.layoutVersion===3?["runtime/server","runtime/core","runtime/node_modules","public-node_modules","platform/src","platform/node_modules"]:["manifest.json","server","core","node_modules"]:["package.json","pnpm-workspace.yaml","packages/server/src","packages/server/package.json","packages/server/node_modules","packages/core/src","packages/core/dist","packages/core/package.json","packages/core/node_modules","packages/client/src","packages/client/dist","packages/client/package.json","packages/client/node_modules","packages/shared/dist","packages/shared/package.json","packages/shared/node_modules","packages/internal/dist","packages/internal/package.json","packages/internal/node_modules","packages/platform/src","packages/platform/package.json","packages/platform/node_modules","packages/cli/server","packages/cli/core"]);for(const lockfile of manifest.packageManager.lockfiles)seeds.add(lockfile.file);for(const snapshot of Object.values(manifest.packages)){if(snapshot.status!=="present"||!snapshot.packageJsonPath)continue;const packagePath=realpathSync6(dirname24(snapshot.packageJsonPath));seeds.add(ensureContainedPath(sourceRoot,packagePath,"runtime package"))}return[...seeds].sort()}function sha256RuntimePaths(sourceRoot,seeds){const canonicalRoot=realpathSync6(sourceRoot);const context={sourceRoot:canonicalRoot,visited:new Set,hash:createHash75("sha256")};for(const seed of seeds)hashRelativeRuntimePath(context,seed);return`sha256:${context.hash.digest("hex")}`}function assertRuntimeClosureMatchesAtRoot(params){const actualClosureSha256=sha256RuntimePaths(params.runtimeRoot,params.closureSeeds);if(actualClosureSha256!==params.expectedClosureSha256){throw new Error(`runtime generation closure hash mismatch: expected ${params.expectedClosureSha256}, got ${actualClosureSha256}`)}}function sha256RuntimeSnapshot(manifest){const sourceRoot=runtimeSnapshotSourceRoot(manifest);return sha256RuntimePaths(sourceRoot,runtimeSnapshotSeeds(manifest,sourceRoot))}function runtimeReleaseId(manifestHash,runtimeClosureSha256){return`sha256:${createHash75("sha256").update(`${manifestHash}\0${runtimeClosureSha256}`).digest("hex")}`}function prepareRuntimeGenerationManifest(manifest){const runtimeClosureSha256=sha256RuntimeSnapshot(manifest);return{...manifest,releaseId:runtimeReleaseId(deploymentRuntimeManifestHash(manifest),runtimeClosureSha256),runtimeClosureSha256}}function runtimeGenerationDirectorySuffix(generationId){if(!RUNTIME_GENERATION_ID_PATTERN.test(generationId)){throw new Error(`invalid runtime generation id: ${generationId}`)}return generationId.replace("sha256:","sha256-")}function formatRuntimeGenerationDirectoryTimestamp(generatedAt){const parsed=new Date(generatedAt);if(Number.isNaN(parsed.getTime())){throw new Error(`invalid runtime generation timestamp: ${generatedAt}`)}return parsed.toISOString().replace(/[-:.]/g,"")}function runtimeGenerationDirectoryName(generationId,generatedAt){return`${formatRuntimeGenerationDirectoryTimestamp(generatedAt)}-${runtimeGenerationDirectorySuffix(generationId)}`}function resolveRuntimeGenerationDirectoryPath(baseDir,generationId){const suffix=runtimeGenerationDirectorySuffix(generationId);const timestampedMatches=[];if(!existsSync34(baseDir))return null;for(const entry of readdirSync12(baseDir,{withFileTypes:true})){if(!entry.isDirectory())continue;if(entry.name.endsWith(`-${suffix}`)&&COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN.test(entry.name)){const timestampSource=entry.name.slice(0,-`-${suffix}`.length);const parsedTimestamp=new Date(timestampSource.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\d{3})Z$/,"$1-$2-$3T$4:$5:$6.$7Z")).getTime();if(!Number.isNaN(parsedTimestamp)){timestampedMatches.push({entryName:entry.name,timestamp:parsedTimestamp})}}}const selected=timestampedMatches.sort((a,b2)=>a.timestamp-b2.timestamp||a.entryName.localeCompare(b2.entryName)).at(-1);if(selected)return resolve89(baseDir,selected.entryName);const legacyGenerationDir=resolve89(baseDir,suffix);return existsSync34(legacyGenerationDir)?legacyGenerationDir:null}function runtimeGenerationDirectoryPath(baseDir,generationId,generatedAt){return resolve89(baseDir,runtimeGenerationDirectoryName(generationId,generatedAt))}function stageRuntimeGeneration(params){const sourceRoot=runtimeSnapshotSourceRoot(params.manifest);if(!params.manifest.releaseId||!params.manifest.runtimeClosureSha256){throw new Error("runtime generation manifest is missing its release content identity")}const finalGenerationDir=runtimeGenerationDirectoryPath(params.baseDir,params.manifest.releaseId,params.manifest.generatedAt);const finalRoot=params.manifest.layoutVersion===3?finalGenerationDir:resolve89(finalGenerationDir,"runtime");mkdirSync6(params.baseDir,{recursive:true,mode:493});const publicationOwner=/^[a-f0-9]{32}$/.test(process.env.GENCOW_RUNTIME_PUBLICATION_OWNER??"")?`-${process.env.GENCOW_RUNTIME_PUBLICATION_OWNER}`:"";const stagedGenerationDir=mkdtempSync5(resolve89(params.baseDir,`.tmp-${params.manifestHash.replace(":","-")}-${process.pid}${publicationOwner}-${randomUUID46()}-`));const stagingRoot=params.manifest.layoutVersion===3?stagedGenerationDir:resolve89(stagedGenerationDir,"runtime");try{const context={sourceRoot,stagingRoot,visited:new Set};const seeds=runtimeSnapshotSeeds(params.manifest,sourceRoot);for(const seed of seeds){copyRelativeRuntimePath(context,seed)}assertRuntimeClosureMatchesAtRoot({runtimeRoot:params.manifest.layoutVersion===3?stagedGenerationDir:stagingRoot,closureSeeds:seeds,expectedClosureSha256:params.manifest.runtimeClosureSha256});const packages=Object.fromEntries(Object.entries(params.manifest.packages).map(([name,snapshot])=>[name,snapshot.status==="present"&&snapshot.packageJsonPath?{...snapshot,packageJsonPath:mapRuntimePath(sourceRoot,finalRoot,snapshot.packageJsonPath,`package ${name}`)}:snapshot]));const binaries=Object.fromEntries(Object.entries(params.manifest.binaries).map(([name,snapshot])=>[name,copyBinarySnapshot({name,snapshot,stagingRoot,finalRoot,layoutVersion:params.manifest.layoutVersion})]));return{stagedGenerationDir,finalGenerationDir,closureSeeds:seeds,publishedManifest:{...params.manifest,runtimeRoot:params.manifest.layoutVersion===3?resolve89(finalGenerationDir,"runtime"):finalRoot,serverEntry:{...params.manifest.serverEntry,path:mapRuntimePath(sourceRoot,finalRoot,params.manifest.serverEntry.path,"server entry")},packages,binaries}}}catch(error62){discardStagedRuntimeGeneration(stagedGenerationDir);throw error62}}function makePathWritable(path5){if(!existsSync34(path5))return;const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){chmodSync(path5,493);for(const entry of readdirSync12(path5))makePathWritable(resolve89(path5,entry))}else if(pathStat.isFile()){chmodSync(path5,pathStat.mode|384)}}function discardStagedRuntimeGeneration(stagedGenerationDir){if(!existsSync34(stagedGenerationDir))return;makePathWritable(stagedGenerationDir);rmSync7(stagedGenerationDir,{recursive:true,force:true})}function commitStagedRuntimeGeneration(stagedGenerationDir,finalGenerationDir){try{renameSync(stagedGenerationDir,finalGenerationDir);return"published"}catch(error62){if(existsSync34(finalGenerationDir)){discardStagedRuntimeGeneration(stagedGenerationDir);return"existing"}discardStagedRuntimeGeneration(stagedGenerationDir);throw error62}}function sealPathReadOnly(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){for(const entry of readdirSync12(path5))sealPathReadOnly(resolve89(path5,entry));chmodSync(path5,365);return}if(pathStat.isFile())chmodSync(path5,canonicalSealedRuntimeFileMode(pathStat.mode))}function sealStagedRuntimeGeneration(stagedGenerationDir){if(existsSync34(resolve89(stagedGenerationDir,"runtime"))){sealPathReadOnly(resolve89(stagedGenerationDir,"runtime"))}if(existsSync34(resolve89(stagedGenerationDir,"public-node_modules"))){sealPathReadOnly(resolve89(stagedGenerationDir,"public-node_modules"))}if(existsSync34(resolve89(stagedGenerationDir,"platform"))){sealPathReadOnly(resolve89(stagedGenerationDir,"platform"))}if(existsSync34(resolve89(stagedGenerationDir,"scripts"))){sealPathReadOnly(resolve89(stagedGenerationDir,"scripts"))}chmodSync(resolve89(stagedGenerationDir,"runtime-manifest.json"),292);chmodSync(stagedGenerationDir,365)}function assertPathReadOnly(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;const mode=pathStat.mode&511;if(pathStat.isDirectory()){if(mode!==365){throw new Error("runtime generation permission invalid")}for(const entry of readdirSync12(path5))assertPathReadOnly(resolve89(path5,entry));return}if(pathStat.isFile()&&mode!==292&&mode!==365){throw new Error("runtime generation permission invalid")}if(!pathStat.isFile()){throw new Error("runtime generation permission invalid")}}function assertRuntimeGenerationSealed(generationDir){assertPathReadOnly(generationDir);if((lstatSync7(resolve89(generationDir,"runtime-manifest.json")).mode&511)!==292){throw new Error("runtime generation permission invalid")}}function fsyncPathTree(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){for(const entry of readdirSync12(path5))fsyncPathTree(resolve89(path5,entry))}const fd=openSync(path5,"r");try{fsyncSync(fd)}finally{closeSync(fd)}}function fsyncStagedRuntimeGeneration(stagedGenerationDir){fsyncPathTree(stagedGenerationDir)}var EXCLUDED_DIRECTORY_NAMES,TEST_FILE_PATTERN,SECRET_FILE_PATTERN,RUNTIME_GENERATION_ID_PATTERN,COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN,RuntimeClosureNativePlanUnsupportedError,NATIVE_PLAN_MAX_RECORDS,NATIVE_PLAN_MAX_BYTES,NATIVE_PLAN_MAX_PATH_BYTES;var init_runtime_generation_publisher=__esm({"../platform/src/runtime-generation-publisher.ts"(){"use strict";init_deployment_runtime_manifest();EXCLUDED_DIRECTORY_NAMES=new Set([".git",".gencow","__tests__"]);TEST_FILE_PATTERN=/\.(?:test|spec)\.[cm]?[jt]sx?$/;SECRET_FILE_PATTERN=/^(?:\.npmrc|\.yarnrc|\.netrc|\.pypirc|id_rsa|id_ed25519)$|(?:private|secret|credential).*\.(?:key|pem|p12|pfx)$|\.(?:key|p12|pfx)$/i;RUNTIME_GENERATION_ID_PATTERN=/^sha256:[a-f0-9]{64}$/;COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN=/^\d{8}T\d{9}Z-sha256-[a-f0-9]{64}$/;RuntimeClosureNativePlanUnsupportedError=class extends Error{constructor(){super("runtime native closure backend unsupported");this.name="RuntimeClosureNativePlanUnsupportedError"}};NATIVE_PLAN_MAX_RECORDS=1e5;NATIVE_PLAN_MAX_BYTES=32*1024*1024;NATIVE_PLAN_MAX_PATH_BYTES=4096}});import{existsSync as existsSync35,statfsSync}from"fs";import{dirname as dirname25}from"path";function requiredRuntimeGenerationFreeBytes(probe={}){const watermark=probe.watermarkBytes??RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES;const closure=probe.expectedClosureBytes??RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES;const withHeadroom=Math.ceil(closure*RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR/RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR);return Math.max(watermark,withHeadroom)}function defaultAvailableBytes(path5){let candidate=path5;while(!existsSync35(candidate)){const parent=dirname25(candidate);if(parent===candidate)return null;candidate=parent}try{const stat13=statfsSync(candidate);return Number(stat13.bavail)*Number(stat13.bsize)}catch{return null}}function assertRuntimeGenerationCapacityPreflight(baseDir,probe={}){const available=(probe.availableBytes??defaultAvailableBytes)(baseDir);if(available===null||!Number.isFinite(available))return;if(available<requiredRuntimeGenerationFreeBytes(probe)){throw new RuntimeGenerationCapacityPreflightError}}var GIB,RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES,RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES,RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR,RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR,RuntimeGenerationCapacityPreflightError;var init_runtime_generation_capacity=__esm({"../platform/src/runtime-generation-capacity.ts"(){"use strict";GIB=1024*1024*1024;RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES=10*GIB;RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES=2*GIB;RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR=3;RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR=2;RuntimeGenerationCapacityPreflightError=class extends Error{reasonCode="runtime_generation_capacity_preflight_failed";constructor(){super("runtime generation capacity preflight failed");this.name="RuntimeGenerationCapacityPreflightError"}}}});import{spawnSync as spawnSync2}from"node:child_process";import{createHash as createHash76}from"node:crypto";import{lstatSync as lstatSync8,readFileSync as readFileSync32}from"node:fs";function tagRuntimeNativeClosureBackendStage(error62,stage){if((typeof error62!=="object"||error62===null)&&typeof error62!=="function")return error62;try{Object.defineProperty(error62,"runtimeNativeClosureBackendStage",{configurable:true,value:stage})}catch{}return error62}function nativeFailure(message,code,runtimeNativeClosureBackendStage="none"){const error62=new Error(message);if(code)error62.code=code;return tagRuntimeNativeClosureBackendStage(error62,runtimeNativeClosureBackendStage)}function isTrustedNativeBinary(dependencies){let stat13;try{stat13=dependencies.lstat(RUNTIME_NATIVE_CLOSURE_BINARY)}catch(error62){const code=error62&&typeof error62==="object"&&"code"in error62?String(error62.code):"";if(code==="ENOENT")return false;if(code==="EACCES"||code==="EPERM"){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_PERMISSION_INVALID","binary_identity")}throw nativeFailure("runtime generation verification failed","RUNTIME_NATIVE_CLOSURE_BINARY_UNREADABLE","binary_identity")}if(!stat13.isFile()||stat13.isSymbolicLink()||stat13.uid!==0||stat13.gid!==0||(stat13.mode&511)!==365){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_PERMISSION_INVALID","binary_identity")}let fingerprintStat;try{fingerprintStat=dependencies.lstat(RUNTIME_NATIVE_CLOSURE_FINGERPRINT)}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_UNREADABLE","binary_identity")}if(!fingerprintStat.isFile()||fingerprintStat.isSymbolicLink()||fingerprintStat.uid!==0||fingerprintStat.gid!==0||(fingerprintStat.mode&511)!==320){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_PERMISSION_INVALID","binary_identity")}let expected;try{expected=dependencies.readFile(RUNTIME_NATIVE_CLOSURE_FINGERPRINT,"utf8").trim()}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_UNREADABLE","binary_identity")}if(!SHA25615.test(expected)){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_INVALID","binary_identity")}let actual;try{actual=createHash76("sha256").update(dependencies.readFile(RUNTIME_NATIVE_CLOSURE_BINARY)).digest("hex")}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_UNREADABLE","binary_identity")}if(actual!==expected){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_MISMATCH","binary_identity")}return true}function execute(dependencies,args,input2){return dependencies.spawn(TIMEOUT_BINARY,["--signal=TERM","--kill-after=250ms",NATIVE_TIMEOUT_SECONDS,RUNTIME_NATIVE_CLOSURE_BINARY,...args],{input:input2,encoding:"utf8",timeout:HOST_TIMEOUT_MS,maxBuffer:NATIVE_MAX_BUFFER_BYTES})}function assertCapability(dependencies){const result3=execute(dependencies,["--capability"]);if(result3.error?.code==="ETIMEDOUT"||result3.status===124||result3.status===137){throw nativeFailure("runtime generation native verifier timeout","ETIMEDOUT","capability")}if(result3.status===77)throw nativeFailure("runtime generation permission invalid",void 0,"capability");if(result3.status===69&&result3.stdout===""&&result3.stderr===""){return false}if(result3.status===70||result3.status===78)throw nativeFailure("runtime generation verification failed",void 0,"capability");if(result3.error||result3.signal||result3.status!==0)throw nativeFailure("runtime generation verification failed",void 0,"capability");if(result3.stdout!==`${RUNTIME_NATIVE_CLOSURE_CAPABILITY}
|
|
10154
|
+
`;const result3=spawnSync(process.execPath,["--no-install","--eval",script],{cwd:resolve87(runtimeDir,"server"),encoding:"utf8",timeout:15e3,maxBuffer:64*1024});if(!result3.error&&result3.status===0)return;const failure2=result3.error?.message??`Bun exited with status ${result3.status??result3.signal??"unknown"}`;const detail=(result3.stderr||result3.stdout||"").trim().slice(-2048);throw new Error(`[runtime-layout] Runtime Core facade import validation failed: ${failure2}${detail?`: ${detail}`:""}`)}var RUNTIME_CORE_FACADE_RECIPE;var init_runtime_core_facade_composer=__esm({"../platform/src/runtime-core-facade-composer.ts"(){"use strict";RUNTIME_CORE_FACADE_RECIPE={version:1,backingCoreSpecifier:"./dist/index.js",compatibilitySpecifier:"../server/legacy-core/index.js",compatibilityFactory:"createLegacyCoreCompatibility",bindings:[["httpAction","legacy.httpAction"],["crud","legacy.crud"],["gencowCrud","legacy.crud"],["getRegisteredHttpActions","legacy.getRegisteredHttpActions"],["getRegisteredCrudCodegenMeta","legacy.getRegisteredCrudCodegenMeta"],["getOwnerRlsTables","legacy.getOwnerRlsTables"]]}}});import{mkdirSync as mkdirSync5,realpathSync as realpathSync5,rmSync as rmSync6,symlinkSync}from"node:fs";import{relative as relative22,resolve as resolve88}from"node:path";function safeRealpath3(path5){try{return realpathSync5(path5)}catch{return path5}}function symlinkRelativeEntry(targetPath,destinationPath,type="dir",options={}){rmSync6(destinationPath,{recursive:true,force:true});const destinationParent=resolve88(destinationPath,"..");mkdirSync5(destinationParent,{recursive:true});const fromPath=options.preserveLogicalPath?destinationParent:realpathSync5(destinationParent);const toPath3=options.preserveLogicalPath?resolve88(targetPath):safeRealpath3(targetPath);const relativeTarget=relative22(fromPath,toPath3)||".";symlinkSync(relativeTarget,destinationPath,type)}var init_runtime_generation_staging=__esm({"../platform/src/runtime-generation-staging.ts"(){"use strict"}});import{createHash as createHash75,randomUUID as randomUUID46}from"crypto";import{chmodSync,closeSync,constants as constants3,copyFileSync as copyFileSync2,existsSync as existsSync34,fsyncSync,lstatSync as lstatSync7,mkdirSync as mkdirSync6,mkdtempSync as mkdtempSync5,openSync,readFileSync as readFileSync31,readdirSync as readdirSync12,realpathSync as realpathSync6,renameSync,rmSync as rmSync7,statSync as statSync6,symlinkSync as symlinkSync2}from"fs";import{basename as basename10,dirname as dirname24,isAbsolute as isAbsolute25,join as join26,relative as relative23,resolve as resolve89,sep as sep3}from"path";function resolveRuntimeClosureNativePlanBudget(budget){const resolved={maxRecords:budget?.maxRecords??NATIVE_PLAN_MAX_RECORDS,maxEncodedBytes:budget?.maxEncodedBytes??NATIVE_PLAN_MAX_BYTES,maxPathBytes:budget?.maxPathBytes??NATIVE_PLAN_MAX_PATH_BYTES};if(!Number.isSafeInteger(resolved.maxRecords)||resolved.maxRecords<0||resolved.maxRecords>NATIVE_PLAN_MAX_RECORDS||!Number.isSafeInteger(resolved.maxEncodedBytes)||resolved.maxEncodedBytes<1||resolved.maxEncodedBytes>NATIVE_PLAN_MAX_BYTES||!Number.isSafeInteger(resolved.maxPathBytes)||resolved.maxPathBytes<1||resolved.maxPathBytes>NATIVE_PLAN_MAX_PATH_BYTES){throw new Error("runtime native closure plan budget invalid")}return resolved}function canonicalSealedRuntimeFileMode(mode){return mode&73?365:292}function packageManagerNodeModulesRoot(sourceRoot,targetPath){const targetRelativePath=ensureContainedPath(sourceRoot,targetPath,"package manager package");const parts=targetRelativePath.split(sep3);const pnpmIndex=parts.indexOf(".pnpm");if(pnpmIndex>=1&&parts[pnpmIndex-1]==="node_modules"&&parts[pnpmIndex+2]==="node_modules"){return parts.slice(0,pnpmIndex+3).join(sep3)}const bunIndex=parts.indexOf(".bun");if(bunIndex>=1&&parts[bunIndex-1]==="node_modules"&&parts[bunIndex+2]==="node_modules"){return parts.slice(0,bunIndex+3).join(sep3)}return null}function ensureContainedPath(root2,path5,label){const rel=relative23(root2,path5);if(!rel||rel===".")return".";if(isAbsolute25(rel)||rel===".."||rel.startsWith(`..${sep3}`)){throw new Error(`${label} escapes runtime root: ${path5}`)}return rel}function shouldExclude(path5,directory){const name=basename10(path5);if(name===".env"||name.startsWith(".env."))return true;if(!directory&&SECRET_FILE_PATTERN.test(name))return true;if(directory&&EXCLUDED_DIRECTORY_NAMES.has(name))return true;return!directory&&TEST_FILE_PATTERN.test(name)}function planFence(path5){const value2=lstatSync7(path5,{bigint:true});return{dev:value2.dev.toString(),ino:value2.ino.toString(),mode:value2.mode.toString(),size:value2.size.toString(),nlink:value2.nlink.toString(),mtimeNs:value2.mtimeNs.toString(),ctimeNs:value2.ctimeNs.toString()}}function planPath(path5,budget){const normalized=path5.replaceAll("\\","/");if(!normalized||normalized.startsWith("/")||normalized.includes("\0")||normalized.split("/").includes("..")){throw new Error("runtime generation plan path invalid")}if(Buffer.byteLength(normalized,"utf8")>budget.maxPathBytes){throw new RuntimeClosureNativePlanUnsupportedError}return normalized}function recordPlan(context,record3){if(!context.planRecords)return;if(context.planRecords.length>=context.planBudget.maxRecords){throw new RuntimeClosureNativePlanUnsupportedError}const encodedBytes=Buffer.byteLength(JSON.stringify(record3),"utf8")+1;const nextBytes=(context.planEncodedBytes??0)+encodedBytes;if(nextBytes>context.planBudget.maxEncodedBytes)throw new RuntimeClosureNativePlanUnsupportedError;context.planEncodedBytes=nextBytes;context.planRecords.push(record3)}function updateHash(context,value2){context.hash?.update(value2)}function copyFileWithClone(sourcePath,destinationPath){mkdirSync6(dirname24(destinationPath),{recursive:true,mode:493});copyFileSync2(sourcePath,destinationPath,constants3.COPYFILE_FICLONE);chmodSync(destinationPath,statSync6(sourcePath).mode&511)}function copyRelativeRuntimePath(context,relativePath){const sourcePath=resolve89(context.sourceRoot,relativePath);const safeRelativePath=ensureContainedPath(context.sourceRoot,sourcePath,"runtime snapshot path");if(context.visited.has(safeRelativePath)||!existsSync34(sourcePath))return;context.visited.add(safeRelativePath);const sourceStat=lstatSync7(sourcePath);if(shouldExclude(sourcePath,sourceStat.isDirectory()))return;const destinationPath=resolve89(context.stagingRoot,safeRelativePath);if(sourceStat.isSymbolicLink()){const targetPath=realpathSync6(sourcePath);const targetRelativePath=ensureContainedPath(context.sourceRoot,targetPath,"runtime symlink");const destinationTarget=resolve89(context.stagingRoot,targetRelativePath);mkdirSync6(dirname24(destinationPath),{recursive:true,mode:493});const linkTarget=relative23(dirname24(destinationPath),destinationTarget)||".";symlinkSync2(linkTarget,destinationPath,statSync6(targetPath).isDirectory()?"dir":"file");copyRelativeRuntimePath(context,targetRelativePath);const dependencyRoot=packageManagerNodeModulesRoot(context.sourceRoot,targetPath);if(dependencyRoot)copyRelativeRuntimePath(context,dependencyRoot);return}if(sourceStat.isDirectory()){mkdirSync6(destinationPath,{recursive:true,mode:sourceStat.mode&511|448});for(const entry of readdirSync12(sourcePath).sort()){copyRelativeRuntimePath(context,join26(safeRelativePath,entry))}return}if(sourceStat.isFile())copyFileWithClone(sourcePath,destinationPath)}function hashRelativeRuntimePath(context,relativePath){const sourcePath=resolve89(context.sourceRoot,relativePath);const safeRelativePath=ensureContainedPath(context.sourceRoot,sourcePath,"runtime hash path");if(context.visited.has(safeRelativePath)||!existsSync34(sourcePath))return;context.visited.add(safeRelativePath);const sourceStat=lstatSync7(sourcePath);if(shouldExclude(sourcePath,sourceStat.isDirectory()))return;if(sourceStat.isSymbolicLink()){const targetPath=realpathSync6(sourcePath);const targetRelativePath=ensureContainedPath(context.sourceRoot,targetPath,"runtime hash symlink");if(context.planRecords){recordPlan(context,{kind:"L",path:planPath(safeRelativePath,context.planBudget),target:planPath(targetRelativePath,context.planBudget),fence:planFence(sourcePath)})}updateHash(context,`L\0${safeRelativePath}\0${targetRelativePath}\0`);hashRelativeRuntimePath(context,targetRelativePath);const dependencyRoot=packageManagerNodeModulesRoot(context.sourceRoot,targetPath);if(dependencyRoot)hashRelativeRuntimePath(context,dependencyRoot);return}if(sourceStat.isDirectory()){if(context.planRecords){recordPlan(context,{kind:"D",path:planPath(safeRelativePath,context.planBudget),fence:planFence(sourcePath)})}updateHash(context,`D\0${safeRelativePath}\0`);for(const entry of readdirSync12(sourcePath).sort()){hashRelativeRuntimePath(context,join26(safeRelativePath,entry))}return}if(sourceStat.isFile()){if(context.planRecords){recordPlan(context,{kind:"F",path:planPath(safeRelativePath,context.planBudget),fence:planFence(sourcePath)})}const executeBits=canonicalSealedRuntimeFileMode(sourceStat.mode)&73;updateHash(context,`F\0${safeRelativePath}\0${executeBits}\0`);if(context.hash){context.hash.update(readFileSync31(sourcePath));context.hash.update("\0")}}}function createRuntimeClosureNativePlan(params){const sourceRoot=realpathSync6(params.runtimeRoot);const budget=resolveRuntimeClosureNativePlanBudget(params.budget);if(Buffer.byteLength(sourceRoot,"utf8")>budget.maxPathBytes){throw new RuntimeClosureNativePlanUnsupportedError}const root2={path:sourceRoot,...planFence(sourceRoot)};const initialPlanEncodedBytes=Buffer.byteLength(JSON.stringify({version:1,root:root2,records:[]}),"utf8");if(initialPlanEncodedBytes>budget.maxEncodedBytes){throw new RuntimeClosureNativePlanUnsupportedError}const context={sourceRoot,visited:new Set,planRecords:[],planEncodedBytes:initialPlanEncodedBytes,planBudget:budget};for(const seed of params.closureSeeds)hashRelativeRuntimePath(context,seed);return{version:1,root:root2,records:context.planRecords}}function createRuntimeClosureNativePlanForManifest(manifest){const sourceRoot=runtimeSnapshotSourceRoot(manifest);return createRuntimeClosureNativePlan({runtimeRoot:sourceRoot,closureSeeds:runtimeSnapshotSeeds(manifest,sourceRoot)})}function mapRuntimePath(sourceRoot,finalRoot,path5,label){const sourcePath=realpathSync6(path5);const relativePath=ensureContainedPath(sourceRoot,sourcePath,label);return resolve89(finalRoot,relativePath)}function copyBinarySnapshot(params){if(params.snapshot.status!=="present"||!params.snapshot.path)return params.snapshot;const sourcePath=realpathSync6(params.snapshot.path);const extension=process.platform==="win32"?".exe":"";const relativePath=params.layoutVersion===3?join26("runtime","bin",`${params.name}${extension}`):join26("bin",`${params.name}${extension}`);copyFileWithClone(sourcePath,resolve89(params.stagingRoot,relativePath));return{...params.snapshot,path:resolve89(params.finalRoot,relativePath)}}function runtimeSnapshotSourceRoot(manifest){const runtimeRoot=realpathSync6(manifest.runtimeRoot);return manifest.layoutVersion===3?realpathSync6(resolve89(runtimeRoot,"..")):runtimeRoot}function runtimeSnapshotSeeds(manifest,sourceRoot){const layout=detectRuntimeManifestLayout(manifest.runtimeRoot,manifest.serverEntry.path);const seeds=new Set(layout==="managed-release"?manifest.layoutVersion===3?["runtime/server","runtime/core","runtime/node_modules","public-node_modules","platform/src","platform/node_modules"]:["manifest.json","server","core","node_modules"]:["package.json","pnpm-workspace.yaml","packages/server/src","packages/server/package.json","packages/server/node_modules","packages/core/src","packages/core/dist","packages/core/package.json","packages/core/node_modules","packages/client/src","packages/client/dist","packages/client/package.json","packages/client/node_modules","packages/shared/dist","packages/shared/package.json","packages/shared/node_modules","packages/internal/dist","packages/internal/package.json","packages/internal/node_modules","packages/platform/src","packages/platform/package.json","packages/platform/node_modules","packages/cli/server","packages/cli/core"]);for(const lockfile of manifest.packageManager.lockfiles)seeds.add(lockfile.file);for(const snapshot of Object.values(manifest.packages)){if(snapshot.status!=="present"||!snapshot.packageJsonPath)continue;const packagePath=realpathSync6(dirname24(snapshot.packageJsonPath));seeds.add(ensureContainedPath(sourceRoot,packagePath,"runtime package"))}return[...seeds].sort()}function sha256RuntimePaths(sourceRoot,seeds){const canonicalRoot=realpathSync6(sourceRoot);const context={sourceRoot:canonicalRoot,visited:new Set,hash:createHash75("sha256")};for(const seed of seeds)hashRelativeRuntimePath(context,seed);return`sha256:${context.hash.digest("hex")}`}function assertRuntimeClosureMatchesAtRoot(params){const actualClosureSha256=sha256RuntimePaths(params.runtimeRoot,params.closureSeeds);if(actualClosureSha256!==params.expectedClosureSha256){throw new Error(`runtime generation closure hash mismatch: expected ${params.expectedClosureSha256}, got ${actualClosureSha256}`)}}function sha256RuntimeSnapshot(manifest){const sourceRoot=runtimeSnapshotSourceRoot(manifest);return sha256RuntimePaths(sourceRoot,runtimeSnapshotSeeds(manifest,sourceRoot))}function runtimeReleaseId(manifestHash,runtimeClosureSha256){return`sha256:${createHash75("sha256").update(`${manifestHash}\0${runtimeClosureSha256}`).digest("hex")}`}function prepareRuntimeGenerationManifest(manifest){const runtimeClosureSha256=sha256RuntimeSnapshot(manifest);return{...manifest,releaseId:runtimeReleaseId(deploymentRuntimeManifestHash(manifest),runtimeClosureSha256),runtimeClosureSha256}}function runtimeGenerationDirectorySuffix(generationId){if(!RUNTIME_GENERATION_ID_PATTERN.test(generationId)){throw new Error(`invalid runtime generation id: ${generationId}`)}return generationId.replace("sha256:","sha256-")}function formatRuntimeGenerationDirectoryTimestamp(generatedAt){const parsed=new Date(generatedAt);if(Number.isNaN(parsed.getTime())){throw new Error(`invalid runtime generation timestamp: ${generatedAt}`)}return parsed.toISOString().replace(/[-:.]/g,"")}function runtimeGenerationDirectoryName(generationId,generatedAt){return`${formatRuntimeGenerationDirectoryTimestamp(generatedAt)}-${runtimeGenerationDirectorySuffix(generationId)}`}function resolveRuntimeGenerationDirectoryPath(baseDir,generationId){const suffix=runtimeGenerationDirectorySuffix(generationId);const timestampedMatches=[];if(!existsSync34(baseDir))return null;for(const entry of readdirSync12(baseDir,{withFileTypes:true})){if(!entry.isDirectory())continue;if(entry.name.endsWith(`-${suffix}`)&&COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN.test(entry.name)){const timestampSource=entry.name.slice(0,-`-${suffix}`.length);const parsedTimestamp=new Date(timestampSource.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\d{3})Z$/,"$1-$2-$3T$4:$5:$6.$7Z")).getTime();if(!Number.isNaN(parsedTimestamp)){timestampedMatches.push({entryName:entry.name,timestamp:parsedTimestamp})}}}const selected=timestampedMatches.sort((a,b2)=>a.timestamp-b2.timestamp||a.entryName.localeCompare(b2.entryName)).at(-1);if(selected)return resolve89(baseDir,selected.entryName);const legacyGenerationDir=resolve89(baseDir,suffix);return existsSync34(legacyGenerationDir)?legacyGenerationDir:null}function runtimeGenerationDirectoryPath(baseDir,generationId,generatedAt){return resolve89(baseDir,runtimeGenerationDirectoryName(generationId,generatedAt))}function stageRuntimeGeneration(params){const sourceRoot=runtimeSnapshotSourceRoot(params.manifest);if(!params.manifest.releaseId||!params.manifest.runtimeClosureSha256){throw new Error("runtime generation manifest is missing its release content identity")}const finalGenerationDir=runtimeGenerationDirectoryPath(params.baseDir,params.manifest.releaseId,params.manifest.generatedAt);const finalRoot=params.manifest.layoutVersion===3?finalGenerationDir:resolve89(finalGenerationDir,"runtime");mkdirSync6(params.baseDir,{recursive:true,mode:493});const publicationOwner=/^[a-f0-9]{32}$/.test(process.env.GENCOW_RUNTIME_PUBLICATION_OWNER??"")?`-${process.env.GENCOW_RUNTIME_PUBLICATION_OWNER}`:"";const stagedGenerationDir=mkdtempSync5(resolve89(params.baseDir,`.tmp-${params.manifestHash.replace(":","-")}-${process.pid}${publicationOwner}-${randomUUID46()}-`));const stagingRoot=params.manifest.layoutVersion===3?stagedGenerationDir:resolve89(stagedGenerationDir,"runtime");try{const context={sourceRoot,stagingRoot,visited:new Set};const seeds=runtimeSnapshotSeeds(params.manifest,sourceRoot);for(const seed of seeds){copyRelativeRuntimePath(context,seed)}assertRuntimeClosureMatchesAtRoot({runtimeRoot:params.manifest.layoutVersion===3?stagedGenerationDir:stagingRoot,closureSeeds:seeds,expectedClosureSha256:params.manifest.runtimeClosureSha256});const packages=Object.fromEntries(Object.entries(params.manifest.packages).map(([name,snapshot])=>[name,snapshot.status==="present"&&snapshot.packageJsonPath?{...snapshot,packageJsonPath:mapRuntimePath(sourceRoot,finalRoot,snapshot.packageJsonPath,`package ${name}`)}:snapshot]));const binaries=Object.fromEntries(Object.entries(params.manifest.binaries).map(([name,snapshot])=>[name,copyBinarySnapshot({name,snapshot,stagingRoot,finalRoot,layoutVersion:params.manifest.layoutVersion})]));return{stagedGenerationDir,finalGenerationDir,closureSeeds:seeds,publishedManifest:{...params.manifest,runtimeRoot:params.manifest.layoutVersion===3?resolve89(finalGenerationDir,"runtime"):finalRoot,serverEntry:{...params.manifest.serverEntry,path:mapRuntimePath(sourceRoot,finalRoot,params.manifest.serverEntry.path,"server entry")},packages,binaries}}}catch(error62){discardStagedRuntimeGeneration(stagedGenerationDir);throw error62}}function makePathWritable(path5){if(!existsSync34(path5))return;const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){chmodSync(path5,493);for(const entry of readdirSync12(path5))makePathWritable(resolve89(path5,entry))}else if(pathStat.isFile()){chmodSync(path5,pathStat.mode|384)}}function discardStagedRuntimeGeneration(stagedGenerationDir){if(!existsSync34(stagedGenerationDir))return;makePathWritable(stagedGenerationDir);rmSync7(stagedGenerationDir,{recursive:true,force:true})}function commitStagedRuntimeGeneration(stagedGenerationDir,finalGenerationDir){try{renameSync(stagedGenerationDir,finalGenerationDir);return"published"}catch(error62){if(existsSync34(finalGenerationDir)){discardStagedRuntimeGeneration(stagedGenerationDir);return"existing"}discardStagedRuntimeGeneration(stagedGenerationDir);throw error62}}function sealPathReadOnly(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){for(const entry of readdirSync12(path5))sealPathReadOnly(resolve89(path5,entry));chmodSync(path5,365);return}if(pathStat.isFile())chmodSync(path5,canonicalSealedRuntimeFileMode(pathStat.mode))}function sealStagedRuntimeGeneration(stagedGenerationDir){if(existsSync34(resolve89(stagedGenerationDir,"runtime"))){sealPathReadOnly(resolve89(stagedGenerationDir,"runtime"))}if(existsSync34(resolve89(stagedGenerationDir,"public-node_modules"))){sealPathReadOnly(resolve89(stagedGenerationDir,"public-node_modules"))}if(existsSync34(resolve89(stagedGenerationDir,"platform"))){sealPathReadOnly(resolve89(stagedGenerationDir,"platform"))}if(existsSync34(resolve89(stagedGenerationDir,"scripts"))){sealPathReadOnly(resolve89(stagedGenerationDir,"scripts"))}chmodSync(resolve89(stagedGenerationDir,"runtime-manifest.json"),292);chmodSync(stagedGenerationDir,365)}function assertPathReadOnly(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;const mode=pathStat.mode&511;if(pathStat.isDirectory()){if(mode!==365){throw new Error("runtime generation permission invalid")}for(const entry of readdirSync12(path5))assertPathReadOnly(resolve89(path5,entry));return}if(pathStat.isFile()&&mode!==292&&mode!==365){throw new Error("runtime generation permission invalid")}if(!pathStat.isFile()){throw new Error("runtime generation permission invalid")}}function assertRuntimeGenerationSealed(generationDir){assertPathReadOnly(generationDir);if((lstatSync7(resolve89(generationDir,"runtime-manifest.json")).mode&511)!==292){throw new Error("runtime generation permission invalid")}}function fsyncPathTree(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){for(const entry of readdirSync12(path5))fsyncPathTree(resolve89(path5,entry))}const fd=openSync(path5,"r");try{fsyncSync(fd)}finally{closeSync(fd)}}function fsyncStagedRuntimeGeneration(stagedGenerationDir){fsyncPathTree(stagedGenerationDir)}var EXCLUDED_DIRECTORY_NAMES,TEST_FILE_PATTERN,SECRET_FILE_PATTERN,RUNTIME_GENERATION_ID_PATTERN,COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN,RuntimeClosureNativePlanUnsupportedError,NATIVE_PLAN_MAX_RECORDS,NATIVE_PLAN_MAX_BYTES,NATIVE_PLAN_MAX_PATH_BYTES;var init_runtime_generation_publisher=__esm({"../platform/src/runtime-generation-publisher.ts"(){"use strict";init_deployment_runtime_manifest();EXCLUDED_DIRECTORY_NAMES=new Set([".git",".gencow","__tests__"]);TEST_FILE_PATTERN=/\.(?:test|spec)\.[cm]?[jt]sx?$/;SECRET_FILE_PATTERN=/^(?:\.npmrc|\.yarnrc|\.netrc|\.pypirc|id_rsa|id_ed25519)$|(?:private|secret|credential).*\.(?:key|pem|p12|pfx)$|\.(?:key|p12|pfx)$/i;RUNTIME_GENERATION_ID_PATTERN=/^sha256:[a-f0-9]{64}$/;COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN=/^\d{8}T\d{9}Z-sha256-[a-f0-9]{64}$/;RuntimeClosureNativePlanUnsupportedError=class extends Error{constructor(){super("runtime native closure backend unsupported");this.name="RuntimeClosureNativePlanUnsupportedError"}};NATIVE_PLAN_MAX_RECORDS=1e5;NATIVE_PLAN_MAX_BYTES=32*1024*1024;NATIVE_PLAN_MAX_PATH_BYTES=4096}});import{existsSync as existsSync35,statfsSync}from"fs";import{dirname as dirname25}from"path";function requiredRuntimeGenerationFreeBytes(probe={}){const watermark=probe.watermarkBytes??RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES;const closure=probe.expectedClosureBytes??RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES;const withHeadroom=Math.ceil(closure*RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR/RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR);return Math.max(watermark,withHeadroom)}function defaultAvailableBytes(path5){let candidate=path5;while(!existsSync35(candidate)){const parent=dirname25(candidate);if(parent===candidate)return null;candidate=parent}try{const stat13=statfsSync(candidate);return Number(stat13.bavail)*Number(stat13.bsize)}catch{return null}}function formatGiB(bytes2,rounding){const hundredths=bytes2/GIB*100;const rounded=rounding==="floor"?Math.floor(hundredths):Math.ceil(hundredths);return(rounded/100).toFixed(2)}function assertRuntimeGenerationCapacityPreflight(baseDir,probe={}){const available=(probe.availableBytes??defaultAvailableBytes)(baseDir);if(available===null||!Number.isFinite(available))return;const required3=requiredRuntimeGenerationFreeBytes(probe);if(available<required3){throw new RuntimeGenerationCapacityPreflightError(available,required3)}}var GIB,RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES,RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES,RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR,RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR,RuntimeGenerationCapacityPreflightError;var init_runtime_generation_capacity=__esm({"../platform/src/runtime-generation-capacity.ts"(){"use strict";GIB=1024*1024*1024;RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES=10*GIB;RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES=2*GIB;RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR=3;RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR=2;RuntimeGenerationCapacityPreflightError=class extends Error{constructor(availableBytes,requiredBytes){const shortfall=formatGiB(requiredBytes-availableBytes,"ceil");super(`runtime generation capacity preflight failed: available ${formatGiB(availableBytes,"floor")} GiB, required ${formatGiB(requiredBytes,"ceil")} GiB. Free at least ${shortfall} GiB on the filesystem that holds the runtime generation store on this node or worker, then retry the same operation. No runtime generation or serving state was changed.`);this.availableBytes=availableBytes;this.requiredBytes=requiredBytes;this.name="RuntimeGenerationCapacityPreflightError"}availableBytes;requiredBytes;reasonCode="runtime_generation_capacity_preflight_failed"}}});import{spawnSync as spawnSync2}from"node:child_process";import{createHash as createHash76}from"node:crypto";import{lstatSync as lstatSync8,readFileSync as readFileSync32}from"node:fs";function tagRuntimeNativeClosureBackendStage(error62,stage){if((typeof error62!=="object"||error62===null)&&typeof error62!=="function")return error62;try{Object.defineProperty(error62,"runtimeNativeClosureBackendStage",{configurable:true,value:stage})}catch{}return error62}function nativeFailure(message,code,runtimeNativeClosureBackendStage="none"){const error62=new Error(message);if(code)error62.code=code;return tagRuntimeNativeClosureBackendStage(error62,runtimeNativeClosureBackendStage)}function isTrustedNativeBinary(dependencies){let stat13;try{stat13=dependencies.lstat(RUNTIME_NATIVE_CLOSURE_BINARY)}catch(error62){const code=error62&&typeof error62==="object"&&"code"in error62?String(error62.code):"";if(code==="ENOENT")return false;if(code==="EACCES"||code==="EPERM"){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_PERMISSION_INVALID","binary_identity")}throw nativeFailure("runtime generation verification failed","RUNTIME_NATIVE_CLOSURE_BINARY_UNREADABLE","binary_identity")}if(!stat13.isFile()||stat13.isSymbolicLink()||stat13.uid!==0||stat13.gid!==0||(stat13.mode&511)!==365){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_PERMISSION_INVALID","binary_identity")}let fingerprintStat;try{fingerprintStat=dependencies.lstat(RUNTIME_NATIVE_CLOSURE_FINGERPRINT)}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_UNREADABLE","binary_identity")}if(!fingerprintStat.isFile()||fingerprintStat.isSymbolicLink()||fingerprintStat.uid!==0||fingerprintStat.gid!==0||(fingerprintStat.mode&511)!==320){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_PERMISSION_INVALID","binary_identity")}let expected;try{expected=dependencies.readFile(RUNTIME_NATIVE_CLOSURE_FINGERPRINT,"utf8").trim()}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_UNREADABLE","binary_identity")}if(!SHA25615.test(expected)){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_INVALID","binary_identity")}let actual;try{actual=createHash76("sha256").update(dependencies.readFile(RUNTIME_NATIVE_CLOSURE_BINARY)).digest("hex")}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_UNREADABLE","binary_identity")}if(actual!==expected){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_MISMATCH","binary_identity")}return true}function execute(dependencies,args,input2){return dependencies.spawn(TIMEOUT_BINARY,["--signal=TERM","--kill-after=250ms",NATIVE_TIMEOUT_SECONDS,RUNTIME_NATIVE_CLOSURE_BINARY,...args],{input:input2,encoding:"utf8",timeout:HOST_TIMEOUT_MS,maxBuffer:NATIVE_MAX_BUFFER_BYTES})}function assertCapability(dependencies){const result3=execute(dependencies,["--capability"]);if(result3.error?.code==="ETIMEDOUT"||result3.status===124||result3.status===137){throw nativeFailure("runtime generation native verifier timeout","ETIMEDOUT","capability")}if(result3.status===77)throw nativeFailure("runtime generation permission invalid",void 0,"capability");if(result3.status===69&&result3.stdout===""&&result3.stderr===""){return false}if(result3.status===70||result3.status===78)throw nativeFailure("runtime generation verification failed",void 0,"capability");if(result3.error||result3.signal||result3.status!==0)throw nativeFailure("runtime generation verification failed",void 0,"capability");if(result3.stdout!==`${RUNTIME_NATIVE_CLOSURE_CAPABILITY}
|
|
10155
10155
|
`||result3.stderr){throw nativeFailure("runtime generation verification failed",void 0,"capability")}return true}function encodePlan(plan2,budget){if(plan2.records.length>budget.maxRecords)throw new RuntimeClosureNativePlanUnsupportedError;const encoded=JSON.stringify(plan2);if(Buffer.byteLength(encoded,"utf8")>budget.maxEncodedBytes){throw new RuntimeClosureNativePlanUnsupportedError}return encoded}function plannedFileBytes(plan2){const total=plan2.records.filter(entry=>entry.kind==="F").reduce((sum,entry)=>sum+BigInt(entry.fence.size),0n);if(total>BigInt(Number.MAX_SAFE_INTEGER))throw new RuntimeClosureNativePlanUnsupportedError;return Number(total)}function parseNativeOutput(result3,plan2,expectedByteCount){if(result3.error?.code==="ETIMEDOUT"||result3.status===124||result3.status===137){throw nativeFailure("runtime generation native verifier timeout","ETIMEDOUT","execute")}if(result3.status===77)throw nativeFailure("runtime generation permission invalid",void 0,"execute");if(result3.status===78)throw nativeFailure("runtime generation closure hash mismatch",void 0,"execute");if(result3.status!==0)throw nativeFailure("runtime generation verification failed",void 0,"output");if(result3.error||result3.signal||result3.stderr)throw nativeFailure("runtime generation verification failed",void 0,result3.stderr?"output":"execute");let output2;try{output2=JSON.parse(result3.stdout)}catch{throw nativeFailure("runtime generation verification failed",void 0,"output")}if(!output2||typeof output2!=="object"||Array.isArray(output2)){throw nativeFailure("runtime generation verification failed",void 0,"output")}const record3=output2;if(Object.keys(record3).sort().join("\0")!=="byteCount\0digest\0recordCount\0version"||record3.version!==1||typeof record3.digest!=="string"||!DIGEST.test(record3.digest)||record3.recordCount!==plan2.records.length||typeof record3.byteCount!=="number"||!Number.isSafeInteger(record3.byteCount)||record3.byteCount<0||record3.byteCount!==expectedByteCount){throw nativeFailure("runtime generation verification failed",void 0,"output")}return record3}function configured(dependencies){return dependencies.env.GENCOW_PROD_SIM_RUNTIME_NATIVE_CLOSURE_BACKEND==="cowbox-v1"}function selectTrustedRuntimeNativeClosureBackend(partial3={}){const{planBudget,...partialDependencies}=partial3;const budget={maxRecords:planBudget?.maxRecords??MAX_PLAN_RECORDS,maxEncodedBytes:planBudget?.maxEncodedBytes??MAX_PLAN_BYTES};if(!Number.isSafeInteger(budget.maxRecords)||budget.maxRecords<0||budget.maxRecords>MAX_PLAN_RECORDS||!Number.isSafeInteger(budget.maxEncodedBytes)||budget.maxEncodedBytes<1||budget.maxEncodedBytes>MAX_PLAN_BYTES){throw new Error("runtime native closure plan budget invalid")}const dependencies={platform:process.platform,env:process.env,lstat:lstatSync8,readFile:readFileSync32,spawn:spawnSync2,...partialDependencies};if(!configured(dependencies)||dependencies.platform!=="linux")return null;if(!isTrustedNativeBinary(dependencies)||!assertCapability(dependencies))return null;return{capability:RUNTIME_NATIVE_CLOSURE_CAPABILITY,verify(manifest){let plan2;let encoded;let expectedByteCount;try{plan2=createRuntimeClosureNativePlanForManifest(manifest);encoded=encodePlan(plan2,budget);expectedByteCount=plannedFileBytes(plan2)}catch(error62){if(error62 instanceof RuntimeClosureNativePlanUnsupportedError)return{kind:"unsupported"};throw tagRuntimeNativeClosureBackendStage(error62,"plan")}return{kind:"verified",output:parseNativeOutput(execute(dependencies,[],encoded),plan2,expectedByteCount)}}}}var RUNTIME_NATIVE_CLOSURE_CAPABILITY,RUNTIME_NATIVE_CLOSURE_BINARY,RUNTIME_NATIVE_CLOSURE_FINGERPRINT,TIMEOUT_BINARY,NATIVE_TIMEOUT_SECONDS,HOST_TIMEOUT_MS,NATIVE_MAX_BUFFER_BYTES,MAX_PLAN_BYTES,MAX_PLAN_RECORDS,SHA25615,DIGEST;var init_runtime_native_closure_backend=__esm({"../platform/src/runtime-native-closure-backend.ts"(){"use strict";init_runtime_generation_publisher();RUNTIME_NATIVE_CLOSURE_CAPABILITY="gencow_runtime_closure_plan_v1";RUNTIME_NATIVE_CLOSURE_BINARY="/usr/local/bin/runtime-closure-plan-v1";RUNTIME_NATIVE_CLOSURE_FINGERPRINT="/opt/gencow/prod-sim-runtime-integrity/runtime-closure-plan-v1.sha256";TIMEOUT_BINARY="/usr/bin/timeout";NATIVE_TIMEOUT_SECONDS="3s";HOST_TIMEOUT_MS=3e3;NATIVE_MAX_BUFFER_BYTES=4096;MAX_PLAN_BYTES=32*1024*1024;MAX_PLAN_RECORDS=1e5;SHA25615=/^[a-f0-9]{64}$/u;DIGEST=/^sha256:[a-f0-9]{64}$/u}});function readNow(clock){try{const value2=clock();return Number.isFinite(value2)&&value2>=0?value2:null}catch{return null}}function createRuntimeGenerationVerificationContext(observer,options={}){if(!observer)return void 0;const clock=options.now??(()=>performance.now());const origin=readNow(clock);if(origin===null)return void 0;return{observe(phase,work,reason=()=>"runtime_generation_verification_failed"){const startedAt=readNow(clock);if(startedAt!==null&&startedAt>=origin){try{observer.observe({phase,outcome:"started",elapsedMs:startedAt-origin})}catch{}}try{const result3=work();const endedAt=readNow(clock);if(startedAt!==null&&endedAt!==null&&endedAt>=startedAt&&endedAt>=origin){try{observer.observe({phase,outcome:"completed",elapsedMs:endedAt-origin,durationMs:endedAt-startedAt})}catch{}}return result3}catch(error62){const endedAt=readNow(clock);if(startedAt!==null&&endedAt!==null&&endedAt>=startedAt&&endedAt>=origin){try{observer.observe({phase,outcome:"failed",elapsedMs:endedAt-origin,durationMs:endedAt-startedAt,reasonCode:reason(error62)})}catch{}}throw error62}}}}var init_runtime_generation_verification_observer=__esm({"../platform/src/runtime-generation-verification-observer.ts"(){"use strict"}});import{createHash as createHash77}from"crypto";import{closeSync as closeSync2,existsSync as existsSync36,fsyncSync as fsyncSync2,openSync as openSync2,readFileSync as readFileSync33,writeFileSync as writeFileSync5}from"fs";import{resolve as resolve90}from"path";function runtimeGenerationFailureReason(error62){if(error62 instanceof RuntimeGenerationPublishError)return error62.reasonCode;if(error62 instanceof RuntimeGenerationCapacityPreflightError)return error62.reasonCode;const errno=error62&&typeof error62==="object"&&"code"in error62?String(error62.code):"";if(errno==="ENOSPC"||errno==="EDQUOT")return"runtime_generation_capacity_exhausted";if(errno==="ETIMEDOUT"||errno==="ETIME")return"runtime_generation_timeout";const message=error62 instanceof Error?error62.message:String(error62);if(message.includes("runtime generation incomplete"))return"runtime_generation_incomplete";if(message.includes("closure hash mismatch"))return"runtime_closure_mismatch";if(message.includes("permission")||message.includes("EACCES")||message.includes("EPERM")){return"runtime_generation_permission_invalid"}if(message.includes("manifest")||message.includes("identity")||message.includes("catalog")||message.includes("invalid runtime generation id")){return"runtime_manifest_invalid"}if(message.includes("hash mismatch")||message.includes("content hash mismatch")){return"runtime_artifact_hash_mismatch"}if(message.includes("missing"))return"runtime_generation_missing";return"runtime_generation_verification_failed"}function asRuntimeGenerationPublicationError(error62,stage){return runtimeGenerationFailureReason(error62)==="runtime_generation_verification_failed"?new RuntimeGenerationPublishError(stage):error62}function isRuntimeGenerationFullyVerifiedInCurrentProcess(value2){return typeof value2==="object"&&value2!==null&&fullyVerifiedRuntimeReferences.has(value2)}function markRuntimeGenerationFullyVerified(reference){fullyVerifiedRuntimeReferences.add(reference);return reference}function observeRuntimeClosureVerification(observer,stats){if(!observer)return;try{observer.observe(stats)}catch{}}function observed(observer,phase,work){return observer?observer.observe(phase,work,runtimeGenerationFailureReason):work()}function assertRuntimeClosureMatches(manifest,expectedRoot,releaseId,forceVerification=false,observer,closureVerificationBackend,closureVerificationObserver){if(!manifest.runtimeClosureSha256){throw new Error(`runtime generation closure identity missing: ${releaseId}`)}const verificationRoot=manifest.layoutVersion===3?resolve90(expectedRoot,".."):expectedRoot;const closureCacheKey=`${verificationRoot}\0${manifest.runtimeClosureSha256}`;if(!forceVerification&&verifiedRuntimeClosures.has(closureCacheKey))return;if(forceVerification)verifiedRuntimeClosures.delete(closureCacheKey);observed(observer,"generation_seal_traversal",()=>assertRuntimeGenerationSealed(resolve90(expectedRoot,"..")));observed(observer,"runtime_closure_hash",()=>{const nativeResult=closureVerificationBackend==="trusted-native-if-supported"?selectTrustedRuntimeNativeClosureBackend()?.verify(manifest):void 0;const actualClosureSha256=nativeResult?.kind==="verified"?nativeResult.output.digest:sha256RuntimeSnapshot(manifest);if(actualClosureSha256!==manifest.runtimeClosureSha256){verifiedRuntimeClosures.delete(closureCacheKey);const mismatch=new Error(`runtime generation closure hash mismatch: ${releaseId} expected ${manifest.runtimeClosureSha256}, got ${actualClosureSha256}`);throw nativeResult?.kind==="verified"?tagRuntimeNativeClosureBackendStage(mismatch,"digest_compare"):mismatch}const stats=Object.freeze(nativeResult?.kind==="verified"?{backend:"gencow_runtime_closure_plan_v1",recordCount:nativeResult.output.recordCount,byteCount:nativeResult.output.byteCount}:{backend:"typescript",recordCount:null,byteCount:null});observeRuntimeClosureVerification(closureVerificationObserver,stats)});verifiedRuntimeClosures.add(closureCacheKey)}function getRuntimeGenerationsDir(env=process.env){if(env.GENCOW_RUNTIME_GENERATIONS_DIR)return env.GENCOW_RUNTIME_GENERATIONS_DIR;if(env.IS_PLATFORM==="true"||env.NODE_ENV==="production")return DEFAULT_GENERATIONS_DIR;return resolve90(process.cwd(),".gencow-runtime","runtime-generations")}function generationManifestPath(generationId,baseDir=getRuntimeGenerationsDir()){const generationDir=resolveRuntimeGenerationDirectoryPath(baseDir,generationId)||resolve90(baseDir,generationId);return resolve90(generationDir,"runtime-manifest.json")}function readPublishedRuntimeManifest(releaseId,baseDir){try{return parseDeploymentRuntimeManifest(readFileSync33(generationManifestPath(releaseId,baseDir),"utf-8"))}catch(error62){const code=error62.code;if(code==="EACCES"||code==="EPERM"){throw new Error(`runtime generation permission invalid: ${releaseId}`)}if(code==="ENOENT"){throw new Error(`runtime generation missing: ${releaseId}`)}throw new Error(`runtime generation manifest invalid: ${releaseId}`)}}function normalizeRuntimeManifestHash(manifestHash){if(/^sha256:[a-f0-9]{64}$/.test(manifestHash)){return manifestHash}if(/^[a-f0-9]{64}$/.test(manifestHash)){return`sha256:${manifestHash}`}throw new Error(`invalid runtime manifest hash: ${manifestHash}`)}function ensureSafeManifestHash(manifestHash){normalizeRuntimeManifestHash(manifestHash)}function hasRuntimeContentIdentity(manifest){return Boolean(manifest.releaseId&&manifest.runtimeClosureSha256)}function assertLegacyIdentityFieldsAreAbsent(manifest,releaseId,manifestHash){if(manifest.releaseId||manifest.runtimeClosureSha256){throw new Error(`runtime generation release identity mismatch: ${releaseId}`)}if(releaseId!==manifestHash){throw new Error(`runtime generation content identity mismatch: ${releaseId}`)}}function sha256File2(path5){return`sha256:${createHash77("sha256").update(readFileSync33(path5)).digest("hex")}`}function assertFileHashMatches(path5,expectedSha256,label,manifestHash){if(!existsSync36(path5)){throw new Error(`runtime generation ${label} missing: ${manifestHash}`)}const actualSha256=sha256File2(path5);if(actualSha256!==expectedSha256){throw new Error(`runtime generation ${label} hash mismatch: ${manifestHash} expected ${expectedSha256}, got ${actualSha256}`)}}function assertRuntimeArtifactsMatchManifest(manifest,manifestHash,verifyContent,observer){observed(observer,"scalar_artifact_verification",()=>assertFileHashMatches(manifest.serverEntry.path,manifest.serverEntry.sha256,"server entry",manifestHash));for(const lockfile of manifest.packageManager.lockfiles){observed(observer,"scalar_artifact_verification",()=>assertFileHashMatches(resolve90(manifest.runtimeRoot,lockfile.file),lockfile.sha256,lockfile.file,manifestHash))}for(const[packageName,snapshot]of Object.entries(manifest.packages)){if(snapshot.status!=="present"||!snapshot.packageJsonPath)continue;observed(observer,"scalar_artifact_verification",()=>{const parsed=JSON.parse(readFileSync33(snapshot.packageJsonPath,"utf-8"));const actualVersion=typeof parsed.version==="string"?parsed.version:"";if(actualVersion!==snapshot.version){throw new Error(`runtime generation package ${packageName} version mismatch: ${manifestHash} expected ${snapshot.version}, got ${actualVersion}`)}});if(verifyContent&&snapshot.treeSha256){observed(observer,"package_tree_hashes",()=>{if(sha256RuntimeTree(resolve90(snapshot.packageJsonPath,".."))!==snapshot.treeSha256){throw new Error(`runtime generation package ${packageName} content hash mismatch: ${manifestHash}`)}})}}for(const[binaryName,snapshot]of Object.entries(manifest.binaries)){if(snapshot.status!=="present"||!snapshot.path||!snapshot.sha256)continue;observed(observer,"scalar_artifact_verification",()=>assertFileHashMatches(snapshot.path,snapshot.sha256,`binary ${binaryName}`,manifestHash))}if(!verifyContent)return;const layout=detectRuntimeManifestLayout(manifest.runtimeRoot,manifest.serverEntry.path);const artifactPaths=runtimeArtifactPathsForLayout(layout);observed(observer,"managed_artifact_hashes",()=>{const managedArtifactHashes=layout==="managed-release"?hashManagedRuntimeArtifacts(manifest.runtimeRoot):null;for(const[artifactName,expectedSha256]of Object.entries(manifest.runtimeArtifacts??{})){const actualSha256=artifactName==="publicNodeModules"?sha256RuntimeTree(resolve90(manifest.runtimeRoot,"..","public-node_modules")):managedArtifactHashes&&artifactName in managedArtifactHashes?managedArtifactHashes[artifactName]:artifactPaths[artifactName]?sha256RuntimeTree(resolve90(manifest.runtimeRoot,artifactPaths[artifactName])):"";if(actualSha256!==expectedSha256){throw new Error(`runtime generation artifact ${artifactName} hash mismatch: ${manifestHash} expected ${expectedSha256}, got ${actualSha256}`)}}})}function assertManagedRuntimePackageContract(manifest,manifestHash){if(detectRuntimeManifestLayout(manifest.runtimeRoot,manifest.serverEntry.path)!=="managed-release"){return}for(const packageName of manifest.requiredPackages??[]){const parts=packageName.split("/");const validName=packageName.startsWith("@")?parts.length===2&&/^@[a-z0-9][a-z0-9._-]*$/.test(parts[0])&&/^[a-z0-9][a-z0-9._-]*$/.test(parts[1]):parts.length===1&&/^[a-z0-9][a-z0-9._-]*$/.test(parts[0]);if(!validName){throw new Error(`runtime generation manifest invalid: required package name: ${manifestHash}`)}const packageJsonPath=resolve90(manifest.runtimeRoot,"node_modules",...packageName.split("/"),"package.json");if(!existsSync36(packageJsonPath)){throw new Error(`runtime generation incomplete: required package ${packageName} missing: ${manifestHash}`)}let parsed;try{parsed=JSON.parse(readFileSync33(packageJsonPath,"utf-8"))}catch{throw new Error(`runtime generation incomplete: required package ${packageName} catalog invalid: ${manifestHash}`)}const version3=typeof parsed.version==="string"?parsed.version:"";if(!version3||manifest.releaseOwnedPackages?.[packageName]!==version3){throw new Error(`runtime generation incomplete: required package ${packageName} catalog mismatch: ${manifestHash}`)}}if(manifest.layoutVersion===3){const publicPackages=manifest.managedDependencyContract?.publicPackages??[];const publicNodeModulesRoot=resolve90(manifest.runtimeRoot,"..","public-node_modules");if(!manifest.managedDependencyContract||publicPackages.length===0){throw new Error(`runtime generation incomplete: managed dependency contract missing: ${manifestHash}`)}if(!existsSync36(publicNodeModulesRoot)){throw new Error(`runtime generation incomplete: public node_modules missing: ${manifestHash}`)}for(const packageName of publicPackages){const releasePackageJsonPath=resolve90(manifest.runtimeRoot,"node_modules",...packageName.split("/"),"package.json");const publicPackageJsonPath=resolve90(publicNodeModulesRoot,...packageName.split("/"),"package.json");if(!existsSync36(releasePackageJsonPath)||!existsSync36(publicPackageJsonPath)){throw new Error(`runtime generation incomplete: public package ${packageName} missing: ${manifestHash}`)}}}}function assertGenerationUsable(manifest,manifestHash,verification2="full",observer){const calculated=deploymentRuntimeManifestHash(manifest);if(calculated!==manifestHash){throw new Error(`runtime generation hash mismatch: expected ${manifestHash}, got ${calculated}`)}if(!existsSync36(manifest.runtimeRoot))throw new Error(`runtime generation root missing: ${manifestHash}`);if(!existsSync36(manifest.serverEntry.path)){throw new Error(`runtime generation server entry missing: ${manifestHash}`)}if(verification2==="full"){assertRuntimeArtifactsMatchManifest(manifest,manifestHash,true,observer);observed(observer,"managed_package_contract",()=>assertManagedRuntimePackageContract(manifest,manifestHash))}const executionSource={kind:"verified-generation",layout:detectRuntimeManifestLayout(manifest.runtimeRoot,manifest.serverEntry.path),layoutVersion:manifest.layoutVersion??1,manifestHash,releaseId:manifest.releaseId||manifestHash,generationRoot:resolve90(manifest.runtimeRoot,".."),runtimeRoot:manifest.runtimeRoot,serverEntry:manifest.serverEntry.path,generationNodeModules:resolve90(manifest.runtimeRoot,"node_modules"),publicNodeModules:manifest.layoutVersion===3?resolve90(manifest.runtimeRoot,"..","public-node_modules"):void 0,runtimeContractPath:resolve90(manifest.runtimeRoot,"..","runtime-manifest.json"),managedDependencyContract:manifest.managedDependencyContract,bunBinary:manifest.binaries.bun?.status==="present"?manifest.binaries.bun.path:void 0,cowboxBinary:manifest.binaries.cowbox?.status==="present"?manifest.binaries.cowbox.path:void 0};return{...executionSource,source:"deployment-manifest"}}function loadPublishedRuntimeGeneration(releaseId,manifestHash,baseDir,runtimeChannel,forceClosureVerification=false){const generationDir=resolveRuntimeGenerationDirectoryPath(baseDir,releaseId);if(!generationDir)return null;const manifestPath=resolve90(generationDir,"runtime-manifest.json");if(!existsSync36(manifestPath))return null;const manifest=readPublishedRuntimeManifest(releaseId,baseDir);assertDeploymentRuntimeManifestSecretFree(manifest);const expectedRoot=resolve90(generationDir,"runtime");if(hasRuntimeContentIdentity(manifest)){if(manifest.releaseId!==releaseId){throw new Error(`runtime generation release identity mismatch: ${releaseId}`)}const expectedReleaseId=runtimeReleaseId(manifestHash,manifest.runtimeClosureSha256);if(expectedReleaseId!==releaseId){throw new Error(`runtime generation content identity mismatch: ${releaseId}`)}}else{assertLegacyIdentityFieldsAreAbsent(manifest,releaseId,manifestHash)}if(resolve90(manifest.runtimeRoot)!==expectedRoot){throw new Error(`runtime generation catalog is not immutable: ${releaseId}`)}assertGenerationUsable(manifest,manifestHash);if(manifest.runtimeClosureSha256){assertRuntimeClosureMatches(manifest,expectedRoot,releaseId,forceClosureVerification)}return buildDeploymentRuntimeRecord(manifest,runtimeChannel)}function writeStagedManifest(path5,manifest){writeFileSync5(path5,`${JSON.stringify(manifest,null,2)}
|
|
10156
10156
|
`,{mode:420});const fd=openSync2(path5,"r");try{fsyncSync2(fd)}finally{closeSync2(fd)}}function fsyncDirectory(path5){const fd=openSync2(path5,"r");try{fsyncSync2(fd)}finally{closeSync2(fd)}}function persistRuntimeGeneration(record3,baseDir=getRuntimeGenerationsDir(),overrides={}){ensureSafeManifestHash(record3.runtimeManifestHash);const sourceManifest=parseDeploymentRuntimeManifest(record3.runtimeManifestJson);assertGenerationUsable(sourceManifest,record3.runtimeManifestHash);const publishableManifest=prepareRuntimeGenerationManifest(sourceManifest);const releaseId=publishableManifest.releaseId;const published=loadPublishedRuntimeGeneration(releaseId,record3.runtimeManifestHash,baseDir,record3.runtimeChannel,true);if(published)return published;assertRuntimeGenerationCapacityPreflight(baseDir,overrides.capacity);const operations={sealStaged:sealStagedRuntimeGeneration,assertSealed:assertRuntimeGenerationSealed,assertClosure:assertRuntimeClosureMatchesAtRoot,fsyncStaged:fsyncStagedRuntimeGeneration,commitStaged:commitStagedRuntimeGeneration,...overrides};let staged;let publicationStage="staging";try{staged=stageRuntimeGeneration({manifest:publishableManifest,manifestHash:record3.runtimeManifestHash,baseDir});publicationStage="manifest_write";writeStagedManifest(resolve90(staged.stagedGenerationDir,"runtime-manifest.json"),staged.publishedManifest);publicationStage="seal";operations.sealStaged(staged.stagedGenerationDir);publicationStage="sealed_permission_verification";operations.assertSealed(staged.stagedGenerationDir);publicationStage="sealed_closure_verification";operations.assertClosure({runtimeRoot:publishableManifest.layoutVersion===3?staged.stagedGenerationDir:resolve90(staged.stagedGenerationDir,"runtime"),closureSeeds:staged.closureSeeds,expectedClosureSha256:publishableManifest.runtimeClosureSha256});publicationStage="fsync";operations.fsyncStaged(staged.stagedGenerationDir);publicationStage="rename";operations.commitStaged(staged.stagedGenerationDir,staged.finalGenerationDir);publicationStage="parent_fsync";fsyncDirectory(baseDir);publicationStage="final_verification";const committed=loadPublishedRuntimeGeneration(releaseId,record3.runtimeManifestHash,baseDir,record3.runtimeChannel,true);if(!committed)throw new Error(`runtime generation publication failed: ${record3.runtimeManifestHash}`);return committed}catch(error62){if(staged)discardStagedRuntimeGeneration(staged.stagedGenerationDir);throw asRuntimeGenerationPublicationError(error62,publicationStage)}}function resolveRuntimeGenerationRef(params){if(!params.deploymentManifestJson||!params.deploymentManifestHash)return null;const deploymentManifestHash=normalizeRuntimeManifestHash(params.deploymentManifestHash);const deploymentManifest=parseDeploymentRuntimeManifest(params.deploymentManifestJson);assertDeploymentRuntimeManifestSecretFree(deploymentManifest);const deploymentManifestReference=resolveDeploymentRuntimeManifestHashReference(deploymentManifest,deploymentManifestHash);const releaseManifestHash=deploymentManifestReference.usesLegacyReference?deploymentManifestReference.referenceHash:deploymentManifestReference.manifestHash;const releaseId=normalizeRuntimeManifestHash(deploymentManifest.releaseId||deploymentManifestReference.referenceHash);const baseDir=params.baseDir||getRuntimeGenerationsDir();const generationDir=resolveRuntimeGenerationDirectoryPath(baseDir,releaseId);if(!generationDir){throw new Error(`runtime generation missing: ${releaseId}`)}const catalogManifest=readPublishedRuntimeManifest(releaseId,baseDir);assertDeploymentRuntimeManifestSecretFree(catalogManifest);const expectedRoot=resolve90(generationDir,"runtime");if(hasRuntimeContentIdentity(catalogManifest)){if(catalogManifest.releaseId!==releaseId){throw new Error(`runtime generation release identity mismatch: ${releaseId}`)}}else{assertLegacyIdentityFieldsAreAbsent(catalogManifest,releaseId,deploymentManifestHash)}if(resolve90(catalogManifest.runtimeRoot)!==expectedRoot){throw new Error(`runtime generation catalog is not immutable: ${releaseId}`)}const integrity=params.integrity==="sealed"&&hasRuntimeContentIdentity(catalogManifest)?"sealed":"full";if(catalogManifest.runtimeClosureSha256){const expectedReleaseId=runtimeReleaseId(releaseManifestHash,catalogManifest.runtimeClosureSha256);if(expectedReleaseId!==releaseId){throw new Error(`runtime generation content identity mismatch: ${releaseId}`)}if(integrity==="full"){assertRuntimeClosureMatches(catalogManifest,expectedRoot,releaseId)}}const reference={...assertGenerationUsable(catalogManifest,deploymentManifestReference.manifestHash,integrity),source:"catalog"};return integrity==="full"?markRuntimeGenerationFullyVerified(reference):reference}function resolvePublishedRuntimeGenerationRef(params){const observer=createRuntimeGenerationVerificationContext(params.verificationObserver);const catalog=observed(observer,"catalog_manifest_identity",()=>{const releaseId=normalizeRuntimeManifestHash(params.releaseId);const baseDir=params.baseDir||getRuntimeGenerationsDir();const generationDir=resolveRuntimeGenerationDirectoryPath(baseDir,releaseId);if(!generationDir){throw new Error(`runtime generation missing: ${releaseId}`)}const manifestPath=resolve90(generationDir,"runtime-manifest.json");const catalogManifest=parseDeploymentRuntimeManifest(readFileSync33(manifestPath,"utf-8"));assertDeploymentRuntimeManifestSecretFree(catalogManifest);const expectedRoot=resolve90(generationDir,"runtime");const manifestHash=deploymentRuntimeManifestHash(catalogManifest);if(hasRuntimeContentIdentity(catalogManifest)){if(catalogManifest.releaseId!==releaseId){throw new Error(`runtime generation release identity mismatch: ${releaseId}`)}const expectedReleaseId=runtimeReleaseId(manifestHash,catalogManifest.runtimeClosureSha256);if(expectedReleaseId!==releaseId){throw new Error(`runtime generation content identity mismatch: ${releaseId}`)}}else{assertLegacyIdentityFieldsAreAbsent(catalogManifest,releaseId,manifestHash)}if(resolve90(catalogManifest.runtimeRoot)!==expectedRoot){throw new Error(`runtime generation catalog is not immutable: ${releaseId}`)}return{releaseId,catalogManifest,expectedRoot,manifestHash}});const integrity=params.integrity==="sealed"?"sealed":"full";if(catalog.catalogManifest.runtimeClosureSha256&&integrity==="full"){assertRuntimeClosureMatches(catalog.catalogManifest,catalog.expectedRoot,catalog.releaseId,false,observer,params.closureVerificationBackend,params.closureVerificationObserver)}const reference={...assertGenerationUsable(catalog.catalogManifest,catalog.manifestHash,integrity,observer),source:"catalog"};return integrity==="full"?markRuntimeGenerationFullyVerified(reference):reference}var DEFAULT_GENERATIONS_DIR,RuntimeGenerationPublishError,verifiedRuntimeClosures,fullyVerifiedRuntimeReferences;var init_runtime_generation_store=__esm({"../platform/src/runtime-generation-store.ts"(){"use strict";init_deployment_runtime_manifest();init_runtime_generation_publisher();init_runtime_generation_capacity();init_runtime_native_closure_backend();init_runtime_generation_verification_observer();DEFAULT_GENERATIONS_DIR="/opt/gencow/shared/runtime-generations";RuntimeGenerationPublishError=class extends Error{reasonCode="runtime_generation_publish_io_failed";constructor(stage){super(`runtime generation publication I/O failed at ${stage}`);this.name="RuntimeGenerationPublishError"}};verifiedRuntimeClosures=new Set;fullyVerifiedRuntimeReferences=new WeakSet}});import{existsSync as existsSync37}from"fs";import{resolve as resolve91}from"path";function isPublishedRuntimeRootUsable(path5){return existsSync37(resolve91(path5,"..","runtime-manifest.json"))&&existsSync37(resolve91(path5,"server","index.js"))&&existsSync37(resolve91(path5,"core","index.js"))&&existsSync37(resolve91(path5,"node_modules"))}function getAppRuntimeMetadataPath(dataDir){return resolve91(dataDir,APP_RUNTIME_METADATA_RELATIVE_PATH)}function getAppOwnedDepsDir(dataDir){return resolve91(dataDir,APP_OWNED_DEPS_DIRNAME)}function getAppOwnedDepsPackageJsonPath(dataDir){return resolve91(getAppOwnedDepsDir(dataDir),"package.json")}function getAppOwnedNodeModulesPath(dataDir){return resolve91(getAppOwnedDepsDir(dataDir),"node_modules")}function getManagedRuntimeDir(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_DIRNAME)}function getManagedRuntimeGenerationDir(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_GENERATION_RELATIVE_PATH)}function getManagedRuntimeRuntimeDir(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_RUNTIME_RELATIVE_PATH)}function getManagedRuntimeNodeModulesPath(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_NODE_MODULES_RELATIVE_PATH)}function getManagedRuntimeReleaseDir(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_RELEASE_RELATIVE_PATH)}function getManagedRuntimeReleaseManifestPath(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_RELEASE_MANIFEST_RELATIVE_PATH)}function getManagedRuntimeServerEntryPath(dataDir){return resolve91(getManagedRuntimeReleaseDir(dataDir),"server","index.js")}function getManagedRuntimeCoreDir(dataDir){return resolve91(getManagedRuntimeReleaseDir(dataDir),"core")}function getManagedRuntimePublicNodeModulesPath(dataDir){return resolve91(getManagedRuntimeGenerationDir(dataDir),"public-node_modules")}var APP_RUNTIME_METADATA_RELATIVE_PATH,APP_OWNED_DEPS_DIRNAME,MANAGED_RUNTIME_DIRNAME,MANAGED_RUNTIME_GENERATION_DIRNAME,MANAGED_RUNTIME_RUNTIME_DIRNAME,MANAGED_RUNTIME_RELEASE_DIRNAME,MANAGED_RUNTIME_NODE_MODULES_RELATIVE_PATH,MANAGED_RUNTIME_GENERATION_RELATIVE_PATH,MANAGED_RUNTIME_RUNTIME_RELATIVE_PATH,MANAGED_RUNTIME_RELEASE_RELATIVE_PATH,MANAGED_RUNTIME_RELEASE_MANIFEST_RELATIVE_PATH,MANAGED_RUNTIME_NODE_MODULES_MARKER,RUNTIME_RELEASE_LAYOUT_VERSION;var init_provisioner_runtime_paths=__esm({"../platform/src/provisioner-runtime-paths.ts"(){"use strict";APP_RUNTIME_METADATA_RELATIVE_PATH=".gencow-runtime.json";APP_OWNED_DEPS_DIRNAME=".gencow-app-deps";MANAGED_RUNTIME_DIRNAME=".gencow-runtime";MANAGED_RUNTIME_GENERATION_DIRNAME="generation";MANAGED_RUNTIME_RUNTIME_DIRNAME="runtime";MANAGED_RUNTIME_RELEASE_DIRNAME="release";MANAGED_RUNTIME_NODE_MODULES_RELATIVE_PATH=`${MANAGED_RUNTIME_DIRNAME}/node_modules`;MANAGED_RUNTIME_GENERATION_RELATIVE_PATH=`${MANAGED_RUNTIME_DIRNAME}/${MANAGED_RUNTIME_GENERATION_DIRNAME}`;MANAGED_RUNTIME_RUNTIME_RELATIVE_PATH=`${MANAGED_RUNTIME_DIRNAME}/${MANAGED_RUNTIME_RUNTIME_DIRNAME}`;MANAGED_RUNTIME_RELEASE_RELATIVE_PATH=`${MANAGED_RUNTIME_DIRNAME}/${MANAGED_RUNTIME_RELEASE_DIRNAME}`;MANAGED_RUNTIME_RELEASE_MANIFEST_RELATIVE_PATH=`${MANAGED_RUNTIME_DIRNAME}/runtime-manifest.json`;MANAGED_RUNTIME_NODE_MODULES_MARKER=".gencow-managed-runtime.json";RUNTIME_RELEASE_LAYOUT_VERSION=3}});import{copyFileSync as copyFileSync3,cpSync,existsSync as existsSync38,lstatSync as lstatSync9,mkdirSync as mkdirSync7,mkdtempSync as mkdtempSync6,readFileSync as readFileSync34,readdirSync as readdirSync13,realpathSync as realpathSync7,rmSync as rmSync8,writeFileSync as writeFileSync6}from"fs";import{tmpdir as tmpdir6}from"os";import{dirname as dirname26,relative as relative24,resolve as resolve92}from"path";function getRuntimeCompatibilityResolver(runtimeCompatibility){const resolver=RUNTIME_COMPATIBILITY_RESOLVERS.find(candidate=>candidate.matches(runtimeCompatibility));if(resolver)return resolver;throw new Error(`[runtime-layout] No runtime compatibility resolver for selector: ${runtimeCompatibility}`)}function readManagedRuntimeManifestForApp(dataDir){return readManagedRuntimeManifest(getManagedRuntimeReleaseManifestPath(dataDir))}function readManagedRuntimeManifest(manifestPath){if(!existsSync38(manifestPath))return null;try{return parseDeploymentRuntimeManifest(readFileSync34(manifestPath,"utf-8"))}catch{return null}}function prepareManagedRuntimePointers(dataDir,publishedReleaseDir,manifest){const generationDir=dirname26(publishedReleaseDir);const managedRuntimeDir=getManagedRuntimeDir(dataDir);mkdirSync7(managedRuntimeDir,{recursive:true});symlinkRelativeEntry(generationDir,getManagedRuntimeGenerationDir(dataDir),"dir");symlinkRelativeEntry(publishedReleaseDir,getManagedRuntimeRuntimeDir(dataDir),"dir");symlinkRelativeEntry(publishedReleaseDir,getManagedRuntimeReleaseDir(dataDir),"dir");const manifestPath=getManagedRuntimeReleaseManifestPath(dataDir);rmSync8(manifestPath,{force:true});if(manifest){writeFileSync6(manifestPath,`${JSON.stringify(manifest,null,2)}
|
|
10157
10157
|
`)}else{copyFileSync3(resolve92(generationDir,"runtime-manifest.json"),manifestPath)}return managedRuntimeDir}function collectPnpmVirtualStoreResolutionRoots2(repoRoot2){const pnpmStoreDir=resolve92(repoRoot2,"node_modules/.pnpm");if(!existsSync38(pnpmStoreDir))return[];const roots=[];for(const entry of readdirSync13(pnpmStoreDir,{withFileTypes:true})){if(!entry.isDirectory()||entry.name.startsWith("."))continue;roots.push(resolve92(pnpmStoreDir,entry.name,"node_modules"))}return roots}function buildResolvedRuntimeReleaseId(repoRoot2){return buildRuntimeReleaseId(repoRoot2,RUNTIME_RELEASE_LAYOUT_VERSION)}function readAppRuntimeMetadata(dataDir){const metadataPath=getAppRuntimeMetadataPath(dataDir);if(!existsSync38(metadataPath))return null;try{const parsed=JSON.parse(readFileSync34(metadataPath,"utf-8"));if(typeof parsed.runtimeCompatibility==="string"&&parsed.runtimeCompatibility.trim()&&typeof parsed.resolvedReleaseId==="string"&&parsed.resolvedReleaseId.trim()){return{runtimeCompatibility:parsed.runtimeCompatibility.trim(),resolvedReleaseId:parsed.resolvedReleaseId.trim()}}}catch{}return null}function resolveAppRuntimeMetadata(dataDir,repoRoot2){const existing=readAppRuntimeMetadata(dataDir);const runtimeCompatibility=existing?.runtimeCompatibility||DEFAULT_RUNTIME_COMPATIBILITY;const resolver=getRuntimeCompatibilityResolver(runtimeCompatibility);return{...resolver.resolve({repoRoot:repoRoot2,runtimeCompatibility}),resolutionStrategy:resolver.strategy,publicationPolicy:resolver.publicationPolicy}}function writeAppRuntimeMetadata(dataDir,metadata){const runtimeDir=getManagedRuntimeDir(dataDir);mkdirSync7(runtimeDir,{recursive:true});const{runtimeCompatibility,resolvedReleaseId}=metadata;writeFileSync6(getAppRuntimeMetadataPath(dataDir),`${JSON.stringify({runtimeCompatibility,resolvedReleaseId},null,2)}
|
|
@@ -10909,10 +10909,7 @@ CREATE INDEX IF NOT EXISTS idx_gencow_realtime_outbox_pending
|
|
|
10909
10909
|
)
|
|
10910
10910
|
)
|
|
10911
10911
|
)
|
|
10912
|
-
`);return new Set(postgresExecuteRows(result3).map(row=>Number(row.app_id)))}var init_runtime_pending_stop_candidate_filter=__esm({"../platform/src/runtime-pending-stop-candidate-filter.ts"(){"use strict";init_postgres_execute_rows()}});function unavailable(){throw new Error("RUNTIME_STOP_EFFECT_FEATURE_BARRIER_UNAVAILABLE")}function validPort3(value2){if(typeof value2!=="string"&&typeof value2!=="number"||!/^\d+$/u.test(String(value2)))return unavailable();const port=Number(value2);return Number.isSafeInteger(port)&&port>0&&port<=65535?port:unavailable()}function resolveRuntimeStopEffectConfiguration(input2){const required3=runtimeStopEffectHandoffRequired(input2.environment.GENCOW_RUNTIME_STOP_EFFECT_HANDOFF)||input2.stopEffectHandoffRequired===true;if(!required3)return{stopEffectHandoffRequired:false};const nodeId=(input2.currentNodeId??input2.environment.GENCOW_NODE_ID)?.trim();if(input2.currentNodeId!=null&&input2.environment.GENCOW_NODE_ID?.trim()&&input2.currentNodeId.trim()!==input2.environment.GENCOW_NODE_ID.trim())return unavailable();if(!nodeId||!/^[A-Za-z0-9._:-]{1,128}$/u.test(nodeId)||nodeId==="unknown-node"||!Number.isSafeInteger(input2.processId)||input2.processId<1)return unavailable();const owner=`${nodeId}:${input2.processId}`;if(input2.stopEffectOwnerId!==void 0&&input2.stopEffectOwnerId!==owner)return unavailable();const slots=[input2.currentSlotId,input2.environment.GENCOW_PLATFORM_SLOT].filter(slot=>slot!==void 0);const ports=slots.map(slot=>{const port=deploymentExecutorSlotPort(slot);return port===null?unavailable():Number(port)});if(input2.currentPort!==void 0)ports.push(validPort3(input2.currentPort));if(input2.environment.PORT!==void 0)ports.push(validPort3(input2.environment.PORT));let url2;if(input2.stopEffectAuthorizationUrl!==void 0){try{url2=new URL(input2.stopEffectAuthorizationUrl)}catch{return unavailable()}if(url2.protocol!=="http:"||url2.hostname!=="127.0.0.1"||url2.username||url2.password||url2.search||url2.hash||url2.pathname!==RUNTIME_STOP_EFFECT_AUTHORIZATION_PATH||!url2.port)return unavailable();ports.push(validPort3(url2.port))}if(!ports.length||ports.some(port=>port!==ports[0]))return unavailable();return{stopEffectHandoffRequired:true,stopEffectOwnerId:owner,stopEffectAuthorizationUrl:url2?.href??`http://127.0.0.1:${ports[0]}${RUNTIME_STOP_EFFECT_AUTHORIZATION_PATH}`}}function withRuntimeStopEffectConfiguration(input2,environment,processId){return{...input2,...resolveRuntimeStopEffectConfiguration({...input2,environment,processId})}}var RUNTIME_STOP_EFFECT_AUTHORIZATION_PATH;var init_runtime_stop_effect_configuration=__esm({"../platform/src/runtime-stop-effect-configuration.ts"(){"use strict";init_deployment_executor_lifecycle_authority();init_runtime_stop_effect_store();RUNTIME_STOP_EFFECT_AUTHORIZATION_PATH="/internal/runtime-stop-effects/authorize"}});var OWNER_BY_REASON,EXECUTION_OWNERS,REASONS_BY_OWNER;var init_runtime_explicit_stop_owner_contract=__esm({"../platform/src/runtime-explicit-stop-owner-contract.ts"(){"use strict";OWNER_BY_REASON=Object.freeze({operator_stop:"deployment_executor",app_delete:"deployment_executor",freeze:"dedicated_workflow",backup_restore:"dedicated_workflow",platform_shutdown:"dedicated_workflow"});EXECUTION_OWNERS=Object.freeze(["public_platform","deployment_executor","dedicated_workflow"]);REASONS_BY_OWNER=Object.freeze(Object.fromEntries(EXECUTION_OWNERS.map(owner=>[owner,Object.freeze(Object.keys(OWNER_BY_REASON).filter(reason=>OWNER_BY_REASON[reason]===owner))])))}});import{and as and48,eq as eq53,inArray as inArray27,isNotNull as isNotNull4,isNull as isNull17,lte as lte7,or as or16}from"drizzle-orm";async function releaseRejectedStopDispatch(input2){return input2.db.transaction(async tx=>{const released=await tx.update(runtimeStopIntents).set({dispatchStartedAt:null,effectOwnerId:null,effectLeaseExpiresAt:null,effectToken:null,effectBindingDigest:null,effectPhase:"none",effectObservedAt:null,effectOutcomeCode:null}).where(and48(eq53(runtimeStopIntents.id,input2.intentId),eq53(runtimeStopIntents.appId,input2.appId),inArray27(runtimeStopIntents.reason,["app_delete",...AUTOMATIC_IDLE_STOP_REASONS]),isNotNull4(runtimeStopIntents.dispatchStartedAt),isNull17(runtimeStopIntents.consumedAt),isNull17(runtimeStopIntents.cancelledAt),or16(and48(eq53(runtimeStopIntents.effectPhase,"observed_changed"),eq53(runtimeStopIntents.effectOutcomeCode,RUNTIME_STOP_DISPATCH_REJECTED_OUTCOME)),and48(eq53(runtimeStopIntents.effectPhase,"node_receipt_pending"),isNotNull4(runtimeStopIntents.effectLeaseExpiresAt),lte7(runtimeStopIntents.effectLeaseExpiresAt,input2.now??new Date),isNull17(runtimeStopIntents.effectObservedAt))),isNull17(runtimeStopIntents.effectPreSyscallAt),isNull17(runtimeStopIntents.effectSyscallAckAt))).returning({drainRequestId:runtimeStopIntents.drainRequestId});if(!released[0])return false;if(released[0].drainRequestId){await tx.update(runtimeDrainRequests).set({state:"armed",updatedAt:new Date}).where(and48(eq53(runtimeDrainRequests.id,released[0].drainRequestId),eq53(runtimeDrainRequests.appId,input2.appId),eq53(runtimeDrainRequests.state,"dispatched")))}return true})}var RUNTIME_STOP_DISPATCH_REJECTED_OUTCOME;var init_runtime_stop_dispatch_rejection_release=__esm({"../platform/src/runtime-stop-dispatch-rejection-release.ts"(){"use strict";init_schema();init_runtime_automatic_idle_contract();RUNTIME_STOP_DISPATCH_REJECTED_OUTCOME="RUNTIME_STOP_DISPATCH_REJECTED"}});import{and as and49,eq as eq54,inArray as inArray28,isNotNull as isNotNull5,isNull as isNull18,lte as lte8,or as or17}from"drizzle-orm";async function restoreUndispatchedDrainProjection(input2){const intentRows=await input2.tx.select({dispatchStartedAt:runtimeStopIntents.dispatchStartedAt,consumedAt:runtimeStopIntents.consumedAt}).from(runtimeStopIntents).where(eq54(runtimeStopIntents.drainRequestId,input2.drain.id));if(intentRows.some(intent=>intent.dispatchStartedAt||intent.consumedAt))return false;await Promise.all([input2.tx.update(appRuntimeDesiredState).set({desiredRuntimeState:"serving",updatedAt:input2.now}).where(and49(eq54(appRuntimeDesiredState.appId,input2.drain.appId),eq54(appRuntimeDesiredState.desiredActivationId,input2.drain.activationId),eq54(appRuntimeDesiredState.desiredRuntimeState,"draining"))),input2.tx.update(appDeploymentActivations).set({state:"serving",updatedAt:input2.now}).where(and49(eq54(appDeploymentActivations.id,input2.drain.activationId),eq54(appDeploymentActivations.appId,input2.drain.appId),eq54(appDeploymentActivations.state,"draining"))),input2.tx.update(appRuntimeInstances).set({state:"serving",updatedAt:input2.now}).where(and49(eq54(appRuntimeInstances.instanceId,input2.drain.instanceId),eq54(appRuntimeInstances.appId,input2.drain.appId),eq54(appRuntimeInstances.state,"draining")))]);return true}async function retireExpiredUndispatchedDrain(input2){const intentRows=await input2.tx.select({id:runtimeStopIntents.id,dispatchStartedAt:runtimeStopIntents.dispatchStartedAt,consumedAt:runtimeStopIntents.consumedAt}).from(runtimeStopIntents).where(eq54(runtimeStopIntents.drainRequestId,input2.drain.id));const intent=intentRows[0];if(intent?.dispatchStartedAt||intent?.consumedAt)return false;if(intent){await input2.tx.update(runtimeStopIntents).set({cancelledAt:input2.now,cancelReason:"expired_before_dispatch"}).where(and49(eq54(runtimeStopIntents.id,intent.id),isNull18(runtimeStopIntents.cancelledAt)))}const cancelled=await input2.tx.update(runtimeDrainRequests).set({state:"cancelled",cancelReason:"expired_before_dispatch",updatedAt:input2.now}).where(and49(eq54(runtimeDrainRequests.id,input2.drain.id),inArray28(runtimeDrainRequests.state,["planned","armed"]))).returning({id:runtimeDrainRequests.id});if(!cancelled[0])throw new Error("RUNTIME_EXPLICIT_STOP_RETRY_CAS_FAILED");const terminalized=await input2.tx.update(runtimeLifecycleRequests).set({state:"failed",terminalResultCode:"RUNTIME_EXPLICIT_DRAIN_EXPIRED",leaseOwner:null,leaseExpiresAt:null,updatedAt:input2.now}).where(and49(eq54(runtimeLifecycleRequests.id,input2.drain.lifecycleRequestId),inArray28(runtimeLifecycleRequests.state,["accepted","queued","executing"]))).returning({id:runtimeLifecycleRequests.id});if(!terminalized[0]||!await restoreUndispatchedDrainProjection(input2)){throw new Error("RUNTIME_EXPLICIT_STOP_RETRY_CAS_FAILED")}return true}async function retireBlockedUndispatchedDrainForReplan(input2){const intents=await input2.tx.select({id:runtimeStopIntents.id,cancelledAt:runtimeStopIntents.cancelledAt,dispatchStartedAt:runtimeStopIntents.dispatchStartedAt,consumedAt:runtimeStopIntents.consumedAt,effectPhase:runtimeStopIntents.effectPhase}).from(runtimeStopIntents).where(eq54(runtimeStopIntents.drainRequestId,input2.drain.id));if(intents.some(intent=>intent.dispatchStartedAt||intent.consumedAt||intent.effectPhase!=="none")){return false}for(const intent of intents.filter(row=>row.cancelledAt===null)){await input2.tx.update(runtimeStopIntents).set({cancelledAt:input2.now,cancelReason:"drain_expired_blocked"}).where(and49(eq54(runtimeStopIntents.id,intent.id),isNull18(runtimeStopIntents.cancelledAt)))}return restoreUndispatchedDrainProjection(input2)}async function terminalizeExpiredUndispatchedStopForDelete(input2){if(!EXPLICIT_STOP_REASONS.includes(input2.drain.reason)||input2.drain.expiresAt>input2.now)return false;const keys2=["deploymentId","activationId","instanceId","nodeId","nodeEpoch","leaseEpoch"];if(keys2.some(key2=>input2.drain[key2]!==input2.expectedBinding[key2]))return false;const binding=await input2.tx.select({id:appRuntimeInstances.instanceId}).from(appRuntimeInstances).where(and49(eq54(appRuntimeInstances.appId,input2.drain.appId),eq54(appRuntimeInstances.deploymentId,input2.expectedBinding.deploymentId),eq54(appRuntimeInstances.activationId,input2.expectedBinding.activationId),eq54(appRuntimeInstances.instanceId,input2.expectedBinding.instanceId),eq54(appRuntimeInstances.nodeId,input2.expectedBinding.nodeId),eq54(appRuntimeInstances.nodeEpoch,input2.expectedBinding.nodeEpoch),eq54(appRuntimeInstances.leaseEpoch,input2.expectedBinding.leaseEpoch))).for("update");if(binding.length!==1)return false;return retireExpiredUndispatchedDrain(input2)}async function cancelExpiredUndispatchedIntentsOfTerminalDrains(input2){const cancelled=await input2.tx.update(runtimeStopIntents).set({cancelledAt:input2.now,cancelReason:"expired_before_dispatch"}).where(and49(eq54(runtimeStopIntents.appId,input2.appId),eq54(runtimeStopIntents.instanceId,input2.instanceId),input2.intentId?eq54(runtimeStopIntents.id,input2.intentId):and49(eq54(runtimeStopIntents.reason,"app_delete"),lte8(runtimeStopIntents.expiresAt,input2.now)),isNull18(runtimeStopIntents.consumedAt),isNull18(runtimeStopIntents.cancelledAt),isNull18(runtimeStopIntents.dispatchStartedAt),isNull18(runtimeStopIntents.effectPreSyscallAt),inArray28(runtimeStopIntents.drainRequestId,input2.tx.select({id:runtimeDrainRequests.id}).from(runtimeDrainRequests).where(and49(eq54(runtimeDrainRequests.appId,input2.appId),inArray28(runtimeDrainRequests.state,["blocked","cancelled"])))))).returning({id:runtimeStopIntents.id});return cancelled.length}async function cancelUnsignalledIntentsOfTerminalDrains(input2){const cancelled=await input2.tx.update(runtimeStopIntents).set({cancelledAt:input2.now,cancelReason:"dispatch_rejected_unsignalled"}).where(and49(eq54(runtimeStopIntents.appId,input2.appId),eq54(runtimeStopIntents.instanceId,input2.instanceId),isNull18(runtimeStopIntents.consumedAt),isNull18(runtimeStopIntents.cancelledAt),isNotNull5(runtimeStopIntents.dispatchStartedAt),isNull18(runtimeStopIntents.effectPreSyscallAt),isNull18(runtimeStopIntents.effectSyscallAckAt),lte8(runtimeStopIntents.expiresAt,input2.now),or17(and49(eq54(runtimeStopIntents.effectPhase,"observed_changed"),eq54(runtimeStopIntents.effectOutcomeCode,RUNTIME_STOP_DISPATCH_REJECTED_OUTCOME)),and49(eq54(runtimeStopIntents.effectPhase,"node_receipt_pending"),isNotNull5(runtimeStopIntents.effectLeaseExpiresAt),lte8(runtimeStopIntents.effectLeaseExpiresAt,input2.now),isNull18(runtimeStopIntents.effectObservedAt))),inArray28(runtimeStopIntents.drainRequestId,input2.tx.select({id:runtimeDrainRequests.id}).from(runtimeDrainRequests).where(and49(eq54(runtimeDrainRequests.appId,input2.appId),inArray28(runtimeDrainRequests.state,["blocked","cancelled"])))))).returning({id:runtimeStopIntents.id});return cancelled.length}var EXPLICIT_STOP_REASONS;var init_runtime_explicit_stop_expired_drain=__esm({"../platform/src/runtime-explicit-stop-expired-drain.ts"(){"use strict";init_schema();init_runtime_explicit_stop_owner_contract();init_runtime_stop_dispatch_rejection_release();EXPLICIT_STOP_REASONS=["app_delete","operator_stop","freeze","backup_restore","platform_shutdown"]}});function resolveRuntimeAppEnvironment(parentAppId){return parentAppId==null?"dev":"prod"}function resolveAutomaticScaleDownRolloutEnvironment(parentAppId,reason){if(!isAutomaticIdleStopReason(reason))return null;const appEnvironment=resolveRuntimeAppEnvironment(parentAppId);if(requiresIdleCertificationEvidence(reason))return appEnvironment;return appEnvironment==="dev"?"dev":null}var init_runtime_app_environment=__esm({"../platform/src/runtime-app-environment.ts"(){"use strict";init_runtime_automatic_idle_contract()}});import{and as and50,eq as eq55,inArray as inArray29,isNotNull as isNotNull6,isNull as isNull19,sql as sql144}from"drizzle-orm";function normalizeAllowlist2(value2){if(!Array.isArray(value2)||value2.length>1e4){throw new Error("RUNTIME_LIFECYCLE_ROLLOUT_ALLOWLIST_INVALID")}const normalized=[...new Set(value2)];if(normalized.length!==value2.length){throw new Error("RUNTIME_LIFECYCLE_ROLLOUT_ALLOWLIST_INVALID")}if(normalized.some(appId=>!Number.isSafeInteger(appId)||Number(appId)<=0)){throw new Error("RUNTIME_LIFECYCLE_ROLLOUT_ALLOWLIST_INVALID")}return normalized.sort((left,right)=>left-right)}function parseRuntimeLifecycleRolloutAllowlistJson(value2){try{return normalizeAllowlist2(JSON.parse(value2))}catch{return null}}function validateRuntimeLifecycleRolloutConfig(input2){if(input2.mode==="enforce"&&(input2.enforceAll&&input2.allowlistAppIds.length!==0||!input2.enforceAll&&input2.allowlistAppIds.length===0)||input2.mode!=="enforce"&&(input2.enforceAll||input2.allowlistAppIds.length!==0)){throw new Error("RUNTIME_LIFECYCLE_ROLLOUT_CONFIGURATION_INVALID")}}function isRuntimeLifecycleRolloutAppEligible(input2){if(!Number.isSafeInteger(input2.appId)||input2.appId<=0)return false;let allowlistAppIds;try{allowlistAppIds=normalizeAllowlist2(input2.allowlistAppIds);validateRuntimeLifecycleRolloutConfig({mode:input2.mode,enforceAll:input2.enforceAll,allowlistAppIds})}catch{return false}return Boolean(input2.mode==="enforce"&&typeof input2.enforceAll==="boolean"&&Number.isSafeInteger(input2.revision)&&Number(input2.revision)>0&&(input2.expectedRevision===void 0||input2.revision===input2.expectedRevision)&&(input2.enforceAll||allowlistAppIds.includes(input2.appId)))}var init_runtime_lifecycle_rollout=__esm({"../platform/src/runtime-lifecycle-rollout.ts"(){"use strict";init_schema();init_runtime_app_environment();init_deployment_control_plane_rollout()}});var init_runtime_lifecycle_policy=__esm({"../platform/src/runtime-lifecycle-policy.ts"(){"use strict"}});function runtimeIdleCertificationControllerId(scope,appId){return`${scope==="prod"?RUNTIME_PROD_IDLE_CERTIFICATION_CONTROLLER_PREFIX:RUNTIME_QC_IDLE_CERTIFICATION_CONTROLLER_PREFIX}${appId}`}function idleCertificationRolloutShapeAllows(input2){const globallyEnforced=input2.enforceAll===true&&input2.allowlist?.length===0;if(input2.scope==="prod")return globallyEnforced;return globallyEnforced||input2.enforceAll===false&&input2.allowlist?.length===1&&input2.allowlist[0]===input2.appId}var RUNTIME_PROD_IDLE_CERTIFICATION_CONTROLLER_PREFIX,RUNTIME_QC_IDLE_CERTIFICATION_CONTROLLER_PREFIX;var init_runtime_idle_certification=__esm({"../platform/src/runtime-idle-certification.ts"(){"use strict";init_runtime_lifecycle_rollout();RUNTIME_PROD_IDLE_CERTIFICATION_CONTROLLER_PREFIX="runtime-prod-idle-certification-v1:";RUNTIME_QC_IDLE_CERTIFICATION_CONTROLLER_PREFIX="runtime-qc-idle-certification-v1:"}});import{eq as eq56}from"drizzle-orm";var init_runtime_legacy_idle_observation=__esm({"../platform/src/runtime-legacy-idle-observation.ts"(){"use strict";init_schema();init_runtime_automatic_idle_contract()}});import{createHash as createHash107}from"node:crypto";import{and as and51,eq as eq57,inArray as inArray30,isNull as isNull20,sql as sql145}from"drizzle-orm";function hash4(value2){return createHash107("sha256").update(JSON.stringify(value2)).digest("hex")}async function acquireAppLock(tx,appId){await tx.execute(sql145`SELECT pg_advisory_xact_lock(hashtextextended(${"app-activation:"+appId}::text, 0))`);await tx.execute(sql145`SELECT pg_advisory_xact_lock(hashtextextended(${"runtime-lifecycle:"+appId}::text, 0))`)}async function cancelAutomaticScaleDown(input2){const now=input2.now??new Date;return input2.db.transaction(async tx=>{const drainRows=await tx.select().from(runtimeDrainRequests).where(eq57(runtimeDrainRequests.id,input2.drainId));const drain=drainRows[0];if(!drain)return false;await(input2.acquireLock??acquireAppLock)(tx,drain.appId);const intentRows=await tx.select().from(runtimeStopIntents).where(eq57(runtimeStopIntents.drainRequestId,drain.id));const intent=intentRows[0];if(intent?.dispatchStartedAt||intent?.consumedAt)return false;if(intent){await tx.update(runtimeStopIntents).set({cancelledAt:now,cancelReason:input2.reason}).where(and51(eq57(runtimeStopIntents.id,intent.id),isNull20(runtimeStopIntents.cancelledAt)));await Promise.all([tx.update(appRuntimeDesiredState).set({desiredRuntimeState:"serving",updatedAt:now}).where(and51(eq57(appRuntimeDesiredState.appId,drain.appId),eq57(appRuntimeDesiredState.desiredActivationId,drain.activationId),eq57(appRuntimeDesiredState.desiredRuntimeState,"draining"))),tx.update(appDeploymentActivations).set({state:"serving",updatedAt:now}).where(and51(eq57(appDeploymentActivations.id,drain.activationId),eq57(appDeploymentActivations.appId,drain.appId),eq57(appDeploymentActivations.state,"draining"))),tx.update(appRuntimeInstances).set({state:"serving",updatedAt:now}).where(and51(eq57(appRuntimeInstances.instanceId,drain.instanceId),eq57(appRuntimeInstances.appId,drain.appId),eq57(appRuntimeInstances.state,"draining")))])}const cancelled=await tx.update(runtimeDrainRequests).set({state:"cancelled",cancelReason:input2.reason,updatedAt:now}).where(and51(eq57(runtimeDrainRequests.id,drain.id),inArray30(runtimeDrainRequests.state,["planned","armed"]))).returning({id:runtimeDrainRequests.id});if(!cancelled[0])return false;await tx.update(runtimeLifecycleRequests).set({state:"completed",terminalResultCode:"cancelled",updatedAt:now}).where(eq57(runtimeLifecycleRequests.id,drain.lifecycleRequestId));return true})}async function recordLegacyRuntimePreserveReplaceRemediation(input2){const now=input2.now??new Date;const evidenceHash=hash4(input2.evidence);const nextState=sql145`CASE
|
|
10913
|
-
WHEN ${runtimeLifecycleRemediations.conflictCount} + 1 >= 3 THEN 'manual'
|
|
10914
|
-
ELSE ${runtimeLifecycleRemediations.state}
|
|
10915
|
-
END`;const id=`remediation_${hash4([input2.appId,input2.code,evidenceHash]).slice(0,32)}`;await input2.db.insert(runtimeLifecycleRemediations).values({id,appId:input2.appId,instanceId:input2.instanceId??null,code:input2.code,evidenceHash,conflictCount:1,state:"pending",lastObservedAt:now,updatedAt:now}).onConflictDoUpdate({target:runtimeLifecycleRemediations.id,setWhere:isNull20(runtimeLifecycleRemediations.resolvedAt),set:{conflictCount:sql145`${runtimeLifecycleRemediations.conflictCount} + 1`,state:nextState,lastObservedAt:now,updatedAt:now}});return{id,evidenceHash}}var init_runtime_scale_down_store=__esm({"../platform/src/runtime-scale-down-store.ts"(){"use strict";init_schema();init_runtime_lifecycle_policy();init_runtime_app_environment();init_runtime_idle_certification();init_runtime_lifecycle_rollout();init_runtime_process_identity();init_runtime_stop_intent_store();init_runtime_automatic_idle_contract();init_runtime_legacy_idle_observation();init_deploy_contract_admission();init_runtime_owner_resolution();init_runtime_idle_certification()}});import{createHash as createHash108}from"node:crypto";import{and as and52,eq as eq58,gt as gt11,isNull as isNull21,sql as sql146}from"drizzle-orm";function sha25620(value2){return createHash108("sha256").update(value2).digest("hex")}function fail44(code){throw new Error(code)}function intentSelection(){return{id:runtimeStopIntents.id,appId:runtimeStopIntents.appId,deploymentId:runtimeStopIntents.deploymentId,activationId:runtimeStopIntents.activationId,instanceId:runtimeStopIntents.instanceId,nodeId:runtimeStopIntents.nodeId,nodeEpoch:runtimeStopIntents.nodeEpoch,leaseEpoch:runtimeStopIntents.leaseEpoch,sourceGenerationRef:runtimeStopIntents.sourceGenerationRef,reason:runtimeStopIntents.reason,expiresAt:runtimeStopIntents.expiresAt,consumedAt:runtimeStopIntents.consumedAt,consumedByEventId:runtimeStopIntents.consumedByEventId,createdByKind:runtimeStopIntents.createdByKind,createdById:runtimeStopIntents.createdById,correlationId:runtimeStopIntents.correlationId,drainRequestId:runtimeStopIntents.drainRequestId,rolloutRevision:runtimeStopIntents.rolloutRevision,rolloutEligibilityHash:runtimeStopIntents.rolloutEligibilityHash,cancelledAt:runtimeStopIntents.cancelledAt,cancelReason:runtimeStopIntents.cancelReason,dispatchStartedAt:runtimeStopIntents.dispatchStartedAt}}async function loadIntent(db,intentId){const rows8=await db.select(intentSelection()).from(runtimeStopIntents).where(eq58(runtimeStopIntents.id,intentId));return rows8[0]??null}async function dispatchRuntimeStopIntent(input2){if(input2.effectHandoffRequired&&!input2.effectOwnerId){return fail44("RUNTIME_STOP_EFFECT_FEATURE_BARRIER_UNAVAILABLE")}const now=input2.now??new Date;const target=await input2.db.transaction(async tx=>{let intent=await loadIntent(tx,input2.intentId);if(!intent||intent.consumedAt||intent.cancelledAt||intent.dispatchStartedAt||intent.expiresAt<=now){return fail44("RUNTIME_STOP_INTENT_NOT_PENDING")}if(intent.drainRequestId){const drainRows=await tx.select({drain:runtimeDrainRequests,parentAppId:apps.parentAppId}).from(runtimeDrainRequests).innerJoin(apps,eq58(apps.id,runtimeDrainRequests.appId)).where(eq58(runtimeDrainRequests.id,intent.drainRequestId));const row=drainRows[0];const drain=row?.drain;const automaticDrain=drain?isAutomaticIdleStopReason(drain.reason):false;if(!drain||drain.state!=="armed"||drain.appId!==intent.appId||drain.instanceId!==intent.instanceId||drain.rolloutRevision!==intent.rolloutRevision||drain.rolloutEligibilityHash!==intent.rolloutEligibilityHash){return fail44("RUNTIME_STOP_INTENT_DRAIN_INVALID")}const activityRows=await tx.select().from(appRuntimeActivityState).where(eq58(appRuntimeActivityState.appId,intent.appId));const activity=activityRows[0];const appDeleteWithoutActivityObservation=drain.reason==="app_delete"&&!activity;if(!appDeleteWithoutActivityObservation&&(!activity||!activity.observationComplete||activity.activityEpoch!==drain.activityEpoch||activity.activationId!==drain.activationId||activity.instanceId!==drain.instanceId||activity.nodeId!==drain.nodeId||activity.nodeEpoch!==drain.nodeEpoch||activity.httpActive!==0||activity.streamActive!==0||activity.websocketActive!==0||activity.workloadActive!==0)){return fail44("RUNTIME_STOP_INTENT_ACTIVITY_CHANGED")}if(automaticDrain){const rolloutEnvironment=resolveAutomaticScaleDownRolloutEnvironment(row.parentAppId,drain.reason);if(!rolloutEnvironment)return fail44("RUNTIME_STOP_INTENT_ROLLOUT_STALE");const acquireRolloutFence=input2.acquireRolloutFence??((fenceTx,environment)=>fenceTx.execute(sql146`SELECT pg_advisory_xact_lock(hashtextextended(${"runtime-lifecycle-rollout:"+environment}::text, 0))`));await acquireRolloutFence(tx,rolloutEnvironment);const rolloutRows=await tx.select().from(runtimeLifecycleRollouts).where(eq58(runtimeLifecycleRollouts.environment,rolloutEnvironment));const rollout=rolloutRows[0];const allowlist2=parseRuntimeLifecycleRolloutAllowlistJson(rollout?.allowlistJson??"null");const validRollout=isRuntimeLifecycleRolloutAppEligible({mode:rollout?.mode,enforceAll:rollout?.enforceAll,allowlistAppIds:allowlist2,revision:rollout?.revision,expectedRevision:intent.rolloutRevision,appId:intent.appId});const validCertificationAuthority=drain.reason!=="idle_certification"||Boolean(rollout&&allowlist2&&idleCertificationRolloutShapeAllows({scope:row.parentAppId==null?"qc":"prod",enforceAll:rollout.enforceAll,allowlist:allowlist2,appId:intent.appId})&&intent.createdById===sha25620(JSON.stringify(runtimeIdleCertificationControllerId(row.parentAppId==null?"qc":"prod",intent.appId))));if(!validRollout||!rollout||!allowlist2||!validCertificationAuthority){return fail44("RUNTIME_STOP_INTENT_ROLLOUT_STALE")}}intent=await loadIntent(tx,input2.intentId);if(!intent||intent.cancelledAt||intent.consumedAt||intent.dispatchStartedAt||intent.expiresAt<=now){return fail44("RUNTIME_STOP_INTENT_NOT_PENDING")}}const instances=await tx.select({instanceId:appRuntimeInstances.instanceId,appId:appRuntimeInstances.appId,deploymentId:appRuntimeInstances.deploymentId,activationId:appRuntimeInstances.activationId,nodeEpoch:appRuntimeInstances.nodeEpoch,leaseEpoch:appRuntimeInstances.leaseEpoch,runnerRef:appRuntimeInstances.runnerRef,runnerKind:appRuntimeInstances.runnerKind,processIdentityHash:appRuntimeInstances.processIdentityHash,pid:appRuntimeInstances.pid,pidStartTicks:appRuntimeInstances.pidStartTicks,processGroupId:appRuntimeInstances.processGroupId,processGroupStartTicks:appRuntimeInstances.processGroupStartTicks,cgroupRefHash:appRuntimeInstances.cgroupRefHash,runnerSessionId:appRuntimeInstances.runnerSessionId,port:appRuntimeInstances.port,readyContractHash:appRuntimeInstances.readyContractHash,state:appRuntimeInstances.state}).from(appRuntimeInstances).where(and52(eq58(appRuntimeInstances.instanceId,intent.instanceId),eq58(appRuntimeInstances.appId,intent.appId),eq58(appRuntimeInstances.deploymentId,intent.deploymentId),eq58(appRuntimeInstances.activationId,intent.activationId),eq58(appRuntimeInstances.nodeEpoch,intent.nodeEpoch),eq58(appRuntimeInstances.leaseEpoch,intent.leaseEpoch)));const instance=instances[0];if(!instance||instance.processIdentityHash!==input2.observedProcessIdentityHash||!isCompleteRuntimeProcessIdentity(instance)||!["serving","draining"].includes(instance.state)){return fail44("RUNTIME_STOP_OWNERSHIP_AMBIGUOUS")}if(input2.assertControllerActive&&!await input2.assertControllerActive(tx)){return fail44("RUNTIME_STOP_CONTROLLER_INACTIVE")}let stopEffect;if(input2.effectOwnerId){stopEffect=await claimRuntimeStopEffectInTransaction({tx,ownerId:input2.effectOwnerId,now,intent:{intentId:intent.id,appId:intent.appId,deploymentId:intent.deploymentId,activationId:intent.activationId,instanceId:intent.instanceId,nodeId:intent.nodeId,nodeEpoch:intent.nodeEpoch,leaseEpoch:intent.leaseEpoch,sourceGenerationRef:intent.sourceGenerationRef,runnerKind:instance.runnerKind,runnerRef:instance.runnerRef,processIdentityHash:instance.processIdentityHash,pid:instance.pid,pidStartTicks:instance.pidStartTicks,processGroupId:instance.processGroupId,processGroupStartTicks:instance.processGroupStartTicks,cgroupRefHash:instance.cgroupRefHash,runnerSessionId:instance.runnerSessionId,port:instance.port,readyContractHash:instance.readyContractHash}})}else{const claimed=await tx.update(runtimeStopIntents).set({dispatchStartedAt:now}).where(and52(eq58(runtimeStopIntents.id,intent.id),isNull21(runtimeStopIntents.consumedAt),isNull21(runtimeStopIntents.cancelledAt),isNull21(runtimeStopIntents.dispatchStartedAt),gt11(runtimeStopIntents.expiresAt,now))).returning({id:runtimeStopIntents.id});if(!claimed[0])return fail44("RUNTIME_STOP_INTENT_DISPATCH_CAS_FAILED")}if(intent.drainRequestId){const dispatched=await tx.update(runtimeDrainRequests).set({state:"dispatched",updatedAt:now}).where(and52(eq58(runtimeDrainRequests.id,intent.drainRequestId),eq58(runtimeDrainRequests.state,"armed"))).returning({id:runtimeDrainRequests.id});if(!dispatched[0])return fail44("RUNTIME_STOP_INTENT_DRAIN_DISPATCH_CAS_FAILED")}return{intentId:intent.id,instanceId:intent.instanceId,nodeId:intent.nodeId,nodeEpoch:intent.nodeEpoch,leaseEpoch:intent.leaseEpoch,processIdentityHash:instance.processIdentityHash,runnerRef:instance.runnerRef,pid:instance.pid,pidStartTicks:instance.pidStartTicks,processGroupId:instance.processGroupId,processGroupStartTicks:instance.processGroupStartTicks,cgroupRefHash:instance.cgroupRefHash,runnerSessionId:instance.runnerSessionId,...stopEffect?{stopEffect}:{}}});try{await input2.stop(target)}catch(error62){if(target.stopEffect){await revokeRuntimeStopEffect({db:input2.db,capability:target.stopEffect,outcomeCode:RUNTIME_STOP_DISPATCH_REJECTED_OUTCOME}).catch(()=>false)}throw error62}return target}var init_runtime_stop_intent_dispatch=__esm({"../platform/src/runtime-stop-intent-dispatch.ts"(){"use strict";init_schema();init_runtime_process_identity();init_runtime_lifecycle_rollout();init_runtime_app_environment();init_runtime_automatic_idle_contract();init_runtime_scale_down_store();init_runtime_idle_certification();init_runtime_stop_effect_store();init_runtime_stop_dispatch_rejection_release()}});import{createHash as createHash109}from"node:crypto";import{and as and53,eq as eq59,inArray as inArray31,isNotNull as isNotNull8,isNull as isNull22,sql as sql147}from"drizzle-orm";function sha25621(value2){return createHash109("sha256").update(value2).digest("hex")}async function loadIdleCertificationEvidence(input2){const[routeRows,activationRows]=await Promise.all([input2.tx.select({environment:appServingRouteAuthorities.environment,appInstanceId:appServingRouteAuthorities.appInstanceId,canonicalAppInstanceId:apps.instanceId,routeEpoch:appServingRouteAuthorities.routeEpoch,entryHash:appServingRouteAuthorities.entryHash}).from(appServingRouteAuthorities).innerJoin(apps,eq59(apps.id,appServingRouteAuthorities.appId)).where(eq59(appServingRouteAuthorities.appId,input2.appId)),input2.tx.select({activationEpoch:appDeploymentActivations.activationEpoch}).from(appDeploymentActivations).where(and53(eq59(appDeploymentActivations.id,input2.activationId),eq59(appDeploymentActivations.appId,input2.appId),eq59(appDeploymentActivations.deploymentId,input2.deploymentId)))]);const route=routeRows[0];const activation=activationRows[0];if(!route||!SERVING_ROUTE_ENVIRONMENTS.has(route.environment)||route.appInstanceId!==route.canonicalAppInstanceId||!Number.isSafeInteger(route.routeEpoch)||route.routeEpoch<=0||!/^[a-f0-9]{64}$/u.test(route.entryHash)||!activation?.activationEpoch){return null}const payload=JSON.stringify({protocolVersion:1,servingRouteEnvironment:route.environment,appInstanceId:route.appInstanceId,routeEpoch:route.routeEpoch,entryHash:route.entryHash,activationId:input2.activationId,activationEpoch:activation.activationEpoch});return{digest:sha25621(payload),payload}}async function recoverDispatchedIdleStopForResume(input2){const now=input2.now??new Date;return input2.db.transaction(async tx=>{await tx.execute(sql147`SELECT pg_advisory_xact_lock(hashtextextended(${`runtime-lifecycle:${input2.appId}`}::text, 0))`);const rows8=await tx.select({intentId:runtimeStopIntents.id,drainId:runtimeDrainRequests.id,lifecycleRequestId:runtimeDrainRequests.lifecycleRequestId}).from(runtimeStopIntents).innerJoin(runtimeDrainRequests,and53(eq59(runtimeDrainRequests.id,runtimeStopIntents.drainRequestId),eq59(runtimeDrainRequests.appId,runtimeStopIntents.appId))).innerJoin(appRuntimeDesiredState,and53(eq59(appRuntimeDesiredState.appId,runtimeStopIntents.appId),eq59(appRuntimeDesiredState.desiredActivationId,runtimeStopIntents.activationId))).innerJoin(appDeploymentActivations,and53(eq59(appDeploymentActivations.id,runtimeStopIntents.activationId),eq59(appDeploymentActivations.appId,runtimeStopIntents.appId))).innerJoin(appRuntimeInstances,and53(eq59(appRuntimeInstances.instanceId,runtimeStopIntents.instanceId),eq59(appRuntimeInstances.appId,runtimeStopIntents.appId),eq59(appRuntimeInstances.activationId,runtimeStopIntents.activationId))).where(and53(eq59(runtimeStopIntents.appId,input2.appId),eq59(runtimeStopIntents.instanceId,input2.instanceId),eq59(runtimeStopIntents.activationId,input2.activationId),eq59(runtimeStopIntents.nodeEpoch,input2.nodeEpoch),eq59(runtimeStopIntents.leaseEpoch,input2.leaseEpoch),eq59(runtimeStopIntents.reason,"idle_certification"),isNotNull8(runtimeStopIntents.dispatchStartedAt),isNull22(runtimeStopIntents.consumedAt),isNull22(runtimeStopIntents.cancelledAt),eq59(runtimeDrainRequests.state,"dispatched"),eq59(appRuntimeDesiredState.authorityMode,"enforce"),eq59(appRuntimeDesiredState.desiredRuntimeState,"serving"),eq59(appRuntimeDesiredState.desiredActivationId,input2.activationId),eq59(appDeploymentActivations.state,"draining"),eq59(appRuntimeInstances.state,"draining"),eq59(appRuntimeInstances.processIdentityHash,input2.processIdentityHash))).limit(1);const row=rows8[0];if(!row)return false;const intent=await tx.update(runtimeStopIntents).set({cancelledAt:now,cancelReason:"resume_after_idle_exit_uncertain"}).where(and53(eq59(runtimeStopIntents.id,row.intentId),eq59(runtimeStopIntents.appId,input2.appId),isNotNull8(runtimeStopIntents.dispatchStartedAt),isNull22(runtimeStopIntents.consumedAt),isNull22(runtimeStopIntents.cancelledAt))).returning({id:runtimeStopIntents.id});if(!intent[0])return false;const drain=await tx.update(runtimeDrainRequests).set({state:"cancelled",cancelReason:"resume_after_idle_exit_uncertain",updatedAt:now}).where(and53(eq59(runtimeDrainRequests.id,row.drainId),eq59(runtimeDrainRequests.appId,input2.appId),eq59(runtimeDrainRequests.state,"dispatched"))).returning({id:runtimeDrainRequests.id});if(!drain[0])throw new Error("RUNTIME_IDLE_RESUME_DRAIN_CAS_FAILED");const activation=await tx.update(appDeploymentActivations).set({state:"serving",updatedAt:now}).where(and53(eq59(appDeploymentActivations.id,input2.activationId),eq59(appDeploymentActivations.appId,input2.appId),eq59(appDeploymentActivations.nodeEpoch,input2.nodeEpoch),eq59(appDeploymentActivations.state,"draining"))).returning({id:appDeploymentActivations.id});if(!activation[0])throw new Error("RUNTIME_IDLE_RESUME_ACTIVATION_CAS_FAILED");await tx.update(runtimeLifecycleRequests).set({state:"completed",terminalResultCode:"cancelled_for_resume",updatedAt:now}).where(and53(eq59(runtimeLifecycleRequests.id,row.lifecycleRequestId),eq59(runtimeLifecycleRequests.appId,input2.appId),inArray31(runtimeLifecycleRequests.state,["accepted","queued","executing"])));await tx.update(appRuntimeInstances).set({state:"serving",updatedAt:now}).where(and53(eq59(appRuntimeInstances.instanceId,input2.instanceId),eq59(appRuntimeInstances.appId,input2.appId),eq59(appRuntimeInstances.activationId,input2.activationId),eq59(appRuntimeInstances.nodeEpoch,input2.nodeEpoch),eq59(appRuntimeInstances.leaseEpoch,input2.leaseEpoch),eq59(appRuntimeInstances.state,"draining"),eq59(appRuntimeInstances.processIdentityHash,input2.processIdentityHash)));return true})}async function quarantineTerminalAutomaticStopForResume(input2){const now=input2.now??new Date;return input2.db.transaction(async tx=>{await tx.execute(sql147`SELECT pg_advisory_xact_lock(hashtextextended(${`runtime-lifecycle:${input2.appId}`}::text, 0))`);const rows8=await tx.select({intentId:runtimeStopIntents.id,drainId:runtimeDrainRequests.id,lifecycleRequestId:runtimeDrainRequests.lifecycleRequestId}).from(runtimeStopIntents).innerJoin(runtimeDrainRequests,and53(eq59(runtimeDrainRequests.id,runtimeStopIntents.drainRequestId),eq59(runtimeDrainRequests.appId,runtimeStopIntents.appId))).innerJoin(appRuntimeDesiredState,and53(eq59(appRuntimeDesiredState.appId,runtimeStopIntents.appId),eq59(appRuntimeDesiredState.desiredActivationId,runtimeStopIntents.activationId),eq59(appRuntimeDesiredState.nodeId,runtimeStopIntents.nodeId),eq59(appRuntimeDesiredState.nodeEpoch,runtimeStopIntents.nodeEpoch))).innerJoin(appDeploymentActivations,and53(eq59(appDeploymentActivations.id,runtimeStopIntents.activationId),eq59(appDeploymentActivations.appId,runtimeStopIntents.appId),eq59(appDeploymentActivations.nodeId,runtimeStopIntents.nodeId),eq59(appDeploymentActivations.nodeEpoch,runtimeStopIntents.nodeEpoch))).innerJoin(appRuntimeInstances,and53(eq59(appRuntimeInstances.instanceId,runtimeStopIntents.instanceId),eq59(appRuntimeInstances.appId,runtimeStopIntents.appId),eq59(appRuntimeInstances.activationId,runtimeStopIntents.activationId),eq59(appRuntimeInstances.nodeEpoch,runtimeStopIntents.nodeEpoch),eq59(appRuntimeInstances.leaseEpoch,runtimeStopIntents.leaseEpoch))).where(and53(eq59(runtimeStopIntents.appId,input2.appId),inArray31(runtimeStopIntents.reason,AUTOMATIC_IDLE_STOP_REASONS),isNotNull8(runtimeStopIntents.dispatchStartedAt),isNull22(runtimeStopIntents.consumedAt),isNull22(runtimeStopIntents.cancelledAt),eq59(runtimeDrainRequests.state,"dispatched"),eq59(appRuntimeDesiredState.authorityMode,"enforce"),eq59(appRuntimeDesiredState.desiredRuntimeState,"serving"),inArray31(appDeploymentActivations.state,["draining","serving"]),inArray31(appRuntimeInstances.state,["stopped","exited"]))).limit(1);const row=rows8[0];if(!row)return false;const intent=await tx.update(runtimeStopIntents).set({cancelledAt:now,cancelReason:"resume_after_terminal_automatic_stop"}).where(and53(eq59(runtimeStopIntents.id,row.intentId),eq59(runtimeStopIntents.appId,input2.appId),isNotNull8(runtimeStopIntents.dispatchStartedAt),isNull22(runtimeStopIntents.consumedAt),isNull22(runtimeStopIntents.cancelledAt))).returning({id:runtimeStopIntents.id});if(!intent[0])return false;const drain=await tx.update(runtimeDrainRequests).set({state:"cancelled",cancelReason:"resume_after_terminal_automatic_stop",updatedAt:now}).where(and53(eq59(runtimeDrainRequests.id,row.drainId),eq59(runtimeDrainRequests.appId,input2.appId),eq59(runtimeDrainRequests.state,"dispatched"))).returning({id:runtimeDrainRequests.id});if(!drain[0])throw new Error("RUNTIME_TERMINAL_STOP_RESUME_DRAIN_CAS_FAILED");await tx.update(runtimeLifecycleRequests).set({state:"completed",terminalResultCode:"cancelled_for_terminal_resume",updatedAt:now}).where(and53(eq59(runtimeLifecycleRequests.id,row.lifecycleRequestId),eq59(runtimeLifecycleRequests.appId,input2.appId),inArray31(runtimeLifecycleRequests.state,["accepted","queued","executing"])));return true})}var SERVING_ROUTE_ENVIRONMENTS;var init_runtime_idle_certification_stop_recovery=__esm({"../platform/src/runtime-idle-certification-stop-recovery.ts"(){"use strict";init_schema();init_runtime_automatic_idle_contract();SERVING_ROUTE_ENVIRONMENTS=new Set(["local","dev","qc","prod"])}});import{and as and54,eq as eq60}from"drizzle-orm";function fail45(code){throw new Error(code)}async function resumeDispatchedRuntimeStopIntent(input2){const target=await input2.db.transaction(async tx=>{const intents=await tx.select().from(runtimeStopIntents).where(eq60(runtimeStopIntents.id,input2.intentId));const intent=intents[0];if(!intent||intent.consumedAt||intent.cancelledAt||!intent.dispatchStartedAt){return fail45("RUNTIME_STOP_INTENT_DISPATCH_NOT_RESUMABLE")}if(intent.drainRequestId){const drains=await tx.select({state:runtimeDrainRequests.state}).from(runtimeDrainRequests).where(and54(eq60(runtimeDrainRequests.id,intent.drainRequestId),eq60(runtimeDrainRequests.appId,intent.appId),eq60(runtimeDrainRequests.instanceId,intent.instanceId)));if(drains[0]?.state!=="dispatched"){return fail45("RUNTIME_STOP_INTENT_DRAIN_INVALID")}}const instances=await tx.select({processIdentityHash:appRuntimeInstances.processIdentityHash,runnerRef:appRuntimeInstances.runnerRef,pid:appRuntimeInstances.pid,pidStartTicks:appRuntimeInstances.pidStartTicks,processGroupId:appRuntimeInstances.processGroupId,processGroupStartTicks:appRuntimeInstances.processGroupStartTicks,cgroupRefHash:appRuntimeInstances.cgroupRefHash,runnerSessionId:appRuntimeInstances.runnerSessionId,state:appRuntimeInstances.state}).from(appRuntimeInstances).where(and54(eq60(appRuntimeInstances.instanceId,intent.instanceId),eq60(appRuntimeInstances.appId,intent.appId),eq60(appRuntimeInstances.deploymentId,intent.deploymentId),eq60(appRuntimeInstances.activationId,intent.activationId),eq60(appRuntimeInstances.nodeEpoch,intent.nodeEpoch),eq60(appRuntimeInstances.leaseEpoch,intent.leaseEpoch)));const instance=instances[0];if(!instance||instance.processIdentityHash!==input2.observedProcessIdentityHash||!isCompleteRuntimeProcessIdentity(instance)||!["serving","draining"].includes(instance.state)){return fail45("RUNTIME_STOP_OWNERSHIP_AMBIGUOUS")}return{intentId:intent.id,instanceId:intent.instanceId,nodeId:intent.nodeId,nodeEpoch:intent.nodeEpoch,leaseEpoch:intent.leaseEpoch,processIdentityHash:instance.processIdentityHash,runnerRef:instance.runnerRef,pid:instance.pid,pidStartTicks:instance.pidStartTicks,processGroupId:instance.processGroupId,processGroupStartTicks:instance.processGroupStartTicks,cgroupRefHash:instance.cgroupRefHash,runnerSessionId:instance.runnerSessionId}});return target}var init_runtime_stop_dispatch_recovery=__esm({"../platform/src/runtime-stop-dispatch-recovery.ts"(){"use strict";init_schema();init_runtime_process_identity()}});import{createHash as createHash110}from"node:crypto";import{and as and55,eq as eq61,exists as exists3,gt as gt12,inArray as inArray32,isNotNull as isNotNull9,isNull as isNull23,lte as lte9,ne as ne14,or as or19,sql as sql148}from"drizzle-orm";function sha25622(value2){return createHash110("sha256").update(value2).digest("hex")}function fail46(code){throw new Error(code)}function matchesRequestIdentity(row,input2){return row.reason===input2.reason&&row.createdByKind===input2.createdByKind&&row.createdById===input2.createdById&&row.correlationId===input2.correlationId&&row.drainRequestId===(input2.drainRequestId??null)&&row.rolloutRevision===(input2.rolloutRevision??null)&&row.rolloutEligibilityHash===(input2.rolloutEligibilityHash??null)}function matchesLeaseIdentity(row,instance){return LEASE_IDENTITY_FIELDS.every(field=>row[field]===instance[field])}function matchesBindingIdentity(row,instance){return BINDING_IDENTITY_FIELDS.every(field=>row[field]===instance[field])}function intentSelection2(){return{id:runtimeStopIntents.id,appId:runtimeStopIntents.appId,deploymentId:runtimeStopIntents.deploymentId,activationId:runtimeStopIntents.activationId,instanceId:runtimeStopIntents.instanceId,nodeId:runtimeStopIntents.nodeId,nodeEpoch:runtimeStopIntents.nodeEpoch,leaseEpoch:runtimeStopIntents.leaseEpoch,sourceGenerationRef:runtimeStopIntents.sourceGenerationRef,reason:runtimeStopIntents.reason,expiresAt:runtimeStopIntents.expiresAt,consumedAt:runtimeStopIntents.consumedAt,consumedByEventId:runtimeStopIntents.consumedByEventId,createdByKind:runtimeStopIntents.createdByKind,createdById:runtimeStopIntents.createdById,correlationId:runtimeStopIntents.correlationId,drainRequestId:runtimeStopIntents.drainRequestId,rolloutRevision:runtimeStopIntents.rolloutRevision,rolloutEligibilityHash:runtimeStopIntents.rolloutEligibilityHash,cancelledAt:runtimeStopIntents.cancelledAt,cancelReason:runtimeStopIntents.cancelReason,dispatchStartedAt:runtimeStopIntents.dispatchStartedAt}}async function loadIntent2(db,intentId){const rows8=await db.select(intentSelection2()).from(runtimeStopIntents).where(eq61(runtimeStopIntents.id,intentId));return rows8[0]??null}async function createRuntimeStopIntentInTransaction(input2){if(!Number.isSafeInteger(input2.ttlMs)||input2.ttlMs<1e3||input2.ttlMs>60*60*1e3){return fail46("RUNTIME_STOP_INTENT_TTL_INVALID")}if(!Number.isSafeInteger(input2.appId)||input2.appId<=0||!["controller","operator","platform"].includes(input2.createdByKind)||!/^[A-Za-z0-9_.:@/-]{1,128}$/u.test(input2.createdById)||!/^[A-Za-z0-9_.:@/-]{1,128}$/u.test(input2.correlationId)){return fail46("RUNTIME_STOP_INTENT_INPUT_INVALID")}const now=input2.now??new Date;const desiredRows=await input2.db.select().from(appRuntimeDesiredState).where(eq61(appRuntimeDesiredState.appId,input2.appId));const currentRows=await input2.db.select().from(appDeploymentActivations).where(and55(eq61(appDeploymentActivations.id,input2.currentActivationId),eq61(appDeploymentActivations.appId,input2.appId)));const instanceRows=await input2.db.select({instanceId:appRuntimeInstances.instanceId,appId:appRuntimeInstances.appId,deploymentId:appRuntimeInstances.deploymentId,activationId:appRuntimeInstances.activationId,sourceGenerationRef:appRuntimeInstances.sourceGenerationRef,nodeId:appRuntimeInstances.nodeId,nodeEpoch:appRuntimeInstances.nodeEpoch,leaseEpoch:appRuntimeInstances.leaseEpoch,runnerRef:appRuntimeInstances.runnerRef,processIdentityHash:appRuntimeInstances.processIdentityHash,pid:appRuntimeInstances.pid,state:appRuntimeInstances.state}).from(appRuntimeInstances).where(and55(eq61(appRuntimeInstances.instanceId,input2.targetInstanceId),eq61(appRuntimeInstances.appId,input2.appId)));const desired=desiredRows[0];const current=currentRows[0];const instance=instanceRows[0];if(!desired||!current||!instance||desired.desiredActivationId!==current.id||desired.activationEpoch!==current.activationEpoch||desired.nodeId!==current.nodeId||desired.nodeEpoch!==current.nodeEpoch||current.routeAckEpoch!==current.activationEpoch){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}const stopsDesiredInstance=instance.activationId===current.id;if(stopsDesiredInstance){if(instance.nodeId!==current.nodeId||instance.nodeEpoch!==current.nodeEpoch){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}const alreadyDraining=desired.desiredRuntimeState==="draining"&¤t.state==="draining"&&instance.state==="draining";const serving=desired.desiredRuntimeState==="serving"&¤t.state==="serving"&&instance.state==="serving";if(input2.reason==="deploy_replace"||!serving&&!alreadyDraining){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}if(serving){const desiredUpdates=await input2.db.update(appRuntimeDesiredState).set({desiredRuntimeState:"draining",updatedAt:now}).where(and55(eq61(appRuntimeDesiredState.appId,input2.appId),eq61(appRuntimeDesiredState.desiredActivationId,current.id),eq61(appRuntimeDesiredState.activationEpoch,current.activationEpoch),eq61(appRuntimeDesiredState.nodeEpoch,current.nodeEpoch),eq61(appRuntimeDesiredState.desiredRuntimeState,"serving"))).returning({appId:appRuntimeDesiredState.appId});const activationUpdates=await input2.db.update(appDeploymentActivations).set({state:"draining",updatedAt:now}).where(and55(eq61(appDeploymentActivations.id,current.id),eq61(appDeploymentActivations.appId,input2.appId),eq61(appDeploymentActivations.state,"serving"))).returning({id:appDeploymentActivations.id});const instanceUpdates=await input2.db.update(appRuntimeInstances).set({state:"draining",updatedAt:now}).where(and55(eq61(appRuntimeInstances.instanceId,instance.instanceId),eq61(appRuntimeInstances.appId,input2.appId),eq61(appRuntimeInstances.nodeEpoch,instance.nodeEpoch),eq61(appRuntimeInstances.leaseEpoch,instance.leaseEpoch),eq61(appRuntimeInstances.state,"serving"))).returning({id:appRuntimeInstances.instanceId});if(!desiredUpdates[0]||!activationUpdates[0]||!instanceUpdates[0]){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}}}else{if(input2.reason!=="deploy_replace"||current.state!=="serving"||!["serving","draining"].includes(instance.state)){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}const oldActivationRows=await input2.db.select({state:appDeploymentActivations.state,nodeId:appDeploymentActivations.nodeId,nodeEpoch:appDeploymentActivations.nodeEpoch}).from(appDeploymentActivations).where(and55(eq61(appDeploymentActivations.id,instance.activationId),eq61(appDeploymentActivations.appId,input2.appId),eq61(appDeploymentActivations.deploymentId,instance.deploymentId)));if(oldActivationRows[0]?.state!=="draining"||oldActivationRows[0].nodeId!==instance.nodeId||oldActivationRows[0].nodeEpoch!==instance.nodeEpoch){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}}if(input2.reason==="app_delete"){await cancelUnsignalledIntentsOfTerminalDrains({tx:input2.db,appId:input2.appId,instanceId:instance.instanceId,now})}const pending=await input2.db.select(intentSelection2()).from(runtimeStopIntents).where(and55(eq61(runtimeStopIntents.appId,input2.appId),eq61(runtimeStopIntents.instanceId,instance.instanceId),isNull23(runtimeStopIntents.consumedAt),isNull23(runtimeStopIntents.cancelledAt),gt12(runtimeStopIntents.expiresAt,now)));if(pending[0]){if(matchesRequestIdentity(pending[0],input2)){return pending[0]}return fail46("RUNTIME_STOP_INTENT_IDENTITY_MISMATCH")}const expired=await input2.db.select(intentSelection2()).from(runtimeStopIntents).where(and55(eq61(runtimeStopIntents.appId,input2.appId),eq61(runtimeStopIntents.instanceId,instance.instanceId),isNull23(runtimeStopIntents.consumedAt),isNull23(runtimeStopIntents.cancelledAt),lte9(runtimeStopIntents.expiresAt,now)));if(expired.length>1)return fail46("RUNTIME_STOP_INTENT_IDENTITY_MISMATCH");if(expired[0]){const previous=expired[0];if(!matchesBindingIdentity(previous,instance)||!matchesRequestIdentity(previous,input2)){return fail46("RUNTIME_STOP_INTENT_IDENTITY_MISMATCH")}const renewed=await input2.db.update(runtimeStopIntents).set({expiresAt:new Date(now.getTime()+input2.ttlMs)}).where(and55(eq61(runtimeStopIntents.id,previous.id),isNull23(runtimeStopIntents.consumedAt),lte9(runtimeStopIntents.expiresAt,now))).returning(intentSelection2());if(!renewed[0])return fail46("RUNTIME_STOP_INTENT_RENEWAL_FAILED");return renewed[0]}const id=`stop_${sha25622(JSON.stringify([input2.appId,current.id,current.activationEpoch,instance.instanceId,instance.leaseEpoch,input2.reason,input2.createdByKind,input2.createdById,input2.correlationId,input2.drainRequestId??null])).slice(0,32)}`;await input2.db.insert(runtimeStopIntents).values({id,appId:input2.appId,deploymentId:instance.deploymentId,activationId:instance.activationId,instanceId:instance.instanceId,nodeId:instance.nodeId,nodeEpoch:instance.nodeEpoch,leaseEpoch:instance.leaseEpoch,sourceGenerationRef:instance.sourceGenerationRef,reason:input2.reason,expiresAt:new Date(now.getTime()+input2.ttlMs),createdByKind:input2.createdByKind,createdById:input2.createdById,correlationId:input2.correlationId,drainRequestId:input2.drainRequestId??null,rolloutRevision:input2.rolloutRevision??null,rolloutEligibilityHash:input2.rolloutEligibilityHash??null}).onConflictDoNothing({target:runtimeStopIntents.id});const intent=await loadIntent2(input2.db,id);if(!intent||intent.appId!==input2.appId||intent.instanceId!==instance.instanceId||!matchesLeaseIdentity(intent,instance)||!matchesRequestIdentity(intent,input2)){return fail46("RUNTIME_STOP_INTENT_IDENTITY_MISMATCH")}if(!intent.consumedAt&&intent.expiresAt<=now){const renewed=await input2.db.update(runtimeStopIntents).set({expiresAt:new Date(now.getTime()+input2.ttlMs)}).where(and55(eq61(runtimeStopIntents.id,id),isNull23(runtimeStopIntents.consumedAt),lte9(runtimeStopIntents.expiresAt,now),eq61(runtimeStopIntents.createdByKind,input2.createdByKind),eq61(runtimeStopIntents.createdById,input2.createdById),eq61(runtimeStopIntents.correlationId,input2.correlationId))).returning(intentSelection2());if(!renewed[0])return fail46("RUNTIME_STOP_INTENT_RENEWAL_FAILED");return renewed[0]}return intent}async function createRuntimeStopIntent(input2){const acquireLock=input2.acquireLock??((tx,key2)=>tx.execute(sql148`SELECT pg_advisory_xact_lock(hashtextextended(${key2}::text, 0))`));return input2.db.transaction(async tx=>{await acquireLock(tx,`runtime-stop-intent:${input2.appId}`);return createRuntimeStopIntentInTransaction({...input2,db:tx})})}async function consumeRuntimeStopIntent(input2){const unexpected={expected:false,consumed:false,replayed:false,restartBudgetDelta:1};if(!Number.isSafeInteger(input2.eventId)||input2.eventId<=0)return unexpected;return input2.db.transaction(async tx=>{const now=input2.now??new Date;const consumed=await tx.update(runtimeStopIntents).set({consumedAt:sql148`GREATEST(${toPostgresTimestamp2(now)}, ${runtimeStopIntents.createdAt})`,consumedByEventId:input2.eventId}).where(and55(eq61(runtimeStopIntents.id,input2.intentId),eq61(runtimeStopIntents.appId,input2.appId),input2.expectedIntentId?eq61(runtimeStopIntents.id,input2.expectedIntentId):sql148`true`,input2.expectedIntentReason?eq61(runtimeStopIntents.reason,input2.expectedIntentReason):sql148`true`,eq61(runtimeStopIntents.instanceId,input2.instanceId),input2.expectedNodeId?eq61(runtimeStopIntents.nodeId,input2.expectedNodeId):sql148`true`,eq61(runtimeStopIntents.nodeEpoch,input2.nodeEpoch),eq61(runtimeStopIntents.leaseEpoch,input2.leaseEpoch),isNull23(runtimeStopIntents.consumedAt),isNull23(runtimeStopIntents.cancelledAt),or19(gt12(runtimeStopIntents.expiresAt,now),isNotNull9(runtimeStopIntents.dispatchStartedAt),input2.allowExpiredAfterExactObservation?sql148`true`:sql148`false`),input2.allowExpiredAfterExactObservation?exists3(tx.select({one:sql148`1`}).from(appRuntimeDesiredState).where(and55(eq61(appRuntimeDesiredState.appId,input2.appId),eq61(appRuntimeDesiredState.authorityMode,"enforce"),input2.expectedNodeId?eq61(appRuntimeDesiredState.nodeId,input2.expectedNodeId):sql148`true`,or19(and55(eq61(appRuntimeDesiredState.desiredRuntimeState,"absent"),isNull23(appRuntimeDesiredState.desiredActivationId)),and55(isNotNull9(appRuntimeDesiredState.desiredActivationId),ne14(appRuntimeDesiredState.desiredActivationId,runtimeStopIntents.activationId)),and55(eq61(appRuntimeDesiredState.desiredActivationId,runtimeStopIntents.activationId),eq61(appRuntimeDesiredState.desiredRuntimeState,"draining"),sql148`EXISTS (SELECT 1 FROM runtime_drain_requests AS ended_drain
|
|
10912
|
+
`);return new Set(postgresExecuteRows(result3).map(row=>Number(row.app_id)))}var init_runtime_pending_stop_candidate_filter=__esm({"../platform/src/runtime-pending-stop-candidate-filter.ts"(){"use strict";init_postgres_execute_rows()}});function unavailable(){throw new Error("RUNTIME_STOP_EFFECT_FEATURE_BARRIER_UNAVAILABLE")}function validPort3(value2){if(typeof value2!=="string"&&typeof value2!=="number"||!/^\d+$/u.test(String(value2)))return unavailable();const port=Number(value2);return Number.isSafeInteger(port)&&port>0&&port<=65535?port:unavailable()}function resolveRuntimeStopEffectConfiguration(input2){const required3=runtimeStopEffectHandoffRequired(input2.environment.GENCOW_RUNTIME_STOP_EFFECT_HANDOFF)||input2.stopEffectHandoffRequired===true;if(!required3)return{stopEffectHandoffRequired:false};const nodeId=(input2.currentNodeId??input2.environment.GENCOW_NODE_ID)?.trim();if(input2.currentNodeId!=null&&input2.environment.GENCOW_NODE_ID?.trim()&&input2.currentNodeId.trim()!==input2.environment.GENCOW_NODE_ID.trim())return unavailable();if(!nodeId||!/^[A-Za-z0-9._:-]{1,128}$/u.test(nodeId)||nodeId==="unknown-node"||!Number.isSafeInteger(input2.processId)||input2.processId<1)return unavailable();const owner=`${nodeId}:${input2.processId}`;if(input2.stopEffectOwnerId!==void 0&&input2.stopEffectOwnerId!==owner)return unavailable();const slots=[input2.currentSlotId,input2.environment.GENCOW_PLATFORM_SLOT].filter(slot=>slot!==void 0);const ports=slots.map(slot=>{const port=deploymentExecutorSlotPort(slot);return port===null?unavailable():Number(port)});if(input2.currentPort!==void 0)ports.push(validPort3(input2.currentPort));if(input2.environment.PORT!==void 0)ports.push(validPort3(input2.environment.PORT));let url2;if(input2.stopEffectAuthorizationUrl!==void 0){try{url2=new URL(input2.stopEffectAuthorizationUrl)}catch{return unavailable()}if(url2.protocol!=="http:"||url2.hostname!=="127.0.0.1"||url2.username||url2.password||url2.search||url2.hash||url2.pathname!==RUNTIME_STOP_EFFECT_AUTHORIZATION_PATH||!url2.port)return unavailable();ports.push(validPort3(url2.port))}if(!ports.length||ports.some(port=>port!==ports[0]))return unavailable();return{stopEffectHandoffRequired:true,stopEffectOwnerId:owner,stopEffectAuthorizationUrl:url2?.href??`http://127.0.0.1:${ports[0]}${RUNTIME_STOP_EFFECT_AUTHORIZATION_PATH}`}}function withRuntimeStopEffectConfiguration(input2,environment,processId){return{...input2,...resolveRuntimeStopEffectConfiguration({...input2,environment,processId})}}var RUNTIME_STOP_EFFECT_AUTHORIZATION_PATH;var init_runtime_stop_effect_configuration=__esm({"../platform/src/runtime-stop-effect-configuration.ts"(){"use strict";init_deployment_executor_lifecycle_authority();init_runtime_stop_effect_store();RUNTIME_STOP_EFFECT_AUTHORIZATION_PATH="/internal/runtime-stop-effects/authorize"}});var OWNER_BY_REASON,EXECUTION_OWNERS,REASONS_BY_OWNER;var init_runtime_explicit_stop_owner_contract=__esm({"../platform/src/runtime-explicit-stop-owner-contract.ts"(){"use strict";OWNER_BY_REASON=Object.freeze({operator_stop:"deployment_executor",app_delete:"deployment_executor",freeze:"dedicated_workflow",backup_restore:"dedicated_workflow",platform_shutdown:"dedicated_workflow"});EXECUTION_OWNERS=Object.freeze(["public_platform","deployment_executor","dedicated_workflow"]);REASONS_BY_OWNER=Object.freeze(Object.fromEntries(EXECUTION_OWNERS.map(owner=>[owner,Object.freeze(Object.keys(OWNER_BY_REASON).filter(reason=>OWNER_BY_REASON[reason]===owner))])))}});import{and as and48,eq as eq53,inArray as inArray27,isNotNull as isNotNull4,isNull as isNull17,lte as lte7,or as or16}from"drizzle-orm";async function releaseRejectedStopDispatch(input2){return input2.db.transaction(async tx=>{const released=await tx.update(runtimeStopIntents).set({dispatchStartedAt:null,effectOwnerId:null,effectLeaseExpiresAt:null,effectToken:null,effectBindingDigest:null,effectPhase:"none",effectObservedAt:null,effectOutcomeCode:null}).where(and48(eq53(runtimeStopIntents.id,input2.intentId),eq53(runtimeStopIntents.appId,input2.appId),inArray27(runtimeStopIntents.reason,["app_delete",...AUTOMATIC_IDLE_STOP_REASONS]),isNotNull4(runtimeStopIntents.dispatchStartedAt),isNull17(runtimeStopIntents.consumedAt),isNull17(runtimeStopIntents.cancelledAt),or16(and48(eq53(runtimeStopIntents.effectPhase,"observed_changed"),eq53(runtimeStopIntents.effectOutcomeCode,RUNTIME_STOP_DISPATCH_REJECTED_OUTCOME)),and48(eq53(runtimeStopIntents.effectPhase,"node_receipt_pending"),isNotNull4(runtimeStopIntents.effectLeaseExpiresAt),lte7(runtimeStopIntents.effectLeaseExpiresAt,input2.now??new Date),isNull17(runtimeStopIntents.effectObservedAt))),isNull17(runtimeStopIntents.effectPreSyscallAt),isNull17(runtimeStopIntents.effectSyscallAckAt))).returning({drainRequestId:runtimeStopIntents.drainRequestId});if(!released[0])return false;if(released[0].drainRequestId){await tx.update(runtimeDrainRequests).set({state:"armed",updatedAt:new Date}).where(and48(eq53(runtimeDrainRequests.id,released[0].drainRequestId),eq53(runtimeDrainRequests.appId,input2.appId),eq53(runtimeDrainRequests.state,"dispatched")))}return true})}var RUNTIME_STOP_DISPATCH_REJECTED_OUTCOME;var init_runtime_stop_dispatch_rejection_release=__esm({"../platform/src/runtime-stop-dispatch-rejection-release.ts"(){"use strict";init_schema();init_runtime_automatic_idle_contract();RUNTIME_STOP_DISPATCH_REJECTED_OUTCOME="RUNTIME_STOP_DISPATCH_REJECTED"}});import{and as and49,eq as eq54,inArray as inArray28,isNotNull as isNotNull5,isNull as isNull18,lte as lte8,or as or17}from"drizzle-orm";async function restoreUndispatchedDrainProjection(input2){const intentRows=await input2.tx.select({dispatchStartedAt:runtimeStopIntents.dispatchStartedAt,consumedAt:runtimeStopIntents.consumedAt}).from(runtimeStopIntents).where(eq54(runtimeStopIntents.drainRequestId,input2.drain.id));if(intentRows.some(intent=>intent.dispatchStartedAt||intent.consumedAt))return false;await Promise.all([input2.tx.update(appRuntimeDesiredState).set({desiredRuntimeState:"serving",updatedAt:input2.now}).where(and49(eq54(appRuntimeDesiredState.appId,input2.drain.appId),eq54(appRuntimeDesiredState.desiredActivationId,input2.drain.activationId),eq54(appRuntimeDesiredState.desiredRuntimeState,"draining"))),input2.tx.update(appDeploymentActivations).set({state:"serving",updatedAt:input2.now}).where(and49(eq54(appDeploymentActivations.id,input2.drain.activationId),eq54(appDeploymentActivations.appId,input2.drain.appId),eq54(appDeploymentActivations.state,"draining"))),input2.tx.update(appRuntimeInstances).set({state:"serving",updatedAt:input2.now}).where(and49(eq54(appRuntimeInstances.instanceId,input2.drain.instanceId),eq54(appRuntimeInstances.appId,input2.drain.appId),eq54(appRuntimeInstances.state,"draining")))]);return true}async function retireExpiredUndispatchedDrain(input2){const intentRows=await input2.tx.select({id:runtimeStopIntents.id,dispatchStartedAt:runtimeStopIntents.dispatchStartedAt,consumedAt:runtimeStopIntents.consumedAt}).from(runtimeStopIntents).where(eq54(runtimeStopIntents.drainRequestId,input2.drain.id));const intent=intentRows[0];if(intent?.dispatchStartedAt||intent?.consumedAt)return false;if(intent){await input2.tx.update(runtimeStopIntents).set({cancelledAt:input2.now,cancelReason:"expired_before_dispatch"}).where(and49(eq54(runtimeStopIntents.id,intent.id),isNull18(runtimeStopIntents.cancelledAt)))}const cancelled=await input2.tx.update(runtimeDrainRequests).set({state:"cancelled",cancelReason:"expired_before_dispatch",updatedAt:input2.now}).where(and49(eq54(runtimeDrainRequests.id,input2.drain.id),inArray28(runtimeDrainRequests.state,["planned","armed"]))).returning({id:runtimeDrainRequests.id});if(!cancelled[0])throw new Error("RUNTIME_EXPLICIT_STOP_RETRY_CAS_FAILED");const terminalized=await input2.tx.update(runtimeLifecycleRequests).set({state:"failed",terminalResultCode:"RUNTIME_EXPLICIT_DRAIN_EXPIRED",leaseOwner:null,leaseExpiresAt:null,updatedAt:input2.now}).where(and49(eq54(runtimeLifecycleRequests.id,input2.drain.lifecycleRequestId),inArray28(runtimeLifecycleRequests.state,["accepted","queued","executing"]))).returning({id:runtimeLifecycleRequests.id});if(!terminalized[0]||!await restoreUndispatchedDrainProjection(input2)){throw new Error("RUNTIME_EXPLICIT_STOP_RETRY_CAS_FAILED")}return true}async function retireBlockedUndispatchedDrainForReplan(input2){const intents=await input2.tx.select({id:runtimeStopIntents.id,cancelledAt:runtimeStopIntents.cancelledAt,dispatchStartedAt:runtimeStopIntents.dispatchStartedAt,consumedAt:runtimeStopIntents.consumedAt,effectPhase:runtimeStopIntents.effectPhase}).from(runtimeStopIntents).where(eq54(runtimeStopIntents.drainRequestId,input2.drain.id));if(intents.some(intent=>intent.dispatchStartedAt||intent.consumedAt||intent.effectPhase!=="none")){return false}for(const intent of intents.filter(row=>row.cancelledAt===null)){await input2.tx.update(runtimeStopIntents).set({cancelledAt:input2.now,cancelReason:"drain_expired_blocked"}).where(and49(eq54(runtimeStopIntents.id,intent.id),isNull18(runtimeStopIntents.cancelledAt)))}return restoreUndispatchedDrainProjection(input2)}async function terminalizeExpiredUndispatchedStopForDelete(input2){if(!EXPLICIT_STOP_REASONS.includes(input2.drain.reason)||input2.drain.expiresAt>input2.now)return false;const keys2=["deploymentId","activationId","instanceId","nodeId","nodeEpoch","leaseEpoch"];if(keys2.some(key2=>input2.drain[key2]!==input2.expectedBinding[key2]))return false;const binding=await input2.tx.select({id:appRuntimeInstances.instanceId}).from(appRuntimeInstances).where(and49(eq54(appRuntimeInstances.appId,input2.drain.appId),eq54(appRuntimeInstances.deploymentId,input2.expectedBinding.deploymentId),eq54(appRuntimeInstances.activationId,input2.expectedBinding.activationId),eq54(appRuntimeInstances.instanceId,input2.expectedBinding.instanceId),eq54(appRuntimeInstances.nodeId,input2.expectedBinding.nodeId),eq54(appRuntimeInstances.nodeEpoch,input2.expectedBinding.nodeEpoch),eq54(appRuntimeInstances.leaseEpoch,input2.expectedBinding.leaseEpoch))).for("update");if(binding.length!==1)return false;return retireExpiredUndispatchedDrain(input2)}async function cancelExpiredUndispatchedIntentsOfTerminalDrains(input2){const cancelled=await input2.tx.update(runtimeStopIntents).set({cancelledAt:input2.now,cancelReason:"expired_before_dispatch"}).where(and49(eq54(runtimeStopIntents.appId,input2.appId),eq54(runtimeStopIntents.instanceId,input2.instanceId),input2.intentId?eq54(runtimeStopIntents.id,input2.intentId):and49(eq54(runtimeStopIntents.reason,"app_delete"),lte8(runtimeStopIntents.expiresAt,input2.now)),isNull18(runtimeStopIntents.consumedAt),isNull18(runtimeStopIntents.cancelledAt),isNull18(runtimeStopIntents.dispatchStartedAt),isNull18(runtimeStopIntents.effectPreSyscallAt),inArray28(runtimeStopIntents.drainRequestId,input2.tx.select({id:runtimeDrainRequests.id}).from(runtimeDrainRequests).where(and49(eq54(runtimeDrainRequests.appId,input2.appId),inArray28(runtimeDrainRequests.state,["blocked","cancelled"])))))).returning({id:runtimeStopIntents.id});return cancelled.length}async function cancelUnsignalledIntentsOfTerminalDrains(input2){const cancelled=await input2.tx.update(runtimeStopIntents).set({cancelledAt:input2.now,cancelReason:"dispatch_rejected_unsignalled"}).where(and49(eq54(runtimeStopIntents.appId,input2.appId),eq54(runtimeStopIntents.instanceId,input2.instanceId),isNull18(runtimeStopIntents.consumedAt),isNull18(runtimeStopIntents.cancelledAt),isNotNull5(runtimeStopIntents.dispatchStartedAt),isNull18(runtimeStopIntents.effectPreSyscallAt),isNull18(runtimeStopIntents.effectSyscallAckAt),lte8(runtimeStopIntents.expiresAt,input2.now),or17(and49(eq54(runtimeStopIntents.effectPhase,"observed_changed"),eq54(runtimeStopIntents.effectOutcomeCode,RUNTIME_STOP_DISPATCH_REJECTED_OUTCOME)),and49(eq54(runtimeStopIntents.effectPhase,"node_receipt_pending"),isNotNull5(runtimeStopIntents.effectLeaseExpiresAt),lte8(runtimeStopIntents.effectLeaseExpiresAt,input2.now),isNull18(runtimeStopIntents.effectObservedAt))),inArray28(runtimeStopIntents.drainRequestId,input2.tx.select({id:runtimeDrainRequests.id}).from(runtimeDrainRequests).where(and49(eq54(runtimeDrainRequests.appId,input2.appId),inArray28(runtimeDrainRequests.state,["blocked","cancelled"])))))).returning({id:runtimeStopIntents.id});return cancelled.length}var EXPLICIT_STOP_REASONS;var init_runtime_explicit_stop_expired_drain=__esm({"../platform/src/runtime-explicit-stop-expired-drain.ts"(){"use strict";init_schema();init_runtime_explicit_stop_owner_contract();init_runtime_stop_dispatch_rejection_release();EXPLICIT_STOP_REASONS=["app_delete","operator_stop","freeze","backup_restore","platform_shutdown"]}});function resolveRuntimeAppEnvironment(parentAppId){return parentAppId==null?"dev":"prod"}function resolveAutomaticScaleDownRolloutEnvironment(parentAppId,reason){if(!isAutomaticIdleStopReason(reason))return null;const appEnvironment=resolveRuntimeAppEnvironment(parentAppId);if(requiresIdleCertificationEvidence(reason))return appEnvironment;return appEnvironment==="dev"?"dev":null}var init_runtime_app_environment=__esm({"../platform/src/runtime-app-environment.ts"(){"use strict";init_runtime_automatic_idle_contract()}});import{and as and50,eq as eq55,inArray as inArray29,isNotNull as isNotNull6,isNull as isNull19,sql as sql144}from"drizzle-orm";function normalizeAllowlist2(value2){if(!Array.isArray(value2)||value2.length>1e4){throw new Error("RUNTIME_LIFECYCLE_ROLLOUT_ALLOWLIST_INVALID")}const normalized=[...new Set(value2)];if(normalized.length!==value2.length){throw new Error("RUNTIME_LIFECYCLE_ROLLOUT_ALLOWLIST_INVALID")}if(normalized.some(appId=>!Number.isSafeInteger(appId)||Number(appId)<=0)){throw new Error("RUNTIME_LIFECYCLE_ROLLOUT_ALLOWLIST_INVALID")}return normalized.sort((left,right)=>left-right)}function parseRuntimeLifecycleRolloutAllowlistJson(value2){try{return normalizeAllowlist2(JSON.parse(value2))}catch{return null}}function validateRuntimeLifecycleRolloutConfig(input2){if(input2.mode==="enforce"&&(input2.enforceAll&&input2.allowlistAppIds.length!==0||!input2.enforceAll&&input2.allowlistAppIds.length===0)||input2.mode!=="enforce"&&(input2.enforceAll||input2.allowlistAppIds.length!==0)){throw new Error("RUNTIME_LIFECYCLE_ROLLOUT_CONFIGURATION_INVALID")}}function isRuntimeLifecycleRolloutAppEligible(input2){if(!Number.isSafeInteger(input2.appId)||input2.appId<=0)return false;let allowlistAppIds;try{allowlistAppIds=normalizeAllowlist2(input2.allowlistAppIds);validateRuntimeLifecycleRolloutConfig({mode:input2.mode,enforceAll:input2.enforceAll,allowlistAppIds})}catch{return false}return Boolean(input2.mode==="enforce"&&typeof input2.enforceAll==="boolean"&&Number.isSafeInteger(input2.revision)&&Number(input2.revision)>0&&(input2.expectedRevision===void 0||input2.revision===input2.expectedRevision)&&(input2.enforceAll||allowlistAppIds.includes(input2.appId)))}var init_runtime_lifecycle_rollout=__esm({"../platform/src/runtime-lifecycle-rollout.ts"(){"use strict";init_schema();init_runtime_app_environment();init_deployment_control_plane_rollout()}});var init_runtime_lifecycle_policy=__esm({"../platform/src/runtime-lifecycle-policy.ts"(){"use strict"}});function runtimeIdleCertificationControllerId(scope,appId){return`${scope==="prod"?RUNTIME_PROD_IDLE_CERTIFICATION_CONTROLLER_PREFIX:RUNTIME_QC_IDLE_CERTIFICATION_CONTROLLER_PREFIX}${appId}`}function idleCertificationRolloutShapeAllows(input2){const globallyEnforced=input2.enforceAll===true&&input2.allowlist?.length===0;if(input2.scope==="prod")return globallyEnforced;return globallyEnforced||input2.enforceAll===false&&input2.allowlist?.length===1&&input2.allowlist[0]===input2.appId}var RUNTIME_PROD_IDLE_CERTIFICATION_CONTROLLER_PREFIX,RUNTIME_QC_IDLE_CERTIFICATION_CONTROLLER_PREFIX;var init_runtime_idle_certification=__esm({"../platform/src/runtime-idle-certification.ts"(){"use strict";init_runtime_lifecycle_rollout();RUNTIME_PROD_IDLE_CERTIFICATION_CONTROLLER_PREFIX="runtime-prod-idle-certification-v1:";RUNTIME_QC_IDLE_CERTIFICATION_CONTROLLER_PREFIX="runtime-qc-idle-certification-v1:"}});import{eq as eq56}from"drizzle-orm";var init_runtime_legacy_idle_observation=__esm({"../platform/src/runtime-legacy-idle-observation.ts"(){"use strict";init_schema();init_runtime_automatic_idle_contract()}});import{createHash as createHash107}from"node:crypto";import{and as and51,eq as eq57,inArray as inArray30,isNull as isNull20,sql as sql145}from"drizzle-orm";function hash4(value2){return createHash107("sha256").update(JSON.stringify(value2)).digest("hex")}async function acquireAppLock(tx,appId){await tx.execute(sql145`SELECT pg_advisory_xact_lock(hashtextextended(${"app-activation:"+appId}::text, 0))`);await tx.execute(sql145`SELECT pg_advisory_xact_lock(hashtextextended(${"runtime-lifecycle:"+appId}::text, 0))`)}async function cancelAutomaticScaleDown(input2){const now=input2.now??new Date;return input2.db.transaction(async tx=>{const drainRows=await tx.select().from(runtimeDrainRequests).where(eq57(runtimeDrainRequests.id,input2.drainId));const drain=drainRows[0];if(!drain)return false;await(input2.acquireLock??acquireAppLock)(tx,drain.appId);const intentRows=await tx.select().from(runtimeStopIntents).where(eq57(runtimeStopIntents.drainRequestId,drain.id));const intent=intentRows[0];if(intent?.dispatchStartedAt||intent?.consumedAt)return false;if(intent){await tx.update(runtimeStopIntents).set({cancelledAt:now,cancelReason:input2.reason}).where(and51(eq57(runtimeStopIntents.id,intent.id),isNull20(runtimeStopIntents.cancelledAt)));await Promise.all([tx.update(appRuntimeDesiredState).set({desiredRuntimeState:"serving",updatedAt:now}).where(and51(eq57(appRuntimeDesiredState.appId,drain.appId),eq57(appRuntimeDesiredState.desiredActivationId,drain.activationId),eq57(appRuntimeDesiredState.desiredRuntimeState,"draining"))),tx.update(appDeploymentActivations).set({state:"serving",updatedAt:now}).where(and51(eq57(appDeploymentActivations.id,drain.activationId),eq57(appDeploymentActivations.appId,drain.appId),eq57(appDeploymentActivations.state,"draining"))),tx.update(appRuntimeInstances).set({state:"serving",updatedAt:now}).where(and51(eq57(appRuntimeInstances.instanceId,drain.instanceId),eq57(appRuntimeInstances.appId,drain.appId),eq57(appRuntimeInstances.state,"draining")))])}const cancelled=await tx.update(runtimeDrainRequests).set({state:"cancelled",cancelReason:input2.reason,updatedAt:now}).where(and51(eq57(runtimeDrainRequests.id,drain.id),inArray30(runtimeDrainRequests.state,["planned","armed"]))).returning({id:runtimeDrainRequests.id});if(!cancelled[0])return false;await tx.update(runtimeLifecycleRequests).set({state:"completed",terminalResultCode:"cancelled",updatedAt:now}).where(eq57(runtimeLifecycleRequests.id,drain.lifecycleRequestId));return true})}async function recordLegacyRuntimePreserveReplaceRemediation(input2){const now=input2.now??new Date;const evidenceHash=hash4(input2.evidence);const id=`remediation_${hash4([input2.appId,input2.code,evidenceHash]).slice(0,32)}`;await input2.db.insert(runtimeLifecycleRemediations).values({id,appId:input2.appId,instanceId:input2.instanceId??null,code:input2.code,evidenceHash,conflictCount:1,state:"pending",lastObservedAt:now,updatedAt:now}).onConflictDoUpdate({target:runtimeLifecycleRemediations.id,setWhere:isNull20(runtimeLifecycleRemediations.resolvedAt),set:{conflictCount:sql145`${runtimeLifecycleRemediations.conflictCount} + 1`,lastObservedAt:now,updatedAt:now}});return{id,evidenceHash}}var init_runtime_scale_down_store=__esm({"../platform/src/runtime-scale-down-store.ts"(){"use strict";init_schema();init_runtime_lifecycle_policy();init_runtime_app_environment();init_runtime_idle_certification();init_runtime_lifecycle_rollout();init_runtime_process_identity();init_runtime_stop_intent_store();init_runtime_automatic_idle_contract();init_runtime_legacy_idle_observation();init_deploy_contract_admission();init_runtime_owner_resolution();init_runtime_idle_certification()}});import{createHash as createHash108}from"node:crypto";import{and as and52,eq as eq58,gt as gt11,isNull as isNull21,sql as sql146}from"drizzle-orm";function sha25620(value2){return createHash108("sha256").update(value2).digest("hex")}function fail44(code){throw new Error(code)}function intentSelection(){return{id:runtimeStopIntents.id,appId:runtimeStopIntents.appId,deploymentId:runtimeStopIntents.deploymentId,activationId:runtimeStopIntents.activationId,instanceId:runtimeStopIntents.instanceId,nodeId:runtimeStopIntents.nodeId,nodeEpoch:runtimeStopIntents.nodeEpoch,leaseEpoch:runtimeStopIntents.leaseEpoch,sourceGenerationRef:runtimeStopIntents.sourceGenerationRef,reason:runtimeStopIntents.reason,expiresAt:runtimeStopIntents.expiresAt,consumedAt:runtimeStopIntents.consumedAt,consumedByEventId:runtimeStopIntents.consumedByEventId,createdByKind:runtimeStopIntents.createdByKind,createdById:runtimeStopIntents.createdById,correlationId:runtimeStopIntents.correlationId,drainRequestId:runtimeStopIntents.drainRequestId,rolloutRevision:runtimeStopIntents.rolloutRevision,rolloutEligibilityHash:runtimeStopIntents.rolloutEligibilityHash,cancelledAt:runtimeStopIntents.cancelledAt,cancelReason:runtimeStopIntents.cancelReason,dispatchStartedAt:runtimeStopIntents.dispatchStartedAt}}async function loadIntent(db,intentId){const rows8=await db.select(intentSelection()).from(runtimeStopIntents).where(eq58(runtimeStopIntents.id,intentId));return rows8[0]??null}async function dispatchRuntimeStopIntent(input2){if(input2.effectHandoffRequired&&!input2.effectOwnerId){return fail44("RUNTIME_STOP_EFFECT_FEATURE_BARRIER_UNAVAILABLE")}const now=input2.now??new Date;const target=await input2.db.transaction(async tx=>{let intent=await loadIntent(tx,input2.intentId);if(!intent||intent.consumedAt||intent.cancelledAt||intent.dispatchStartedAt||intent.expiresAt<=now){return fail44("RUNTIME_STOP_INTENT_NOT_PENDING")}if(intent.drainRequestId){const drainRows=await tx.select({drain:runtimeDrainRequests,parentAppId:apps.parentAppId}).from(runtimeDrainRequests).innerJoin(apps,eq58(apps.id,runtimeDrainRequests.appId)).where(eq58(runtimeDrainRequests.id,intent.drainRequestId));const row=drainRows[0];const drain=row?.drain;const automaticDrain=drain?isAutomaticIdleStopReason(drain.reason):false;if(!drain||drain.state!=="armed"||drain.appId!==intent.appId||drain.instanceId!==intent.instanceId||drain.rolloutRevision!==intent.rolloutRevision||drain.rolloutEligibilityHash!==intent.rolloutEligibilityHash){return fail44("RUNTIME_STOP_INTENT_DRAIN_INVALID")}const activityRows=await tx.select().from(appRuntimeActivityState).where(eq58(appRuntimeActivityState.appId,intent.appId));const activity=activityRows[0];const appDeleteWithoutActivityObservation=drain.reason==="app_delete"&&!activity;if(!appDeleteWithoutActivityObservation&&(!activity||!activity.observationComplete||activity.activityEpoch!==drain.activityEpoch||activity.activationId!==drain.activationId||activity.instanceId!==drain.instanceId||activity.nodeId!==drain.nodeId||activity.nodeEpoch!==drain.nodeEpoch||activity.httpActive!==0||activity.streamActive!==0||activity.websocketActive!==0||activity.workloadActive!==0)){return fail44("RUNTIME_STOP_INTENT_ACTIVITY_CHANGED")}if(automaticDrain){const rolloutEnvironment=resolveAutomaticScaleDownRolloutEnvironment(row.parentAppId,drain.reason);if(!rolloutEnvironment)return fail44("RUNTIME_STOP_INTENT_ROLLOUT_STALE");const acquireRolloutFence=input2.acquireRolloutFence??((fenceTx,environment)=>fenceTx.execute(sql146`SELECT pg_advisory_xact_lock(hashtextextended(${"runtime-lifecycle-rollout:"+environment}::text, 0))`));await acquireRolloutFence(tx,rolloutEnvironment);const rolloutRows=await tx.select().from(runtimeLifecycleRollouts).where(eq58(runtimeLifecycleRollouts.environment,rolloutEnvironment));const rollout=rolloutRows[0];const allowlist2=parseRuntimeLifecycleRolloutAllowlistJson(rollout?.allowlistJson??"null");const validRollout=isRuntimeLifecycleRolloutAppEligible({mode:rollout?.mode,enforceAll:rollout?.enforceAll,allowlistAppIds:allowlist2,revision:rollout?.revision,expectedRevision:intent.rolloutRevision,appId:intent.appId});const validCertificationAuthority=drain.reason!=="idle_certification"||Boolean(rollout&&allowlist2&&idleCertificationRolloutShapeAllows({scope:row.parentAppId==null?"qc":"prod",enforceAll:rollout.enforceAll,allowlist:allowlist2,appId:intent.appId})&&intent.createdById===sha25620(JSON.stringify(runtimeIdleCertificationControllerId(row.parentAppId==null?"qc":"prod",intent.appId))));if(!validRollout||!rollout||!allowlist2||!validCertificationAuthority){return fail44("RUNTIME_STOP_INTENT_ROLLOUT_STALE")}}intent=await loadIntent(tx,input2.intentId);if(!intent||intent.cancelledAt||intent.consumedAt||intent.dispatchStartedAt||intent.expiresAt<=now){return fail44("RUNTIME_STOP_INTENT_NOT_PENDING")}}const instances=await tx.select({instanceId:appRuntimeInstances.instanceId,appId:appRuntimeInstances.appId,deploymentId:appRuntimeInstances.deploymentId,activationId:appRuntimeInstances.activationId,nodeEpoch:appRuntimeInstances.nodeEpoch,leaseEpoch:appRuntimeInstances.leaseEpoch,runnerRef:appRuntimeInstances.runnerRef,runnerKind:appRuntimeInstances.runnerKind,processIdentityHash:appRuntimeInstances.processIdentityHash,pid:appRuntimeInstances.pid,pidStartTicks:appRuntimeInstances.pidStartTicks,processGroupId:appRuntimeInstances.processGroupId,processGroupStartTicks:appRuntimeInstances.processGroupStartTicks,cgroupRefHash:appRuntimeInstances.cgroupRefHash,runnerSessionId:appRuntimeInstances.runnerSessionId,port:appRuntimeInstances.port,readyContractHash:appRuntimeInstances.readyContractHash,state:appRuntimeInstances.state}).from(appRuntimeInstances).where(and52(eq58(appRuntimeInstances.instanceId,intent.instanceId),eq58(appRuntimeInstances.appId,intent.appId),eq58(appRuntimeInstances.deploymentId,intent.deploymentId),eq58(appRuntimeInstances.activationId,intent.activationId),eq58(appRuntimeInstances.nodeEpoch,intent.nodeEpoch),eq58(appRuntimeInstances.leaseEpoch,intent.leaseEpoch)));const instance=instances[0];if(!instance||instance.processIdentityHash!==input2.observedProcessIdentityHash||!isCompleteRuntimeProcessIdentity(instance)||!["serving","draining"].includes(instance.state)){return fail44("RUNTIME_STOP_OWNERSHIP_AMBIGUOUS")}if(input2.assertControllerActive&&!await input2.assertControllerActive(tx)){return fail44("RUNTIME_STOP_CONTROLLER_INACTIVE")}let stopEffect;if(input2.effectOwnerId){stopEffect=await claimRuntimeStopEffectInTransaction({tx,ownerId:input2.effectOwnerId,now,intent:{intentId:intent.id,appId:intent.appId,deploymentId:intent.deploymentId,activationId:intent.activationId,instanceId:intent.instanceId,nodeId:intent.nodeId,nodeEpoch:intent.nodeEpoch,leaseEpoch:intent.leaseEpoch,sourceGenerationRef:intent.sourceGenerationRef,runnerKind:instance.runnerKind,runnerRef:instance.runnerRef,processIdentityHash:instance.processIdentityHash,pid:instance.pid,pidStartTicks:instance.pidStartTicks,processGroupId:instance.processGroupId,processGroupStartTicks:instance.processGroupStartTicks,cgroupRefHash:instance.cgroupRefHash,runnerSessionId:instance.runnerSessionId,port:instance.port,readyContractHash:instance.readyContractHash}})}else{const claimed=await tx.update(runtimeStopIntents).set({dispatchStartedAt:now}).where(and52(eq58(runtimeStopIntents.id,intent.id),isNull21(runtimeStopIntents.consumedAt),isNull21(runtimeStopIntents.cancelledAt),isNull21(runtimeStopIntents.dispatchStartedAt),gt11(runtimeStopIntents.expiresAt,now))).returning({id:runtimeStopIntents.id});if(!claimed[0])return fail44("RUNTIME_STOP_INTENT_DISPATCH_CAS_FAILED")}if(intent.drainRequestId){const dispatched=await tx.update(runtimeDrainRequests).set({state:"dispatched",updatedAt:now}).where(and52(eq58(runtimeDrainRequests.id,intent.drainRequestId),eq58(runtimeDrainRequests.state,"armed"))).returning({id:runtimeDrainRequests.id});if(!dispatched[0])return fail44("RUNTIME_STOP_INTENT_DRAIN_DISPATCH_CAS_FAILED")}return{intentId:intent.id,instanceId:intent.instanceId,nodeId:intent.nodeId,nodeEpoch:intent.nodeEpoch,leaseEpoch:intent.leaseEpoch,processIdentityHash:instance.processIdentityHash,runnerRef:instance.runnerRef,pid:instance.pid,pidStartTicks:instance.pidStartTicks,processGroupId:instance.processGroupId,processGroupStartTicks:instance.processGroupStartTicks,cgroupRefHash:instance.cgroupRefHash,runnerSessionId:instance.runnerSessionId,...stopEffect?{stopEffect}:{}}});try{await input2.stop(target)}catch(error62){if(target.stopEffect){await revokeRuntimeStopEffect({db:input2.db,capability:target.stopEffect,outcomeCode:RUNTIME_STOP_DISPATCH_REJECTED_OUTCOME}).catch(()=>false)}throw error62}return target}var init_runtime_stop_intent_dispatch=__esm({"../platform/src/runtime-stop-intent-dispatch.ts"(){"use strict";init_schema();init_runtime_process_identity();init_runtime_lifecycle_rollout();init_runtime_app_environment();init_runtime_automatic_idle_contract();init_runtime_scale_down_store();init_runtime_idle_certification();init_runtime_stop_effect_store();init_runtime_stop_dispatch_rejection_release()}});import{createHash as createHash109}from"node:crypto";import{and as and53,eq as eq59,inArray as inArray31,isNotNull as isNotNull8,isNull as isNull22,sql as sql147}from"drizzle-orm";function sha25621(value2){return createHash109("sha256").update(value2).digest("hex")}async function loadIdleCertificationEvidence(input2){const[routeRows,activationRows]=await Promise.all([input2.tx.select({environment:appServingRouteAuthorities.environment,appInstanceId:appServingRouteAuthorities.appInstanceId,canonicalAppInstanceId:apps.instanceId,routeEpoch:appServingRouteAuthorities.routeEpoch,entryHash:appServingRouteAuthorities.entryHash}).from(appServingRouteAuthorities).innerJoin(apps,eq59(apps.id,appServingRouteAuthorities.appId)).where(eq59(appServingRouteAuthorities.appId,input2.appId)),input2.tx.select({activationEpoch:appDeploymentActivations.activationEpoch}).from(appDeploymentActivations).where(and53(eq59(appDeploymentActivations.id,input2.activationId),eq59(appDeploymentActivations.appId,input2.appId),eq59(appDeploymentActivations.deploymentId,input2.deploymentId)))]);const route=routeRows[0];const activation=activationRows[0];if(!route||!SERVING_ROUTE_ENVIRONMENTS.has(route.environment)||route.appInstanceId!==route.canonicalAppInstanceId||!Number.isSafeInteger(route.routeEpoch)||route.routeEpoch<=0||!/^[a-f0-9]{64}$/u.test(route.entryHash)||!activation?.activationEpoch){return null}const payload=JSON.stringify({protocolVersion:1,servingRouteEnvironment:route.environment,appInstanceId:route.appInstanceId,routeEpoch:route.routeEpoch,entryHash:route.entryHash,activationId:input2.activationId,activationEpoch:activation.activationEpoch});return{digest:sha25621(payload),payload}}async function recoverDispatchedIdleStopForResume(input2){const now=input2.now??new Date;return input2.db.transaction(async tx=>{await tx.execute(sql147`SELECT pg_advisory_xact_lock(hashtextextended(${`runtime-lifecycle:${input2.appId}`}::text, 0))`);const rows8=await tx.select({intentId:runtimeStopIntents.id,drainId:runtimeDrainRequests.id,lifecycleRequestId:runtimeDrainRequests.lifecycleRequestId}).from(runtimeStopIntents).innerJoin(runtimeDrainRequests,and53(eq59(runtimeDrainRequests.id,runtimeStopIntents.drainRequestId),eq59(runtimeDrainRequests.appId,runtimeStopIntents.appId))).innerJoin(appRuntimeDesiredState,and53(eq59(appRuntimeDesiredState.appId,runtimeStopIntents.appId),eq59(appRuntimeDesiredState.desiredActivationId,runtimeStopIntents.activationId))).innerJoin(appDeploymentActivations,and53(eq59(appDeploymentActivations.id,runtimeStopIntents.activationId),eq59(appDeploymentActivations.appId,runtimeStopIntents.appId))).innerJoin(appRuntimeInstances,and53(eq59(appRuntimeInstances.instanceId,runtimeStopIntents.instanceId),eq59(appRuntimeInstances.appId,runtimeStopIntents.appId),eq59(appRuntimeInstances.activationId,runtimeStopIntents.activationId))).where(and53(eq59(runtimeStopIntents.appId,input2.appId),eq59(runtimeStopIntents.instanceId,input2.instanceId),eq59(runtimeStopIntents.activationId,input2.activationId),eq59(runtimeStopIntents.nodeEpoch,input2.nodeEpoch),eq59(runtimeStopIntents.leaseEpoch,input2.leaseEpoch),eq59(runtimeStopIntents.reason,"idle_certification"),isNotNull8(runtimeStopIntents.dispatchStartedAt),isNull22(runtimeStopIntents.consumedAt),isNull22(runtimeStopIntents.cancelledAt),eq59(runtimeDrainRequests.state,"dispatched"),eq59(appRuntimeDesiredState.authorityMode,"enforce"),eq59(appRuntimeDesiredState.desiredRuntimeState,"serving"),eq59(appRuntimeDesiredState.desiredActivationId,input2.activationId),eq59(appDeploymentActivations.state,"draining"),eq59(appRuntimeInstances.state,"draining"),eq59(appRuntimeInstances.processIdentityHash,input2.processIdentityHash))).limit(1);const row=rows8[0];if(!row)return false;const intent=await tx.update(runtimeStopIntents).set({cancelledAt:now,cancelReason:"resume_after_idle_exit_uncertain"}).where(and53(eq59(runtimeStopIntents.id,row.intentId),eq59(runtimeStopIntents.appId,input2.appId),isNotNull8(runtimeStopIntents.dispatchStartedAt),isNull22(runtimeStopIntents.consumedAt),isNull22(runtimeStopIntents.cancelledAt))).returning({id:runtimeStopIntents.id});if(!intent[0])return false;const drain=await tx.update(runtimeDrainRequests).set({state:"cancelled",cancelReason:"resume_after_idle_exit_uncertain",updatedAt:now}).where(and53(eq59(runtimeDrainRequests.id,row.drainId),eq59(runtimeDrainRequests.appId,input2.appId),eq59(runtimeDrainRequests.state,"dispatched"))).returning({id:runtimeDrainRequests.id});if(!drain[0])throw new Error("RUNTIME_IDLE_RESUME_DRAIN_CAS_FAILED");const activation=await tx.update(appDeploymentActivations).set({state:"serving",updatedAt:now}).where(and53(eq59(appDeploymentActivations.id,input2.activationId),eq59(appDeploymentActivations.appId,input2.appId),eq59(appDeploymentActivations.nodeEpoch,input2.nodeEpoch),eq59(appDeploymentActivations.state,"draining"))).returning({id:appDeploymentActivations.id});if(!activation[0])throw new Error("RUNTIME_IDLE_RESUME_ACTIVATION_CAS_FAILED");await tx.update(runtimeLifecycleRequests).set({state:"completed",terminalResultCode:"cancelled_for_resume",updatedAt:now}).where(and53(eq59(runtimeLifecycleRequests.id,row.lifecycleRequestId),eq59(runtimeLifecycleRequests.appId,input2.appId),inArray31(runtimeLifecycleRequests.state,["accepted","queued","executing"])));await tx.update(appRuntimeInstances).set({state:"serving",updatedAt:now}).where(and53(eq59(appRuntimeInstances.instanceId,input2.instanceId),eq59(appRuntimeInstances.appId,input2.appId),eq59(appRuntimeInstances.activationId,input2.activationId),eq59(appRuntimeInstances.nodeEpoch,input2.nodeEpoch),eq59(appRuntimeInstances.leaseEpoch,input2.leaseEpoch),eq59(appRuntimeInstances.state,"draining"),eq59(appRuntimeInstances.processIdentityHash,input2.processIdentityHash)));return true})}async function quarantineTerminalAutomaticStopForResume(input2){const now=input2.now??new Date;return input2.db.transaction(async tx=>{await tx.execute(sql147`SELECT pg_advisory_xact_lock(hashtextextended(${`runtime-lifecycle:${input2.appId}`}::text, 0))`);const rows8=await tx.select({intentId:runtimeStopIntents.id,drainId:runtimeDrainRequests.id,lifecycleRequestId:runtimeDrainRequests.lifecycleRequestId}).from(runtimeStopIntents).innerJoin(runtimeDrainRequests,and53(eq59(runtimeDrainRequests.id,runtimeStopIntents.drainRequestId),eq59(runtimeDrainRequests.appId,runtimeStopIntents.appId))).innerJoin(appRuntimeDesiredState,and53(eq59(appRuntimeDesiredState.appId,runtimeStopIntents.appId),eq59(appRuntimeDesiredState.desiredActivationId,runtimeStopIntents.activationId),eq59(appRuntimeDesiredState.nodeId,runtimeStopIntents.nodeId),eq59(appRuntimeDesiredState.nodeEpoch,runtimeStopIntents.nodeEpoch))).innerJoin(appDeploymentActivations,and53(eq59(appDeploymentActivations.id,runtimeStopIntents.activationId),eq59(appDeploymentActivations.appId,runtimeStopIntents.appId),eq59(appDeploymentActivations.nodeId,runtimeStopIntents.nodeId),eq59(appDeploymentActivations.nodeEpoch,runtimeStopIntents.nodeEpoch))).innerJoin(appRuntimeInstances,and53(eq59(appRuntimeInstances.instanceId,runtimeStopIntents.instanceId),eq59(appRuntimeInstances.appId,runtimeStopIntents.appId),eq59(appRuntimeInstances.activationId,runtimeStopIntents.activationId),eq59(appRuntimeInstances.nodeEpoch,runtimeStopIntents.nodeEpoch),eq59(appRuntimeInstances.leaseEpoch,runtimeStopIntents.leaseEpoch))).where(and53(eq59(runtimeStopIntents.appId,input2.appId),inArray31(runtimeStopIntents.reason,AUTOMATIC_IDLE_STOP_REASONS),isNotNull8(runtimeStopIntents.dispatchStartedAt),isNull22(runtimeStopIntents.consumedAt),isNull22(runtimeStopIntents.cancelledAt),eq59(runtimeDrainRequests.state,"dispatched"),eq59(appRuntimeDesiredState.authorityMode,"enforce"),eq59(appRuntimeDesiredState.desiredRuntimeState,"serving"),inArray31(appDeploymentActivations.state,["draining","serving"]),inArray31(appRuntimeInstances.state,["stopped","exited"]))).limit(1);const row=rows8[0];if(!row)return false;const intent=await tx.update(runtimeStopIntents).set({cancelledAt:now,cancelReason:"resume_after_terminal_automatic_stop"}).where(and53(eq59(runtimeStopIntents.id,row.intentId),eq59(runtimeStopIntents.appId,input2.appId),isNotNull8(runtimeStopIntents.dispatchStartedAt),isNull22(runtimeStopIntents.consumedAt),isNull22(runtimeStopIntents.cancelledAt))).returning({id:runtimeStopIntents.id});if(!intent[0])return false;const drain=await tx.update(runtimeDrainRequests).set({state:"cancelled",cancelReason:"resume_after_terminal_automatic_stop",updatedAt:now}).where(and53(eq59(runtimeDrainRequests.id,row.drainId),eq59(runtimeDrainRequests.appId,input2.appId),eq59(runtimeDrainRequests.state,"dispatched"))).returning({id:runtimeDrainRequests.id});if(!drain[0])throw new Error("RUNTIME_TERMINAL_STOP_RESUME_DRAIN_CAS_FAILED");await tx.update(runtimeLifecycleRequests).set({state:"completed",terminalResultCode:"cancelled_for_terminal_resume",updatedAt:now}).where(and53(eq59(runtimeLifecycleRequests.id,row.lifecycleRequestId),eq59(runtimeLifecycleRequests.appId,input2.appId),inArray31(runtimeLifecycleRequests.state,["accepted","queued","executing"])));return true})}var SERVING_ROUTE_ENVIRONMENTS;var init_runtime_idle_certification_stop_recovery=__esm({"../platform/src/runtime-idle-certification-stop-recovery.ts"(){"use strict";init_schema();init_runtime_automatic_idle_contract();SERVING_ROUTE_ENVIRONMENTS=new Set(["local","dev","qc","prod"])}});import{and as and54,eq as eq60}from"drizzle-orm";function fail45(code){throw new Error(code)}async function resumeDispatchedRuntimeStopIntent(input2){const target=await input2.db.transaction(async tx=>{const intents=await tx.select().from(runtimeStopIntents).where(eq60(runtimeStopIntents.id,input2.intentId));const intent=intents[0];if(!intent||intent.consumedAt||intent.cancelledAt||!intent.dispatchStartedAt){return fail45("RUNTIME_STOP_INTENT_DISPATCH_NOT_RESUMABLE")}if(intent.drainRequestId){const drains=await tx.select({state:runtimeDrainRequests.state}).from(runtimeDrainRequests).where(and54(eq60(runtimeDrainRequests.id,intent.drainRequestId),eq60(runtimeDrainRequests.appId,intent.appId),eq60(runtimeDrainRequests.instanceId,intent.instanceId)));if(drains[0]?.state!=="dispatched"){return fail45("RUNTIME_STOP_INTENT_DRAIN_INVALID")}}const instances=await tx.select({processIdentityHash:appRuntimeInstances.processIdentityHash,runnerRef:appRuntimeInstances.runnerRef,pid:appRuntimeInstances.pid,pidStartTicks:appRuntimeInstances.pidStartTicks,processGroupId:appRuntimeInstances.processGroupId,processGroupStartTicks:appRuntimeInstances.processGroupStartTicks,cgroupRefHash:appRuntimeInstances.cgroupRefHash,runnerSessionId:appRuntimeInstances.runnerSessionId,state:appRuntimeInstances.state}).from(appRuntimeInstances).where(and54(eq60(appRuntimeInstances.instanceId,intent.instanceId),eq60(appRuntimeInstances.appId,intent.appId),eq60(appRuntimeInstances.deploymentId,intent.deploymentId),eq60(appRuntimeInstances.activationId,intent.activationId),eq60(appRuntimeInstances.nodeEpoch,intent.nodeEpoch),eq60(appRuntimeInstances.leaseEpoch,intent.leaseEpoch)));const instance=instances[0];if(!instance||instance.processIdentityHash!==input2.observedProcessIdentityHash||!isCompleteRuntimeProcessIdentity(instance)||!["serving","draining"].includes(instance.state)){return fail45("RUNTIME_STOP_OWNERSHIP_AMBIGUOUS")}return{intentId:intent.id,instanceId:intent.instanceId,nodeId:intent.nodeId,nodeEpoch:intent.nodeEpoch,leaseEpoch:intent.leaseEpoch,processIdentityHash:instance.processIdentityHash,runnerRef:instance.runnerRef,pid:instance.pid,pidStartTicks:instance.pidStartTicks,processGroupId:instance.processGroupId,processGroupStartTicks:instance.processGroupStartTicks,cgroupRefHash:instance.cgroupRefHash,runnerSessionId:instance.runnerSessionId}});return target}var init_runtime_stop_dispatch_recovery=__esm({"../platform/src/runtime-stop-dispatch-recovery.ts"(){"use strict";init_schema();init_runtime_process_identity()}});import{createHash as createHash110}from"node:crypto";import{and as and55,eq as eq61,exists as exists3,gt as gt12,inArray as inArray32,isNotNull as isNotNull9,isNull as isNull23,lte as lte9,ne as ne14,or as or19,sql as sql148}from"drizzle-orm";function sha25622(value2){return createHash110("sha256").update(value2).digest("hex")}function fail46(code){throw new Error(code)}function matchesRequestIdentity(row,input2){return row.reason===input2.reason&&row.createdByKind===input2.createdByKind&&row.createdById===input2.createdById&&row.correlationId===input2.correlationId&&row.drainRequestId===(input2.drainRequestId??null)&&row.rolloutRevision===(input2.rolloutRevision??null)&&row.rolloutEligibilityHash===(input2.rolloutEligibilityHash??null)}function matchesLeaseIdentity(row,instance){return LEASE_IDENTITY_FIELDS.every(field=>row[field]===instance[field])}function matchesBindingIdentity(row,instance){return BINDING_IDENTITY_FIELDS.every(field=>row[field]===instance[field])}function intentSelection2(){return{id:runtimeStopIntents.id,appId:runtimeStopIntents.appId,deploymentId:runtimeStopIntents.deploymentId,activationId:runtimeStopIntents.activationId,instanceId:runtimeStopIntents.instanceId,nodeId:runtimeStopIntents.nodeId,nodeEpoch:runtimeStopIntents.nodeEpoch,leaseEpoch:runtimeStopIntents.leaseEpoch,sourceGenerationRef:runtimeStopIntents.sourceGenerationRef,reason:runtimeStopIntents.reason,expiresAt:runtimeStopIntents.expiresAt,consumedAt:runtimeStopIntents.consumedAt,consumedByEventId:runtimeStopIntents.consumedByEventId,createdByKind:runtimeStopIntents.createdByKind,createdById:runtimeStopIntents.createdById,correlationId:runtimeStopIntents.correlationId,drainRequestId:runtimeStopIntents.drainRequestId,rolloutRevision:runtimeStopIntents.rolloutRevision,rolloutEligibilityHash:runtimeStopIntents.rolloutEligibilityHash,cancelledAt:runtimeStopIntents.cancelledAt,cancelReason:runtimeStopIntents.cancelReason,dispatchStartedAt:runtimeStopIntents.dispatchStartedAt}}async function loadIntent2(db,intentId){const rows8=await db.select(intentSelection2()).from(runtimeStopIntents).where(eq61(runtimeStopIntents.id,intentId));return rows8[0]??null}async function createRuntimeStopIntentInTransaction(input2){if(!Number.isSafeInteger(input2.ttlMs)||input2.ttlMs<1e3||input2.ttlMs>60*60*1e3){return fail46("RUNTIME_STOP_INTENT_TTL_INVALID")}if(!Number.isSafeInteger(input2.appId)||input2.appId<=0||!["controller","operator","platform"].includes(input2.createdByKind)||!/^[A-Za-z0-9_.:@/-]{1,128}$/u.test(input2.createdById)||!/^[A-Za-z0-9_.:@/-]{1,128}$/u.test(input2.correlationId)){return fail46("RUNTIME_STOP_INTENT_INPUT_INVALID")}const now=input2.now??new Date;const desiredRows=await input2.db.select().from(appRuntimeDesiredState).where(eq61(appRuntimeDesiredState.appId,input2.appId));const currentRows=await input2.db.select().from(appDeploymentActivations).where(and55(eq61(appDeploymentActivations.id,input2.currentActivationId),eq61(appDeploymentActivations.appId,input2.appId)));const instanceRows=await input2.db.select({instanceId:appRuntimeInstances.instanceId,appId:appRuntimeInstances.appId,deploymentId:appRuntimeInstances.deploymentId,activationId:appRuntimeInstances.activationId,sourceGenerationRef:appRuntimeInstances.sourceGenerationRef,nodeId:appRuntimeInstances.nodeId,nodeEpoch:appRuntimeInstances.nodeEpoch,leaseEpoch:appRuntimeInstances.leaseEpoch,runnerRef:appRuntimeInstances.runnerRef,processIdentityHash:appRuntimeInstances.processIdentityHash,pid:appRuntimeInstances.pid,state:appRuntimeInstances.state}).from(appRuntimeInstances).where(and55(eq61(appRuntimeInstances.instanceId,input2.targetInstanceId),eq61(appRuntimeInstances.appId,input2.appId)));const desired=desiredRows[0];const current=currentRows[0];const instance=instanceRows[0];if(!desired||!current||!instance||desired.desiredActivationId!==current.id||desired.activationEpoch!==current.activationEpoch||desired.nodeId!==current.nodeId||desired.nodeEpoch!==current.nodeEpoch||current.routeAckEpoch!==current.activationEpoch){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}const stopsDesiredInstance=instance.activationId===current.id;if(stopsDesiredInstance){if(instance.nodeId!==current.nodeId||instance.nodeEpoch!==current.nodeEpoch){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}const alreadyDraining=desired.desiredRuntimeState==="draining"&¤t.state==="draining"&&instance.state==="draining";const serving=desired.desiredRuntimeState==="serving"&¤t.state==="serving"&&instance.state==="serving";if(input2.reason==="deploy_replace"||!serving&&!alreadyDraining){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}if(serving){const desiredUpdates=await input2.db.update(appRuntimeDesiredState).set({desiredRuntimeState:"draining",updatedAt:now}).where(and55(eq61(appRuntimeDesiredState.appId,input2.appId),eq61(appRuntimeDesiredState.desiredActivationId,current.id),eq61(appRuntimeDesiredState.activationEpoch,current.activationEpoch),eq61(appRuntimeDesiredState.nodeEpoch,current.nodeEpoch),eq61(appRuntimeDesiredState.desiredRuntimeState,"serving"))).returning({appId:appRuntimeDesiredState.appId});const activationUpdates=await input2.db.update(appDeploymentActivations).set({state:"draining",updatedAt:now}).where(and55(eq61(appDeploymentActivations.id,current.id),eq61(appDeploymentActivations.appId,input2.appId),eq61(appDeploymentActivations.state,"serving"))).returning({id:appDeploymentActivations.id});const instanceUpdates=await input2.db.update(appRuntimeInstances).set({state:"draining",updatedAt:now}).where(and55(eq61(appRuntimeInstances.instanceId,instance.instanceId),eq61(appRuntimeInstances.appId,input2.appId),eq61(appRuntimeInstances.nodeEpoch,instance.nodeEpoch),eq61(appRuntimeInstances.leaseEpoch,instance.leaseEpoch),eq61(appRuntimeInstances.state,"serving"))).returning({id:appRuntimeInstances.instanceId});if(!desiredUpdates[0]||!activationUpdates[0]||!instanceUpdates[0]){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}}}else{if(input2.reason!=="deploy_replace"||current.state!=="serving"||!["serving","draining"].includes(instance.state)){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}const oldActivationRows=await input2.db.select({state:appDeploymentActivations.state,nodeId:appDeploymentActivations.nodeId,nodeEpoch:appDeploymentActivations.nodeEpoch}).from(appDeploymentActivations).where(and55(eq61(appDeploymentActivations.id,instance.activationId),eq61(appDeploymentActivations.appId,input2.appId),eq61(appDeploymentActivations.deploymentId,instance.deploymentId)));if(oldActivationRows[0]?.state!=="draining"||oldActivationRows[0].nodeId!==instance.nodeId||oldActivationRows[0].nodeEpoch!==instance.nodeEpoch){return fail46("RUNTIME_STOP_INTENT_PRECONDITION_FAILED")}}if(input2.reason==="app_delete"){await cancelUnsignalledIntentsOfTerminalDrains({tx:input2.db,appId:input2.appId,instanceId:instance.instanceId,now})}const pending=await input2.db.select(intentSelection2()).from(runtimeStopIntents).where(and55(eq61(runtimeStopIntents.appId,input2.appId),eq61(runtimeStopIntents.instanceId,instance.instanceId),isNull23(runtimeStopIntents.consumedAt),isNull23(runtimeStopIntents.cancelledAt),gt12(runtimeStopIntents.expiresAt,now)));if(pending[0]){if(matchesRequestIdentity(pending[0],input2)){return pending[0]}return fail46("RUNTIME_STOP_INTENT_IDENTITY_MISMATCH")}const expired=await input2.db.select(intentSelection2()).from(runtimeStopIntents).where(and55(eq61(runtimeStopIntents.appId,input2.appId),eq61(runtimeStopIntents.instanceId,instance.instanceId),isNull23(runtimeStopIntents.consumedAt),isNull23(runtimeStopIntents.cancelledAt),lte9(runtimeStopIntents.expiresAt,now)));if(expired.length>1)return fail46("RUNTIME_STOP_INTENT_IDENTITY_MISMATCH");if(expired[0]){const previous=expired[0];if(!matchesBindingIdentity(previous,instance)||!matchesRequestIdentity(previous,input2)){return fail46("RUNTIME_STOP_INTENT_IDENTITY_MISMATCH")}const renewed=await input2.db.update(runtimeStopIntents).set({expiresAt:new Date(now.getTime()+input2.ttlMs)}).where(and55(eq61(runtimeStopIntents.id,previous.id),isNull23(runtimeStopIntents.consumedAt),lte9(runtimeStopIntents.expiresAt,now))).returning(intentSelection2());if(!renewed[0])return fail46("RUNTIME_STOP_INTENT_RENEWAL_FAILED");return renewed[0]}const id=`stop_${sha25622(JSON.stringify([input2.appId,current.id,current.activationEpoch,instance.instanceId,instance.leaseEpoch,input2.reason,input2.createdByKind,input2.createdById,input2.correlationId,input2.drainRequestId??null])).slice(0,32)}`;await input2.db.insert(runtimeStopIntents).values({id,appId:input2.appId,deploymentId:instance.deploymentId,activationId:instance.activationId,instanceId:instance.instanceId,nodeId:instance.nodeId,nodeEpoch:instance.nodeEpoch,leaseEpoch:instance.leaseEpoch,sourceGenerationRef:instance.sourceGenerationRef,reason:input2.reason,expiresAt:new Date(now.getTime()+input2.ttlMs),createdByKind:input2.createdByKind,createdById:input2.createdById,correlationId:input2.correlationId,drainRequestId:input2.drainRequestId??null,rolloutRevision:input2.rolloutRevision??null,rolloutEligibilityHash:input2.rolloutEligibilityHash??null}).onConflictDoNothing({target:runtimeStopIntents.id});const intent=await loadIntent2(input2.db,id);if(!intent||intent.appId!==input2.appId||intent.instanceId!==instance.instanceId||!matchesLeaseIdentity(intent,instance)||!matchesRequestIdentity(intent,input2)){return fail46("RUNTIME_STOP_INTENT_IDENTITY_MISMATCH")}if(!intent.consumedAt&&intent.expiresAt<=now){const renewed=await input2.db.update(runtimeStopIntents).set({expiresAt:new Date(now.getTime()+input2.ttlMs)}).where(and55(eq61(runtimeStopIntents.id,id),isNull23(runtimeStopIntents.consumedAt),lte9(runtimeStopIntents.expiresAt,now),eq61(runtimeStopIntents.createdByKind,input2.createdByKind),eq61(runtimeStopIntents.createdById,input2.createdById),eq61(runtimeStopIntents.correlationId,input2.correlationId))).returning(intentSelection2());if(!renewed[0])return fail46("RUNTIME_STOP_INTENT_RENEWAL_FAILED");return renewed[0]}return intent}async function createRuntimeStopIntent(input2){const acquireLock=input2.acquireLock??((tx,key2)=>tx.execute(sql148`SELECT pg_advisory_xact_lock(hashtextextended(${key2}::text, 0))`));return input2.db.transaction(async tx=>{await acquireLock(tx,`runtime-stop-intent:${input2.appId}`);return createRuntimeStopIntentInTransaction({...input2,db:tx})})}async function consumeRuntimeStopIntent(input2){const unexpected={expected:false,consumed:false,replayed:false,restartBudgetDelta:1};if(!Number.isSafeInteger(input2.eventId)||input2.eventId<=0)return unexpected;return input2.db.transaction(async tx=>{const now=input2.now??new Date;const consumed=await tx.update(runtimeStopIntents).set({consumedAt:sql148`GREATEST(${toPostgresTimestamp2(now)}, ${runtimeStopIntents.createdAt})`,consumedByEventId:input2.eventId}).where(and55(eq61(runtimeStopIntents.id,input2.intentId),eq61(runtimeStopIntents.appId,input2.appId),input2.expectedIntentId?eq61(runtimeStopIntents.id,input2.expectedIntentId):sql148`true`,input2.expectedIntentReason?eq61(runtimeStopIntents.reason,input2.expectedIntentReason):sql148`true`,eq61(runtimeStopIntents.instanceId,input2.instanceId),input2.expectedNodeId?eq61(runtimeStopIntents.nodeId,input2.expectedNodeId):sql148`true`,eq61(runtimeStopIntents.nodeEpoch,input2.nodeEpoch),eq61(runtimeStopIntents.leaseEpoch,input2.leaseEpoch),isNull23(runtimeStopIntents.consumedAt),isNull23(runtimeStopIntents.cancelledAt),or19(gt12(runtimeStopIntents.expiresAt,now),isNotNull9(runtimeStopIntents.dispatchStartedAt),input2.allowExpiredAfterExactObservation?sql148`true`:sql148`false`),input2.allowExpiredAfterExactObservation?exists3(tx.select({one:sql148`1`}).from(appRuntimeDesiredState).where(and55(eq61(appRuntimeDesiredState.appId,input2.appId),eq61(appRuntimeDesiredState.authorityMode,"enforce"),input2.expectedNodeId?eq61(appRuntimeDesiredState.nodeId,input2.expectedNodeId):sql148`true`,or19(and55(eq61(appRuntimeDesiredState.desiredRuntimeState,"absent"),isNull23(appRuntimeDesiredState.desiredActivationId)),and55(isNotNull9(appRuntimeDesiredState.desiredActivationId),ne14(appRuntimeDesiredState.desiredActivationId,runtimeStopIntents.activationId)),and55(eq61(appRuntimeDesiredState.desiredActivationId,runtimeStopIntents.activationId),eq61(appRuntimeDesiredState.desiredRuntimeState,"draining"),sql148`EXISTS (SELECT 1 FROM runtime_drain_requests AS ended_drain
|
|
10916
10913
|
WHERE ended_drain.id = ${runtimeStopIntents.drainRequestId}
|
|
10917
10914
|
AND ended_drain.app_id = ${runtimeStopIntents.appId}
|
|
10918
10915
|
AND ended_drain.state = 'blocked')`))))):sql148`true`)).returning(intentSelection2());if(!consumed[0]){const existing=await loadIntent2(tx,input2.intentId);const isSameEventReplay=existing?.consumedByEventId===input2.eventId;const isExactObserverReplay=input2.expectedIntentId===existing?.id&&Boolean(input2.expectedProcessIdentityHash);const matchesConsumedIntent=existing?.appId===input2.appId&&existing.instanceId===input2.instanceId&&existing.nodeEpoch===input2.nodeEpoch&&existing.leaseEpoch===input2.leaseEpoch&&(!input2.expectedNodeId||existing.nodeId===input2.expectedNodeId)&&(!input2.expectedIntentReason||existing.reason===input2.expectedIntentReason)&&existing.cancelledAt===null&&existing.consumedAt!==null&&(isSameEventReplay||isExactObserverReplay);const matchingInstances=matchesConsumedIntent&&input2.expectedProcessIdentityHash?await tx.select({instanceId:appRuntimeInstances.instanceId}).from(appRuntimeInstances).where(and55(eq61(appRuntimeInstances.appId,input2.appId),eq61(appRuntimeInstances.instanceId,input2.instanceId),eq61(appRuntimeInstances.nodeEpoch,input2.nodeEpoch),eq61(appRuntimeInstances.leaseEpoch,input2.leaseEpoch),eq61(appRuntimeInstances.processIdentityHash,input2.expectedProcessIdentityHash),inArray32(appRuntimeInstances.state,["stopped","exited"]))):[];if(matchesConsumedIntent&&(!input2.expectedProcessIdentityHash||matchingInstances.length===1)){return{expected:true,consumed:false,replayed:true,restartBudgetDelta:0}}return unexpected}const endedDrain=input2.allowExpiredAfterExactObservation===true&&consumed[0].drainRequestId!==null&&(await tx.select({id:runtimeDrainRequests.id}).from(runtimeDrainRequests).where(and55(eq61(runtimeDrainRequests.id,consumed[0].drainRequestId),eq61(runtimeDrainRequests.appId,consumed[0].appId),eq61(runtimeDrainRequests.state,"blocked")))).length===1;const instanceUpdates=await tx.update(appRuntimeInstances).set({state:"stopped",lastObservedAt:now,updatedAt:now}).where(and55(eq61(appRuntimeInstances.instanceId,input2.instanceId),eq61(appRuntimeInstances.appId,consumed[0].appId),eq61(appRuntimeInstances.deploymentId,consumed[0].deploymentId),eq61(appRuntimeInstances.activationId,consumed[0].activationId),input2.expectedNodeId?eq61(appRuntimeInstances.nodeId,input2.expectedNodeId):sql148`true`,eq61(appRuntimeInstances.nodeEpoch,input2.nodeEpoch),eq61(appRuntimeInstances.leaseEpoch,input2.leaseEpoch),input2.expectedProcessIdentityHash?eq61(appRuntimeInstances.processIdentityHash,input2.expectedProcessIdentityHash):sql148`true`,inArray32(appRuntimeInstances.state,input2.allowExpiredAfterExactObservation?["stopped","exited","unknown",...endedDrain?["draining"]:[]]:["serving","draining"]))).returning({id:appRuntimeInstances.instanceId});if(!instanceUpdates[0])return fail46("RUNTIME_STOP_INSTANCE_CAS_FAILED");const preservesActivation=consumed[0].reason==="operator_stop"||isAutomaticIdleStopReason(consumed[0].reason);const activationUpdates=await tx.update(appDeploymentActivations).set({state:preservesActivation?"serving":"retired",updatedAt:now}).where(and55(eq61(appDeploymentActivations.id,consumed[0].activationId),eq61(appDeploymentActivations.appId,consumed[0].appId),eq61(appDeploymentActivations.deploymentId,consumed[0].deploymentId),input2.allowExpiredAfterExactObservation?inArray32(appDeploymentActivations.state,["draining","retired","superseded"]):eq61(appDeploymentActivations.state,"draining"))).returning({id:appDeploymentActivations.id});if(!activationUpdates[0])return fail46("RUNTIME_STOP_ACTIVATION_CAS_FAILED");const desiredRows=await tx.select({desiredActivationId:appRuntimeDesiredState.desiredActivationId,desiredRuntimeState:appRuntimeDesiredState.desiredRuntimeState}).from(appRuntimeDesiredState).where(eq61(appRuntimeDesiredState.appId,consumed[0].appId));let desiredStopApplied=false;if(desiredRows[0]?.desiredActivationId===consumed[0].activationId&&desiredRows[0].desiredRuntimeState==="draining"){const desiredUpdates=await tx.update(appRuntimeDesiredState).set(preservesActivation?{desiredRuntimeState:"stopped",updatedAt:now}:{desiredActivationId:null,desiredRuntimeState:"absent",updatedAt:now}).where(and55(eq61(appRuntimeDesiredState.appId,consumed[0].appId),eq61(appRuntimeDesiredState.desiredActivationId,consumed[0].activationId),eq61(appRuntimeDesiredState.nodeEpoch,input2.nodeEpoch),eq61(appRuntimeDesiredState.desiredRuntimeState,"draining"))).returning({appId:appRuntimeDesiredState.appId});if(!desiredUpdates[0])return fail46("RUNTIME_STOP_DESIRED_STATE_CAS_FAILED");desiredStopApplied=true}if(consumed[0].drainRequestId){const drainRows=await tx.select({lifecycleRequestId:runtimeDrainRequests.lifecycleRequestId,reason:runtimeDrainRequests.reason,state:runtimeDrainRequests.state}).from(runtimeDrainRequests).where(and55(eq61(runtimeDrainRequests.id,consumed[0].drainRequestId),eq61(runtimeDrainRequests.appId,consumed[0].appId)));const drain=drainRows[0];const drainTerminalElsewhere=!drain||["completed","expired","blocked","cancelled"].includes(drain.state);if(drain&&drain.state!=="dispatched"&&!drainTerminalElsewhere)return fail46("RUNTIME_STOP_DRAIN_CAS_FAILED");if(drain&&drain.state==="dispatched"&&isAutomaticIdleStopReason(drain.reason)){let idleCertificationEvidence=null;const drainUpdates=await tx.update(runtimeDrainRequests).set({state:"completed",updatedAt:now}).where(and55(eq61(runtimeDrainRequests.id,consumed[0].drainRequestId),eq61(runtimeDrainRequests.appId,consumed[0].appId),eq61(runtimeDrainRequests.state,"dispatched"))).returning({id:runtimeDrainRequests.id});if(!drainUpdates[0])return fail46("RUNTIME_STOP_DRAIN_CAS_FAILED");if(requiresIdleCertificationEvidence(drain.reason)){idleCertificationEvidence=await loadIdleCertificationEvidence({tx,appId:consumed[0].appId,activationId:consumed[0].activationId,deploymentId:consumed[0].deploymentId});if(!idleCertificationEvidence){return fail46("RUNTIME_IDLE_CERTIFICATION_ROUTE_EVIDENCE_MISSING")}}await tx.update(runtimeLifecycleRequests).set({...idleCertificationEvidence?{evidenceDigest:idleCertificationEvidence.digest,evidencePayloadJson:idleCertificationEvidence.payload}:{},state:"completed",terminalResultCode:resolveAutomaticIdleTerminalResultCode(drain.reason),updatedAt:now}).where(eq61(runtimeLifecycleRequests.id,drain.lifecycleRequestId));if(desiredStopApplied){await projectAppStatus(tx,{status:"idle",statusReason:"automatic_scale_down",statusMessage:null,statusUpdatedAt:now}).where(eq61(apps.id,consumed[0].appId))}}}return{expected:true,consumed:true,replayed:false,restartBudgetDelta:0}})}var LEASE_IDENTITY_FIELDS,BINDING_IDENTITY_FIELDS;var init_runtime_stop_intent_store=__esm({"../platform/src/runtime-stop-intent-store.ts"(){"use strict";init_schema();init_app_status_projector();init_runtime_automatic_idle_contract();init_postgres_temporal2();init_runtime_explicit_stop_expired_drain();init_runtime_stop_intent_dispatch();init_runtime_idle_certification_stop_recovery();init_runtime_stop_dispatch_recovery();LEASE_IDENTITY_FIELDS=["nodeEpoch","leaseEpoch","sourceGenerationRef"];BINDING_IDENTITY_FIELDS=["deploymentId","activationId","nodeId",...LEASE_IDENTITY_FIELDS]}});function createOwnedRuntimeStopDispatcher(input2){return request=>dispatchRuntimeStopIntent({db:input2.db,intentId:request.intentId,observedProcessIdentityHash:request.observedProcessIdentityHash,effectHandoffRequired:input2.stopEffectHandoffRequired,effectOwnerId:input2.stopEffectHandoffRequired?input2.stopEffectOwnerId:void 0,stop:target=>input2.stopExactTarget(request.appName,{...target,appInstanceId:request.appInstanceId})})}var init_runtime_owned_stop_dispatch=__esm({"../platform/src/runtime-owned-stop-dispatch.ts"(){"use strict";init_runtime_stop_intent_store()}});import{readFileSync as readFileSync69}from"node:fs";function sampleRuntimeProcess(pid,procRoot="/proc"){if(!pid||!Number.isSafeInteger(pid)||pid<=1)return EMPTY;try{const stat13=readFileSync69(`${procRoot}/${pid}/stat`,"utf8");const rest2=stat13.slice(stat13.lastIndexOf(")")+2).split(" ");const state2=rest2[0]??null;const utime=Number(rest2[11]);const stime=Number(rest2[12]);let threads=Number(rest2[17]);if(!Number.isFinite(threads))threads=null;let rssKb=null;try{const status=readFileSync69(`${procRoot}/${pid}/status`,"utf8");const match2=/^VmRSS:\s+(\d+)\s+kB/m.exec(status);rssKb=match2?Number(match2[1]):null}catch{rssKb=null}return{state:state2,threads,cpuTicks:Number.isFinite(utime)&&Number.isFinite(stime)?utime+stime:null,rssKb}}catch{return EMPTY}}function listChildPids(pid,procRoot="/proc"){try{return readFileSync69(`${procRoot}/${pid}/task/${pid}/children`,"utf8").split(/\s+/).map(Number).filter(child=>Number.isSafeInteger(child)&&child>1)}catch{return[]}}function sampleRuntimeWorkload(pid,procRoot="/proc"){if(!pid||!Number.isSafeInteger(pid)||pid<=1)return{...EMPTY,pid:null};let best=null;for(const child of listChildPids(pid,procRoot)){const sample2=sampleRuntimeProcess(child,procRoot);if(!best||(sample2.cpuTicks??0)>(best.sample.cpuTicks??0))best={pid:child,sample:sample2}}return best?{...best.sample,pid:best.pid}:{...sampleRuntimeProcess(pid,procRoot),pid}}var EMPTY;var init_runtime_process_sample=__esm({"../platform/src/runtime-process-sample.ts"(){"use strict";EMPTY={state:null,threads:null,cpuTicks:null,rssKb:null}}});import{execFile}from"node:child_process";import{mkdtempSync as mkdtempSync11,readFileSync as readFileSync70,readdirSync as readdirSync27,readlinkSync as readlinkSync2,rmSync as rmSync20}from"node:fs";import{tmpdir as tmpdir10}from"node:os";import{join as join39}from"node:path";import{promisify}from"node:util";function sampleOpenPaths(pid,procRoot){try{const counts=new Map;for(const fd of readdirSync27(`${procRoot}/${pid}/fd`)){let target;try{target=readlinkSync2(`${procRoot}/${pid}/fd/${fd}`)}catch{continue}if(!target.startsWith("/"))continue;const path5=target.slice(0,OPEN_PATH_MAX_LENGTH);counts.set(path5,(counts.get(path5)??0)+1)}return[...counts.entries()].sort((a,b2)=>b2[1]-a[1]||a[0].localeCompare(b2[0])).slice(0,OPEN_PATH_ROWS).map(([path5,count3])=>`${count3} ${path5}`)}catch{return[]}}function parseSyscallSummary(summary){const rows8=[];for(const line of summary.split("\n")){const match2=/^\s*\d+(?:\.\d+)?\s+\d+(?:\.\d+)?\s+\d+\s+(\d+)(?:\s+(\d+))?\s+([a-z_0-9]+)\s*$/.exec(line);if(match2&&match2[3]!=="total")rows8.push({name:match2[3],calls:Number(match2[1]),errors:match2[2]??null})}return rows8.sort((a,b2)=>b2.calls-a.calls).slice(0,SYSCALL_ROWS).map(row=>row.errors===null?`${row.name}:${row.calls}`:`${row.name}:${row.calls}/${row.errors}`)}function parsePathErrors(trace){const counts=new Map;for(const line of trace.split("\n")){const match2=/\b(mkdirat|newfstatat)\(\w+, "([^"]*)".*\) = -1 (E[A-Z0-9]+)/.exec(line);if(!match2)continue;const[,syscall,rawPath,errno]=match2;if(QUERY_PATH_PATTERN.test(rawPath)||SECRET_PATH_PATTERN.test(rawPath))continue;const path5=rawPath.split("/").map(segment=>segment.length>=OPAQUE_SEGMENT_MIN_LENGTH&&/^[A-Za-z0-9_-]+$/.test(segment)?"<id>":segment).join("/").slice(0,OPEN_PATH_MAX_LENGTH);const key2=`${syscall}(${path5}) = ${errno}`;counts.set(key2,(counts.get(key2)??0)+1)}return[...counts.entries()].sort((a,b2)=>b2[1]-a[1]||a[0].localeCompare(b2[0])).slice(0,PATH_ERROR_ROWS).map(([key2])=>key2)}function sampleHotThread(pid,procRoot){let best=null;try{for(const tid of readdirSync27(`${procRoot}/${pid}/task`)){try{const stat13=readFileSync70(`${procRoot}/${pid}/task/${tid}/stat`,"utf8");const fields=stat13.slice(stat13.lastIndexOf(")")+2).split(" ");const cpuTicks=Number(fields[11])+Number(fields[12]);if(!Number.isFinite(cpuTicks))continue;if(!best||cpuTicks>best.cpuTicks){best={comm:stat13.slice(stat13.indexOf("(")+1,stat13.lastIndexOf(")")),cpuTicks}}}catch{continue}}}catch{return null}return best}function sampleCwd(pid,procRoot){try{return readlinkSync2(`${procRoot}/${pid}/cwd`).slice(0,OPEN_PATH_MAX_LENGTH)}catch{return null}}async function sampleSyscallPaths(exec,pid,dir){const out=join39(dir,"strace-paths.txt");try{await exec("timeout",["-s","INT",String(PROFILE_SECONDS),"strace","-f","-e","trace=mkdirat,newfstatat","-s","160","-o",out,"-p",String(pid)],{timeout:(PROFILE_SECONDS+3)*1e3})}catch{}try{const rows8=parsePathErrors(readFileSync70(out,"utf8"));return rows8.length>0?rows8:["strace recorded no path errors"]}catch{return["strace unavailable"]}}async function sampleSyscalls(exec,pid,dir){const out=join39(dir,"strace.txt");try{await exec("timeout",["-s","INT",String(PROFILE_SECONDS),"strace","-c","-f","-o",out,"-p",String(pid)],{timeout:(PROFILE_SECONDS+3)*1e3})}catch{}try{const rows8=parseSyscallSummary(readFileSync70(out,"utf8"));return rows8.length>0?rows8:["strace recorded no syscalls"]}catch{return["strace unavailable"]}}async function captureRuntimeHangDiagnostics(wrapperPid,deps={}){const workload=sampleRuntimeWorkload(wrapperPid,deps.procRoot);if(!workload.pid){return{workload,profile:["no process to profile"],syscalls:[],openPaths:[],pathErrors:[],hotThread:null,cwd:null}}const procRoot=deps.procRoot??"/proc";const openPaths=sampleOpenPaths(workload.pid,procRoot);const hotThread=sampleHotThread(workload.pid,procRoot);const cwd=sampleCwd(workload.pid,procRoot);const nowMs2=deps.nowMs??Date.now();if(nowMs2-lastProfileAtMs<PROFILE_MIN_INTERVAL_MS){return{workload,profile:["skipped: another runtime was profiled within the last minute"],syscalls:[],openPaths,pathErrors:[],hotThread,cwd}}lastProfileAtMs=nowMs2;const exec=deps.exec??((file2,args,options)=>run(file2,args,options));const dir=mkdtempSync11(join39(tmpdir10(),"hang-profile-"));const data=join39(dir,"perf.data");const pathErrors=sampleSyscallPaths(exec,workload.pid,dir);try{await exec("perf",["record","-F","199","-g","-o",data,"-p",String(workload.pid),"--","sleep",String(PROFILE_SECONDS)],{timeout:(PROFILE_SECONDS+4)*1e3});const{stdout}=await exec("perf",["report","-i",data,"--stdio","--no-children","--sort","dso,sym"],{timeout:5e3});const rows8=stdout.split("\n").map(line=>line.trim()).filter(line=>/^\d+(\.\d+)?%/.test(line)).slice(0,PROFILE_ROWS);return{workload,profile:rows8.length>0?rows8:["perf recorded no samples"],pathErrors:await pathErrors,syscalls:await sampleSyscalls(exec,workload.pid,dir),openPaths,hotThread,cwd}}catch(error62){const reason=error62 instanceof Error?error62.message.split("\n")[0].slice(0,160):"unknown";return{workload,profile:[`perf unavailable: ${reason}`],pathErrors:await pathErrors,syscalls:await sampleSyscalls(exec,workload.pid,dir),openPaths,hotThread,cwd}}finally{rmSync20(dir,{recursive:true,force:true})}}var run,PROFILE_SECONDS,PROFILE_ROWS,SYSCALL_ROWS,OPEN_PATH_ROWS,OPEN_PATH_MAX_LENGTH,PATH_ERROR_ROWS,QUERY_PATH_PATTERN,SECRET_PATH_PATTERN,OPAQUE_SEGMENT_MIN_LENGTH,PROFILE_MIN_INTERVAL_MS,lastProfileAtMs;var init_runtime_hang_profile=__esm({"../platform/src/runtime-hang-profile.ts"(){"use strict";init_runtime_process_sample();run=promisify(execFile);PROFILE_SECONDS=2;PROFILE_ROWS=12;SYSCALL_ROWS=6;OPEN_PATH_ROWS=5;OPEN_PATH_MAX_LENGTH=120;PATH_ERROR_ROWS=5;QUERY_PATH_PATTERN=/[?=&#%]/;SECRET_PATH_PATTERN=/token|secret|passw|credential|api[-_]?key|auth|signature|session/i;OPAQUE_SEGMENT_MIN_LENGTH=32;PROFILE_MIN_INTERVAL_MS=6e4;lastProfileAtMs=Number.NEGATIVE_INFINITY}});async function restoreDeploymentWithCrashRecoveryBudget(input2){await input2.beforeClaim?.();if(await input2.resolveStableRecovery?.()){return{alreadyStable:true}}const recovery=await claimRuntimeCrashRecoveryAttempt({db:input2.db,appId:input2.app.id,instanceId:input2.instanceId,evidence:{artifactRef:input2.artifactRef,sourceGenerationRef:input2.sourceGenerationRef,runtimeGenerationRef:input2.runtimeGenerationRef,nodeId:input2.nodeId},now:input2.now,inspectAttempt:input2.inspectRestoreAttempt?({recoveryId,attemptEpoch})=>input2.inspectRestoreAttempt(runtimeCrashRecoveryRequestId({appId:input2.app.id,deploymentId:input2.currentDeploymentId,recoveryId,attemptEpoch})):void 0,immediateRetryCapability:input2.immediateRetryCapability});if(recovery.kind==="deferred"){throw new Error("RUNTIME_CRASH_RECOVERY_BACKOFF")}const requestId=runtimeCrashRecoveryRequestId({appId:input2.app.id,deploymentId:input2.currentDeploymentId,recoveryId:recovery.recoveryId,attemptEpoch:recovery.attemptEpoch});const restored=await input2.restore({db:input2.db,missingSourceRecoveryTarget:input2.missingSourceRecoveryTarget,app:input2.app,environment:input2.environment,currentDeploymentId:input2.currentDeploymentId,requestId,correlationId:input2.correlationId,sourceActivationId:input2.sourceActivationId,beforeActivationCommit:input2.beforeActivationCommit});return restored}function runtimeCrashRecoveryRequestId(input2){const recoveryKey=input2.recoveryId.replace(/^remediation_/u,"").slice(0,16);return`restore_${input2.appId}_${input2.deploymentId}_${recoveryKey}_${input2.attemptEpoch}`}var init_runtime_crash_recovery_orchestrator=__esm({"../platform/src/runtime-crash-recovery-orchestrator.ts"(){"use strict";init_runtime_crash_recovery_store()}});import{and as and56,eq as eq62,gt as gt13,inArray as inArray33,isNotNull as isNotNull10,isNull as isNull24,or as or20,sql as sql149}from"drizzle-orm";function boundedDiagnosis(diagnosis){if(!diagnosis)return void 0;const entries=Object.entries(diagnosis).slice(0,DIAGNOSIS_MAX_KEYS).map(([key2,value2])=>[key2.slice(0,40),typeof value2==="string"?value2.slice(0,DIAGNOSIS_MAX_TEXT):value2]);return entries.length>0?Object.fromEntries(entries):void 0}async function recordRuntimeControlPlaneExit(input2){const now=input2.now??new Date;const[appRows,instanceRows]=await Promise.all([input2.db.select({name:apps.name,status:apps.status}).from(apps).where(eq62(apps.id,input2.appId)),input2.db.select({instanceId:appRuntimeInstances.instanceId,nodeEpoch:appRuntimeInstances.nodeEpoch,leaseEpoch:appRuntimeInstances.leaseEpoch,processIdentityHash:appRuntimeInstances.processIdentityHash,pid:appRuntimeInstances.pid,state:appRuntimeInstances.state}).from(appRuntimeInstances).where(and56(eq62(appRuntimeInstances.appId,input2.appId),eq62(appRuntimeInstances.instanceId,input2.instanceId),eq62(appRuntimeInstances.nodeEpoch,input2.nodeEpoch),eq62(appRuntimeInstances.leaseEpoch,input2.leaseEpoch)))]);const app2=appRows[0];const instance=instanceRows[0];if(!app2||!instance||instance.processIdentityHash!==input2.processIdentityHash){return{expected:false,consumed:false,replayed:false,restartBudgetDelta:1}}const expectedIntentRows=input2.expectedIntentId?await input2.db.select({id:runtimeStopIntents.id,reason:runtimeStopIntents.reason,expiresAt:runtimeStopIntents.expiresAt,consumedAt:runtimeStopIntents.consumedAt,consumedByEventId:runtimeStopIntents.consumedByEventId,cancelledAt:runtimeStopIntents.cancelledAt,dispatchStartedAt:runtimeStopIntents.dispatchStartedAt}).from(runtimeStopIntents).where(and56(eq62(runtimeStopIntents.id,input2.expectedIntentId),eq62(runtimeStopIntents.appId,input2.appId),eq62(runtimeStopIntents.instanceId,input2.instanceId),eq62(runtimeStopIntents.nodeEpoch,input2.nodeEpoch),eq62(runtimeStopIntents.leaseEpoch,input2.leaseEpoch),input2.expectedNodeId?eq62(runtimeStopIntents.nodeId,input2.expectedNodeId):sql149`true`,input2.expectedIntentReason?eq62(runtimeStopIntents.reason,input2.expectedIntentReason):sql149`true`)):[];const expectedIntent=expectedIntentRows[0];if(input2.expectedIntentId&&!expectedIntent){return{expected:false,consumed:false,replayed:false,restartBudgetDelta:1}}if(expectedIntent?.consumedAt&&!expectedIntent.cancelledAt&&expectedIntent.consumedByEventId&&["stopped","exited"].includes(instance.state)){return{expected:true,consumed:false,replayed:true,restartBudgetDelta:0,eventId:expectedIntent.consumedByEventId,intentId:expectedIntent.id}}const expectedIntentIsPending=expectedIntent&&!expectedIntent.consumedAt&&!expectedIntent.cancelledAt&&(expectedIntent.expiresAt>now||expectedIntent.dispatchStartedAt!==null||input2.allowExpiredAfterExactObservation===true);const intentRows=expectedIntentIsPending?[{id:expectedIntent.id}]:input2.expectedIntentId?[]:await input2.db.select({id:runtimeStopIntents.id}).from(runtimeStopIntents).where(and56(eq62(runtimeStopIntents.appId,input2.appId),eq62(runtimeStopIntents.instanceId,input2.instanceId),eq62(runtimeStopIntents.nodeEpoch,input2.nodeEpoch),eq62(runtimeStopIntents.leaseEpoch,input2.leaseEpoch),input2.expectedIntentReason?eq62(runtimeStopIntents.reason,input2.expectedIntentReason):sql149`true`,isNull24(runtimeStopIntents.consumedAt),isNull24(runtimeStopIntents.cancelledAt),or20(gt13(runtimeStopIntents.expiresAt,now),isNotNull10(runtimeStopIntents.dispatchStartedAt),input2.allowExpiredAfterExactObservation?sql149`true`:sql149`false`)));const intent=intentRows[0];const eventRows=await input2.db.insert(appRuntimeEvents).values({appId:input2.appId,appName:app2.name,kind:intent?"runtime_stop_exit_observed":"runtime_exit_unexpected",source:input2.source??"runtime_control_plane",severity:intent?"info":"warn",statusBefore:app2.status,statusAfter:app2.status,exitCode:input2.code,signal:input2.signal??null,workerKind:input2.workerKind??null,workerId:input2.workerId??null,pid:input2.pid??instance.pid,message:intent?"Runtime exit matched a durable stop intent":"Runtime exited without a matching durable stop intent",metadataJson:JSON.stringify({instanceId:input2.instanceId,nodeEpoch:input2.nodeEpoch,leaseEpoch:input2.leaseEpoch,...intent?{stopIntentId:intent.id}:{},...boundedDiagnosis(input2.diagnosis)?{diagnosis:boundedDiagnosis(input2.diagnosis)}:{}}),createdAt:now}).returning({id:appRuntimeEvents.id});const eventId=eventRows[0]?.id;if(!eventId)throw new Error("RUNTIME_EXIT_EVENT_WRITE_FAILED");if(intent){const result3=await consumeRuntimeStopIntent({db:input2.db,appId:input2.appId,intentId:intent.id,instanceId:input2.instanceId,nodeEpoch:input2.nodeEpoch,leaseEpoch:input2.leaseEpoch,eventId,now,allowExpiredAfterExactObservation:input2.allowExpiredAfterExactObservation,expectedIntentId:input2.expectedIntentId??intent.id,expectedIntentReason:input2.expectedIntentReason,expectedProcessIdentityHash:input2.processIdentityHash,expectedNodeId:input2.expectedNodeId});if(result3.expected){if(!result3.replayed)return{...result3,eventId,intentId:intent.id};const receiptRows=await input2.db.select({eventId:runtimeStopIntents.consumedByEventId}).from(runtimeStopIntents).where(and56(eq62(runtimeStopIntents.id,intent.id),eq62(runtimeStopIntents.appId,input2.appId),eq62(runtimeStopIntents.instanceId,input2.instanceId)));return{...result3,eventId:receiptRows[0]?.eventId??eventId,intentId:intent.id}}}await input2.db.update(appRuntimeInstances).set({state:"exited",exitCode:input2.code,signal:input2.signal??null,lastObservedAt:now,updatedAt:now}).where(and56(eq62(appRuntimeInstances.appId,input2.appId),eq62(appRuntimeInstances.instanceId,input2.instanceId),eq62(appRuntimeInstances.nodeEpoch,input2.nodeEpoch),eq62(appRuntimeInstances.leaseEpoch,input2.leaseEpoch),eq62(appRuntimeInstances.processIdentityHash,input2.processIdentityHash),inArray33(appRuntimeInstances.state,["starting","ready","serving","draining","unknown"])));return{expected:false,consumed:false,replayed:false,restartBudgetDelta:1,eventId,intentId:intent?.id??null}}var DIAGNOSIS_MAX_KEYS,DIAGNOSIS_MAX_TEXT;var init_runtime_exit_store=__esm({"../platform/src/runtime-exit-store.ts"(){"use strict";init_schema();init_runtime_stop_intent_store();DIAGNOSIS_MAX_KEYS=16;DIAGNOSIS_MAX_TEXT=600}});import{resolve as resolve135}from"node:path";function resolveAppCandidateGenerationRoot(env,fallbackAppsRoot){const appsRoot=env.GENCOW_APPS_DIR||fallbackAppsRoot;return resolve135(env.GENCOW_APP_GENERATIONS_DIR||resolve135(appsRoot,".control-plane","generations"))}function resolveAppCandidateGenerationWorkspace(generationRoot2,generationRef){const match2=generationRef.match(GENERATION_REF2);return match2?resolve135(generationRoot2,"v1",match2[1],"workspace"):null}var GENERATION_REF2;var init_app_candidate_generation_path=__esm({"../platform/src/app-candidate-generation-path.ts"(){"use strict";GENERATION_REF2=/^app-generation-v1\.([0-9a-f]{64})$/u}});import{sql as sql150}from"drizzle-orm";function firstRow(result3){if(Array.isArray(result3))return result3[0];const rows8=result3?.rows;return Array.isArray(rows8)?rows8[0]:void 0}async function acquireRuntimeControlPlaneLock(input2){for(let attempt=0;attempt<LOCK_RETRY_ATTEMPTS;attempt+=1){const result3=await input2.db.execute(sql150`SELECT pg_try_advisory_xact_lock(hashtextextended(${`runtime-control-plane:${input2.appId}`}::text, 0)) AS acquired`);const acquired=firstRow(result3)?.acquired;if(acquired===true||acquired==="t"||acquired==="true")return;if(attempt+1<LOCK_RETRY_ATTEMPTS){await new Promise(resolve159=>setTimeout(resolve159,LOCK_RETRY_DELAY_MS))}}throw new Error("RUNTIME_CONTROL_PLANE_LOCK_BUSY")}var LOCK_RETRY_ATTEMPTS,LOCK_RETRY_DELAY_MS;var init_runtime_control_plane_lock=__esm({"../platform/src/runtime-control-plane-lock.ts"(){"use strict";LOCK_RETRY_ATTEMPTS=10;LOCK_RETRY_DELAY_MS=100}});function processEnvironmentMatchesRuntimeTarget(source,appName,target){const entries=source.split("\0").filter(Boolean).map(entry=>{const separator=entry.indexOf("=");return separator>0?[entry.slice(0,separator),entry.slice(separator+1)]:[entry,""]});const env=new Map(entries);const expected=[["GENCOW_APP_NAME",appName],["GENCOW_CONTROL_PLANE_APP_ID",String(target.appId)],["GENCOW_CONTROL_PLANE_DEPLOYMENT_ID",String(target.deploymentId)],["GENCOW_CONTROL_PLANE_ACTIVATION_ID",target.activationId],["GENCOW_CONTROL_PLANE_INSTANCE_ID",target.instanceId],["GENCOW_CONTROL_PLANE_ARTIFACT_REF",target.artifactRef],["GENCOW_CONTROL_PLANE_SOURCE_GENERATION_REF",target.sourceGenerationRef],["GENCOW_CONTROL_PLANE_RUNTIME_GENERATION_REF",target.runtimeGenerationRef],["GENCOW_CONTROL_PLANE_NODE_ID",target.nodeId],["GENCOW_CONTROL_PLANE_NODE_EPOCH",String(target.nodeEpoch)],["GENCOW_CONTROL_PLANE_LEASE_EPOCH",String(target.leaseEpoch)],["GENCOW_CONTROL_PLANE_PORT",String(target.port)]];return expected.every(([key2,value2])=>env.get(key2)===value2&&entries.filter(([entryKey])=>entryKey===key2).length===1)}var init_runtime_process_environment_binding=__esm({"../platform/src/runtime-process-environment-binding.ts"(){"use strict"}});import{resolve as resolve136}from"node:path";function fail47(){throw new Error("RUNTIME_STOP_OWNERSHIP_AMBIGUOUS")}function absentFile(readFile23,path5){try{readFile23(path5);return false}catch(error62){return error62.code==="ENOENT"}}function assertServingOrphanRunnerReceiptsAbsent(input2){if(!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(input2.appName))fail47();if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(input2.instanceId))fail47();const names=new Set([input2.appName,directRunnerRuntimeName(input2.instanceId)]);for(const name of names){for(const extension of["pid","identity.json"]){if(!absentFile(input2.readFile,resolve136(input2.pidsDir,`${name}.${extension}`)))fail47()}}}function memberPids(source){const pids=source.trim().split(/\s+/u).filter(Boolean).map(Number);if(pids.length<2||new Set(pids).size!==pids.length||pids.some(pid=>!Number.isSafeInteger(pid)||pid<=1))fail47();return pids}function proveExactServingOrphanCgroup(input2){const{target,readFile:readFile23,readLink}=input2;if(target.runnerKind!=="direct"||target.runnerRef!==`direct:${target.instanceId}`)fail47();const observed2=observeLinuxKernelProcessIdentity(target.pid,readFile23);if(!runtimeKernelProcessIdentityMatches(observed2,target))fail47();const cgroupMatch=readFile23(`/proc/${target.pid}/cgroup`).trim().match(COWBOX_CGROUP);if(!cgroupMatch)fail47();const groupLeaderPid=Number(cgroupMatch[2]);if(groupLeaderPid!==target.processGroupId)fail47();const cgroup=cgroupMatch[1];const membersPath=`/sys/fs/cgroup${cgroup}/cgroup.procs`;const members2=memberPids(readFile23(membersPath));if(!members2.includes(target.pid)||!members2.includes(groupLeaderPid))fail47();const expectedWorkspace=resolveAppCandidateGenerationWorkspace(resolve136(input2.generationRoot),target.sourceGenerationRef);if(!expectedWorkspace)fail47();const executable=readLink(`/proc/${groupLeaderPid}/exe`);const command=readFile23(`/proc/${groupLeaderPid}/cmdline`).split("\0").filter(Boolean);if(!(COWBOX_EXECUTABLE.test(executable)||executable===INSTALLED_COWBOX_EXECUTABLE)||command[0]!==executable||!command.includes(`APP_DIR=${expectedWorkspace}`)||!command.includes(`APP_PORT=${target.port}`)||!command.includes(`TMP_DIR=${directRunnerTmpDir(directRunnerRuntimeName(target.instanceId))}`))fail47();for(const pid of members2){const stat13=readFile23(`/proc/${pid}/stat`);const state2=parseLinuxProcessState(stat13);if(!state2||state2==="Z"||parseLinuxProcStat(stat13)?.processGroupId!==target.processGroupId)fail47();if(readFile23(`/proc/${pid}/cgroup`).trim()!==`0::${cgroup}`)fail47();if(pid!==groupLeaderPid&&!processEnvironmentMatchesRuntimeTarget(readFile23(`/proc/${pid}/environ`),input2.appName,target))fail47()}if(memberPids(readFile23(membersPath)).join(",")!==members2.join(","))fail47();if(!runtimeKernelProcessIdentityMatches(observeLinuxKernelProcessIdentity(target.pid,readFile23),target))fail47();return{killPath:`/sys/fs/cgroup${cgroup}/cgroup.kill`,membersPath,members:members2}}function proveServingOrphanListenersOwned(input2){const{target,readFile:readFile23,readLink,readDir}=input2;const listeners=new Set;for(const family of["tcp","tcp6"]){const lines=readFile23(`/proc/${target.pid}/net/${family}`).trim().split("\n");if(!lines[0]?.includes("local_address")||!lines[0]?.includes("inode"))fail47();for(const line of lines.slice(1)){const fields=line.trim().split(/\s+/u);if(fields.length<10||!/^[0-9A-Fa-f]+:[0-9A-Fa-f]{4}$/u.test(fields[1]??""))fail47();const port=Number.parseInt(fields[1].split(":")[1],16);if(port!==target.port||fields[3]!=="0A")continue;const inode=fields[9];if(!inode||!/^[1-9][0-9]*$/u.test(inode))fail47();listeners.add(inode)}}if(listeners.size===0)fail47();const owned=new Set;for(const pid of input2.members){for(const fd of readDir(`/proc/${pid}/fd`)){if(!/^[0-9]+$/u.test(fd))fail47();let link4;try{link4=readLink(`/proc/${pid}/fd/${fd}`)}catch(error62){if(error62.code==="ENOENT")continue;throw error62}const match2=link4.match(/^socket:\[([1-9][0-9]*)\]$/u);if(match2)owned.add(match2[1])}}if([...listeners].some(inode=>!owned.has(inode)))fail47()}var COWBOX_CGROUP,COWBOX_EXECUTABLE,INSTALLED_COWBOX_EXECUTABLE;var init_runtime_serving_orphan_cgroup_proof=__esm({"../platform/src/runtime-serving-orphan-cgroup-proof.ts"(){"use strict";init_app_candidate_generation_path();init_runtime_process_environment_binding();init_direct_runner_runtime_contract();init_runtime_process_identity();COWBOX_CGROUP=/^0::(\/cowbox\/cowbox-(\d+)-\d+)$/u;COWBOX_EXECUTABLE=/^\/opt\/gencow\/shared\/runtime-generations\/[^/]+\/runtime\/bin\/cowbox$/u;INSTALLED_COWBOX_EXECUTABLE="/usr/local/bin/cowbox"}});import{readFileSync as readFileSync71,readdirSync as readdirSync28,readlinkSync as readlinkSync3,writeFileSync as writeFileSync19}from"node:fs";import{resolve as resolve137}from"node:path";import{and as and57,eq as eq63,gt as gt14,inArray as inArray34,isNull as isNull25,ne as ne15,or as or21,sql as sql151}from"drizzle-orm";function fail48(code="RUNTIME_STOP_OWNERSHIP_AMBIGUOUS"){throw new Error(code)}async function stopExactServingOrphanCgroup(input2){const readFile23=input2.readFile??(path5=>readFileSync71(path5,"utf8"));const readLink=input2.readLink??(path5=>readlinkSync3(path5));const readDir=input2.readDir??(path5=>readdirSync28(path5));const writeFile8=input2.writeFile??((path5,value2)=>writeFileSync19(path5,value2));if(input2.command.appId!==input2.target.appId||!input2.command.leaseOwner||!Number.isSafeInteger(input2.command.leaseEpoch)||input2.command.leaseEpoch<1||input2.currentNodeId!==input2.target.nodeId)fail48();let stage="app_binding";await input2.db.transaction(async tx=>{await tx.execute(sql151`SELECT pg_advisory_xact_lock(hashtextextended(${`app-activation:${input2.target.appId}`}::text, 0))`);await tx.execute(sql151`SELECT pg_advisory_xact_lock(hashtextextended(${`runtime-stop-intent:${input2.target.appId}`}::text, 0))`);await acquireRuntimeControlPlaneLock({db:tx,appId:input2.target.appId});const appRows=await tx.select({name:apps.name,instanceId:apps.instanceId,currentDeploymentId:apps.currentDeployId,nodeId:apps.nodeId,hasBackend:apps.hasBackend,archiveStatus:apps.archiveStatus}).from(apps).where(eq63(apps.id,input2.target.appId)).for("update");const app2=appRows[0];if(!app2||app2.name!==input2.appName||app2.instanceId!==input2.target.appInstanceId||app2.currentDeploymentId!==input2.target.deploymentId||app2.nodeId!==input2.target.nodeId||!app2.hasBackend||!["none","thawed"].includes(app2.archiveStatus))fail48();stage="command_receipt";const commandRows=await tx.select({appId:runtimeLifecycleRequests.appId,action:runtimeLifecycleRequests.action,actorKind:runtimeLifecycleRequests.actorKind,actorIdHash:runtimeLifecycleRequests.actorIdHash,state:runtimeLifecycleRequests.state,targetRuntimeState:runtimeLifecycleRequests.targetRuntimeState,leaseOwner:runtimeLifecycleRequests.leaseOwner,leaseEpoch:runtimeLifecycleRequests.leaseEpoch,leaseExpiresAt:runtimeLifecycleRequests.leaseExpiresAt,payloadJson:runtimeLifecycleRequests.evidencePayloadJson,digest:runtimeLifecycleRequests.evidenceDigest}).from(runtimeLifecycleRequests).where(eq63(runtimeLifecycleRequests.id,input2.command.id)).for("update");const command=commandRows[0];if(!command||command.appId!==input2.command.appId||command.action!=="converge"||command.actorKind!=="admin"||!command.actorIdHash||command.state!=="executing"||command.targetRuntimeState!=="running"||command.leaseOwner!==input2.command.leaseOwner||command.leaseEpoch!==input2.command.leaseEpoch)fail48("RUNTIME_CONVERGENCE_COMMAND_LEASE_LOST");const binding=parseRuntimeServingOrphanBinding({payloadJson:command.payloadJson,digest:command.digest});if(!binding||!runtimeServingOrphanBindingMatches(binding,input2.target))fail48();const desiredRows=await tx.select({appId:appRuntimeDesiredState.appId}).from(appRuntimeDesiredState).where(eq63(appRuntimeDesiredState.appId,input2.target.appId)).for("update");const activationRows=await tx.select({id:appDeploymentActivations.id}).from(appDeploymentActivations).where(eq63(appDeploymentActivations.id,input2.target.activationId)).for("update");const instanceRows=await tx.select({id:appRuntimeInstances.instanceId}).from(appRuntimeInstances).where(eq63(appRuntimeInstances.instanceId,input2.target.instanceId)).for("update");if(desiredRows.length!==1||activationRows.length!==1||instanceRows.length!==1)fail48();stage="route_authority";const routeRows=await tx.execute(sql151`
|