@xlinklight/testkit 0.0.0-stage → 7.0.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +169 -3
- package/content/platform-baseline.sql +273 -0
- package/package.json +274 -3
- package/src/acceptance-oracle.d.mts +24 -0
- package/src/acceptance-oracle.mjs +79 -0
- package/src/architecture-database.d.mts +36 -0
- package/src/architecture-database.mjs +64 -0
- package/src/artifact-build.d.mts +3 -0
- package/src/artifact-build.mjs +35 -0
- package/src/artifact-declarations.mjs +24 -0
- package/src/artifact-graphs.mjs +61 -0
- package/src/artifact-lock.mjs +32 -0
- package/src/artifact-observation.mjs +50 -0
- package/src/artifact-publisher.d.mts +30 -0
- package/src/artifact-publisher.mjs +84 -0
- package/src/browser-lifecycle.mjs +45 -0
- package/src/browser-operation-owner.mjs +28 -0
- package/src/cloudflare-browser.d.mts +14 -0
- package/src/cloudflare-browser.mjs +41 -0
- package/src/cloudflare-build.d.mts +19 -0
- package/src/cloudflare-build.mjs +61 -0
- package/src/cloudflare-http.d.mts +5 -0
- package/src/cloudflare-http.mjs +65 -0
- package/src/cloudflare-pages.d.mts +34 -0
- package/src/cloudflare-pages.mjs +170 -0
- package/src/cloudflare-provider-http.d.mts +8 -0
- package/src/cloudflare-provider-http.mjs +32 -0
- package/src/cloudflare-worker-package.d.mts +6 -0
- package/src/cloudflare-worker-package.mjs +24 -0
- package/src/cloudflare-worker-qualification.d.mts +4 -0
- package/src/cloudflare-worker-qualification.mjs +63 -0
- package/src/cloudflare-workers.d.mts +37 -0
- package/src/cloudflare-workers.mjs +90 -0
- package/src/cluster-directory.d.mts +16 -0
- package/src/cluster-directory.mjs +90 -0
- package/src/core-publishing.d.mts +75 -0
- package/src/core-publishing.mjs +214 -0
- package/src/dev-command-runner.mjs +97 -0
- package/src/fixture-path.mjs +19 -0
- package/src/function-admission.d.mts +1 -0
- package/src/function-admission.mjs +58 -0
- package/src/host-artifact.mjs +32 -0
- package/src/host-stop.mjs +15 -0
- package/src/independent-artifact-qualification.mjs +67 -0
- package/src/independent-runtime-qualification.mjs +647 -0
- package/src/isolated-browser-child.mjs +29 -0
- package/src/isolated-browser.mjs +69 -0
- package/src/lifecycle-trace.mjs +32 -0
- package/src/managed-native-fixture.d.mts +84 -0
- package/src/managed-native-fixture.mjs +209 -0
- package/src/native-fixture.mjs +125 -0
- package/src/native-platform.mjs +56 -0
- package/src/operator-accounts.mjs +103 -0
- package/src/operator-vault.d.mts +2 -0
- package/src/operator-vault.mjs +9 -0
- package/src/owned-process.mjs +75 -0
- package/src/owner-build-cli.d.mts +1 -0
- package/src/owner-build-cli.mjs +31 -0
- package/src/owner-database.mjs +215 -0
- package/src/owner-operator-build.d.mts +1 -0
- package/src/owner-operator-build.mjs +33 -0
- package/src/owner-package-build.d.mts +2 -0
- package/src/owner-package-build.mjs +29 -0
- package/src/owner-production-browser.mjs +215 -0
- package/src/owner-production-instances.mjs +41 -0
- package/src/owner-production.d.mts +104 -0
- package/src/owner-production.mjs +338 -0
- package/src/owner-release.mjs +41 -0
- package/src/owner-worker-build.d.mts +3 -0
- package/src/owner-worker-build.mjs +83 -0
- package/src/prebuilt-build.d.mts +8 -0
- package/src/prebuilt-build.mjs +69 -0
- package/src/prebuilt-output.d.mts +2 -0
- package/src/prebuilt-output.mjs +104 -0
- package/src/production-hosts.mjs +38 -0
- package/src/publisher-acceptance-host-cli.mjs +23 -0
- package/src/publisher-acceptance-owner.mjs +116 -0
- package/src/publisher-acceptance-runner.mjs +250 -0
- package/src/publisher-acceptance-service.mjs +49 -0
- package/src/publisher-acceptance.d.mts +61 -0
- package/src/publisher-acceptance.mjs +3 -0
- package/src/publishing-source.d.mts +11 -0
- package/src/publishing-source.mjs +32 -0
- package/src/qualification-function-host.mjs +26 -0
- package/src/qualification-route-owner.mjs +64 -0
- package/src/qualification-transport.mjs +18 -0
- package/src/registry-core-selection.mjs +41 -0
- package/src/release-artifact.d.mts +17 -0
- package/src/release-artifact.mjs +113 -0
- package/src/release-build.d.mts +12 -0
- package/src/release-build.mjs +71 -0
- package/src/release-cli.d.mts +27 -0
- package/src/release-cli.mjs +79 -0
- package/src/release-control.mjs +45 -0
- package/src/release-coordinator.d.mts +9 -0
- package/src/release-coordinator.mjs +222 -0
- package/src/release-credentials.d.mts +8 -0
- package/src/release-credentials.mjs +97 -0
- package/src/release-environment.mjs +60 -0
- package/src/release-mutex.d.mts +10 -0
- package/src/release-mutex.mjs +38 -0
- package/src/release-operator.d.mts +6 -0
- package/src/release-operator.mjs +59 -0
- package/src/release-supabase.d.mts +7 -0
- package/src/release-supabase.mjs +37 -0
- package/src/release-vercel.d.mts +22 -0
- package/src/release-vercel.mjs +51 -0
- package/src/release-writer.d.mts +6 -0
- package/src/release-writer.mjs +172 -0
- package/src/retained-postgres-shutdown.d.mts +51 -0
- package/src/retained-postgres-shutdown.mjs +262 -0
- package/src/schema-snapshot.mjs +51 -0
- package/src/static-ui-artifact.mjs +54 -0
- package/src/static-ui-routes.mjs +3 -0
- package/src/temporary-acquisition.mjs +62 -0
- package/src/temporary-scope.d.mts +47 -0
- package/src/temporary-scope.mjs +268 -0
- package/src/unscoped-read.mjs +14 -0
- package/src/worker-artifact.mjs +214 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type {JsonValue} from '@xlinklight/contracts';
|
|
2
|
+
import type {PublishingDeploymentStage,PublishingDurableJournal,PublishingActivation,preparePublishingRelease} from '@xlinklight/publishing/worker';
|
|
3
|
+
import type {PublishingConfiguration,PublishingIntent,PublishingMetadataTransport} from '@xlinklight/publishing';
|
|
4
|
+
import type {SolutionReleaseManifest} from '@xlinklight/contracts';
|
|
5
|
+
import type {ArtifactOperationBinding} from '@openge/forge-artifact-publish';
|
|
6
|
+
|
|
7
|
+
type StageContext=Parameters<PublishingDeploymentStage['createDeployment']>[0];
|
|
8
|
+
type Candidate=Awaited<ReturnType<typeof preparePublishingRelease>>;
|
|
9
|
+
type Projection=Parameters<typeof preparePublishingRelease>[0];
|
|
10
|
+
/** Installed trusted callbacks must honor signal, settle all owned resources
|
|
11
|
+
* before returning, and use this explicit bounded request for Core HTTP.
|
|
12
|
+
* Observation callbacks must never replay an existing mutation or signer.
|
|
13
|
+
* A production phase may continue from a proven original checkpoint.
|
|
14
|
+
* No callback may import package code. */
|
|
15
|
+
export interface CorePublishingOperation {
|
|
16
|
+
context:StageContext;candidate:Candidate;projection:Projection;
|
|
17
|
+
configuration:PublishingConfiguration;intent:PublishingIntent;
|
|
18
|
+
signal:AbortSignal;request:typeof fetch;metadataTransport:PublishingMetadataTransport;
|
|
19
|
+
timeoutMilliseconds:number;
|
|
20
|
+
binding:ArtifactOperationBinding;
|
|
21
|
+
}
|
|
22
|
+
export interface CoreAcceptanceReceipt {
|
|
23
|
+
status:'PASS';releaseDigest:string;content:{manifestSha256:string};
|
|
24
|
+
syntheticInstancesCreated:number;syntheticInstancesDisabled:number;
|
|
25
|
+
closure:{status:'closed';activeRequests:0};
|
|
26
|
+
/** Small sanitized actual owner-runner evidence; never credentials or bodies. */
|
|
27
|
+
evidence?:JsonValue;
|
|
28
|
+
}
|
|
29
|
+
export type CoreAcceptanceOperation=CorePublishingOperation&{
|
|
30
|
+
manifest:Readonly<SolutionReleaseManifest>;
|
|
31
|
+
openQualification(input:{jobId:string;actors:readonly [string,string]}):Promise<void>;
|
|
32
|
+
};
|
|
33
|
+
export interface CoreExternalAcceptance {
|
|
34
|
+
jobId:string;receiptSha256:string;receipt:CoreAcceptanceReceipt;
|
|
35
|
+
}
|
|
36
|
+
/** Consumer-owned bounded HTTP port; no optional transport SDK is required.
|
|
37
|
+
* A void close confirms retirement. A returned receipt must prove closed/0. */
|
|
38
|
+
export interface CorePublishingHttpTransport {
|
|
39
|
+
fetch:typeof fetch;
|
|
40
|
+
close():Promise<void|{status:'closed'|'unconfirmed';activeRequests:number}>;
|
|
41
|
+
}
|
|
42
|
+
export interface CorePublishingOptions {
|
|
43
|
+
coreOrigin:string;credentialId:string;configurationSha256:string;
|
|
44
|
+
journal:Pick<PublishingDurableJournal,'load'|'compareAndSet'>;
|
|
45
|
+
uiStageName:string;serverStageName:string;uiReceiptPath:string;serverReceiptPath:string;
|
|
46
|
+
loadAccount(input:{configuration:PublishingConfiguration;intent:PublishingIntent;signal:AbortSignal}):Promise<{email:string;password:string}>;
|
|
47
|
+
/** Sign the validated inert candidate with the selected installed publisher.
|
|
48
|
+
* This adapter independently verifies the signature and exact payload. */
|
|
49
|
+
signCandidate(input:Candidate&{signal:AbortSignal}):Promise<Readonly<SolutionReleaseManifest>>;
|
|
50
|
+
prepareOriginAdmission(input:CorePublishingOperation):Promise<{state:'succeeded'|'pending'}>;
|
|
51
|
+
observeOriginAdmission(input:CorePublishingOperation&{reference?:string}):Promise<{state:'succeeded'|'pending'|'unknown'}>;
|
|
52
|
+
/** Authorize one separately recorded recovery registration after a fresh
|
|
53
|
+
* Core 404 for the exact original immutable candidate. */
|
|
54
|
+
authorizeRegistrationRecovery?(input:CorePublishingOperation):boolean|Promise<boolean>;
|
|
55
|
+
/** Persist the job identity, open the exact Core scope, and dispatch it once. */
|
|
56
|
+
startAcceptance(input:CoreAcceptanceOperation):Promise<string>;
|
|
57
|
+
/** Observe the original signed completion. A provably absent acceptance
|
|
58
|
+
* admission may be completed idempotently under the original job identity. */
|
|
59
|
+
observeAcceptance(input:CoreAcceptanceOperation&{reference?:string}):Promise<CoreExternalAcceptance|undefined>;
|
|
60
|
+
/** Installed signer; final recovery reads the original durable activation
|
|
61
|
+
* without invoking this callback again. Public verification/current Core
|
|
62
|
+
* admission still runs independently before the result can succeed. */
|
|
63
|
+
createActivation(input:{configuration:PublishingConfiguration;intent:PublishingIntent;manifest:Readonly<SolutionReleaseManifest>;acceptanceReceiptSha256:string;metadataTransport:PublishingMetadataTransport;signal:AbortSignal}):Promise<PublishingActivation>;
|
|
64
|
+
/** Trusted constructor-only qualification port, lazy inside the operation.
|
|
65
|
+
* close must actually retire its dispatcher and settle requests. */
|
|
66
|
+
createHttpTransport(options:{signal:AbortSignal}):CorePublishingHttpTransport|Promise<CorePublishingHttpTransport>;
|
|
67
|
+
/** Defaults to the public raw-byte observePreparedDeployment helper. A
|
|
68
|
+
* replacement is an explicit trusted service composition port, not a client
|
|
69
|
+
* supplied attestation. It must verify actual deployed receipts/assets. */
|
|
70
|
+
verifyDeployment?(input:Projection&{request:typeof fetch}):Promise<unknown>;
|
|
71
|
+
}
|
|
72
|
+
/** Stages after the provider deploys. Candidate qualification and closure
|
|
73
|
+
* precede production drain and promotion. Outputs and evidence <=64 KiB.
|
|
74
|
+
* No provider/Git/source controller or listener is created here. */
|
|
75
|
+
export function createCorePublishingStages(options:CorePublishingOptions):PublishingDeploymentStage[];
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
3
|
+
import {preparePublishingRelease,verifyPublishingActivation} from '@xlinklight/publishing/worker';
|
|
4
|
+
import {verifySolutionRelease,releasePayload,resolveApprovedIndependentRelease} from '@xlinklight/platform/worker';
|
|
5
|
+
import {withReleaseControlSession,releaseJson} from './release-control.mjs';
|
|
6
|
+
import {observePreparedDeployment} from './artifact-observation.mjs';
|
|
7
|
+
|
|
8
|
+
const hash=value=>createHash('sha256').update(typeof value==='string'?value:JSON.stringify(value)).digest('hex');
|
|
9
|
+
const fail=(code,cause)=>Error('CORE_PUBLISHING_'+code,cause===undefined?undefined:{cause});
|
|
10
|
+
const sha=value=>typeof value==='string'&&/^[a-f0-9]{64}$/.test(value);
|
|
11
|
+
const names=['core-origins','core-register','core-drain','core-activate','core-acceptance','core-activation'];
|
|
12
|
+
const artifactName='core-artifacts';
|
|
13
|
+
function snapshot(value){try{const bytes=JSON.stringify(value);if(typeof bytes!=='string'||Buffer.byteLength(bytes)>65536)throw Error();return JSON.parse(bytes);}catch{throw fail('RESULT_INVALID');}}
|
|
14
|
+
function previous(context,name){const matches=context.previous.filter(item=>item.name===name);if(matches.length!==1)throw fail('PREDECESSOR_MISSING');return matches[0].output;}
|
|
15
|
+
function origin(value){try{const url=new URL(value);if(url.protocol!=='https:'||url.origin!==value)throw Error();return value;}catch{throw fail('ORIGIN_INVALID');}}
|
|
16
|
+
|
|
17
|
+
/** Bounded explicit Core operations for the existing PublishingWorker. All ports
|
|
18
|
+
* are installed service infrastructure; no uploaded module is ever imported.
|
|
19
|
+
* Factories and readResult are synchronous, pure and resource-free. */
|
|
20
|
+
export function createCorePublishingStages(options){
|
|
21
|
+
const {coreOrigin,credentialId,configurationSha256,journal,uiStageName,serverStageName,uiReceiptPath,serverReceiptPath,loadAccount,signCandidate,prepareOriginAdmission,observeOriginAdmission,authorizeRegistrationRecovery,startAcceptance,observeAcceptance,createActivation,createHttpTransport,verifyDeployment=observePreparedDeployment}=options;
|
|
22
|
+
if(authorizeRegistrationRecovery!==undefined&&typeof authorizeRegistrationRecovery!=='function')throw fail('CONFIGURATION_INVALID');
|
|
23
|
+
origin(coreOrigin);
|
|
24
|
+
if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(credentialId??'')||!sha(configurationSha256)||!journal||['load','compareAndSet'].some(name=>typeof journal[name]!=='function')||![uiStageName,serverStageName].every(name=>typeof name==='string'&&/^[a-z][a-z0-9-]{0,63}$/.test(name)&&!names.includes(name)&&name!==artifactName)||uiStageName===serverStageName||typeof uiReceiptPath!=='string'||!uiReceiptPath.startsWith('ui/')||typeof serverReceiptPath!=='string'||!serverReceiptPath.startsWith('server/')||![loadAccount,signCandidate,prepareOriginAdmission,observeOriginAdmission,startAcceptance,observeAcceptance,createActivation,verifyDeployment,createHttpTransport].every(value=>typeof value==='function'))throw fail('CONFIGURATION_INVALID');
|
|
25
|
+
const configuration=hash({coreOrigin,credentialId,configurationSha256,uiStageName,serverStageName,uiReceiptPath,serverReceiptPath}),target={provider:'link-light-core',namespace:credentialId,endpoint:coreOrigin};
|
|
26
|
+
const key=(context,name)=>'core:'+hash({projectId:context.intent.projectId,requestId:context.intent.requestId,name});
|
|
27
|
+
const save=async(key,expectedRevision,payload,signal)=>{
|
|
28
|
+
let stored;try{stored=await journal.compareAndSet({key,expectedRevision,payload:snapshot(payload)},{signal});}catch{/* A lost acknowledgement is resolved only by reading the exact write. */}
|
|
29
|
+
if(stored==='stored')return;
|
|
30
|
+
const actual=await journal.load(key,{signal});if(actual?.revision!==expectedRevision+1||!isDeepStrictEqual(actual.payload,payload))throw fail('LOCAL_STATE_UNKNOWN');
|
|
31
|
+
};
|
|
32
|
+
const candidateFor=async(context,signal)=>{
|
|
33
|
+
if(context.policy.configuration.coreOrigin!==coreOrigin||context.intent.projectId!==context.policy.configuration.projectId||context.prepared.content.manifestSha256!==context.intent.package.content.manifestSha256)throw fail('BINDING_INVALID');
|
|
34
|
+
const ui=previous(context,uiStageName),server=previous(context,serverStageName);
|
|
35
|
+
if([ui,server].some(value=>value?.content?.manifestSha256!==context.intent.package.content.manifestSha256))throw fail('PREDECESSOR_MISMATCH');
|
|
36
|
+
const projection={prepared:context.prepared,configuration:context.policy.configuration,limits:context.policy.limits,serverUrl:server.runtimeUrl,uiUrl:ui.uiUrl,serverReceiptPath,uiReceiptPath,signal};
|
|
37
|
+
const candidate=await preparePublishingRelease(projection);
|
|
38
|
+
if(['solutionId','publisherId','version'].some(name=>candidate.payload[name]!==context.intent.package[name]))throw fail('BINDING_INVALID');
|
|
39
|
+
return {candidate,projection};
|
|
40
|
+
};
|
|
41
|
+
const verifiedManifest=(input,candidate)=>{
|
|
42
|
+
const manifest=verifySolutionRelease(input,candidate.publisher);
|
|
43
|
+
if(manifest.releaseDigest!==candidate.releaseDigest||!isDeepStrictEqual(releasePayload(manifest),candidate.payload))throw fail('MANIFEST_MISMATCH');return manifest;
|
|
44
|
+
};
|
|
45
|
+
const registered=(context,candidate)=>verifiedManifest(previous(context,names[1]).manifest,candidate);
|
|
46
|
+
const validateRoute=(value,candidate)=>{
|
|
47
|
+
if(value?.solutionId!==candidate.payload.solutionId||typeof value.accepting!=='boolean'||!Number.isSafeInteger(value.activeRuns)||value.activeRuns<0||!(value.releaseDigest===null||/^sha256:[a-f0-9]{64}$/.test(value.releaseDigest??''))||!(value.version===null||typeof value.version==='string'&&value.version.length<=64)||((value.version===null)!==(value.releaseDigest===null)))throw fail('ROUTE_UNKNOWN');return value;
|
|
48
|
+
};
|
|
49
|
+
const routeIdentity=value=>({solutionId:value.solutionId,releaseDigest:value.releaseDigest,version:value.version});
|
|
50
|
+
const acceptedReceipt=(value,context,candidate)=>{
|
|
51
|
+
const receipt=snapshot(value);
|
|
52
|
+
if(receipt?.status!=='PASS'||receipt.releaseDigest!==candidate.releaseDigest||!isDeepStrictEqual(receipt.content,context.intent.package.content)||!Number.isSafeInteger(receipt.syntheticInstancesCreated)||receipt.syntheticInstancesCreated<1||receipt.syntheticInstancesCreated>1024||receipt.syntheticInstancesDisabled!==receipt.syntheticInstancesCreated||receipt.closure?.status!=='closed'||receipt.closure.activeRequests!==0)throw fail('ACCEPTANCE_UNPROVEN');return receipt;
|
|
53
|
+
};
|
|
54
|
+
const stage=(name,capability,actions,waitForSignal=false)=>({name,capability,...(waitForSignal?{waitForSignal}:{}),configurationSha256:hash({configuration,name}),createDeployment(context){
|
|
55
|
+
let httpPromise,closed=false,closureConfirmed=false,result;const controller=new AbortController(),pending=new Set();
|
|
56
|
+
const run=(requestContext,work)=>{
|
|
57
|
+
if(closed)throw fail('TRANSPORT_CLOSED');
|
|
58
|
+
const signal=AbortSignal.any([context.signal,requestContext.signal,controller.signal].filter(Boolean));
|
|
59
|
+
const task=(async()=>{
|
|
60
|
+
try{
|
|
61
|
+
signal.throwIfAborted();await context.assertAuthorized();
|
|
62
|
+
httpPromise??=Promise.resolve(createHttpTransport({signal}));
|
|
63
|
+
const http=await httpPromise;signal.throwIfAborted();
|
|
64
|
+
const request=async(url,init={})=>{signal.throwIfAborted();await context.assertAuthorized();return http.fetch(url,{...init,signal:AbortSignal.any([signal,...(init.signal?[init.signal]:[])])});};
|
|
65
|
+
const {candidate,projection}=await candidateFor(context,signal);
|
|
66
|
+
const metadataTransport=async(address,settings={})=>{const response=await releaseJson(address,{}, {signal:settings.signal??signal,request,maximumBytes:1048576});if(response.status!==200)throw fail('ADMISSION_UNKNOWN');return response.value;};
|
|
67
|
+
const ports={context,candidate,projection,configuration:context.policy.configuration,intent:context.intent,signal,request,metadataTransport,timeoutMilliseconds:requestContext.timeoutMilliseconds};
|
|
68
|
+
const session=async exercise=>{const account=await loadAccount({configuration:context.policy.configuration,intent:context.intent,signal});await context.assertAuthorized();return withReleaseControlSession({origin:coreOrigin,account:{email:account?.email,password:account?.password},signal,request},exercise);};
|
|
69
|
+
const value=await work({...ports,session});signal.throwIfAborted();await context.assertAuthorized();return value;
|
|
70
|
+
}catch(error){throw fail('OPERATION_UNKNOWN',error);}
|
|
71
|
+
})();pending.add(task);task.then(()=>pending.delete(task),()=>pending.delete(task));return task;
|
|
72
|
+
};
|
|
73
|
+
const transport={target,capability,configurationSha256:hash({configuration,name}),
|
|
74
|
+
execute(binding,requestContext){return run(requestContext,ports=>actions.execute({...ports,binding}));},
|
|
75
|
+
observe(binding,reference,requestContext){return run(requestContext,async ports=>{const observation=await actions.observe({...ports,binding,reference});if(observation.result!==undefined)result=snapshot(observation.result);return {state:observation.state,fingerprint:binding.fingerprint,...(observation.reference?{reference:observation.reference}:{})};});},
|
|
76
|
+
async close(){closed=true;closureConfirmed=false;controller.abort();let failure,failed=false;try{if(httpPromise){const closure=await(await httpPromise).close();if(closure!==undefined&&(closure?.status!=='closed'||closure.activeRequests!==0))throw fail('HTTP_CLOSE_UNCONFIRMED');}}catch(error){failure=error;failed=true;}await Promise.allSettled([...pending]);if(failed)throw fail('CLOSE_UNKNOWN',failure);closureConfirmed=pending.size===0;return {status:closureConfirmed?'closed':'unconfirmed',activeRequests:pending.size};},
|
|
77
|
+
};
|
|
78
|
+
return {transport,readResult(){if(!closureConfirmed||result===undefined)throw fail('RESULT_NOT_OBSERVED');return snapshot(result);}};
|
|
79
|
+
}});
|
|
80
|
+
const proof=(context,candidate)=>({schemaVersion:1,releaseDigest:candidate.releaseDigest,content:{...context.intent.package.content}});
|
|
81
|
+
const requireProof=(context,candidate,name)=>{const value=previous(context,name);if(value.releaseDigest!==candidate.releaseDigest||!isDeepStrictEqual(value.content,context.intent.package.content))throw fail('PREDECESSOR_MISMATCH');return value;};
|
|
82
|
+
const admission=async ports=>resolveApprovedIndependentRelease({coreOrigin,candidate:ports.candidate,transport:ports.metadataTransport,signal:ports.signal});
|
|
83
|
+
const verifyArtifactBatch=async ports=>{
|
|
84
|
+
const recordKey=key(ports.context,artifactName),stored=await journal.load(recordKey,{signal:ports.signal}),binding=ports.binding.fingerprint,total=ports.context.prepared.manifest.files.filter(file=>file.role==='asset').length;
|
|
85
|
+
if(stored&&(stored.payload.bindingFingerprint!==binding||stored.payload.releaseDigest!==ports.candidate.releaseDigest||!isDeepStrictEqual(stored.payload.content,ports.context.intent.package.content)||!Number.isSafeInteger(stored.payload.cursor)||stored.payload.cursor<1||stored.payload.cursor>total||typeof stored.payload.complete!=='boolean'))throw fail('VERIFICATION_CURSOR_INVALID');
|
|
86
|
+
if(stored?.payload.complete)return stored.payload.result;
|
|
87
|
+
const cursor=stored?.payload.cursor??0,result=snapshot(await verifyDeployment({...ports.projection,request:ports.request,cursor,maximumFiles:8})),complete=result.status==='ARTIFACT_DEPLOYMENT_VERIFIED';
|
|
88
|
+
if(!['ARTIFACT_DEPLOYMENT_VERIFIED','ARTIFACT_DEPLOYMENT_PENDING'].includes(result.status)||result.releaseDigest!==ports.candidate.releaseDigest||!isDeepStrictEqual(result.content,ports.context.intent.package.content)||!Number.isSafeInteger(result.staticFilesVerified)||result.staticFilesVerified<=cursor||result.staticFilesVerified>Math.min(total,cursor+8)||complete!==(result.staticFilesVerified===total)||!complete&&result.nextCursor!==result.staticFilesVerified)throw fail('VERIFICATION_CURSOR_INVALID');
|
|
89
|
+
await ports.context.assertAuthorized();await save(recordKey,stored?.revision??0,{schemaVersion:1,bindingFingerprint:binding,releaseDigest:ports.candidate.releaseDigest,content:{...ports.context.intent.package.content},cursor:result.staticFilesVerified,complete,result},ports.signal);return result;
|
|
90
|
+
};
|
|
91
|
+
const artifacts=stage(artifactName,'deployment-ready',{
|
|
92
|
+
async execute(ports){await verifyArtifactBatch(ports);return {state:'accepted',reference:ports.candidate.releaseDigest};},
|
|
93
|
+
async observe(ports){const result=await verifyArtifactBatch(ports);return {state:result.status==='ARTIFACT_DEPLOYMENT_VERIFIED'?'succeeded':'pending',reference:ports.candidate.releaseDigest,...(result.status==='ARTIFACT_DEPLOYMENT_VERIFIED'?{result:{...proof(ports.context,ports.candidate),...result}}:{})};},
|
|
94
|
+
});
|
|
95
|
+
const origins=stage(names[0],'deployment-ready',{
|
|
96
|
+
async execute(ports){requireProof(ports.context,ports.candidate,artifactName);await ports.context.assertAuthorized();const value=await prepareOriginAdmission({...ports,configuration:ports.context.policy.configuration,intent:ports.context.intent});if(!['succeeded','pending'].includes(value?.state))throw fail('ORIGINS_UNKNOWN');return {state:'accepted',reference:ports.candidate.releaseDigest};},
|
|
97
|
+
async observe(ports){requireProof(ports.context,ports.candidate,artifactName);const value=await observeOriginAdmission({...ports,configuration:ports.context.policy.configuration,intent:ports.context.intent});return {state:value?.state==='succeeded'?'succeeded':value?.state==='pending'?'pending':'unknown',reference:ports.candidate.releaseDigest,...(value?.state==='succeeded'?{result:{...proof(ports.context,ports.candidate),status:'ORIGINS_ADMITTED'}}:{})};},
|
|
98
|
+
});
|
|
99
|
+
const registerCandidate=async ports=>{
|
|
100
|
+
requireProof(ports.context,ports.candidate,names[0]);await ports.context.assertAuthorized();
|
|
101
|
+
const manifest=verifiedManifest(await signCandidate({...ports.candidate,signal:ports.signal}),ports.candidate);snapshot(manifest);
|
|
102
|
+
return ports.session(async({call})=>{
|
|
103
|
+
await ports.context.assertAuthorized();
|
|
104
|
+
const response=await call('/api/registry/releases',{body:manifest,expected:[201]});
|
|
105
|
+
if(response.value?.releaseDigest!==manifest.releaseDigest)throw fail('REGISTRATION_UNKNOWN');
|
|
106
|
+
return {state:'accepted',reference:manifest.releaseDigest};
|
|
107
|
+
});
|
|
108
|
+
};
|
|
109
|
+
const readRegistration=ports=>releaseJson(coreOrigin+'/api/registry/releases/'+encodeURIComponent(ports.candidate.releaseDigest),{}, {...ports,maximumBytes:1048576});
|
|
110
|
+
const register=stage(names[1],'deployment-create',{
|
|
111
|
+
execute:registerCandidate,
|
|
112
|
+
async observe(ports){
|
|
113
|
+
requireProof(ports.context,ports.candidate,names[0]);
|
|
114
|
+
let response=await readRegistration(ports);
|
|
115
|
+
const absent=()=>response.status===404&&response.value?.code==='NOT_FOUND';
|
|
116
|
+
if(absent()&&await authorizeRegistrationRecovery?.(ports)===true){
|
|
117
|
+
const recoveryKey=key(ports.context,'core-register-recovery');
|
|
118
|
+
const claim={schemaVersion:1,recovery:'register',bindingFingerprint:ports.binding.fingerprint,releaseDigest:ports.candidate.releaseDigest};
|
|
119
|
+
const stored=await journal.load(recoveryKey,{signal:ports.signal});
|
|
120
|
+
if(stored){
|
|
121
|
+
if(stored.revision!==1||!isDeepStrictEqual(stored.payload,claim))throw fail('REGISTRATION_RECOVERY_CHANGED');
|
|
122
|
+
}else{
|
|
123
|
+
await ports.context.assertAuthorized();
|
|
124
|
+
await save(recoveryKey,0,claim,ports.signal);
|
|
125
|
+
await registerCandidate(ports);
|
|
126
|
+
response=await readRegistration(ports);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if(absent())return {state:'absent'};
|
|
130
|
+
if(response.status!==200)return {state:'unknown'};
|
|
131
|
+
const manifest=verifiedManifest(response.value?.manifest,ports.candidate);
|
|
132
|
+
return {state:'succeeded',reference:manifest.releaseDigest,result:{...proof(ports.context,ports.candidate),manifest}};
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
const qualificationPath=ports=>'/api/registry/releases/'+encodeURIComponent(ports.candidate.releaseDigest)+'/qualification';
|
|
136
|
+
const qualification=(value,ports,{jobId,receiptSha256},state)=>{
|
|
137
|
+
if(value?.jobId!==jobId||value.releaseDigest!==ports.candidate.releaseDigest||value.state!==state||value.receiptSha256!==(receiptSha256??null))throw fail('QUALIFICATION_UNKNOWN');
|
|
138
|
+
};
|
|
139
|
+
const acceptancePorts=ports=>({...ports,manifest:registered(ports.context,ports.candidate),openQualification:async input=>{
|
|
140
|
+
if(!sha(input.jobId)||!Array.isArray(input.actors)||input.actors.length!==2)throw fail('QUALIFICATION_INVALID');
|
|
141
|
+
return ports.session(async({call})=>{
|
|
142
|
+
const route=qualificationPath(ports);
|
|
143
|
+
const existing=await call(route+'?jobId='+input.jobId,{expected:[200,404]});
|
|
144
|
+
if(existing.status===200){qualification(existing.value,ports,input,'open');return;}
|
|
145
|
+
qualification((await call(route,{body:input,expected:[200,201]})).value,ports,input,'open');
|
|
146
|
+
});
|
|
147
|
+
}});
|
|
148
|
+
const acceptance=stage(names[4],'deployment-ready',{
|
|
149
|
+
async execute(ports){
|
|
150
|
+
await admission(ports);
|
|
151
|
+
const jobId=await startAcceptance(acceptancePorts(ports));
|
|
152
|
+
if(!sha(jobId))throw fail('ACCEPTANCE_JOB_UNKNOWN');
|
|
153
|
+
return {state:'accepted',reference:jobId};
|
|
154
|
+
},
|
|
155
|
+
async observe(ports){
|
|
156
|
+
await admission(ports);
|
|
157
|
+
const external=await observeAcceptance(acceptancePorts(ports));
|
|
158
|
+
if(!external)return {state:'pending',...(ports.reference?{reference:ports.reference}:{})};
|
|
159
|
+
if(!sha(external.jobId)||!sha(external.receiptSha256)||ports.reference!==undefined&&ports.reference!==external.jobId)throw fail('ACCEPTANCE_CHANGED');
|
|
160
|
+
const receipt=acceptedReceipt(external.receipt,ports.context,ports.candidate);
|
|
161
|
+
return {state:'succeeded',reference:external.jobId,result:{...proof(ports.context,ports.candidate),status:'PASS',jobId:external.jobId,receiptSha256:external.receiptSha256,receipt,acceptanceReceiptSha256:hash(receipt)}};
|
|
162
|
+
},
|
|
163
|
+
},true);
|
|
164
|
+
const qualificationProof=ports=>{
|
|
165
|
+
const accepted=requireProof(ports.context,ports.candidate,names[4]);
|
|
166
|
+
if(!sha(accepted.jobId)||!sha(accepted.receiptSha256)||hash(acceptedReceipt(accepted.receipt,ports.context,ports.candidate))!==accepted.acceptanceReceiptSha256)throw fail('ACCEPTANCE_CHANGED');
|
|
167
|
+
return {jobId:accepted.jobId,receiptSha256:accepted.receiptSha256};
|
|
168
|
+
};
|
|
169
|
+
const qualificationClosed=stage('core-qualification-close','deployment-ready',{
|
|
170
|
+
async execute(ports){
|
|
171
|
+
const evidence=qualificationProof(ports);
|
|
172
|
+
await ports.session(async({call})=>qualification((await call(qualificationPath(ports)+'/close',{body:evidence})).value,ports,evidence,'closed'));
|
|
173
|
+
return {state:'accepted',reference:evidence.jobId};
|
|
174
|
+
},
|
|
175
|
+
async observe(ports){
|
|
176
|
+
const evidence=qualificationProof(ports);
|
|
177
|
+
return ports.session(async({call})=>{
|
|
178
|
+
const route=qualificationPath(ports),read=async()=>(await call(route+'?jobId='+evidence.jobId)).value;
|
|
179
|
+
let result=await read();
|
|
180
|
+
if(result?.state==='open'){
|
|
181
|
+
qualification(result,ports,{jobId:evidence.jobId},'open');
|
|
182
|
+
await ports.context.assertAuthorized();
|
|
183
|
+
await call(route+'/close',{body:evidence});
|
|
184
|
+
result=await read();
|
|
185
|
+
}
|
|
186
|
+
qualification(result,ports,evidence,'closed');
|
|
187
|
+
return {state:'succeeded',reference:evidence.jobId,result:{...proof(ports.context,ports.candidate),...evidence}};
|
|
188
|
+
});
|
|
189
|
+
},
|
|
190
|
+
});
|
|
191
|
+
const verifiedClosure=ports=>{
|
|
192
|
+
const evidence=qualificationProof(ports),closed=requireProof(ports.context,ports.candidate,'core-qualification-close');
|
|
193
|
+
if(closed.jobId!==evidence.jobId||closed.receiptSha256!==evidence.receiptSha256)throw fail('QUALIFICATION_CHANGED');
|
|
194
|
+
return evidence;
|
|
195
|
+
};
|
|
196
|
+
const drain=stage(names[2],'deployment-ready',{
|
|
197
|
+
async execute(ports){registered(ports.context,ports.candidate);const evidence=verifiedClosure(ports);return ports.session(async({call})=>{const route='/api/registry/routes/'+encodeURIComponent(ports.candidate.payload.solutionId),baseline=validateRoute((await call(route)).value,ports.candidate),recordKey=key(ports.context,names[2]);if(await journal.load(recordKey,{signal:ports.signal}))throw fail('RECOVERY_REQUIRED');await ports.context.assertAuthorized();await save(recordKey,0,{schemaVersion:1,bindingFingerprint:ports.binding.fingerprint,targetReleaseDigest:ports.candidate.releaseDigest,baseline:routeIdentity(baseline)},ports.signal);await ports.context.assertAuthorized();if(baseline.releaseDigest!==null)await call(route+'/accepting',{body:{accepting:false,releaseDigest:ports.candidate.releaseDigest,...evidence}});return {state:'accepted',reference:ports.candidate.releaseDigest};});},
|
|
198
|
+
async observe(ports){registered(ports.context,ports.candidate);verifiedClosure(ports);const saved=await journal.load(key(ports.context,names[2]),{signal:ports.signal});if(saved?.revision!==1||saved.payload?.bindingFingerprint!==ports.binding.fingerprint||saved.payload.targetReleaseDigest!==ports.candidate.releaseDigest)return {state:'unknown'};return ports.session(async({call})=>{const actual=validateRoute((await call('/api/registry/routes/'+encodeURIComponent(ports.candidate.payload.solutionId))).value,ports.candidate);if(!isDeepStrictEqual(routeIdentity(actual),saved.payload.baseline)||actual.accepting!==false)return {state:'unknown'};return {state:actual.activeRuns===0?'succeeded':'pending',reference:ports.candidate.releaseDigest,...(actual.activeRuns===0?{result:{...proof(ports.context,ports.candidate),baseline:saved.payload.baseline,status:'DRAINED'}}:{})};});},
|
|
199
|
+
});
|
|
200
|
+
const activate=stage(names[3],'deployment-ready',{
|
|
201
|
+
async execute(ports){const manifest=registered(ports.context,ports.candidate),drained=requireProof(ports.context,ports.candidate,names[2]),evidence=verifiedClosure(ports);return ports.session(async({call})=>{const actual=validateRoute((await call('/api/registry/routes/'+encodeURIComponent(manifest.solutionId))).value,ports.candidate);if(!isDeepStrictEqual(routeIdentity(actual),drained.baseline)||actual.accepting!==false||actual.activeRuns!==0)throw fail('DRAIN_CHANGED');await ports.context.assertAuthorized();await call('/api/registry/releases/'+encodeURIComponent(manifest.releaseDigest)+'/activate',{body:evidence});return {state:'accepted',reference:manifest.releaseDigest};});},
|
|
202
|
+
async observe(ports){registered(ports.context,ports.candidate);requireProof(ports.context,ports.candidate,names[2]);verifiedClosure(ports);return ports.session(async({call})=>{const actual=validateRoute((await call('/api/registry/routes/'+encodeURIComponent(ports.candidate.payload.solutionId))).value,ports.candidate);if(actual.releaseDigest!==ports.candidate.releaseDigest||actual.version!==ports.candidate.payload.version||actual.accepting!==true)return {state:'unknown'};await admission(ports);return {state:'succeeded',reference:ports.candidate.releaseDigest,result:{...proof(ports.context,ports.candidate),status:'CORE_ACTIVE'}};});},
|
|
203
|
+
});
|
|
204
|
+
const durableResult=async(ports,name,produce,validate)=>{
|
|
205
|
+
const recordKey=key(ports.context,name);if(await journal.load(recordKey,{signal:ports.signal}))throw fail('RECOVERY_REQUIRED');
|
|
206
|
+
const payload={schemaVersion:1,bindingFingerprint:ports.binding.fingerprint,releaseDigest:ports.candidate.releaseDigest,state:'pending'};await ports.context.assertAuthorized();await save(recordKey,0,payload,ports.signal);await ports.context.assertAuthorized();const result=validate(await produce());await ports.context.assertAuthorized();await save(recordKey,1,{...payload,state:'complete',result},ports.signal);return {state:'accepted',reference:ports.candidate.releaseDigest};
|
|
207
|
+
};
|
|
208
|
+
const loadResult=async(ports,name)=>{const stored=await journal.load(key(ports.context,name),{signal:ports.signal});if(!stored||stored.payload?.schemaVersion!==1||stored.payload.bindingFingerprint!==ports.binding.fingerprint||stored.payload.releaseDigest!==ports.candidate.releaseDigest||!['pending','complete'].includes(stored.payload.state)||stored.revision!==(stored.payload.state==='complete'?2:1))return;return stored;};
|
|
209
|
+
const activation=stage(names[5],'activation',{
|
|
210
|
+
async execute(ports){verifiedClosure(ports);requireProof(ports.context,ports.candidate,names[3]);const manifest=registered(ports.context,ports.candidate),accepted=requireProof(ports.context,ports.candidate,names[4]),receipt=acceptedReceipt(accepted.receipt,ports.context,ports.candidate);if(hash(receipt)!==accepted.acceptanceReceiptSha256)throw fail('ACCEPTANCE_CHANGED');await admission(ports);return durableResult(ports,names[5],()=>createActivation({configuration:ports.context.policy.configuration,intent:ports.context.intent,manifest,acceptanceReceiptSha256:accepted.acceptanceReceiptSha256,metadataTransport:ports.metadataTransport,signal:ports.signal}),value=>{const activation=snapshot(value);verifiedManifest(activation.manifest,ports.candidate);if(activation.payload?.releaseDigest!==ports.candidate.releaseDigest||activation.payload.acceptanceReceiptSha256!==accepted.acceptanceReceiptSha256)throw fail('ACTIVATION_MISMATCH');return activation;});},
|
|
211
|
+
async observe(ports){verifiedClosure(ports);requireProof(ports.context,ports.candidate,names[3]);registered(ports.context,ports.candidate);const accepted=requireProof(ports.context,ports.candidate,names[4]),receipt=acceptedReceipt(accepted.receipt,ports.context,ports.candidate),stored=await loadResult(ports,names[5]);if(!stored||stored.payload.state!=='complete'||hash(receipt)!==accepted.acceptanceReceiptSha256)return {state:'unknown'};const activation=stored.payload.result;verifiedManifest(activation.manifest,ports.candidate);if(activation?.payload?.releaseDigest!==ports.candidate.releaseDigest||activation.payload.acceptanceReceiptSha256!==accepted.acceptanceReceiptSha256)throw fail('ACTIVATION_MISMATCH');await verifyPublishingActivation({configuration:ports.context.policy.configuration,intent:ports.context.intent,activation,metadataTransport:ports.metadataTransport,signal:ports.signal});return {state:'succeeded',reference:ports.candidate.releaseDigest,result:activation};},
|
|
212
|
+
});
|
|
213
|
+
return [artifacts,origins,register,acceptance,qualificationClosed,drain,activate,activation];
|
|
214
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createNodeCommandRunner } from "@openge/forge-command-runner/node";
|
|
2
|
+
import { ProcessControlError, processControlErrorCodes } from "@openge/forge-process-control";
|
|
3
|
+
import {
|
|
4
|
+
createPosixProcessControl,
|
|
5
|
+
createWindowsProcessControl,
|
|
6
|
+
} from "@openge/forge-process-control-node";
|
|
7
|
+
|
|
8
|
+
export function parsePort(value, fallback = 3000) {
|
|
9
|
+
const rawValue = value ?? fallback;
|
|
10
|
+
const port = Number(rawValue);
|
|
11
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
|
12
|
+
throw new Error(`Invalid port: ${rawValue}`);
|
|
13
|
+
}
|
|
14
|
+
return port;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function looksLikeNextDev(commandLine) {
|
|
18
|
+
return /node_modules[\\/]+next[\\/]+dist[\\/]+server[\\/]+lib[\\/]+start-server\.js/i.test(
|
|
19
|
+
String(commandLine ?? ""),
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function createProcessControl(platform = process.platform) {
|
|
24
|
+
return platform === "win32"
|
|
25
|
+
? createWindowsProcessControl({ listenerBackend: "powershell" })
|
|
26
|
+
: createPosixProcessControl({ listenerBackend: "lsof" });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {{port?: number|string, signal?: AbortSignal, platform?: NodeJS.Platform, provider?: import('@openge/forge-process-control').ProcessControlProvider}} options */
|
|
30
|
+
export async function findProcessByPort({
|
|
31
|
+
port,
|
|
32
|
+
signal,
|
|
33
|
+
platform = process.platform,
|
|
34
|
+
provider = createProcessControl(platform),
|
|
35
|
+
} = {}) {
|
|
36
|
+
const safePort = parsePort(port);
|
|
37
|
+
const listeners = await provider.listTcpListeners({ ports: [safePort], ...(signal ? { signal } : {}) });
|
|
38
|
+
return listeners[0]?.process ?? null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function normalizeProcessInfo(processInfo) {
|
|
42
|
+
if (!processInfo) return null;
|
|
43
|
+
|
|
44
|
+
const descriptor = processInfo.process ?? processInfo;
|
|
45
|
+
const pid = Number(descriptor.ProcessId ?? descriptor.pid);
|
|
46
|
+
const commandLine = String(descriptor.CommandLine ?? descriptor.commandLine ?? "");
|
|
47
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
48
|
+
return { pid: null, commandLine, process: null };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const startToken = typeof descriptor.startToken === "string" ? descriptor.startToken : "";
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
pid,
|
|
55
|
+
commandLine,
|
|
56
|
+
process: startToken ? { ...descriptor, pid, startToken } : null,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function killProcess(processInfo, {
|
|
61
|
+
signal,
|
|
62
|
+
platform = process.platform,
|
|
63
|
+
provider = createProcessControl(platform),
|
|
64
|
+
} = {}) {
|
|
65
|
+
const normalized = normalizeProcessInfo(processInfo);
|
|
66
|
+
if (!normalized?.pid || !normalized.process) {
|
|
67
|
+
throw new ProcessControlError(processControlErrorCodes.processIdentityUnavailable, {
|
|
68
|
+
pid: normalized?.pid ?? null,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
await provider.terminateProcess({
|
|
73
|
+
process: normalized.process,
|
|
74
|
+
...(signal ? { signal } : {}),
|
|
75
|
+
policy: { mode: platform === "win32" ? "force" : "graceful" },
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function createDevCommandRunner({
|
|
80
|
+
platform = process.platform,
|
|
81
|
+
provider = createProcessControl(platform),
|
|
82
|
+
} = {}) {
|
|
83
|
+
// Windows process discovery starts a fresh PowerShell/CIM query for both
|
|
84
|
+
// identity acquisition and identity-fenced termination.
|
|
85
|
+
const identityTimeoutMs = platform === "win32" ? 8_000 : 2_000;
|
|
86
|
+
const terminationTimeoutMs = platform === "win32" ? 15_000 : 5_000;
|
|
87
|
+
|
|
88
|
+
return createNodeCommandRunner({
|
|
89
|
+
platform: platform === "win32" ? "win32" : "posix",
|
|
90
|
+
processControl: provider,
|
|
91
|
+
terminationPolicy: platform === "win32"
|
|
92
|
+
? { mode: "force" }
|
|
93
|
+
: { mode: "graceful" },
|
|
94
|
+
identityAcquisition: { timeoutMs: identityTimeoutMs, pollIntervalMs: 20 },
|
|
95
|
+
terminationTimeoutMs,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
export function checkedFixturePath(root, target, {code='FIXTURE', type} = {}) {
|
|
5
|
+
if (typeof root !== 'string' || !path.isAbsolute(root) || typeof target !== 'string' || !path.isAbsolute(target)) throw Error(code + '_PATH_REJECTED');
|
|
6
|
+
const resolvedRoot = path.resolve(root), resolved = path.resolve(target), relative = path.relative(resolvedRoot,resolved);
|
|
7
|
+
if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) throw Error(code + '_PATH_REJECTED');
|
|
8
|
+
for (let current = resolved;; current = path.dirname(current)) {
|
|
9
|
+
let stat;
|
|
10
|
+
try { stat = fs.lstatSync(current); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
11
|
+
if (stat?.isSymbolicLink() || stat?.isFile() && stat.nlink !== 1) throw Error(code + '_LINKED_PATH');
|
|
12
|
+
if (current === path.dirname(current)) break;
|
|
13
|
+
}
|
|
14
|
+
if (type) {
|
|
15
|
+
const stat = fs.lstatSync(resolved);
|
|
16
|
+
if (type === 'file' ? !stat.isFile() : !stat.isDirectory()) throw Error(code + '_PATH_REJECTED');
|
|
17
|
+
}
|
|
18
|
+
return resolved;
|
|
19
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function inspectFunctionAdmission(options:{root:string;preflight?:boolean;environment?:Record<string,string|undefined>;signal?:AbortSignal;request?:typeof fetch;client?:{query(sql:string,options?:{signal?:AbortSignal}):Promise<{rows:Record<string,unknown>[]}>}}):Promise<{status:'ADMITTED';teamId:string;projectId:string;sha:string;phase:'preflight'|'create'|'version-alias'|'promote'|'completion';plan:'hobby';mode:'hobby-controlled-attempt';remainingQuota:'UNKNOWN';quotaRefusal:string;writer:string;functions?:number}>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {readReleaseToken} from './release-credentials.mjs';
|
|
5
|
+
import {releaseJson} from './release-control.mjs';
|
|
6
|
+
import {readReleasePolicy,assertReleaseWriterHeld,enterReleaseWriter} from './release-coordinator.mjs';
|
|
7
|
+
import {validateReleaseWriter,releaseWriterSql} from './release-writer.mjs';
|
|
8
|
+
import {createSupabaseReleaseClient} from './release-supabase.mjs';
|
|
9
|
+
import {requirePrebuiltFunctionRegion} from './prebuilt-output.mjs';
|
|
10
|
+
|
|
11
|
+
function json(file){const info=fs.lstatSync(file);assert(info.isFile()&&!info.isSymbolicLink()&&info.nlink===1&&info.size<=65536&&fs.realpathSync(file)===file,'RELEASE_FUNCTION_CONFIGURATION_INVALID');return JSON.parse(fs.readFileSync(file,'utf8'));}
|
|
12
|
+
function inspectFunctions(root,region){
|
|
13
|
+
const output=path.join(root,'.vercel/output');assert(fs.realpathSync(output)===output,'RELEASE_FUNCTION_CONFIGURATION_INVALID');let entries=0,functions=0;
|
|
14
|
+
const pending=[output];while(pending.length){const file=pending.pop(),info=fs.lstatSync(file);assert(++entries<=25000,'RELEASE_FUNCTION_CONFIGURATION_INVALID');
|
|
15
|
+
// Foundation independently seals link closure, file selection, runtime bytes,
|
|
16
|
+
// and identity. Here each physical function config is inspected once.
|
|
17
|
+
if(info.isSymbolicLink())continue;
|
|
18
|
+
if(info.isDirectory())for(const name of fs.readdirSync(file))pending.push(path.join(file,name));
|
|
19
|
+
else if(info.isFile()&&path.basename(file)==='.vc-config.json'){
|
|
20
|
+
const config=json(file);assert(config.runtime==='nodejs24.x'&&(!Object.hasOwn(config,'memory')||Number.isInteger(config.memory)&&config.memory>=128&&config.memory<=2048)&&(!Object.hasOwn(config,'maxDuration')||Number.isInteger(config.maxDuration)&&config.maxDuration>0&&config.maxDuration<=300)&&Array.isArray(config.regions)&&config.regions.length===1&&config.regions[0]===region,'RELEASE_FUNCTION_CONFIGURATION_INVALID');functions++;
|
|
21
|
+
}else assert(info.isFile(),'RELEASE_FUNCTION_CONFIGURATION_INVALID');
|
|
22
|
+
}
|
|
23
|
+
assert(functions>0,'RELEASE_FUNCTION_CONFIGURATION_INVALID');return functions;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** GET-only consumer admission. Hobby is the hard cost boundary, not proof of
|
|
27
|
+
* free remaining capacity. One controlled attempt may hit a provider quota;
|
|
28
|
+
* neither this gate nor the public publisher purchases or upgrades anything. */
|
|
29
|
+
export async function inspectFunctionAdmission({root,preflight=false,environment=process.env,signal,request=fetch,client}){
|
|
30
|
+
signal?.throwIfAborted();
|
|
31
|
+
assert(path.isAbsolute(root)&&fs.realpathSync(root)===path.resolve(root),'RELEASE_ADMISSION_ROOT_INVALID');
|
|
32
|
+
const config=json(path.join(root,'release.config.json')),policy=readReleasePolicy(root),target=config.vercel,scope=config.delivery?.concurrencyControl?.scope;
|
|
33
|
+
assert(config.schemaVersion===2&&config.delivery?.mode==='prebuilt'&&config.delivery.concurrencyControl.mode==='external-serialization'&&/^team_[A-Za-z0-9]+$/.test(target?.teamId??'')&&/^prj_[A-Za-z0-9]+$/.test(target?.projectId??'')&&['check','publish','verify'].includes(environment.FORGE_RELEASE_COMMAND)&&/^[a-f0-9]{40}$/.test(environment.FORGE_RELEASE_SHA??''),'RELEASE_ADMISSION_CONTEXT_INVALID');
|
|
34
|
+
if(preflight)assert(environment.FORGE_RELEASE_COMMAND!=='verify','RELEASE_ADMISSION_CONTEXT_INVALID');
|
|
35
|
+
else assert(['publish','verify'].includes(environment.FORGE_RELEASE_COMMAND)&&['create','version-alias','promote','completion'].includes(environment.FORGE_RELEASE_PHASE)&&(environment.FORGE_RELEASE_COMMAND!=='verify'||environment.FORGE_RELEASE_PHASE==='completion')&&environment.FORGE_RELEASE_TEAM_ID===target.teamId&&environment.FORGE_RELEASE_PROJECT_ID===target.projectId&&environment.FORGE_RELEASE_SERIALIZATION_SCOPE===scope,'RELEASE_ADMISSION_CONTEXT_INVALID');
|
|
36
|
+
const source=json(path.join(root,'vercel.json'));
|
|
37
|
+
const region=requirePrebuiltFunctionRegion(source.regions);
|
|
38
|
+
assert(source.git?.deploymentEnabled?.['*']===false&&Object.keys(source.services??{}).join(',')==='web'&&source.services.web.framework==='nextjs'&&Object.keys(source.services.web).every(key=>['root','framework','installCommand','buildCommand'].includes(key))&&!source.crons&&!source.functions&&!source.builds,'RELEASE_FUNCTION_CONFIGURATION_INVALID');
|
|
39
|
+
const token=readReleaseToken({root,environment});assert(token,'RELEASE_TOKEN_REQUIRED');
|
|
40
|
+
async function get(endpoint){const response=await releaseJson('https://api.vercel.com'+endpoint,{headers:{authorization:'Bearer '+token}},{signal,request});
|
|
41
|
+
if(response.status===429||['deployment_limit_exceeded','resource_limit_exceeded','quota_exceeded','rate_limit_exceeded'].includes(response.value?.error?.code))throw Error('RELEASE_QUOTA_PAUSED');
|
|
42
|
+
assert(response.status===200&&!response.value?.error,'RELEASE_HOBBY_OBSERVATION_UNKNOWN');return response.value;
|
|
43
|
+
}
|
|
44
|
+
const team=await get('/v2/teams/'+target.teamId);assert(team.id===target.teamId&&team.billing?.plan==='hobby'&&team.billing.status==='active','RELEASE_HOBBY_NOT_ACTIVE');
|
|
45
|
+
const project=await get('/v9/projects/'+target.projectId+'?teamId='+target.teamId);
|
|
46
|
+
assert(project.id===target.projectId&&project.accountId===target.teamId&&!project.link&&!project.rollingRelease&&!project.paused&&[null,undefined,'','.'].includes(project.rootDirectory)&&project.resourceConfig?.fluid===true&&project.resourceConfig.buildMachineType==='basic','RELEASE_HOBBY_PROJECT_INVALID');
|
|
47
|
+
let writer='not required for a read-only check';
|
|
48
|
+
if(['publish','verify'].includes(environment.FORGE_RELEASE_COMMAND)){
|
|
49
|
+
let context;try{context=validateReleaseWriter(JSON.parse(environment.LINK_LIGHT_RELEASE_WRITER??''));}catch{assert.fail('RELEASE_ADMISSION_CONTEXT_INVALID');}
|
|
50
|
+
assert(context.generation>0&&context.teamId===target.teamId&&context.projectId===target.projectId&&context.scope===scope&&context.sha===environment.FORGE_RELEASE_SHA,'RELEASE_ADMISSION_CONTEXT_INVALID');
|
|
51
|
+
client??=createSupabaseReleaseClient(root,policy.projectRef);
|
|
52
|
+
if(preflight)await enterReleaseWriter({root,environment,signal,client});
|
|
53
|
+
else assertReleaseWriterHeld((await client.query(releaseWriterSql(context,'observe'),{signal})).rows,context);
|
|
54
|
+
writer='held by exact candidate';
|
|
55
|
+
}
|
|
56
|
+
const functions=preflight?undefined:inspectFunctions(root,region);
|
|
57
|
+
return {status:'ADMITTED',teamId:target.teamId,projectId:target.projectId,sha:environment.FORGE_RELEASE_SHA,phase:preflight?'preflight':environment.FORGE_RELEASE_PHASE,plan:'hobby',mode:policy.mode,remainingQuota:'UNKNOWN',quotaRefusal:'pause; no upgrade or purchase',writer,...(functions===undefined?{}:{functions})};
|
|
58
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {pathToFileURL} from 'node:url';
|
|
4
|
+
import {checkedFixturePath} from './fixture-path.mjs';
|
|
5
|
+
|
|
6
|
+
const functions = ['dispatchOnDemandWork','createPostgresControlPlane','createRuntimeGateway','createIndependentRuntime','readPlatformSchema'];
|
|
7
|
+
|
|
8
|
+
/** A fixture owner selects one built installation; no sibling source or fallback lookup. */
|
|
9
|
+
export async function loadHostArtifact(installationRoot = process.env.LINK_LIGHT_TEST_HOST_ARTIFACT_ROOT,{artifactRecord='tmp/core-packages/artifacts.json'}={}) {
|
|
10
|
+
if (typeof installationRoot !== 'string' || !path.isAbsolute(installationRoot)) throw Error('HOST_ARTIFACT_ROOT_REQUIRED');
|
|
11
|
+
const root = path.resolve(installationRoot);
|
|
12
|
+
checkedFixturePath(root,root,{code:'HOST_ARTIFACT',type:'directory'});
|
|
13
|
+
const manifest = checkedFixturePath(root,path.join(root,'package.json'),{code:'HOST_ARTIFACT',type:'file'});
|
|
14
|
+
if (typeof JSON.parse(fs.readFileSync(manifest,'utf8')).name !== 'string') throw Error('HOST_ARTIFACT_MANIFEST_INVALID');
|
|
15
|
+
const entry = checkedFixturePath(root,path.join(root,'apps/worker/dist/apps/worker/src/testing.js'),{code:'HOST_ARTIFACT',type:'file'});
|
|
16
|
+
const loaded = await import(pathToFileURL(entry).href);
|
|
17
|
+
if (functions.some(name => typeof loaded[name] !== 'function')) throw Error('HOST_ARTIFACT_EXPORTS_INVALID');
|
|
18
|
+
if(typeof artifactRecord!=='string'||path.isAbsolute(artifactRecord)||artifactRecord.split(/[\\/]/).includes('..'))throw Error('HOST_ARTIFACT_PATH_REJECTED');
|
|
19
|
+
const paths = {
|
|
20
|
+
installationRoot:root,
|
|
21
|
+
workerEntry: path.join(root,'apps/worker/dist/apps/worker/src/main.js'),
|
|
22
|
+
inventoryFile:path.join(root,artifactRecord),
|
|
23
|
+
};
|
|
24
|
+
for (const [name,target] of Object.entries(paths)) {
|
|
25
|
+
if(name==='installationRoot'||name==='inventoryFile')continue;
|
|
26
|
+
checkedFixturePath(root,target,{code:'HOST_ARTIFACT',type:'file'});
|
|
27
|
+
}
|
|
28
|
+
const deliveryRoot = path.join(root,'delivery');
|
|
29
|
+
if (paths.inventoryFile === deliveryRoot) throw Error('HOST_ARTIFACT_PATH_REJECTED');
|
|
30
|
+
checkedFixturePath(deliveryRoot,paths.inventoryFile,{code:'HOST_ARTIFACT',type:'file'});
|
|
31
|
+
return Object.freeze({...loaded,...paths,root});
|
|
32
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export function installFixtureStop(runtime){
|
|
2
|
+
if(runtime.connected){
|
|
3
|
+
let requested=false,delivered=false;
|
|
4
|
+
const deliver=()=>{if(!requested||delivered||!runtime.listenerCount('SIGTERM'))return;delivered=true;runtime.removeListener('newListener',ready);runtime.emit('SIGTERM','SIGTERM');runtime.disconnect();};
|
|
5
|
+
const ready=event=>{if(event==='SIGTERM')queueMicrotask(deliver);};
|
|
6
|
+
runtime.on('message',message=>{if(message?.type==='link-light-fixture-stop'&&!requested){requested=true;if(runtime.listenerCount('SIGTERM'))deliver();else runtime.on('newListener',ready);}});
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
installFixtureStop(process);
|
|
10
|
+
export async function closeFixtureHost(handle,timeoutMs=5000){
|
|
11
|
+
let timer;
|
|
12
|
+
try{const state=handle.state.closed?await handle.completion:await Promise.race([handle.completion,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('FIXTURE_HOST_CLOSE_TIMEOUT')),timeoutMs);try{handle.child.send({type:'link-light-fixture-stop'},error=>{if(error)reject(error);});}catch(error){reject(error);}})]);if(![0,143].includes(state.exitCode)||state.signalCode!=null||state.error||state.stopError)throw Error('FIXTURE_HOST_CLOSE_FAILED');return state;}
|
|
13
|
+
catch(error){handle.state.fixtureCloseError=String(error);try{await handle.stop();}catch(fallback){handle.state.fixtureFallbackError=String(fallback);}throw error;}
|
|
14
|
+
finally{clearTimeout(timer);}
|
|
15
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {qualifyBrowserBundle,qualifyServerGraph} from './artifact-graphs.mjs';
|
|
5
|
+
import {writeArtifactDeclarationProbe} from './artifact-declarations.mjs';
|
|
6
|
+
|
|
7
|
+
export function artifactDevelopmentDependencies(root){
|
|
8
|
+
const metadata=JSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8'));
|
|
9
|
+
return Object.fromEntries(['typescript','@types/node','@types/react'].map(name=>{const version=metadata.devDependencies?.[name];assert(typeof version==='string'&&/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(version),'PINNED_ARTIFACT_TOOL_REQUIRED: '+name);return[name,version];}));
|
|
10
|
+
}
|
|
11
|
+
export function writeArchiveIntegrityProbe({consumer,inventory,program}){
|
|
12
|
+
assert(typeof program==='string'&&program.length>0&&Buffer.byteLength(program)<=128*1024,'OWNED_ARTIFACT_PROGRAM_REQUIRED');
|
|
13
|
+
const pinned=inventory.map(item=>({name:item.metadata.name,files:item.files}));
|
|
14
|
+
const code=`import fs from 'node:fs';import path from 'node:path';import {createHash} from 'node:crypto';import {registerHooks} from 'node:module';import {fileURLToPath} from 'node:url';
|
|
15
|
+
const fail=()=>{throw Error('RELEASE_INTEGRITY_MISMATCH')},root=import.meta.dirname,pinned=${JSON.stringify(pinned)};
|
|
16
|
+
for(const item of pinned){const directory=fs.realpathSync(path.join(root,'node_modules',...item.name.split('/')));if(!directory.startsWith(root+path.sep))fail();const files=new Set();function walk(relative){for(const entry of fs.readdirSync(path.join(directory,relative),{withFileTypes:true})){if(!relative&&entry.name==='node_modules')continue;if(entry.isSymbolicLink())fail();const selected=relative?relative+'/'+entry.name:entry.name;if(entry.isDirectory())walk(selected);else{if(!entry.isFile())fail();files.add(selected);}}}walk('');if(files.size!==item.files.length)fail();for(const file of item.files){if(!files.has(file.path))fail();const selected=path.join(directory,file.path),stat=fs.lstatSync(selected);if(!stat.isFile()||stat.isSymbolicLink()||stat.size!==file.bytes)fail();if('sha256:'+createHash('sha256').update(fs.readFileSync(selected)).digest('hex')!==file.digest)fail();}}
|
|
17
|
+
const check=url=>{if(url.startsWith('node:'))return;if(!url.startsWith('file:')||!fs.realpathSync(fileURLToPath(url)).startsWith(root+path.sep))throw Error('CONSUMER_MODULE_OUTSIDE_INSTALLATION');};
|
|
18
|
+
registerHooks({resolve(specifier,context,next){const result=next(specifier,context);check(result.url);return result;},load(url,context,next){check(url);return next(url,context);}});
|
|
19
|
+
if(process.argv.length===3&&process.argv[2]==='--declarations')await import('./compile-declarations.mjs');
|
|
20
|
+
else {if(process.argv.length!==2)throw Error('ARTIFACT_PROBE_ARGUMENTS');await import('./owned-consumer.mjs');}
|
|
21
|
+
`;
|
|
22
|
+
assert(Buffer.byteLength(code)<=4*1024**2,'ARTIFACT_PROBE_LIMIT');
|
|
23
|
+
fs.writeFileSync(path.join(consumer,'owned-consumer.mjs'),program,{flag:'wx'});
|
|
24
|
+
const probe=path.join(consumer,'verify-consumer.mjs');fs.writeFileSync(probe,code,{flag:'wx'});return probe;
|
|
25
|
+
}
|
|
26
|
+
function publicEntry(metadata,name){
|
|
27
|
+
const value=metadata.exports?.[name],entry=typeof value==='string'?value:value?.import;
|
|
28
|
+
assert(typeof entry==='string'&&entry.startsWith('./')&&!entry.split('/').some(part=>part==='..')&&!entry.includes('\\'),'PUBLISHED_ENTRY_REQUIRED: '+name);
|
|
29
|
+
return entry.slice(2);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The outer fixture owns every subprocess, byte budget and removal. */
|
|
33
|
+
export async function qualifyArtifactConsumer({consumer,inventory,acceptance,run,checks}){
|
|
34
|
+
assert(acceptance&&Object.keys(acceptance).sort().join(',')==='declarations,program','OWNED_ARTIFACT_ACCEPTANCE_REQUIRED');
|
|
35
|
+
assert(typeof acceptance.declarations==='string'&&acceptance.declarations.length>0&&Buffer.byteLength(acceptance.declarations)<=128*1024,'OWNED_ARTIFACT_DECLARATIONS_REQUIRED');
|
|
36
|
+
const metadata=inventory[0].metadata,ownedRoot=fs.realpathSync(path.join(consumer,'node_modules',...metadata.name.split('/')));
|
|
37
|
+
const probe=writeArchiveIntegrityProbe({consumer,inventory,program:acceptance.program}),changed=path.join(consumer,'artifact-changed-cwd');fs.mkdirSync(changed);
|
|
38
|
+
const original=await run([probe],consumer),relocated=await run([probe],changed);assert.deepEqual(JSON.parse(original),JSON.parse(relocated));
|
|
39
|
+
checks.push('owned literal public domain/resource assertions pass from clean archives and another cwd');
|
|
40
|
+
fs.writeFileSync(path.join(consumer,'public-contracts.ts'),acceptance.declarations,{flag:'wx'});
|
|
41
|
+
fs.writeFileSync(path.join(consumer,'tsconfig.artifact.json'),JSON.stringify({compilerOptions:{strict:true,skipLibCheck:false,noEmit:true,target:'ES2022',module:'NodeNext',moduleResolution:'NodeNext',jsx:'react-jsx',types:['node','react'],typeRoots:[path.join(consumer,'node_modules/@types')]},files:['public-contracts.ts']})+'\n',{flag:'wx'});
|
|
42
|
+
writeArtifactDeclarationProbe({consumer,configFile:'tsconfig.artifact.json'});
|
|
43
|
+
await run([probe,'--declarations'],changed);
|
|
44
|
+
checks.push('strict public declaration closure uses only consumer-installed compiler/types and no source aliases');
|
|
45
|
+
const entry=path.join(ownedRoot,publicEntry(metadata,'./server')),uiEntry=path.join(ownedRoot,publicEntry(metadata,'./ui'));
|
|
46
|
+
const server=await qualifyServerGraph({root:consumer,entry,uiEntry});
|
|
47
|
+
const browser=await qualifyBrowserBundle({root:consumer,entry:uiEntry,cacheDirectory:path.join(consumer,'artifact-vite-cache')});
|
|
48
|
+
fs.writeFileSync(path.join(consumer,'artifact-graphs.json'),JSON.stringify({serverModules:server.modules,browserModules:browser.modules,browserOutputBytes:browser.outputBytes})+'\n',{flag:'wx'});
|
|
49
|
+
checks.push('actual installed server graph rejects UI/React/Web, cycles, unresolved sources and escapes; actual browser bundle rejects Node/server/private imports');
|
|
50
|
+
const damage=async(label,relative,change)=>{
|
|
51
|
+
assert(inventory[0].files.some(file=>file.path===relative),'DAMAGE_PATH_NOT_IN_ARCHIVE');const location=path.join(ownedRoot,relative),bytes=fs.readFileSync(location);
|
|
52
|
+
fs.unlinkSync(location);
|
|
53
|
+
try{const replacement=change(bytes);if(replacement!==null)fs.writeFileSync(location,replacement,{flag:'wx'});const failure=await run([probe],changed,1);assert.match(failure,/RELEASE_INTEGRITY_MISMATCH/);checks.push(label);}
|
|
54
|
+
finally{if(fs.existsSync(location))fs.unlinkSync(location);fs.writeFileSync(location,bytes,{flag:'wx'});}
|
|
55
|
+
};
|
|
56
|
+
const implementation=inventory[0].files.find(file=>file.path.startsWith('dist/')&&file.path.endsWith('.js'));
|
|
57
|
+
const resource=inventory[0].files.find(file=>file.path.endsWith('/SKILL.md'))??inventory[0].files.find(file=>file.path==='content/skill.json')??inventory[0].files.find(file=>file.path.startsWith('content/')&&file.path.endsWith('.json'));
|
|
58
|
+
assert(implementation&&resource,'OWNED_ARTIFACT_DAMAGE_INPUTS_REQUIRED');
|
|
59
|
+
await damage('same-version implementation substitution rejected before import',implementation.path,bytes=>Buffer.concat([bytes,Buffer.from('\n// controlled substitution\n')]));
|
|
60
|
+
await damage('missing public server rejected before import',publicEntry(metadata,'./server'),()=>null);
|
|
61
|
+
await damage('missing owned resource rejected before import',resource.path,()=>null);
|
|
62
|
+
await damage('modified owned resource rejected before import',resource.path,bytes=>Buffer.concat([bytes,Buffer.from('\n')]));
|
|
63
|
+
await damage('wrong public export rejected before import','package.json',bytes=>{const value=JSON.parse(bytes);value.exports['./server']={...value.exports['./server'],import:'./dist/absent.js'};return Buffer.from(JSON.stringify(value));});
|
|
64
|
+
await damage('metadata version drift rejected before import','package.json',bytes=>{const value=JSON.parse(bytes);value.version=String(Number(value.version.split('.')[0])+1)+'.0.0';return Buffer.from(JSON.stringify(value));});
|
|
65
|
+
assert.deepEqual(JSON.parse(await run([probe],changed)),JSON.parse(original));checks.push('all exact archive bytes restored after damage without writing through package-store hardlinks');
|
|
66
|
+
return{serverModules:server.modules.length,browserModules:browser.modules.length,browserOutputBytes:browser.outputBytes};
|
|
67
|
+
}
|