@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,214 +1,214 @@
1
- import assert from 'node:assert/strict';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import {createHash} from 'node:crypto';
5
- import {performance} from 'node:perf_hooks';
6
-
7
- const digest=body=>createHash('sha256').update(body).digest('hex');
8
- const inside=(root,file)=>{const relative=path.relative(root,file);assert(relative!== '..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative),'WORKER_ARTIFACT_BOUNDARY');return file;};
9
- const portable=file=>file.split(path.sep).join('/');
10
- export const workerArtifactLimits=Object.freeze({maximumPayloadBytes:64*1024**2,maximumFiles:8192,maximumPathBytes:1024,entriesPerFile:4});
11
- function ownedOutput(root,destination,maximumBytes,maximumFiles,maximumFileBytes=maximumBytes){
12
- try{
13
- const info=fs.lstatSync(destination);assert(info.isDirectory()&&!info.isSymbolicLink()&&fs.realpathSync(destination)===destination);
14
- const receiptFile=path.join(destination,'worker-artifact.json'),receiptInfo=fs.lstatSync(receiptFile);assert(receiptInfo.isFile()&&!receiptInfo.isSymbolicLink()&&receiptInfo.size<=2097152);
15
- const body=fs.readFileSync(receiptFile),manifest=JSON.parse(body);
16
- assert(manifest.schemaVersion===1&&manifest.status==='WORKER_ARTIFACT_PREPARED'&&Array.isArray(manifest.files)&&manifest.files.length<maximumFiles&&Number.isSafeInteger(manifest.payloadBytes)&&manifest.payloadBytes>=0&&manifest.payloadBytes+body.length<=maximumBytes);
17
- const files=new Map();let bytes=0;
18
- for(const record of manifest.files){
19
- assert(typeof record.path==='string'&&Buffer.byteLength(record.path)<=workerArtifactLimits.maximumPathBytes&&!/[\\:\0\r\n]/.test(record.path)&&!record.path.startsWith('/')&&record.path.split('/').every(part=>part&&part!=='.'&&part!=='..')&&!files.has(record.path)&&record.path!=='worker-artifact.json');
20
- assert(Number.isSafeInteger(record.bytes)&&record.bytes>=0&&record.bytes<=maximumFileBytes&&/^[a-f0-9]{64}$/.test(record.sha256));bytes+=record.bytes;assert(bytes<=maximumBytes);files.set(record.path,record);
21
- }
22
- assert(bytes===manifest.payloadBytes&&files.has(manifest.entry)&&files.has('package.json'));
23
- const expected=[...files.keys()];let visited=0;
24
- const walk=filename=>{
25
- assert(++visited<=maximumFiles*4);const relative=portable(path.relative(destination,filename)),stat=fs.lstatSync(filename);
26
- if(stat.isDirectory()&&!stat.isSymbolicLink()){assert(!relative||expected.some(name=>name.startsWith(relative+'/')));for(const name of fs.readdirSync(filename))walk(path.join(filename,name));return;}
27
- if(relative==='worker-artifact.json')return;
28
- const record=files.get(relative);assert(record);
29
- if(Object.hasOwn(record,'link')){assert(stat.isSymbolicLink()&&record.bytes===0&&typeof record.link==='string'&&record.link.length>0&&Buffer.byteLength(record.link)<=workerArtifactLimits.maximumPathBytes&&digest(record.link)===record.sha256);const target=inside(destination,fs.realpathSync(filename));assert(target!==destination&&path.resolve(path.dirname(filename),record.link)===target);}
30
- else{assert(stat.isFile()&&!stat.isSymbolicLink()&&stat.size===record.bytes&&digest(fs.readFileSync(filename))===record.sha256);}
31
- files.delete(relative);
32
- };
33
- walk(destination);assert(files.size===0);
34
- assert(JSON.parse(fs.readFileSync(path.join(destination,'package.json'),'utf8')).name===JSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8')).name);
35
- return {dev:info.dev,ino:info.ino,digest:digest(body)};
36
- }catch{assert.fail('WORKER_ARTIFACT_REPLACEMENT');}
37
- }
38
- /** Read-only final build-stage check. Run immediately before the runtime COPY,
39
- * after every application build command, so an unreceipted extra file cannot
40
- * invalidate the image-size admission bound. */
41
- export function verifyWorkerArtifact({root,output}){
42
- root=fs.realpathSync(root);assert(typeof output==='string'&&!path.isAbsolute(output),'WORKER_ARTIFACT_OUTPUT');
43
- const destination=path.resolve(root,output);assert(path.relative(root,destination).startsWith('tmp'+path.sep),'WORKER_ARTIFACT_OUTPUT');
44
- ownedOutput(root,destination,workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles);
45
- const manifest=JSON.parse(fs.readFileSync(path.join(destination,'worker-artifact.json'),'utf8'));
46
- return {status:'WORKER_ARTIFACT_VERIFIED',files:manifest.files.length+1,payloadBytes:manifest.payloadBytes};
47
- }
48
-
49
- // Preserve the verified relative resolver links. Expanding a package directory
50
- // changes Node's realpath-based transitive dependency lookup. All link targets
51
- // are part of the same pruned payload; no installation/source fallback is used.
52
- function functionWorker(source,manifest){
53
- const files=[];let bytes=0;
54
- for(const record of manifest.files){
55
- const relative=record.path,selected=path.join(source,relative);assert(files.length<workerArtifactLimits.maximumFiles-1,'FUNCTION_FILE_LIMIT');
56
- if(Object.hasOwn(record,'link')){
57
- const target=inside(source,fs.realpathSync(selected)),raw=fs.readlinkSync(selected);assert(!path.isAbsolute(record.link)&&!path.isAbsolute(raw)&&portable(raw)===record.link,'FUNCTION_LINK_INVALID');
58
- bytes+=Buffer.byteLength(record.link);assert(bytes<=workerArtifactLimits.maximumPayloadBytes,'FUNCTION_BYTE_LIMIT');
59
- files.push({...record,directory:fs.statSync(target).isDirectory()});continue;
60
- }
61
- assert(record.bytes<=workerArtifactLimits.maximumPayloadBytes-bytes,'FUNCTION_BYTE_LIMIT');
62
- const body=fs.readFileSync(selected);assert(body.length===record.bytes&&digest(body)===record.sha256,'FUNCTION_SOURCE_CHANGED');
63
- // A native Windows runtime cannot establish Linux Function compatibility.
64
- assert(!/\.(?:dll|exe|pdb)$/i.test(relative)&&(!/\.node$/i.test(relative)||body.length>=20&&body.subarray(0,4).equals(Buffer.from([127,69,76,70]))&&body[4]===2&&body[5]===1&&body.readUInt16LE(18)===62),'FUNCTION_NATIVE_TARGET_INVALID');
65
- bytes+=body.length;files.push({...record,body});
66
- }
67
- const receipt=fs.readFileSync(path.join(source,'worker-artifact.json'));
68
- assert(bytes+receipt.length<=workerArtifactLimits.maximumPayloadBytes,'FUNCTION_BYTE_LIMIT');
69
- return {files,receipt,digest:digest(receipt),bytes:bytes+receipt.length};
70
- }
71
-
72
- /** Capture the same verified Node closure without materializing resolver links
73
- * into a publication format. No provider API or local runtime is invoked. */
74
- export function readWorkerArtifact({root,output,maximumBytes=workerArtifactLimits.maximumPayloadBytes,maximumFiles=workerArtifactLimits.maximumFiles,maximumFileBytes=maximumBytes}){
75
- root=fs.realpathSync(root);assert(typeof output==='string'&&!path.isAbsolute(output),'WORKER_ARTIFACT_OUTPUT');const source=path.resolve(root,output);assert(path.relative(root,source).startsWith('tmp'+path.sep),'WORKER_ARTIFACT_OUTPUT');
76
- assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>0&&maximumBytes<=workerArtifactLimits.maximumPayloadBytes&&Number.isSafeInteger(maximumFiles)&&maximumFiles>0&&maximumFiles<=workerArtifactLimits.maximumFiles&&Number.isSafeInteger(maximumFileBytes)&&maximumFileBytes>0&&maximumFileBytes<=maximumBytes,'WORKER_ARTIFACT_LIMIT_INVALID');
77
- const identity=ownedOutput(root,source,maximumBytes,maximumFiles,maximumFileBytes),manifest=JSON.parse(fs.readFileSync(path.join(source,'worker-artifact.json')));
78
- const captured=functionWorker(source,manifest);assert.deepEqual(ownedOutput(root,source,maximumBytes,maximumFiles,maximumFileBytes),identity,'WORKER_ARTIFACT_SOURCE_CHANGED');
79
- return {entry:manifest.entry,files:captured.files.map(file=>Object.hasOwn(file,'link')?{path:file.path,link:file.link,directory:file.directory}:{path:file.path,bytes:file.body}),receipt:captured.receipt,payloadBytes:captured.bytes};
80
- }
81
-
82
- /** Add exact-path Node functions to a freshly built Build Output API v3 tree.
83
- * Different endpoints have separately budgeted payloads; no billing deduplication
84
- * is assumed. A changed or interrupted tree must be rebuilt by its build owner. */
85
- export function emitVercelWorkerFunctions({root,workerOutput,paths,maxDuration,region,maximumBytes=64*1024**2}){
86
- root=fs.realpathSync(root);
87
- assert(Array.isArray(paths)&&paths.length>=1&&paths.length<=2&&new Set(paths).size===paths.length,'FUNCTION_PATH_INVALID');
88
- assert(Number.isSafeInteger(maxDuration)&&maxDuration>=1&&maxDuration<=300,'FUNCTION_DURATION_INVALID');
89
- assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>0&&maximumBytes<=128*1024**2,'FUNCTION_BYTE_LIMIT');
90
- for(const value of paths)assert(typeof value==='string'&&value.startsWith('/')&&value.length<=512&&value.slice(1).split('/').every(part=>/^[A-Za-z0-9._-]+$/.test(part)&&!['.','..'].includes(part)&&!/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part)),'FUNCTION_PATH_INVALID');
91
- const assertDirectories=selected=>{
92
- inside(root,selected);let current=root;
93
- for(const part of path.relative(root,selected).split(path.sep).filter(Boolean)){
94
- current=path.join(current,part);const info=fs.lstatSync(current,{throwIfNoEntry:false});
95
- if(!info)break;assert(info.isDirectory()&&!info.isSymbolicLink()&&fs.realpathSync(current)===current,'FUNCTION_OUTPUT_BOUNDARY');
96
- }
97
- };
98
- const output=path.join(root,'.vercel/output'),configFile=path.join(output,'config.json');assertDirectories(output);
99
- const info=fs.lstatSync(configFile);assert(info.isFile()&&!info.isSymbolicLink()&&info.nlink===1&&info.size<=2*1024**2,'FUNCTION_OUTPUT_INVALID');
100
- const original=fs.readFileSync(configFile),config=JSON.parse(original);
101
- assert(config?.version===3&&(config.routes===undefined||Array.isArray(config.routes)&&config.routes.length<=4096),'FUNCTION_OUTPUT_INVALID');
102
- verifyWorkerArtifact({root,output:workerOutput});
103
- const source=path.resolve(root,workerOutput),identity=ownedOutput(root,source,workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles);
104
- const manifest=JSON.parse(fs.readFileSync(path.join(source,'worker-artifact.json')));
105
- const materialized=functionWorker(source,manifest);
106
- const wrapper=Buffer.from('export { default } from '+JSON.stringify('./runtime/'+manifest.entry)+';\n');
107
- const functionConfig=Buffer.from(JSON.stringify({runtime:'nodejs24.x',handler:'index.mjs',launcherType:'Nodejs',shouldAddHelpers:false,memory:2048,maxDuration,...(region===undefined?{}:{regions:[region]})})+'\n');
108
- const routes=paths.map(value=>({src:'^'+value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')+'$',dest:value})),sources=new Set(routes.map(route=>route.src));
109
- for(const route of config.routes??[])if(sources.has(route?.src))assert(routes.some(selected=>JSON.stringify(selected)===JSON.stringify(route)),'FUNCTION_ROUTE_CONFLICT');
110
- const configBytes=Buffer.from(JSON.stringify({...config,routes:[...routes,...(config.routes??[]).filter(route=>!sources.has(route?.src))]},null,2)+'\n');
111
- const bytes=paths.length*(materialized.bytes+wrapper.length+functionConfig.length)+configBytes.length;
112
- assert(bytes<=maximumBytes,'FUNCTION_BYTE_LIMIT');
113
- const selected=paths.map(value=>{
114
- const destination=path.join(output,'functions',value.slice(1)+'.func');assertDirectories(destination);
115
- const exists=fs.existsSync(destination);
116
- if(exists){
117
- try{
118
- assert.deepEqual(fs.readdirSync(destination).sort(),['.vc-config.json','index.mjs','runtime']);
119
- for(const [name,body]of [['.vc-config.json',functionConfig],['index.mjs',wrapper]]){const file=path.join(destination,name),stat=fs.lstatSync(file);assert(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&fs.readFileSync(file).equals(body));}
120
- assert.equal(ownedOutput(root,path.join(destination,'runtime'),workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles).digest,materialized.digest);
121
- }catch{assert.fail('FUNCTION_OUTPUT_REBUILD_REQUIRED');}
122
- }
123
- return {destination,exists};
124
- });
125
- for(const {destination,exists}of selected)if(!exists){
126
- fs.mkdirSync(destination,{recursive:true});
127
- for(const file of materialized.files){const target=path.join(destination,'runtime',file.path);fs.mkdirSync(path.dirname(target),{recursive:true});if(!Object.hasOwn(file,'link'))fs.writeFileSync(target,file.body,{flag:'wx'});}
128
- for(const file of materialized.files)if(Object.hasOwn(file,'link'))fs.symlinkSync(file.link,path.join(destination,'runtime',file.path),file.directory?'dir':'file');
129
- fs.writeFileSync(path.join(destination,'runtime/worker-artifact.json'),materialized.receipt,{flag:'wx'});
130
- assert.equal(ownedOutput(root,path.join(destination,'runtime'),workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles).digest,materialized.digest,'FUNCTION_SOURCE_CHANGED');
131
- fs.writeFileSync(path.join(destination,'index.mjs'),wrapper,{flag:'wx'});fs.writeFileSync(path.join(destination,'.vc-config.json'),functionConfig,{flag:'wx'});
132
- }
133
- assert.equal(ownedOutput(root,source,workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles).digest,identity.digest,'FUNCTION_SOURCE_CHANGED');
134
- assert(fs.readFileSync(configFile).equals(original),'FUNCTION_OUTPUT_CHANGED');
135
- if(!original.equals(configBytes))fs.writeFileSync(configFile,configBytes);
136
- return {status:'NODE_FUNCTIONS_PREPARED',functions:paths.length,bytes,paths:[...paths]};
137
- }
138
-
139
- /** Package a caller-selected built entry and assets. The caller supplies its pinned
140
- * tracer and closes all consumers before explicitly replacing a build-only slot. */
141
- export async function prepareWorkerArtifact({root,entry,output,trace,additionalEntries=[],resources=[],maximumBytes=16*1024**2,maximumFiles=4096,ignore=()=>false,replace=false}){
142
- const started=performance.now();root=fs.realpathSync(root);
143
- assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>0&&maximumBytes<=workerArtifactLimits.maximumPayloadBytes,'WORKER_ARTIFACT_BYTE_LIMIT');
144
- assert(Number.isSafeInteger(maximumFiles)&&maximumFiles>0&&maximumFiles<=workerArtifactLimits.maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');
145
- assert(typeof trace==='function'&&typeof entry==='string'&&!path.isAbsolute(entry),'WORKER_ARTIFACT_INPUT');
146
- assert(Array.isArray(additionalEntries)&&additionalEntries.length<=32&&Array.isArray(resources)&&resources.length<=32,'WORKER_ARTIFACT_INPUT');
147
- assert(typeof output==='string'&&!path.isAbsolute(output),'WORKER_ARTIFACT_OUTPUT');
148
- const destination=path.resolve(root,output),relativeOutput=path.relative(root,destination);
149
- const existing=fs.lstatSync(destination,{throwIfNoEntry:false});
150
- assert(typeof replace==='boolean'&&relativeOutput.startsWith('tmp'+path.sep)&&(!existing||replace),'WORKER_ARTIFACT_OUTPUT');
151
- const previous=existing?ownedOutput(root,destination,maximumBytes,maximumFiles):undefined;
152
- let parent=path.dirname(destination);
153
- while(!fs.existsSync(parent))parent=path.dirname(parent);
154
- assert(fs.realpathSync(parent)===parent,'WORKER_ARTIFACT_OUTPUT');
155
- const files=new Map(),links=new Map();let bytes=0;
156
- const add=file=>{
157
- file=inside(root,path.resolve(root,file));inside(root,fs.realpathSync(file));
158
- const relative=portable(path.relative(root,file));if(files.has(relative))return;
159
- assert(Buffer.byteLength(relative)<=workerArtifactLimits.maximumPathBytes,'WORKER_ARTIFACT_PATH_LIMIT');
160
- const stat=fs.lstatSync(file);assert(stat.isFile()||stat.isSymbolicLink(),'WORKER_ARTIFACT_FILE_TYPE');
161
- assert(files.size<maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');
162
- if(stat.isSymbolicLink()){
163
- const target=inside(root,fs.realpathSync(file)),link=portable(path.relative(path.dirname(file),target));assert(Buffer.byteLength(link)<=workerArtifactLimits.maximumPathBytes,'WORKER_ARTIFACT_PATH_LIMIT');links.set(relative,target);files.set(relative,{path:relative,bytes:0,sha256:digest(link),link});return;
164
- }
165
- assert(stat.size<=maximumBytes-bytes,'WORKER_ARTIFACT_BYTE_LIMIT');
166
- let body=fs.readFileSync(file);assert.equal(body.length,stat.size,'WORKER_ARTIFACT_SOURCE_CHANGED');
167
- if(path.basename(file)==='package.json')assert(!['react','react-dom','next','@xlinklight/workbench'].includes(JSON.parse(body).name),'WORKER_ARTIFACT_UI_DEPENDENCY');
168
- if(relative==='package.json'){
169
- const source=JSON.parse(body),metadata={private:true};
170
- for(const key of ['name','version','type','exports','imports'])if(Object.hasOwn(source,key))metadata[key]=source[key];
171
- body=Buffer.from(JSON.stringify(metadata)+'\n');
172
- }
173
- bytes+=body.length;assert(bytes<=maximumBytes,'WORKER_ARTIFACT_BYTE_LIMIT');
174
- files.set(relative,{path:relative,bytes:body.length,sha256:digest(body),source:file,body});
175
- };
176
- const resolverLinks=new Set();
177
- const traced=await trace([entry,...additionalEntries].map(file=>{assert(typeof file==='string'&&!path.isAbsolute(file),'WORKER_ARTIFACT_INPUT');return inside(root,path.resolve(root,file));}),{
178
- base:root,processCwd:root,exportsOnly:true,ignore,
179
- async readlink(file){
180
- try{const target=await fs.promises.readlink(file);inside(root,file);inside(root,fs.realpathSync(file));assert(resolverLinks.size<maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');resolverLinks.add(file);return target;}
181
- catch(error){if(['ENOENT','EINVAL','ENOTDIR'].includes(error.code))return null;throw error;}
182
- },
183
- });
184
- assert.equal(traced.warnings.size,0,'WORKER_ARTIFACT_TRACE_WARNING: '+[...traced.warnings].map(error=>error.message).join('; '));
185
- for(const file of [...traced.fileList,...resolverLinks].sort())add(file);
186
- const walk=file=>{
187
- file=inside(root,path.resolve(root,file));inside(root,fs.realpathSync(file));
188
- assert(!fs.lstatSync(file).isSymbolicLink(),'WORKER_ARTIFACT_BOUNDARY');
189
- if(fs.statSync(file).isDirectory())for(const name of fs.readdirSync(file).sort())walk(path.join(file,name));else add(file);
190
- };
191
- for(const resource of resources)walk(resource);
192
- add('package.json');assert(files.has(portable(entry)),'WORKER_ARTIFACT_ENTRY_MISSING');
193
- for(const [alias,target]of links){
194
- const selected=portable(path.relative(root,target));assert([...files.keys()].some(file=>file===selected||file.startsWith(selected+'/')),'WORKER_ARTIFACT_LINK_TARGET_MISSING: '+alias);
195
- }
196
- const manifest={schemaVersion:1,status:'WORKER_ARTIFACT_PREPARED',entry:portable(entry),files:[...files.values()].map(record=>({path:record.path,bytes:record.bytes,sha256:record.sha256,...(record.link?{link:record.link}:{})})),payloadBytes:bytes};
197
- const receipt=Buffer.from(JSON.stringify(manifest,null,2)+'\n');assert(bytes+receipt.length<=maximumBytes,'WORKER_ARTIFACT_BYTE_LIMIT');
198
- assert(files.size+1<=maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');
199
- const entries=new Set([...files.keys(),'worker-artifact.json']);
200
- for(const record of files.keys()){let parent=path.posix.dirname(record);while(parent!=='.'){entries.add(parent);assert(entries.size+1<=maximumFiles*workerArtifactLimits.entriesPerFile,'WORKER_ARTIFACT_ENTRY_LIMIT');parent=path.posix.dirname(parent);}}
201
- const tracedAt=performance.now();
202
- if(previous){assert.deepEqual(ownedOutput(root,destination,maximumBytes,maximumFiles),previous,'WORKER_ARTIFACT_REPLACEMENT');fs.rmSync(destination,{recursive:true});}
203
- fs.mkdirSync(destination,{recursive:true});
204
- for(const record of files.values())if(!record.link){
205
- const target=path.join(destination,record.path);fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,record.body,{flag:'wx'});
206
- }
207
- for(const [alias,target]of links){
208
- const filename=path.join(destination,alias),selected=path.join(destination,path.relative(root,target));
209
- assert(fs.existsSync(selected),'WORKER_ARTIFACT_LINK_TARGET_MISSING');fs.mkdirSync(path.dirname(filename),{recursive:true});
210
- fs.symlinkSync(path.relative(path.dirname(filename),selected),filename,fs.statSync(target).isDirectory()?'dir':'file');
211
- }
212
- fs.writeFileSync(path.join(destination,'worker-artifact.json'),receipt,{flag:'wx'});
213
- return {...manifest,bytes:bytes+receipt.length,output:destination,timings:{traceMs:tracedAt-started,writeMs:performance.now()-tracedAt,totalMs:performance.now()-started}};
214
- }
1
+ import assert from 'node:assert/strict';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {createHash} from 'node:crypto';
5
+ import {performance} from 'node:perf_hooks';
6
+
7
+ const digest=body=>createHash('sha256').update(body).digest('hex');
8
+ const inside=(root,file)=>{const relative=path.relative(root,file);assert(relative!== '..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative),'WORKER_ARTIFACT_BOUNDARY');return file;};
9
+ const portable=file=>file.split(path.sep).join('/');
10
+ export const workerArtifactLimits=Object.freeze({maximumPayloadBytes:64*1024**2,maximumFiles:8192,maximumPathBytes:1024,entriesPerFile:4});
11
+ function ownedOutput(root,destination,maximumBytes,maximumFiles,maximumFileBytes=maximumBytes){
12
+ try{
13
+ const info=fs.lstatSync(destination);assert(info.isDirectory()&&!info.isSymbolicLink()&&fs.realpathSync(destination)===destination);
14
+ const receiptFile=path.join(destination,'worker-artifact.json'),receiptInfo=fs.lstatSync(receiptFile);assert(receiptInfo.isFile()&&!receiptInfo.isSymbolicLink()&&receiptInfo.size<=2097152);
15
+ const body=fs.readFileSync(receiptFile),manifest=JSON.parse(body);
16
+ assert(manifest.schemaVersion===1&&manifest.status==='WORKER_ARTIFACT_PREPARED'&&Array.isArray(manifest.files)&&manifest.files.length<maximumFiles&&Number.isSafeInteger(manifest.payloadBytes)&&manifest.payloadBytes>=0&&manifest.payloadBytes+body.length<=maximumBytes);
17
+ const files=new Map();let bytes=0;
18
+ for(const record of manifest.files){
19
+ assert(typeof record.path==='string'&&Buffer.byteLength(record.path)<=workerArtifactLimits.maximumPathBytes&&!/[\\:\0\r\n]/.test(record.path)&&!record.path.startsWith('/')&&record.path.split('/').every(part=>part&&part!=='.'&&part!=='..')&&!files.has(record.path)&&record.path!=='worker-artifact.json');
20
+ assert(Number.isSafeInteger(record.bytes)&&record.bytes>=0&&record.bytes<=maximumFileBytes&&/^[a-f0-9]{64}$/.test(record.sha256));bytes+=record.bytes;assert(bytes<=maximumBytes);files.set(record.path,record);
21
+ }
22
+ assert(bytes===manifest.payloadBytes&&files.has(manifest.entry)&&files.has('package.json'));
23
+ const expected=[...files.keys()];let visited=0;
24
+ const walk=filename=>{
25
+ assert(++visited<=maximumFiles*4);const relative=portable(path.relative(destination,filename)),stat=fs.lstatSync(filename);
26
+ if(stat.isDirectory()&&!stat.isSymbolicLink()){assert(!relative||expected.some(name=>name.startsWith(relative+'/')));for(const name of fs.readdirSync(filename))walk(path.join(filename,name));return;}
27
+ if(relative==='worker-artifact.json')return;
28
+ const record=files.get(relative);assert(record);
29
+ if(Object.hasOwn(record,'link')){assert(stat.isSymbolicLink()&&record.bytes===0&&typeof record.link==='string'&&record.link.length>0&&Buffer.byteLength(record.link)<=workerArtifactLimits.maximumPathBytes&&digest(record.link)===record.sha256);const target=inside(destination,fs.realpathSync(filename));assert(target!==destination&&path.resolve(path.dirname(filename),record.link)===target);}
30
+ else{assert(stat.isFile()&&!stat.isSymbolicLink()&&stat.size===record.bytes&&digest(fs.readFileSync(filename))===record.sha256);}
31
+ files.delete(relative);
32
+ };
33
+ walk(destination);assert(files.size===0);
34
+ assert(JSON.parse(fs.readFileSync(path.join(destination,'package.json'),'utf8')).name===JSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8')).name);
35
+ return {dev:info.dev,ino:info.ino,digest:digest(body)};
36
+ }catch{assert.fail('WORKER_ARTIFACT_REPLACEMENT');}
37
+ }
38
+ /** Read-only final build-stage check. Run immediately before the runtime COPY,
39
+ * after every application build command, so an unreceipted extra file cannot
40
+ * invalidate the image-size admission bound. */
41
+ export function verifyWorkerArtifact({root,output}){
42
+ root=fs.realpathSync(root);assert(typeof output==='string'&&!path.isAbsolute(output),'WORKER_ARTIFACT_OUTPUT');
43
+ const destination=path.resolve(root,output);assert(path.relative(root,destination).startsWith('tmp'+path.sep),'WORKER_ARTIFACT_OUTPUT');
44
+ ownedOutput(root,destination,workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles);
45
+ const manifest=JSON.parse(fs.readFileSync(path.join(destination,'worker-artifact.json'),'utf8'));
46
+ return {status:'WORKER_ARTIFACT_VERIFIED',files:manifest.files.length+1,payloadBytes:manifest.payloadBytes};
47
+ }
48
+
49
+ // Preserve the verified relative resolver links. Expanding a package directory
50
+ // changes Node's realpath-based transitive dependency lookup. All link targets
51
+ // are part of the same pruned payload; no installation/source fallback is used.
52
+ function functionWorker(source,manifest){
53
+ const files=[];let bytes=0;
54
+ for(const record of manifest.files){
55
+ const relative=record.path,selected=path.join(source,relative);assert(files.length<workerArtifactLimits.maximumFiles-1,'FUNCTION_FILE_LIMIT');
56
+ if(Object.hasOwn(record,'link')){
57
+ const target=inside(source,fs.realpathSync(selected)),raw=fs.readlinkSync(selected);assert(!path.isAbsolute(record.link)&&!path.isAbsolute(raw)&&portable(raw)===record.link,'FUNCTION_LINK_INVALID');
58
+ bytes+=Buffer.byteLength(record.link);assert(bytes<=workerArtifactLimits.maximumPayloadBytes,'FUNCTION_BYTE_LIMIT');
59
+ files.push({...record,directory:fs.statSync(target).isDirectory()});continue;
60
+ }
61
+ assert(record.bytes<=workerArtifactLimits.maximumPayloadBytes-bytes,'FUNCTION_BYTE_LIMIT');
62
+ const body=fs.readFileSync(selected);assert(body.length===record.bytes&&digest(body)===record.sha256,'FUNCTION_SOURCE_CHANGED');
63
+ // A native Windows runtime cannot establish Linux Function compatibility.
64
+ assert(!/\.(?:dll|exe|pdb)$/i.test(relative)&&(!/\.node$/i.test(relative)||body.length>=20&&body.subarray(0,4).equals(Buffer.from([127,69,76,70]))&&body[4]===2&&body[5]===1&&body.readUInt16LE(18)===62),'FUNCTION_NATIVE_TARGET_INVALID');
65
+ bytes+=body.length;files.push({...record,body});
66
+ }
67
+ const receipt=fs.readFileSync(path.join(source,'worker-artifact.json'));
68
+ assert(bytes+receipt.length<=workerArtifactLimits.maximumPayloadBytes,'FUNCTION_BYTE_LIMIT');
69
+ return {files,receipt,digest:digest(receipt),bytes:bytes+receipt.length};
70
+ }
71
+
72
+ /** Capture the same verified Node closure without materializing resolver links
73
+ * into a publication format. No provider API or local runtime is invoked. */
74
+ export function readWorkerArtifact({root,output,maximumBytes=workerArtifactLimits.maximumPayloadBytes,maximumFiles=workerArtifactLimits.maximumFiles,maximumFileBytes=maximumBytes}){
75
+ root=fs.realpathSync(root);assert(typeof output==='string'&&!path.isAbsolute(output),'WORKER_ARTIFACT_OUTPUT');const source=path.resolve(root,output);assert(path.relative(root,source).startsWith('tmp'+path.sep),'WORKER_ARTIFACT_OUTPUT');
76
+ assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>0&&maximumBytes<=workerArtifactLimits.maximumPayloadBytes&&Number.isSafeInteger(maximumFiles)&&maximumFiles>0&&maximumFiles<=workerArtifactLimits.maximumFiles&&Number.isSafeInteger(maximumFileBytes)&&maximumFileBytes>0&&maximumFileBytes<=maximumBytes,'WORKER_ARTIFACT_LIMIT_INVALID');
77
+ const identity=ownedOutput(root,source,maximumBytes,maximumFiles,maximumFileBytes),manifest=JSON.parse(fs.readFileSync(path.join(source,'worker-artifact.json')));
78
+ const captured=functionWorker(source,manifest);assert.deepEqual(ownedOutput(root,source,maximumBytes,maximumFiles,maximumFileBytes),identity,'WORKER_ARTIFACT_SOURCE_CHANGED');
79
+ return {entry:manifest.entry,files:captured.files.map(file=>Object.hasOwn(file,'link')?{path:file.path,link:file.link,directory:file.directory}:{path:file.path,bytes:file.body}),receipt:captured.receipt,payloadBytes:captured.bytes};
80
+ }
81
+
82
+ /** Add exact-path Node functions to a freshly built Build Output API v3 tree.
83
+ * Different endpoints have separately budgeted payloads; no billing deduplication
84
+ * is assumed. A changed or interrupted tree must be rebuilt by its build owner. */
85
+ export function emitVercelWorkerFunctions({root,workerOutput,paths,maxDuration,region,maximumBytes=64*1024**2}){
86
+ root=fs.realpathSync(root);
87
+ assert(Array.isArray(paths)&&paths.length>=1&&paths.length<=2&&new Set(paths).size===paths.length,'FUNCTION_PATH_INVALID');
88
+ assert(Number.isSafeInteger(maxDuration)&&maxDuration>=1&&maxDuration<=300,'FUNCTION_DURATION_INVALID');
89
+ assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>0&&maximumBytes<=128*1024**2,'FUNCTION_BYTE_LIMIT');
90
+ for(const value of paths)assert(typeof value==='string'&&value.startsWith('/')&&value.length<=512&&value.slice(1).split('/').every(part=>/^[A-Za-z0-9._-]+$/.test(part)&&!['.','..'].includes(part)&&!/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part)),'FUNCTION_PATH_INVALID');
91
+ const assertDirectories=selected=>{
92
+ inside(root,selected);let current=root;
93
+ for(const part of path.relative(root,selected).split(path.sep).filter(Boolean)){
94
+ current=path.join(current,part);const info=fs.lstatSync(current,{throwIfNoEntry:false});
95
+ if(!info)break;assert(info.isDirectory()&&!info.isSymbolicLink()&&fs.realpathSync(current)===current,'FUNCTION_OUTPUT_BOUNDARY');
96
+ }
97
+ };
98
+ const output=path.join(root,'.vercel/output'),configFile=path.join(output,'config.json');assertDirectories(output);
99
+ const info=fs.lstatSync(configFile);assert(info.isFile()&&!info.isSymbolicLink()&&info.nlink===1&&info.size<=2*1024**2,'FUNCTION_OUTPUT_INVALID');
100
+ const original=fs.readFileSync(configFile),config=JSON.parse(original);
101
+ assert(config?.version===3&&(config.routes===undefined||Array.isArray(config.routes)&&config.routes.length<=4096),'FUNCTION_OUTPUT_INVALID');
102
+ verifyWorkerArtifact({root,output:workerOutput});
103
+ const source=path.resolve(root,workerOutput),identity=ownedOutput(root,source,workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles);
104
+ const manifest=JSON.parse(fs.readFileSync(path.join(source,'worker-artifact.json')));
105
+ const materialized=functionWorker(source,manifest);
106
+ const wrapper=Buffer.from('export { default } from '+JSON.stringify('./runtime/'+manifest.entry)+';\n');
107
+ const functionConfig=Buffer.from(JSON.stringify({runtime:'nodejs24.x',handler:'index.mjs',launcherType:'Nodejs',shouldAddHelpers:false,memory:2048,maxDuration,...(region===undefined?{}:{regions:[region]})})+'\n');
108
+ const routes=paths.map(value=>({src:'^'+value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')+'$',dest:value})),sources=new Set(routes.map(route=>route.src));
109
+ for(const route of config.routes??[])if(sources.has(route?.src))assert(routes.some(selected=>JSON.stringify(selected)===JSON.stringify(route)),'FUNCTION_ROUTE_CONFLICT');
110
+ const configBytes=Buffer.from(JSON.stringify({...config,routes:[...routes,...(config.routes??[]).filter(route=>!sources.has(route?.src))]},null,2)+'\n');
111
+ const bytes=paths.length*(materialized.bytes+wrapper.length+functionConfig.length)+configBytes.length;
112
+ assert(bytes<=maximumBytes,'FUNCTION_BYTE_LIMIT');
113
+ const selected=paths.map(value=>{
114
+ const destination=path.join(output,'functions',value.slice(1)+'.func');assertDirectories(destination);
115
+ const exists=fs.existsSync(destination);
116
+ if(exists){
117
+ try{
118
+ assert.deepEqual(fs.readdirSync(destination).sort(),['.vc-config.json','index.mjs','runtime']);
119
+ for(const [name,body]of [['.vc-config.json',functionConfig],['index.mjs',wrapper]]){const file=path.join(destination,name),stat=fs.lstatSync(file);assert(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&fs.readFileSync(file).equals(body));}
120
+ assert.equal(ownedOutput(root,path.join(destination,'runtime'),workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles).digest,materialized.digest);
121
+ }catch{assert.fail('FUNCTION_OUTPUT_REBUILD_REQUIRED');}
122
+ }
123
+ return {destination,exists};
124
+ });
125
+ for(const {destination,exists}of selected)if(!exists){
126
+ fs.mkdirSync(destination,{recursive:true});
127
+ for(const file of materialized.files){const target=path.join(destination,'runtime',file.path);fs.mkdirSync(path.dirname(target),{recursive:true});if(!Object.hasOwn(file,'link'))fs.writeFileSync(target,file.body,{flag:'wx'});}
128
+ for(const file of materialized.files)if(Object.hasOwn(file,'link'))fs.symlinkSync(file.link,path.join(destination,'runtime',file.path),file.directory?'dir':'file');
129
+ fs.writeFileSync(path.join(destination,'runtime/worker-artifact.json'),materialized.receipt,{flag:'wx'});
130
+ assert.equal(ownedOutput(root,path.join(destination,'runtime'),workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles).digest,materialized.digest,'FUNCTION_SOURCE_CHANGED');
131
+ fs.writeFileSync(path.join(destination,'index.mjs'),wrapper,{flag:'wx'});fs.writeFileSync(path.join(destination,'.vc-config.json'),functionConfig,{flag:'wx'});
132
+ }
133
+ assert.equal(ownedOutput(root,source,workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles).digest,identity.digest,'FUNCTION_SOURCE_CHANGED');
134
+ assert(fs.readFileSync(configFile).equals(original),'FUNCTION_OUTPUT_CHANGED');
135
+ if(!original.equals(configBytes))fs.writeFileSync(configFile,configBytes);
136
+ return {status:'NODE_FUNCTIONS_PREPARED',functions:paths.length,bytes,paths:[...paths]};
137
+ }
138
+
139
+ /** Package a caller-selected built entry and assets. The caller supplies its pinned
140
+ * tracer and closes all consumers before explicitly replacing a build-only slot. */
141
+ export async function prepareWorkerArtifact({root,entry,output,trace,additionalEntries=[],resources=[],maximumBytes=16*1024**2,maximumFiles=4096,ignore=()=>false,replace=false}){
142
+ const started=performance.now();root=fs.realpathSync(root);
143
+ assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>0&&maximumBytes<=workerArtifactLimits.maximumPayloadBytes,'WORKER_ARTIFACT_BYTE_LIMIT');
144
+ assert(Number.isSafeInteger(maximumFiles)&&maximumFiles>0&&maximumFiles<=workerArtifactLimits.maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');
145
+ assert(typeof trace==='function'&&typeof entry==='string'&&!path.isAbsolute(entry),'WORKER_ARTIFACT_INPUT');
146
+ assert(Array.isArray(additionalEntries)&&additionalEntries.length<=32&&Array.isArray(resources)&&resources.length<=32,'WORKER_ARTIFACT_INPUT');
147
+ assert(typeof output==='string'&&!path.isAbsolute(output),'WORKER_ARTIFACT_OUTPUT');
148
+ const destination=path.resolve(root,output),relativeOutput=path.relative(root,destination);
149
+ const existing=fs.lstatSync(destination,{throwIfNoEntry:false});
150
+ assert(typeof replace==='boolean'&&relativeOutput.startsWith('tmp'+path.sep)&&(!existing||replace),'WORKER_ARTIFACT_OUTPUT');
151
+ const previous=existing?ownedOutput(root,destination,maximumBytes,maximumFiles):undefined;
152
+ let parent=path.dirname(destination);
153
+ while(!fs.existsSync(parent))parent=path.dirname(parent);
154
+ assert(fs.realpathSync(parent)===parent,'WORKER_ARTIFACT_OUTPUT');
155
+ const files=new Map(),links=new Map();let bytes=0;
156
+ const add=file=>{
157
+ file=inside(root,path.resolve(root,file));inside(root,fs.realpathSync(file));
158
+ const relative=portable(path.relative(root,file));if(files.has(relative))return;
159
+ assert(Buffer.byteLength(relative)<=workerArtifactLimits.maximumPathBytes,'WORKER_ARTIFACT_PATH_LIMIT');
160
+ const stat=fs.lstatSync(file);assert(stat.isFile()||stat.isSymbolicLink(),'WORKER_ARTIFACT_FILE_TYPE');
161
+ assert(files.size<maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');
162
+ if(stat.isSymbolicLink()){
163
+ const target=inside(root,fs.realpathSync(file)),link=portable(path.relative(path.dirname(file),target));assert(Buffer.byteLength(link)<=workerArtifactLimits.maximumPathBytes,'WORKER_ARTIFACT_PATH_LIMIT');links.set(relative,target);files.set(relative,{path:relative,bytes:0,sha256:digest(link),link});return;
164
+ }
165
+ assert(stat.size<=maximumBytes-bytes,'WORKER_ARTIFACT_BYTE_LIMIT');
166
+ let body=fs.readFileSync(file);assert.equal(body.length,stat.size,'WORKER_ARTIFACT_SOURCE_CHANGED');
167
+ if(path.basename(file)==='package.json')assert(!['react','react-dom','next','@xlinklight/workbench'].includes(JSON.parse(body).name),'WORKER_ARTIFACT_UI_DEPENDENCY');
168
+ if(relative==='package.json'){
169
+ const source=JSON.parse(body),metadata={private:true};
170
+ for(const key of ['name','version','type','exports','imports'])if(Object.hasOwn(source,key))metadata[key]=source[key];
171
+ body=Buffer.from(JSON.stringify(metadata)+'\n');
172
+ }
173
+ bytes+=body.length;assert(bytes<=maximumBytes,'WORKER_ARTIFACT_BYTE_LIMIT');
174
+ files.set(relative,{path:relative,bytes:body.length,sha256:digest(body),source:file,body});
175
+ };
176
+ const resolverLinks=new Set();
177
+ const traced=await trace([entry,...additionalEntries].map(file=>{assert(typeof file==='string'&&!path.isAbsolute(file),'WORKER_ARTIFACT_INPUT');return inside(root,path.resolve(root,file));}),{
178
+ base:root,processCwd:root,exportsOnly:true,ignore,
179
+ async readlink(file){
180
+ try{const target=await fs.promises.readlink(file);inside(root,file);inside(root,fs.realpathSync(file));assert(resolverLinks.size<maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');resolverLinks.add(file);return target;}
181
+ catch(error){if(['ENOENT','EINVAL','ENOTDIR'].includes(error.code))return null;throw error;}
182
+ },
183
+ });
184
+ assert.equal(traced.warnings.size,0,'WORKER_ARTIFACT_TRACE_WARNING: '+[...traced.warnings].map(error=>error.message).join('; '));
185
+ for(const file of [...traced.fileList,...resolverLinks].sort())add(file);
186
+ const walk=file=>{
187
+ file=inside(root,path.resolve(root,file));inside(root,fs.realpathSync(file));
188
+ assert(!fs.lstatSync(file).isSymbolicLink(),'WORKER_ARTIFACT_BOUNDARY');
189
+ if(fs.statSync(file).isDirectory())for(const name of fs.readdirSync(file).sort())walk(path.join(file,name));else add(file);
190
+ };
191
+ for(const resource of resources)walk(resource);
192
+ add('package.json');assert(files.has(portable(entry)),'WORKER_ARTIFACT_ENTRY_MISSING');
193
+ for(const [alias,target]of links){
194
+ const selected=portable(path.relative(root,target));assert([...files.keys()].some(file=>file===selected||file.startsWith(selected+'/')),'WORKER_ARTIFACT_LINK_TARGET_MISSING: '+alias);
195
+ }
196
+ const manifest={schemaVersion:1,status:'WORKER_ARTIFACT_PREPARED',entry:portable(entry),files:[...files.values()].map(record=>({path:record.path,bytes:record.bytes,sha256:record.sha256,...(record.link?{link:record.link}:{})})),payloadBytes:bytes};
197
+ const receipt=Buffer.from(JSON.stringify(manifest,null,2)+'\n');assert(bytes+receipt.length<=maximumBytes,'WORKER_ARTIFACT_BYTE_LIMIT');
198
+ assert(files.size+1<=maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');
199
+ const entries=new Set([...files.keys(),'worker-artifact.json']);
200
+ for(const record of files.keys()){let parent=path.posix.dirname(record);while(parent!=='.'){entries.add(parent);assert(entries.size+1<=maximumFiles*workerArtifactLimits.entriesPerFile,'WORKER_ARTIFACT_ENTRY_LIMIT');parent=path.posix.dirname(parent);}}
201
+ const tracedAt=performance.now();
202
+ if(previous){assert.deepEqual(ownedOutput(root,destination,maximumBytes,maximumFiles),previous,'WORKER_ARTIFACT_REPLACEMENT');fs.rmSync(destination,{recursive:true});}
203
+ fs.mkdirSync(destination,{recursive:true});
204
+ for(const record of files.values())if(!record.link){
205
+ const target=path.join(destination,record.path);fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,record.body,{flag:'wx'});
206
+ }
207
+ for(const [alias,target]of links){
208
+ const filename=path.join(destination,alias),selected=path.join(destination,path.relative(root,target));
209
+ assert(fs.existsSync(selected),'WORKER_ARTIFACT_LINK_TARGET_MISSING');fs.mkdirSync(path.dirname(filename),{recursive:true});
210
+ fs.symlinkSync(path.relative(path.dirname(filename),selected),filename,fs.statSync(target).isDirectory()?'dir':'file');
211
+ }
212
+ fs.writeFileSync(path.join(destination,'worker-artifact.json'),receipt,{flag:'wx'});
213
+ return {...manifest,bytes:bytes+receipt.length,output:destination,timings:{traceMs:tracedAt-started,writeMs:performance.now()-tracedAt,totalMs:performance.now()-started}};
214
+ }