@xlinklight/testkit 7.0.0-rc.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +171 -169
  3. package/package.json +11 -4
  4. package/src/architecture-database.d.mts +36 -36
  5. package/src/architecture-database.mjs +64 -64
  6. package/src/artifact-observation.mjs +50 -50
  7. package/src/browser-lifecycle.mjs +45 -45
  8. package/src/cloudflare-browser.mjs +41 -41
  9. package/src/cloudflare-pages.d.mts +34 -34
  10. package/src/cloudflare-pages.mjs +170 -170
  11. package/src/cloudflare-provider-http.mjs +32 -32
  12. package/src/cluster-directory.d.mts +16 -16
  13. package/src/cluster-directory.mjs +90 -90
  14. package/src/core-publishing.d.mts +75 -75
  15. package/src/core-publishing.mjs +214 -214
  16. package/src/dev-command-runner.mjs +97 -97
  17. package/src/fixture-path.mjs +19 -19
  18. package/src/function-admission.d.mts +1 -1
  19. package/src/function-admission.mjs +58 -58
  20. package/src/host-artifact.mjs +32 -32
  21. package/src/host-stop.mjs +15 -15
  22. package/src/lifecycle-trace.mjs +32 -32
  23. package/src/managed-native-fixture.d.mts +84 -84
  24. package/src/managed-native-fixture.mjs +209 -209
  25. package/src/native-fixture.mjs +125 -125
  26. package/src/native-platform.mjs +56 -56
  27. package/src/operator-accounts.mjs +103 -103
  28. package/src/owned-process.mjs +75 -75
  29. package/src/owner-build-cli.mjs +3 -4
  30. package/src/owner-database.mjs +215 -215
  31. package/src/owner-deployment-definition.mjs +31 -0
  32. package/src/owner-deployment.d.mts +32 -0
  33. package/src/owner-deployment.mjs +105 -0
  34. package/src/owner-operator-build.mjs +63 -33
  35. package/src/owner-production-browser.mjs +215 -215
  36. package/src/owner-production-instances.mjs +41 -41
  37. package/src/owner-production.d.mts +114 -104
  38. package/src/owner-production.mjs +350 -338
  39. package/src/owner-worker-build.mjs +83 -83
  40. package/src/prebuilt-output.d.mts +2 -2
  41. package/src/prebuilt-output.mjs +104 -104
  42. package/src/production-hosts.mjs +38 -38
  43. package/src/publisher-acceptance-host-cli.mjs +12 -5
  44. package/src/release-build.mjs +71 -71
  45. package/src/release-control.mjs +45 -45
  46. package/src/release-coordinator.d.mts +9 -9
  47. package/src/release-coordinator.mjs +222 -222
  48. package/src/release-credentials.d.mts +8 -8
  49. package/src/release-credentials.mjs +97 -97
  50. package/src/release-mutex.mjs +38 -38
  51. package/src/release-operator.d.mts +6 -6
  52. package/src/release-operator.mjs +59 -59
  53. package/src/release-supabase.d.mts +7 -7
  54. package/src/release-supabase.mjs +37 -37
  55. package/src/release-vercel.d.mts +22 -22
  56. package/src/release-vercel.mjs +51 -51
  57. package/src/release-writer.d.mts +6 -6
  58. package/src/release-writer.mjs +172 -172
  59. package/src/retained-postgres-shutdown.d.mts +51 -51
  60. package/src/retained-postgres-shutdown.mjs +262 -262
  61. package/src/temporary-acquisition.mjs +62 -62
  62. package/src/temporary-scope.d.mts +47 -47
  63. package/src/temporary-scope.mjs +268 -268
  64. package/src/worker-artifact.mjs +214 -214
@@ -1,97 +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
- }
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
+ }
@@ -1,19 +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
- }
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
+ }
@@ -1 +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}>;
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}>;
@@ -1,58 +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
- }
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
+ }
@@ -1,32 +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
- }
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
+ }
package/src/host-stop.mjs CHANGED
@@ -1,15 +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
- }
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
+ }
@@ -1,32 +1,32 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- /** Bounded lifecycle metadata for one explicitly owned evidence directory. */
5
- export function createLifecycleTrace({ directory, fixture, enabled = false }) {
6
- if (!enabled) return { path: undefined, record() {}, close() {} };
7
- if (typeof directory !== 'string' || !path.isAbsolute(directory) || typeof fixture !== 'string' || !/^[a-z][a-z0-9-]{0,47}$/.test(fixture)) throw Error('lifecycle_trace_target_rejected');
8
- const parent = fs.lstatSync(directory);
9
- if (!parent.isDirectory() || parent.isSymbolicLink()) throw Error('lifecycle_trace_target_rejected');
10
- const file = path.join(directory, fixture + '.lifecycle.ndjson');
11
- const fd = fs.openSync(file, 'wx', 0o600), identity = fs.fstatSync(fd, { bigint: true });
12
- let bytes = 0, closed = false;
13
- return {
14
- path: file,
15
- record(phase, outcome, postgresPid, error) {
16
- if (closed) throw Error('lifecycle_trace_closed');
17
- if (!/^[a-z][a-z0-9-]{0,47}$/.test(phase) || !/^[a-z][a-z0-9-]{0,47}$/.test(outcome)) throw Error('lifecycle_trace_event_rejected');
18
- const current = fs.lstatSync(file, { bigint: true });
19
- if (!current.isFile() || current.isSymbolicLink() || current.nlink !== 1n || current.dev !== identity.dev || current.ino !== identity.ino) throw Error('lifecycle_trace_identity_changed');
20
- const errorCode = error ? (/^[A-Z0-9_]{1,64}$/.test(error.code ?? '') ? error.code : 'LIFECYCLE_FAILED') : undefined;
21
- const line = Buffer.from(JSON.stringify({
22
- at: new Date().toISOString(), actorPid: process.pid,
23
- postgresPid: Number.isSafeInteger(postgresPid) ? postgresPid : undefined,
24
- fixture, phase, outcome, errorCode,
25
- }) + '\n');
26
- if (bytes + line.length > 65536) throw Error('lifecycle_trace_limit');
27
- if (fs.writeSync(fd, line) !== line.length) throw Error('lifecycle_trace_short_write');
28
- bytes += line.length;
29
- },
30
- close() { if (!closed) { closed = true; fs.closeSync(fd); } },
31
- };
32
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /** Bounded lifecycle metadata for one explicitly owned evidence directory. */
5
+ export function createLifecycleTrace({ directory, fixture, enabled = false }) {
6
+ if (!enabled) return { path: undefined, record() {}, close() {} };
7
+ if (typeof directory !== 'string' || !path.isAbsolute(directory) || typeof fixture !== 'string' || !/^[a-z][a-z0-9-]{0,47}$/.test(fixture)) throw Error('lifecycle_trace_target_rejected');
8
+ const parent = fs.lstatSync(directory);
9
+ if (!parent.isDirectory() || parent.isSymbolicLink()) throw Error('lifecycle_trace_target_rejected');
10
+ const file = path.join(directory, fixture + '.lifecycle.ndjson');
11
+ const fd = fs.openSync(file, 'wx', 0o600), identity = fs.fstatSync(fd, { bigint: true });
12
+ let bytes = 0, closed = false;
13
+ return {
14
+ path: file,
15
+ record(phase, outcome, postgresPid, error) {
16
+ if (closed) throw Error('lifecycle_trace_closed');
17
+ if (!/^[a-z][a-z0-9-]{0,47}$/.test(phase) || !/^[a-z][a-z0-9-]{0,47}$/.test(outcome)) throw Error('lifecycle_trace_event_rejected');
18
+ const current = fs.lstatSync(file, { bigint: true });
19
+ if (!current.isFile() || current.isSymbolicLink() || current.nlink !== 1n || current.dev !== identity.dev || current.ino !== identity.ino) throw Error('lifecycle_trace_identity_changed');
20
+ const errorCode = error ? (/^[A-Z0-9_]{1,64}$/.test(error.code ?? '') ? error.code : 'LIFECYCLE_FAILED') : undefined;
21
+ const line = Buffer.from(JSON.stringify({
22
+ at: new Date().toISOString(), actorPid: process.pid,
23
+ postgresPid: Number.isSafeInteger(postgresPid) ? postgresPid : undefined,
24
+ fixture, phase, outcome, errorCode,
25
+ }) + '\n');
26
+ if (bytes + line.length > 65536) throw Error('lifecycle_trace_limit');
27
+ if (fs.writeSync(fd, line) !== line.length) throw Error('lifecycle_trace_short_write');
28
+ bytes += line.length;
29
+ },
30
+ close() { if (!closed) { closed = true; fs.closeSync(fd); } },
31
+ };
32
+ }