@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,170 +1,170 @@
1
- import {releaseJson} from './release-control.mjs';
2
- import {createHash} from 'node:crypto';
3
- import {rawStaticUiRoute as route,servedStaticUiRoute as servedRoute} from './static-ui-routes.mjs';
4
- import {createCloudflareProviderHttp} from './cloudflare-provider-http.mjs';
5
-
6
- const sha=value=>createHash('sha256').update(value).digest('hex');
7
- const exact=(value,keys)=>value!==null&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).sort().join(',')===[...keys].sort().join(',');
8
- const fail=(code,cause)=>Error('ARTIFACT_PAGES_'+code,cause===undefined?undefined:{cause});
9
- const deploymentIdPattern=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
10
- function publicationIdentity(value){
11
- if(exact(value,['manifestSha256'])&&/^[a-f0-9]{64}$/.test(value.manifestSha256))return value.manifestSha256;
12
- if(exact(value,['publicationId'])&&typeof value.publicationId==='string'&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value.publicationId))return value.publicationId;
13
- throw fail('INPUT_INVALID');
14
- }
15
-
16
- /** Static asset discovery uses the provider's immutable deployment identity;
17
- * neither mutable domains nor a Git integration select a release. */
18
- export function createStaticPagesClient({accountId,projectName,token,signal,request=fetch}){
19
- if(typeof accountId!=='string'||!/^[a-f0-9]{32}$/.test(accountId)||typeof projectName!=='string'||!/^[a-z0-9][-a-z0-9]{2,62}$/.test(projectName)||typeof token!=='string'||!/^[-A-Za-z0-9_]{20,4096}$/.test(token))throw Error('ARTIFACT_PAGES_INPUT_INVALID');
20
- const base='https://api.cloudflare.com/client/v4/accounts/'+accountId+'/pages/projects/'+projectName;
21
- async function api(suffix='',allowMissing=false){
22
- const response=await releaseJson(base+suffix,{headers:{authorization:'Bearer '+token,accept:'application/json'}},{signal,request,maximumBytes:1048576});
23
- if([402,429].includes(response.status))throw Error('ARTIFACT_QUOTA_PAUSED');
24
- if(allowMissing&&response.status===404)return undefined;
25
- if(response.status!==200||response.value?.success!==true)throw Error('ARTIFACT_PAGES_OBSERVATION_UNKNOWN');
26
- return response.value;
27
- }
28
- async function project(){
29
- const value=(await api()).result;
30
- if(value?.name!==projectName||value.source||typeof value.production_branch!=='string'||!value.production_branch)throw Error('ARTIFACT_PAGES_DIRECT_UPLOAD_REQUIRED');
31
- return {name:projectName,productionBranch:value.production_branch,subdomain:value.subdomain};
32
- }
33
- function identity(value,publicationId){
34
- if(value?.project_name!==projectName||value.environment!=='production'||value.uses_functions!==false||value.is_skipped!==false||typeof value.id!=='string'||!deploymentIdPattern.test(value.id)||value.short_id!==value.id.slice(0,8)||value.deployment_trigger?.metadata?.commit_hash!==publicationId||value.deployment_trigger.metadata.commit_dirty!==false)throw Error('ARTIFACT_PAGES_DEPLOYMENT_MISMATCH');
35
- const stage=value.latest_stage,state=stage?.name==='deploy'&&stage.status==='success'?'succeeded':['failure','canceled'].includes(stage?.status)?'failed':['queued','initialize','deploy'].includes(stage?.name)&&['idle','active','success'].includes(stage.status)?'pending':undefined;
36
- if(!state)throw fail('DEPLOYMENT_MISMATCH');
37
- let selected;try{selected=new URL(value.url);}catch{throw Error('ARTIFACT_PAGES_DEPLOYMENT_MISMATCH');}
38
- if(selected.protocol!=='https:'||selected.hostname!==value.short_id+'.'+projectName+'.pages.dev'||selected.pathname!=='/'||selected.search||selected.hash||selected.port||selected.username||selected.password)throw Error('ARTIFACT_PAGES_DEPLOYMENT_MISMATCH');
39
- return {id:value.id,origin:selected.origin,publicationId,state};
40
- }
41
- async function getDeployment(reference,input){
42
- if(typeof reference!=='string'||!deploymentIdPattern.test(reference))throw fail('INPUT_INVALID');
43
- const publicationId=publicationIdentity(input),reply=await api('/deployments/'+reference,true);
44
- if(!reply)return undefined;
45
- if(reply.result?.id!==reference)throw fail('DEPLOYMENT_MISMATCH');
46
- return identity(reply.result,publicationId);
47
- }
48
- async function findPublication(input){
49
- const publicationId=publicationIdentity(input);
50
- const values=[],ids=new Set();let total,pages;
51
- for(let page=1;page<=5;page++){
52
- const response=await api('/deployments?env=production&page='+page+'&per_page=25'),rows=response.result,info=response.result_info;
53
- if(!Array.isArray(rows)||rows.length>25||!info||info.page!==page||info.per_page!==25||info.count!==rows.length||!Number.isSafeInteger(info.total_count)||info.total_count<0||info.total_count>125||!Number.isSafeInteger(info.total_pages)||info.total_pages<0||info.total_pages>5||info.total_pages!==Math.ceil(info.total_count/25)&&!(info.total_count===0&&info.total_pages===1))throw Error('ARTIFACT_PAGES_INVENTORY_INCOMPLETE');
54
- total??=info.total_count;pages??=info.total_pages;if(total!==info.total_count||pages!==info.total_pages)throw Error('ARTIFACT_PAGES_INVENTORY_INCOMPLETE');
55
- for(const row of rows){if(typeof row?.id!=='string'||ids.has(row.id))throw Error('ARTIFACT_PAGES_INVENTORY_INCOMPLETE');ids.add(row.id);values.push(row);}
56
- if(page>=pages){if(values.length!==total)throw Error('ARTIFACT_PAGES_INVENTORY_INCOMPLETE');break;}
57
- }
58
- const matches=values.filter(value=>value?.deployment_trigger?.metadata?.commit_hash===publicationId);
59
- if(matches.length>1)throw Error('ARTIFACT_PAGES_DEPLOYMENT_AMBIGUOUS');
60
- return matches.length?identity(matches[0],publicationId):undefined;
61
- }
62
- return Object.freeze({project,findPublication,getDeployment});
63
- }
64
-
65
- const defaults=Object.freeze({maximumFiles:1000,maximumFileBytes:8388608,maximumTotalBytes:33554432,maximumBatchBytes:8388608,maximumResponseBytes:1048576,maximumHeaderBytes:196608,requestMs:30000});
66
- function checkedLimits(input){
67
- const limits={...defaults,...input};
68
- if(!exact(limits,Object.keys(defaults))||Object.values(limits).some(value=>!Number.isSafeInteger(value)||value<1)||limits.maximumFiles>10000||limits.maximumFileBytes>16*1024**2||limits.maximumTotalBytes>134217728||limits.maximumBatchBytes>16*1024**2||limits.maximumFileBytes>limits.maximumBatchBytes||limits.maximumResponseBytes>2097152||limits.maximumHeaderBytes>262144||limits.requestMs>60000)throw fail('LIMIT_INVALID');return Object.freeze(limits);
69
- }
70
- function assetPath(value){
71
- if(typeof value!=='string'||value.length>1024||/[\\:\0-\x1f\x7f?#%*]/.test(value)||value.split('/').some(part=>!part||part==='.'||part==='..'||part.startsWith('.')))throw fail('ASSET_PATH_INVALID');
72
- if(['_headers','_redirects','_routes.json','_worker.js','functions','wrangler.toml','wrangler.json','wrangler.jsonc'].includes(value.split('/')[0]))throw fail('ASSET_PATH_INVALID');return value;
73
- }
74
- function headerDocument(files,maximumBytes){
75
- const counts=new Map(),groups=new Map(),routes=new Map();
76
- for(const file of files){
77
- const entries=Object.entries(file.responseHeaders).sort(([a],[b])=>a<b?-1:a>b?1:0);
78
- if(!entries.length||entries.some(([key,value])=>!/^[-a-z0-9]+$/.test(key)||typeof value!=='string'||/[\0-\x1f\x7f]/.test(value)))throw fail('HEADERS_INVALID');
79
- const key=JSON.stringify(entries);groups.set(key,entries);counts.set(key,(counts.get(key)??0)+1);
80
- for(const pathname of new Set([route(file.path),servedRoute(file.path)])){if(routes.has(pathname)&&routes.get(pathname).owner!==file.path)throw fail('ASSET_ROUTE_AMBIGUOUS');routes.set(pathname,{owner:file.path,key});}
81
- }
82
- const baseline=[...counts.keys()].sort((a,b)=>counts.get(b)-counts.get(a)||(a<b?-1:a>b?1:0))[0],base=groups.get(baseline),blocks=['/*\n'+base.map(([key,value])=>' '+key+': '+value).join('\n')];
83
- for(const [pathname,{key}]of [...routes].sort(([a],[b])=>a<b?-1:a>b?1:0))if(key!==baseline)blocks.push(pathname+'\n'+base.map(([name])=>' ! '+name).join('\n')+'\n'+groups.get(key).map(([name,value])=>' '+name+': '+value).join('\n'));
84
- const body=blocks.join('\n\n')+'\n';
85
- // Public Pages limits: 100 rules, 2,000 characters per line. Byte bounds are
86
- // conservative for Unicode and keep this generated control file finite.
87
- if(blocks.length>100||body.split('\n').some(line=>Buffer.byteLength(line)>2000)||Buffer.byteLength(body)>maximumBytes)throw fail('HEADERS_LIMIT');return body;
88
- }
89
-
90
- /** Host-selected Cloudflare Pages adapter. Factory and result extraction are
91
- * synchronous; optional provider SDKs and every request start only in transport
92
- * execute/observe. No source, Git process, local credential file or UI tree. */
93
- export function createStaticPagesPublishingStage({accountId,projectName,credentialId,token,name='static-ui',limits:inputLimits,createHttpTransport,apiOrigin='https://api.cloudflare.com',allowLoopback=false,apiVersion='2026-11-01'}={}){
94
- createStaticPagesClient({accountId,projectName,token});
95
- let origin;try{origin=new URL(apiOrigin);}catch{throw fail('INPUT_INVALID');}
96
- if(typeof name!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name)||typeof credentialId!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(credentialId)||!/^\d{4}-\d{2}-\d{2}$/.test(apiVersion)||typeof createHttpTransport!=='function'||origin.origin!==apiOrigin||!(apiOrigin==='https://api.cloudflare.com'||allowLoopback===true&&origin.protocol==='http:'&&['127.0.0.1','[::1]'].includes(origin.hostname)))throw fail('INPUT_INVALID');
97
- const limits=checkedLimits(inputLimits),target=Object.freeze({provider:'cloudflare-pages',namespace:accountId+':'+projectName,endpoint:apiOrigin});
98
- // Egress routes and their rotating authentication do not change the fixed
99
- // provider target or publication identity. They remain explicit I/O policy.
100
- const configurationSha256=sha(JSON.stringify({schemaVersion:1,target,sdk:'cloudflare@7.3.0',http:'host-owned-fetch-v1',assetKey:'blake3-base64-extension-128-v1',hasher:'@noble/hashes@2.4.0',credentialId,limits,apiVersion,maxRetries:0}));
101
- return Object.freeze({name,capability:'deployment-create',configurationSha256,createDeployment(input){
102
- if(typeof input?.assertAuthorized!=='function'||!input.signal||!input.intent?.requestId||!/^[a-f0-9]{64}$/.test(input.intent?.package?.content?.manifestSha256))throw fail('INPUT_INVALID');
103
- const intent=structuredClone(input.intent),publicationId=intent.package.content.manifestSha256,entry=assetPath(input.prepared?.descriptor?.ui?.entry?.slice(3)),controller=new AbortController(),pending=new Set();let closed=false,executed=false,acceptedReference,observed,closePromise;
104
- const http=createCloudflareProviderHttp({createHttpTransport,signal:AbortSignal.any([input.signal,controller.signal]),assertAuthorized:input.assertAuthorized,apiOrigin,maximumResponseBytes:limits.maximumResponseBytes,requestMs:limits.requestMs,allowPath:value=>value.startsWith('/client/v4/')});
105
- const checkBinding=binding=>{if(binding?.requestId!==intent.requestId+'.'+name||binding.capability!=='deployment-create'||binding.configurationSha256!==configurationSha256||binding.content?.manifestSha256!==publicationId||JSON.stringify(binding.target)!==JSON.stringify(target)||!/^[a-f0-9]{64}$/.test(binding.fingerprint??''))throw fail('BINDING_INVALID');};
106
- const run=(context,work)=>{
107
- if(closed)throw fail('TRANSPORT_CLOSED');const signal=AbortSignal.any([input.signal,controller.signal,context.signal].filter(Boolean));signal.throwIfAborted();
108
- const promise=Promise.resolve().then(()=>work(signal)).catch(error=>{throw fail('OPERATION_UNKNOWN',error);});pending.add(promise);const finish=()=>pending.delete(promise);promise.then(finish,finish);return promise;
109
- };
110
- const fetchBounded=(address,options={})=>{
111
- const url=new URL(address);if(url.origin!=='https://api.cloudflare.com'||url.username||url.password||url.hash)throw fail('TARGET_INVALID');
112
- return http.fetch(apiOrigin+url.pathname+url.search,options);
113
- };
114
- const client=signal=>createStaticPagesClient({accountId,projectName,token,request:fetchBounded,signal});
115
- const observe=async(binding,reference,context)=>{
116
- checkBinding(binding);observed=undefined;
117
- return run(context,async signal=>{
118
- // Give provider observation a fresh alarm and transport after an acknowledged upload.
119
- if(reference!==undefined&&reference===acceptedReference)return {state:'pending',reference,fingerprint:binding.fingerprint};
120
- const pages=client(signal);await pages.project();const publication={manifestSha256:publicationId};
121
- const found=reference===undefined?await pages.findPublication(publication):await pages.getDeployment(reference,publication);
122
- // The provider can acknowledge a write before its read endpoint sees the deployment.
123
- if(!found&&reference!==undefined)return {state:'pending',reference,fingerprint:binding.fingerprint};
124
- if(found?.state==='succeeded')observed=Object.freeze({schemaVersion:1,provider:'cloudflare-pages',accountId,projectName,publicationId,deploymentId:found.id,origin:found.origin,baseUrl:found.origin+'/',entryPath:servedRoute(entry),uiUrl:found.origin+servedRoute(entry),content:Object.freeze({manifestSha256:publicationId}),fingerprint:binding.fingerprint});
125
- return {state:found?.state??'absent',fingerprint:binding.fingerprint,...(found?{reference:found.id}:{})};
126
- });
127
- };
128
- return {transport:{target,capability:'deployment-create',configurationSha256,
129
- async execute(binding,context){
130
- checkBinding(binding);if(executed)throw fail('RECOVERY_REQUIRED');executed=true;
131
- return run(context,async signal=>{
132
- await input.assertAuthorized();const pages=client(signal),project=await pages.project(),existing=await pages.findPublication({manifestSha256:publicationId});if(existing){acceptedReference=existing.id;return {state:'accepted',reference:acceptedReference};}
133
- const [{default:Cloudflare},{blake3},{VERSION}]=await Promise.all([import('cloudflare'),import('@noble/hashes/blake3.js'),import('cloudflare/version')]);
134
- if(VERSION!=='7.3.0')throw fail('SDK_VERSION_INVALID');
135
- const prepared=input.prepared;
136
- if(prepared.descriptor.ui.entry!=='ui/'+entry||typeof prepared.readFile!=='function')throw fail('ASSET_PATH_INVALID');const files=[];let total=0;
137
- for(const file of prepared.manifest.files){if(file.role!=='asset')continue;if(!file.path.startsWith('ui/'))throw fail('ASSET_PATH_INVALID');const selected=assetPath(file.path.slice(3));total+=file.byteLength;if(!Number.isSafeInteger(file.byteLength)||file.byteLength<0||file.byteLength>limits.maximumFileBytes||total>limits.maximumTotalBytes||files.length>=limits.maximumFiles)throw fail('ASSET_LIMIT');files.push({path:selected,sourcePath:file.path,sha256:file.sha256,responseHeaders:file.responseHeaders});}
138
- if(!files.length||!files.some(file=>file.path===entry))throw fail('ASSET_PATH_INVALID');const headers=headerDocument(files,limits.maximumHeaderBytes),options={maxRetries:0,timeout:limits.requestMs,signal};
139
- const makeSdk=apiToken=>new Cloudflare({apiToken,apiKey:null,apiEmail:null,userServiceKey:null,baseURL:'https://api.cloudflare.com/client/v4',apiVersion,logLevel:'off',maxRetries:0,timeout:limits.requestMs,fetch:fetchBounded});
140
- const sdk=makeSdk(token),authorization=await sdk.pages.projects.getUploadToken(projectName,{account_id:accountId},options);
141
- if(typeof authorization.jwt!=='string'||authorization.jwt.length<16||authorization.jwt.length>8192)throw fail('UPLOAD_TOKEN_INVALID');const assets=makeSdk(authorization.jwt),manifest={},keys=new Map();let batch=[],batchBytes=0;
142
- const upload=async()=>{if(!batch.length)return;const result=await assets.pages.assets.upload({body:batch},options);if(result.success!==true)throw fail('UPLOAD_UNKNOWN');batch=[];batchBytes=0;};
143
- for(const file of files){
144
- const bytes=await prepared.readFile(file.sourcePath,{maximumBytes:limits.maximumFileBytes,signal}),value=Buffer.from(bytes).toString('base64'),basename=file.path.split('/').at(-1),extension=basename.includes('.')&&basename.lastIndexOf('.')>0?basename.slice(basename.lastIndexOf('.')+1):'',key=Buffer.from(blake3(Buffer.from(value+extension))).toString('hex').slice(0,32),contentType=file.responseHeaders['content-type'];
145
- if(typeof contentType!=='string'||!contentType)throw fail('HEADERS_INVALID');manifest['/'+file.path]=key;
146
- if(keys.has(key)){const previous=keys.get(key);if(previous.sha256!==file.sha256||previous.contentType!==contentType)throw fail('ASSET_KEY_CONFLICT');continue;}
147
- const item={key,value,base64:true,metadata:{contentType}},itemBytes=Buffer.byteLength(JSON.stringify(item));keys.set(key,{sha256:file.sha256,contentType});
148
- if(itemBytes>Math.ceil(limits.maximumBatchBytes*4/3)+4096)throw fail('ASSET_LIMIT');if(batchBytes+itemBytes>Math.ceil(limits.maximumBatchBytes*4/3)+4096)await upload();batch.push(item);batchBytes+=itemBytes;
149
- }
150
- await upload();
151
- const upsert=await assets.pages.assets.upsertHashes({hashes:[...keys.keys()]},options);if(upsert.success!==true)throw fail('UPLOAD_UNKNOWN');await input.assertAuthorized();
152
- // This field is a provider publication binding, not claimed Git provenance.
153
- const deployment=await sdk.pages.projects.deployments.create(projectName,{account_id:accountId,branch:project.productionBranch,commit_hash:publicationId,commit_dirty:'false',commit_message:'Link Light content publication '+publicationId,manifest:JSON.stringify(manifest),_headers:new File([headers],'_headers',{type:'text/plain'})},options);
154
- if(typeof deployment.id!=='string'||!deploymentIdPattern.test(deployment.id))throw fail('DEPLOYMENT_MISMATCH');acceptedReference=deployment.id;return {state:'accepted',reference:acceptedReference};
155
- });
156
- },observe,
157
- async close({timeoutMilliseconds}){
158
- if(!Number.isSafeInteger(timeoutMilliseconds)||timeoutMilliseconds<1||timeoutMilliseconds>300000)throw fail('LIMIT_INVALID');closed=true;controller.abort();
159
- closePromise??=(async()=>{
160
- // Foundation owns dispatcher/request/body teardown. Its promise must
161
- // actually resolve; the outer operation owns the close deadline.
162
- const receipt=await http.close();await Promise.allSettled([...pending]);
163
- const activeRequests=pending.size+receipt.activeRequests;return {status:activeRequests||receipt.status!=='closed'?'unconfirmed':'closed',activeRequests};
164
- })();return closePromise;
165
- },
166
- },readResult({record}){
167
- if(!observed||record?.binding?.fingerprint!==observed.fingerprint||record.observation!=='succeeded'||record.reference!==observed.deploymentId)throw fail('RESULT_NOT_OBSERVED');checkBinding(record.binding);const receipt={...observed};delete receipt.fingerprint;return Object.freeze(receipt);
168
- }};
169
- }});
170
- }
1
+ import {releaseJson} from './release-control.mjs';
2
+ import {createHash} from 'node:crypto';
3
+ import {rawStaticUiRoute as route,servedStaticUiRoute as servedRoute} from './static-ui-routes.mjs';
4
+ import {createCloudflareProviderHttp} from './cloudflare-provider-http.mjs';
5
+
6
+ const sha=value=>createHash('sha256').update(value).digest('hex');
7
+ const exact=(value,keys)=>value!==null&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).sort().join(',')===[...keys].sort().join(',');
8
+ const fail=(code,cause)=>Error('ARTIFACT_PAGES_'+code,cause===undefined?undefined:{cause});
9
+ const deploymentIdPattern=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
10
+ function publicationIdentity(value){
11
+ if(exact(value,['manifestSha256'])&&/^[a-f0-9]{64}$/.test(value.manifestSha256))return value.manifestSha256;
12
+ if(exact(value,['publicationId'])&&typeof value.publicationId==='string'&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value.publicationId))return value.publicationId;
13
+ throw fail('INPUT_INVALID');
14
+ }
15
+
16
+ /** Static asset discovery uses the provider's immutable deployment identity;
17
+ * neither mutable domains nor a Git integration select a release. */
18
+ export function createStaticPagesClient({accountId,projectName,token,signal,request=fetch}){
19
+ if(typeof accountId!=='string'||!/^[a-f0-9]{32}$/.test(accountId)||typeof projectName!=='string'||!/^[a-z0-9][-a-z0-9]{2,62}$/.test(projectName)||typeof token!=='string'||!/^[-A-Za-z0-9_]{20,4096}$/.test(token))throw Error('ARTIFACT_PAGES_INPUT_INVALID');
20
+ const base='https://api.cloudflare.com/client/v4/accounts/'+accountId+'/pages/projects/'+projectName;
21
+ async function api(suffix='',allowMissing=false){
22
+ const response=await releaseJson(base+suffix,{headers:{authorization:'Bearer '+token,accept:'application/json'}},{signal,request,maximumBytes:1048576});
23
+ if([402,429].includes(response.status))throw Error('ARTIFACT_QUOTA_PAUSED');
24
+ if(allowMissing&&response.status===404)return undefined;
25
+ if(response.status!==200||response.value?.success!==true)throw Error('ARTIFACT_PAGES_OBSERVATION_UNKNOWN');
26
+ return response.value;
27
+ }
28
+ async function project(){
29
+ const value=(await api()).result;
30
+ if(value?.name!==projectName||value.source||typeof value.production_branch!=='string'||!value.production_branch)throw Error('ARTIFACT_PAGES_DIRECT_UPLOAD_REQUIRED');
31
+ return {name:projectName,productionBranch:value.production_branch,subdomain:value.subdomain};
32
+ }
33
+ function identity(value,publicationId){
34
+ if(value?.project_name!==projectName||value.environment!=='production'||value.uses_functions!==false||value.is_skipped!==false||typeof value.id!=='string'||!deploymentIdPattern.test(value.id)||value.short_id!==value.id.slice(0,8)||value.deployment_trigger?.metadata?.commit_hash!==publicationId||value.deployment_trigger.metadata.commit_dirty!==false)throw Error('ARTIFACT_PAGES_DEPLOYMENT_MISMATCH');
35
+ const stage=value.latest_stage,state=stage?.name==='deploy'&&stage.status==='success'?'succeeded':['failure','canceled'].includes(stage?.status)?'failed':['queued','initialize','deploy'].includes(stage?.name)&&['idle','active','success'].includes(stage.status)?'pending':undefined;
36
+ if(!state)throw fail('DEPLOYMENT_MISMATCH');
37
+ let selected;try{selected=new URL(value.url);}catch{throw Error('ARTIFACT_PAGES_DEPLOYMENT_MISMATCH');}
38
+ if(selected.protocol!=='https:'||selected.hostname!==value.short_id+'.'+projectName+'.pages.dev'||selected.pathname!=='/'||selected.search||selected.hash||selected.port||selected.username||selected.password)throw Error('ARTIFACT_PAGES_DEPLOYMENT_MISMATCH');
39
+ return {id:value.id,origin:selected.origin,publicationId,state};
40
+ }
41
+ async function getDeployment(reference,input){
42
+ if(typeof reference!=='string'||!deploymentIdPattern.test(reference))throw fail('INPUT_INVALID');
43
+ const publicationId=publicationIdentity(input),reply=await api('/deployments/'+reference,true);
44
+ if(!reply)return undefined;
45
+ if(reply.result?.id!==reference)throw fail('DEPLOYMENT_MISMATCH');
46
+ return identity(reply.result,publicationId);
47
+ }
48
+ async function findPublication(input){
49
+ const publicationId=publicationIdentity(input);
50
+ const values=[],ids=new Set();let total,pages;
51
+ for(let page=1;page<=5;page++){
52
+ const response=await api('/deployments?env=production&page='+page+'&per_page=25'),rows=response.result,info=response.result_info;
53
+ if(!Array.isArray(rows)||rows.length>25||!info||info.page!==page||info.per_page!==25||info.count!==rows.length||!Number.isSafeInteger(info.total_count)||info.total_count<0||info.total_count>125||!Number.isSafeInteger(info.total_pages)||info.total_pages<0||info.total_pages>5||info.total_pages!==Math.ceil(info.total_count/25)&&!(info.total_count===0&&info.total_pages===1))throw Error('ARTIFACT_PAGES_INVENTORY_INCOMPLETE');
54
+ total??=info.total_count;pages??=info.total_pages;if(total!==info.total_count||pages!==info.total_pages)throw Error('ARTIFACT_PAGES_INVENTORY_INCOMPLETE');
55
+ for(const row of rows){if(typeof row?.id!=='string'||ids.has(row.id))throw Error('ARTIFACT_PAGES_INVENTORY_INCOMPLETE');ids.add(row.id);values.push(row);}
56
+ if(page>=pages){if(values.length!==total)throw Error('ARTIFACT_PAGES_INVENTORY_INCOMPLETE');break;}
57
+ }
58
+ const matches=values.filter(value=>value?.deployment_trigger?.metadata?.commit_hash===publicationId);
59
+ if(matches.length>1)throw Error('ARTIFACT_PAGES_DEPLOYMENT_AMBIGUOUS');
60
+ return matches.length?identity(matches[0],publicationId):undefined;
61
+ }
62
+ return Object.freeze({project,findPublication,getDeployment});
63
+ }
64
+
65
+ const defaults=Object.freeze({maximumFiles:1000,maximumFileBytes:8388608,maximumTotalBytes:33554432,maximumBatchBytes:8388608,maximumResponseBytes:1048576,maximumHeaderBytes:196608,requestMs:30000});
66
+ function checkedLimits(input){
67
+ const limits={...defaults,...input};
68
+ if(!exact(limits,Object.keys(defaults))||Object.values(limits).some(value=>!Number.isSafeInteger(value)||value<1)||limits.maximumFiles>10000||limits.maximumFileBytes>16*1024**2||limits.maximumTotalBytes>134217728||limits.maximumBatchBytes>16*1024**2||limits.maximumFileBytes>limits.maximumBatchBytes||limits.maximumResponseBytes>2097152||limits.maximumHeaderBytes>262144||limits.requestMs>60000)throw fail('LIMIT_INVALID');return Object.freeze(limits);
69
+ }
70
+ function assetPath(value){
71
+ if(typeof value!=='string'||value.length>1024||/[\\:\0-\x1f\x7f?#%*]/.test(value)||value.split('/').some(part=>!part||part==='.'||part==='..'||part.startsWith('.')))throw fail('ASSET_PATH_INVALID');
72
+ if(['_headers','_redirects','_routes.json','_worker.js','functions','wrangler.toml','wrangler.json','wrangler.jsonc'].includes(value.split('/')[0]))throw fail('ASSET_PATH_INVALID');return value;
73
+ }
74
+ function headerDocument(files,maximumBytes){
75
+ const counts=new Map(),groups=new Map(),routes=new Map();
76
+ for(const file of files){
77
+ const entries=Object.entries(file.responseHeaders).sort(([a],[b])=>a<b?-1:a>b?1:0);
78
+ if(!entries.length||entries.some(([key,value])=>!/^[-a-z0-9]+$/.test(key)||typeof value!=='string'||/[\0-\x1f\x7f]/.test(value)))throw fail('HEADERS_INVALID');
79
+ const key=JSON.stringify(entries);groups.set(key,entries);counts.set(key,(counts.get(key)??0)+1);
80
+ for(const pathname of new Set([route(file.path),servedRoute(file.path)])){if(routes.has(pathname)&&routes.get(pathname).owner!==file.path)throw fail('ASSET_ROUTE_AMBIGUOUS');routes.set(pathname,{owner:file.path,key});}
81
+ }
82
+ const baseline=[...counts.keys()].sort((a,b)=>counts.get(b)-counts.get(a)||(a<b?-1:a>b?1:0))[0],base=groups.get(baseline),blocks=['/*\n'+base.map(([key,value])=>' '+key+': '+value).join('\n')];
83
+ for(const [pathname,{key}]of [...routes].sort(([a],[b])=>a<b?-1:a>b?1:0))if(key!==baseline)blocks.push(pathname+'\n'+base.map(([name])=>' ! '+name).join('\n')+'\n'+groups.get(key).map(([name,value])=>' '+name+': '+value).join('\n'));
84
+ const body=blocks.join('\n\n')+'\n';
85
+ // Public Pages limits: 100 rules, 2,000 characters per line. Byte bounds are
86
+ // conservative for Unicode and keep this generated control file finite.
87
+ if(blocks.length>100||body.split('\n').some(line=>Buffer.byteLength(line)>2000)||Buffer.byteLength(body)>maximumBytes)throw fail('HEADERS_LIMIT');return body;
88
+ }
89
+
90
+ /** Host-selected Cloudflare Pages adapter. Factory and result extraction are
91
+ * synchronous; optional provider SDKs and every request start only in transport
92
+ * execute/observe. No source, Git process, local credential file or UI tree. */
93
+ export function createStaticPagesPublishingStage({accountId,projectName,credentialId,token,name='static-ui',limits:inputLimits,createHttpTransport,apiOrigin='https://api.cloudflare.com',allowLoopback=false,apiVersion='2026-11-01'}={}){
94
+ createStaticPagesClient({accountId,projectName,token});
95
+ let origin;try{origin=new URL(apiOrigin);}catch{throw fail('INPUT_INVALID');}
96
+ if(typeof name!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name)||typeof credentialId!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(credentialId)||!/^\d{4}-\d{2}-\d{2}$/.test(apiVersion)||typeof createHttpTransport!=='function'||origin.origin!==apiOrigin||!(apiOrigin==='https://api.cloudflare.com'||allowLoopback===true&&origin.protocol==='http:'&&['127.0.0.1','[::1]'].includes(origin.hostname)))throw fail('INPUT_INVALID');
97
+ const limits=checkedLimits(inputLimits),target=Object.freeze({provider:'cloudflare-pages',namespace:accountId+':'+projectName,endpoint:apiOrigin});
98
+ // Egress routes and their rotating authentication do not change the fixed
99
+ // provider target or publication identity. They remain explicit I/O policy.
100
+ const configurationSha256=sha(JSON.stringify({schemaVersion:1,target,sdk:'cloudflare@7.3.0',http:'host-owned-fetch-v1',assetKey:'blake3-base64-extension-128-v1',hasher:'@noble/hashes@2.4.0',credentialId,limits,apiVersion,maxRetries:0}));
101
+ return Object.freeze({name,capability:'deployment-create',configurationSha256,createDeployment(input){
102
+ if(typeof input?.assertAuthorized!=='function'||!input.signal||!input.intent?.requestId||!/^[a-f0-9]{64}$/.test(input.intent?.package?.content?.manifestSha256))throw fail('INPUT_INVALID');
103
+ const intent=structuredClone(input.intent),publicationId=intent.package.content.manifestSha256,entry=assetPath(input.prepared?.descriptor?.ui?.entry?.slice(3)),controller=new AbortController(),pending=new Set();let closed=false,executed=false,acceptedReference,observed,closePromise;
104
+ const http=createCloudflareProviderHttp({createHttpTransport,signal:AbortSignal.any([input.signal,controller.signal]),assertAuthorized:input.assertAuthorized,apiOrigin,maximumResponseBytes:limits.maximumResponseBytes,requestMs:limits.requestMs,allowPath:value=>value.startsWith('/client/v4/')});
105
+ const checkBinding=binding=>{if(binding?.requestId!==intent.requestId+'.'+name||binding.capability!=='deployment-create'||binding.configurationSha256!==configurationSha256||binding.content?.manifestSha256!==publicationId||JSON.stringify(binding.target)!==JSON.stringify(target)||!/^[a-f0-9]{64}$/.test(binding.fingerprint??''))throw fail('BINDING_INVALID');};
106
+ const run=(context,work)=>{
107
+ if(closed)throw fail('TRANSPORT_CLOSED');const signal=AbortSignal.any([input.signal,controller.signal,context.signal].filter(Boolean));signal.throwIfAborted();
108
+ const promise=Promise.resolve().then(()=>work(signal)).catch(error=>{throw fail('OPERATION_UNKNOWN',error);});pending.add(promise);const finish=()=>pending.delete(promise);promise.then(finish,finish);return promise;
109
+ };
110
+ const fetchBounded=(address,options={})=>{
111
+ const url=new URL(address);if(url.origin!=='https://api.cloudflare.com'||url.username||url.password||url.hash)throw fail('TARGET_INVALID');
112
+ return http.fetch(apiOrigin+url.pathname+url.search,options);
113
+ };
114
+ const client=signal=>createStaticPagesClient({accountId,projectName,token,request:fetchBounded,signal});
115
+ const observe=async(binding,reference,context)=>{
116
+ checkBinding(binding);observed=undefined;
117
+ return run(context,async signal=>{
118
+ // Give provider observation a fresh alarm and transport after an acknowledged upload.
119
+ if(reference!==undefined&&reference===acceptedReference)return {state:'pending',reference,fingerprint:binding.fingerprint};
120
+ const pages=client(signal);await pages.project();const publication={manifestSha256:publicationId};
121
+ const found=reference===undefined?await pages.findPublication(publication):await pages.getDeployment(reference,publication);
122
+ // The provider can acknowledge a write before its read endpoint sees the deployment.
123
+ if(!found&&reference!==undefined)return {state:'pending',reference,fingerprint:binding.fingerprint};
124
+ if(found?.state==='succeeded')observed=Object.freeze({schemaVersion:1,provider:'cloudflare-pages',accountId,projectName,publicationId,deploymentId:found.id,origin:found.origin,baseUrl:found.origin+'/',entryPath:servedRoute(entry),uiUrl:found.origin+servedRoute(entry),content:Object.freeze({manifestSha256:publicationId}),fingerprint:binding.fingerprint});
125
+ return {state:found?.state??'absent',fingerprint:binding.fingerprint,...(found?{reference:found.id}:{})};
126
+ });
127
+ };
128
+ return {transport:{target,capability:'deployment-create',configurationSha256,
129
+ async execute(binding,context){
130
+ checkBinding(binding);if(executed)throw fail('RECOVERY_REQUIRED');executed=true;
131
+ return run(context,async signal=>{
132
+ await input.assertAuthorized();const pages=client(signal),project=await pages.project(),existing=await pages.findPublication({manifestSha256:publicationId});if(existing){acceptedReference=existing.id;return {state:'accepted',reference:acceptedReference};}
133
+ const [{default:Cloudflare},{blake3},{VERSION}]=await Promise.all([import('cloudflare'),import('@noble/hashes/blake3.js'),import('cloudflare/version')]);
134
+ if(VERSION!=='7.3.0')throw fail('SDK_VERSION_INVALID');
135
+ const prepared=input.prepared;
136
+ if(prepared.descriptor.ui.entry!=='ui/'+entry||typeof prepared.readFile!=='function')throw fail('ASSET_PATH_INVALID');const files=[];let total=0;
137
+ for(const file of prepared.manifest.files){if(file.role!=='asset')continue;if(!file.path.startsWith('ui/'))throw fail('ASSET_PATH_INVALID');const selected=assetPath(file.path.slice(3));total+=file.byteLength;if(!Number.isSafeInteger(file.byteLength)||file.byteLength<0||file.byteLength>limits.maximumFileBytes||total>limits.maximumTotalBytes||files.length>=limits.maximumFiles)throw fail('ASSET_LIMIT');files.push({path:selected,sourcePath:file.path,sha256:file.sha256,responseHeaders:file.responseHeaders});}
138
+ if(!files.length||!files.some(file=>file.path===entry))throw fail('ASSET_PATH_INVALID');const headers=headerDocument(files,limits.maximumHeaderBytes),options={maxRetries:0,timeout:limits.requestMs,signal};
139
+ const makeSdk=apiToken=>new Cloudflare({apiToken,apiKey:null,apiEmail:null,userServiceKey:null,baseURL:'https://api.cloudflare.com/client/v4',apiVersion,logLevel:'off',maxRetries:0,timeout:limits.requestMs,fetch:fetchBounded});
140
+ const sdk=makeSdk(token),authorization=await sdk.pages.projects.getUploadToken(projectName,{account_id:accountId},options);
141
+ if(typeof authorization.jwt!=='string'||authorization.jwt.length<16||authorization.jwt.length>8192)throw fail('UPLOAD_TOKEN_INVALID');const assets=makeSdk(authorization.jwt),manifest={},keys=new Map();let batch=[],batchBytes=0;
142
+ const upload=async()=>{if(!batch.length)return;const result=await assets.pages.assets.upload({body:batch},options);if(result.success!==true)throw fail('UPLOAD_UNKNOWN');batch=[];batchBytes=0;};
143
+ for(const file of files){
144
+ const bytes=await prepared.readFile(file.sourcePath,{maximumBytes:limits.maximumFileBytes,signal}),value=Buffer.from(bytes).toString('base64'),basename=file.path.split('/').at(-1),extension=basename.includes('.')&&basename.lastIndexOf('.')>0?basename.slice(basename.lastIndexOf('.')+1):'',key=Buffer.from(blake3(Buffer.from(value+extension))).toString('hex').slice(0,32),contentType=file.responseHeaders['content-type'];
145
+ if(typeof contentType!=='string'||!contentType)throw fail('HEADERS_INVALID');manifest['/'+file.path]=key;
146
+ if(keys.has(key)){const previous=keys.get(key);if(previous.sha256!==file.sha256||previous.contentType!==contentType)throw fail('ASSET_KEY_CONFLICT');continue;}
147
+ const item={key,value,base64:true,metadata:{contentType}},itemBytes=Buffer.byteLength(JSON.stringify(item));keys.set(key,{sha256:file.sha256,contentType});
148
+ if(itemBytes>Math.ceil(limits.maximumBatchBytes*4/3)+4096)throw fail('ASSET_LIMIT');if(batchBytes+itemBytes>Math.ceil(limits.maximumBatchBytes*4/3)+4096)await upload();batch.push(item);batchBytes+=itemBytes;
149
+ }
150
+ await upload();
151
+ const upsert=await assets.pages.assets.upsertHashes({hashes:[...keys.keys()]},options);if(upsert.success!==true)throw fail('UPLOAD_UNKNOWN');await input.assertAuthorized();
152
+ // This field is a provider publication binding, not claimed Git provenance.
153
+ const deployment=await sdk.pages.projects.deployments.create(projectName,{account_id:accountId,branch:project.productionBranch,commit_hash:publicationId,commit_dirty:'false',commit_message:'Link Light content publication '+publicationId,manifest:JSON.stringify(manifest),_headers:new File([headers],'_headers',{type:'text/plain'})},options);
154
+ if(typeof deployment.id!=='string'||!deploymentIdPattern.test(deployment.id))throw fail('DEPLOYMENT_MISMATCH');acceptedReference=deployment.id;return {state:'accepted',reference:acceptedReference};
155
+ });
156
+ },observe,
157
+ async close({timeoutMilliseconds}){
158
+ if(!Number.isSafeInteger(timeoutMilliseconds)||timeoutMilliseconds<1||timeoutMilliseconds>300000)throw fail('LIMIT_INVALID');closed=true;controller.abort();
159
+ closePromise??=(async()=>{
160
+ // Foundation owns dispatcher/request/body teardown. Its promise must
161
+ // actually resolve; the outer operation owns the close deadline.
162
+ const receipt=await http.close();await Promise.allSettled([...pending]);
163
+ const activeRequests=pending.size+receipt.activeRequests;return {status:activeRequests||receipt.status!=='closed'?'unconfirmed':'closed',activeRequests};
164
+ })();return closePromise;
165
+ },
166
+ },readResult({record}){
167
+ if(!observed||record?.binding?.fingerprint!==observed.fingerprint||record.observation!=='succeeded'||record.reference!==observed.deploymentId)throw fail('RESULT_NOT_OBSERVED');checkBinding(record.binding);const receipt={...observed};delete receipt.fingerprint;return Object.freeze(receipt);
168
+ }};
169
+ }});
170
+ }
@@ -1,32 +1,32 @@
1
- /** A bounded SDK bridge over the host's explicitly owned fetch provider.
2
- * It creates no dispatcher, reads no environment and never retries a request. */
3
- export function createCloudflareProviderHttp({createHttpTransport,signal,assertAuthorized,apiOrigin,maximumResponseBytes,requestMs,allowPath}){
4
- const controller=new AbortController(),pending=new Set();let ready,closed=false,closing,acquisitionFailed=false,underlyingActiveRequests=0;
5
- const fetch=async(address,options={})=>{
6
- if(closed)throw Error('CLOUDFLARE_TRANSPORT_CLOSED');
7
- // Workers rejects redirect: 'error' at construction. The host never
8
- // follows a redirect and this bridge rejects the returned 3xx response.
9
- const request=new Request(address,{...options,redirect:'manual'}),url=new URL(request.url);
10
- if(url.origin!==apiOrigin||url.username||url.password||url.hash||!allowPath(url.pathname))throw Error('CLOUDFLARE_TARGET_INVALID');
11
- const activeSignal=AbortSignal.any([signal,controller.signal,request.signal,AbortSignal.timeout(requestMs)].filter(Boolean));activeSignal.throwIfAborted();
12
- const work=(async()=>{
13
- await assertAuthorized();activeSignal.throwIfAborted();if(closed)throw Error('CLOUDFLARE_TRANSPORT_CLOSED');
14
- ready??=Promise.resolve().then(()=>createHttpTransport({signal:AbortSignal.any([signal,controller.signal].filter(Boolean))})).catch(error=>{acquisitionFailed=true;throw error;});
15
- const transport=await ready;if(!transport||typeof transport.fetch!=='function'||typeof transport.close!=='function'){acquisitionFailed=true;throw Error('CLOUDFLARE_TRANSPORT_INVALID');}
16
- const response=await transport.fetch(new Request(request,{signal:activeSignal,redirect:'manual',credentials:'omit',cache:'no-store'}));
17
- if(response.status>=300&&response.status<400){await response.body?.cancel();throw Error('CLOUDFLARE_REDIRECT_REFUSED');}
18
- const chunks=[];let count=0,reader,primary;
19
- try{
20
- const length=response.headers.get('content-length');if(length!==null&&(!/^\d+$/.test(length)||Number(length)>maximumResponseBytes))throw Error('CLOUDFLARE_RESPONSE_LIMIT');
21
- if(response.body){reader=response.body.getReader();for(;;){activeSignal.throwIfAborted();const item=await reader.read();if(item.done)break;count+=item.value.byteLength;if(count>maximumResponseBytes)throw Error('CLOUDFLARE_RESPONSE_LIMIT');chunks.push(item.value);}}
22
- }catch(error){primary=error;}finally{try{if(reader){await reader.cancel();reader.releaseLock();}else await response.body?.cancel();}catch(error){primary??=error;}}
23
- if(primary)throw primary;await assertAuthorized();activeSignal.throwIfAborted();const bytes=new Uint8Array(count);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength;}
24
- return new Response(count?bytes:null,{status:response.status,headers:response.headers});
25
- })();pending.add(work);const done=()=>pending.delete(work);work.then(done,done);return work;
26
- };
27
- const close=()=>closing??=(async()=>{
28
- closed=true;controller.abort();const transport=await ready?.catch(()=>undefined);if(transport){const receipt=await transport.close();if(receipt!==undefined&&(receipt?.status!=='closed'||receipt.activeRequests!==0)){acquisitionFailed=true;if(Number.isSafeInteger(receipt?.activeRequests)&&receipt.activeRequests>0)underlyingActiveRequests=receipt.activeRequests;}}await Promise.allSettled([...pending]);
29
- return {status:acquisitionFailed||pending.size?'unconfirmed':'closed',activeRequests:pending.size+underlyingActiveRequests};
30
- })();
31
- return Object.freeze({fetch,close});
32
- }
1
+ /** A bounded SDK bridge over the host's explicitly owned fetch provider.
2
+ * It creates no dispatcher, reads no environment and never retries a request. */
3
+ export function createCloudflareProviderHttp({createHttpTransport,signal,assertAuthorized,apiOrigin,maximumResponseBytes,requestMs,allowPath}){
4
+ const controller=new AbortController(),pending=new Set();let ready,closed=false,closing,acquisitionFailed=false,underlyingActiveRequests=0;
5
+ const fetch=async(address,options={})=>{
6
+ if(closed)throw Error('CLOUDFLARE_TRANSPORT_CLOSED');
7
+ // Workers rejects redirect: 'error' at construction. The host never
8
+ // follows a redirect and this bridge rejects the returned 3xx response.
9
+ const request=new Request(address,{...options,redirect:'manual'}),url=new URL(request.url);
10
+ if(url.origin!==apiOrigin||url.username||url.password||url.hash||!allowPath(url.pathname))throw Error('CLOUDFLARE_TARGET_INVALID');
11
+ const activeSignal=AbortSignal.any([signal,controller.signal,request.signal,AbortSignal.timeout(requestMs)].filter(Boolean));activeSignal.throwIfAborted();
12
+ const work=(async()=>{
13
+ await assertAuthorized();activeSignal.throwIfAborted();if(closed)throw Error('CLOUDFLARE_TRANSPORT_CLOSED');
14
+ ready??=Promise.resolve().then(()=>createHttpTransport({signal:AbortSignal.any([signal,controller.signal].filter(Boolean))})).catch(error=>{acquisitionFailed=true;throw error;});
15
+ const transport=await ready;if(!transport||typeof transport.fetch!=='function'||typeof transport.close!=='function'){acquisitionFailed=true;throw Error('CLOUDFLARE_TRANSPORT_INVALID');}
16
+ const response=await transport.fetch(new Request(request,{signal:activeSignal,redirect:'manual',credentials:'omit',cache:'no-store'}));
17
+ if(response.status>=300&&response.status<400){await response.body?.cancel();throw Error('CLOUDFLARE_REDIRECT_REFUSED');}
18
+ const chunks=[];let count=0,reader,primary;
19
+ try{
20
+ const length=response.headers.get('content-length');if(length!==null&&(!/^\d+$/.test(length)||Number(length)>maximumResponseBytes))throw Error('CLOUDFLARE_RESPONSE_LIMIT');
21
+ if(response.body){reader=response.body.getReader();for(;;){activeSignal.throwIfAborted();const item=await reader.read();if(item.done)break;count+=item.value.byteLength;if(count>maximumResponseBytes)throw Error('CLOUDFLARE_RESPONSE_LIMIT');chunks.push(item.value);}}
22
+ }catch(error){primary=error;}finally{try{if(reader){await reader.cancel();reader.releaseLock();}else await response.body?.cancel();}catch(error){primary??=error;}}
23
+ if(primary)throw primary;await assertAuthorized();activeSignal.throwIfAborted();const bytes=new Uint8Array(count);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength;}
24
+ return new Response(count?bytes:null,{status:response.status,headers:response.headers});
25
+ })();pending.add(work);const done=()=>pending.delete(work);work.then(done,done);return work;
26
+ };
27
+ const close=()=>closing??=(async()=>{
28
+ closed=true;controller.abort();const transport=await ready?.catch(()=>undefined);if(transport){const receipt=await transport.close();if(receipt!==undefined&&(receipt?.status!=='closed'||receipt.activeRequests!==0)){acquisitionFailed=true;if(Number.isSafeInteger(receipt?.activeRequests)&&receipt.activeRequests>0)underlyingActiveRequests=receipt.activeRequests;}}await Promise.allSettled([...pending]);
29
+ return {status:acquisitionFailed||pending.size?'unconfirmed':'closed',activeRequests:pending.size+underlyingActiveRequests};
30
+ })();
31
+ return Object.freeze({fetch,close});
32
+ }
@@ -1,16 +1,16 @@
1
- import type { ManagedRetainedFixture, ManagedNativeRetentionReceipt } from "./managed-native-fixture.mjs";
2
-
3
- export interface ClusterDirectory {
4
- readonly dataDirectory: string;
5
- readonly temporary: string;
6
- readonly volatile: boolean;
7
- readonly managed?: true;
8
- retainAndRelease(outcome?: {status: string; closed: boolean}): Promise<void | ManagedNativeRetentionReceipt>;
9
- }
10
-
11
- export function createClusterDirectory(
12
- evidence: string,
13
- volatileBase?: string,
14
- register?: (handle: ReturnType<typeof import("./owned-process.mjs").startOwnedProcess>) => void,
15
- managed?: ManagedRetainedFixture,
16
- ): ClusterDirectory;
1
+ import type { ManagedRetainedFixture, ManagedNativeRetentionReceipt } from "./managed-native-fixture.mjs";
2
+
3
+ export interface ClusterDirectory {
4
+ readonly dataDirectory: string;
5
+ readonly temporary: string;
6
+ readonly volatile: boolean;
7
+ readonly managed?: true;
8
+ retainAndRelease(outcome?: {status: string; closed: boolean}): Promise<void | ManagedNativeRetentionReceipt>;
9
+ }
10
+
11
+ export function createClusterDirectory(
12
+ evidence: string,
13
+ volatileBase?: string,
14
+ register?: (handle: ReturnType<typeof import("./owned-process.mjs").startOwnedProcess>) => void,
15
+ managed?: ManagedRetainedFixture,
16
+ ): ClusterDirectory;