@enfyra/kernel 1.1.63 → 2.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.
@@ -1,4 +1,6 @@
1
- "use strict";var ne=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ae=ne((Ye,re)=>{"use strict";var{fork:ve}=require("child_process"),be=require("path");function xe({workerDir:e,activeTaskContexts:t}){let s=new Map,n=new Map,r=new Map,i=new Map,o=null,y=0,f=1e3;function w(l){return Math.max(1,Math.trunc(Number(l)||3e4))}function b(l,a,c){let p=new Error(l);return p.code=a,p.details=c,p}function R(l,a){for(let[c,p]of n)p.child===l&&(clearTimeout(p.timer),n.delete(c),r.delete(c),p.reject(a))}function d(l){for(let[a,c]of i)c.child===l&&(clearTimeout(c.timer),i.delete(a))}function u(l,a){if(!l.connected)return;let c=`cancel_${++y}`,p=setTimeout(()=>{i.delete(c);try{l.kill()}catch{}},f);p.unref?.(),i.set(c,{child:l,timer:p});try{l.send({op:"cancelTask",taskId:a,id:c})}catch{clearTimeout(p),i.delete(c);try{l.kill()}catch{}}}function m(l){let a=typeof l=="string"?JSON.parse(l):l;if(a?.error)throw new Error(a.error);return a?.value}async function v(l){let a=t.get(l.taskId);if(!a)throw new Error(`Package callback context not found: ${l.taskId}`);let c=JSON.stringify(l.callbackId),p=JSON.stringify(l.argsJson||"[]"),h=await a.evalClosure(`return __invokeRuntimeCallback(${c}, ${p});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}});return m(h)}function k(){if(o&&o.connected)return o;let l=be.join(e,"package-runtime.child.js"),a=ve(l,[],{stdio:["ignore","ignore","ignore","ipc"],env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_ENV:process.env.NODE_ENV||"production",TMPDIR:process.env.TMPDIR||"",LANG:process.env.LANG||""}});return o=a,a.on("message",c=>{if(!c||!c.id)return;if(c.type==="pkgStreamChunk"){let h=r.get(c.id);if(!h)return;h.onChunk(Buffer.from(c.chunk||"","base64")).then(()=>{try{a.send({type:"pkgStreamAck",ackId:c.ackId})}catch{}}).catch(M=>{try{a.send({type:"pkgStreamError",ackId:c.ackId,error:{message:M.message,stack:M.stack}})}catch{}});return}if(c.type==="taskCancelled"){let h=i.get(c.id);if(!h||h.child!==a)return;clearTimeout(h.timer),i.delete(c.id);return}if(c.type==="pkgCallbackCall"){v(c).then(h=>{try{a.send({type:"pkgCallbackResult",id:c.id,value:h})}catch{}}).catch(h=>{try{a.send({type:"pkgCallbackError",id:c.id,error:{message:h.message,stack:h.stack}})}catch{}});return}let p=n.get(c.id);if(p)if(clearTimeout(p.timer),n.delete(c.id),r.delete(c.id),c.ok)p.resolve(c.value);else{c.error?.code==="ERR_PACKAGE_RUNTIME_TIMEOUT"&&u(a,p.taskId);let h=b(c.error?.message||"Package runtime call failed",c.error?.code,c.error?.details);h.stack=c.error?.stack||h.stack,p.reject(h)}}),a.on("exit",(c,p)=>{o===a&&(o=null),d(a),R(a,b(`Package runtime exited${p?` with signal ${p}`:` with code ${c}`}`,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),a.on("error",c=>{o===a&&(o=null),d(a),R(a,b(c.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),a}function P(l){return new Promise((a,c)=>{let p=k(),h=`pkg_${++y}`,M=w(l.timeoutMs),J=setTimeout(()=>{n.delete(h),r.delete(h),u(p,l.taskId),c(b(`Package runtime call timed out after ${M}ms`,"ERR_PACKAGE_RUNTIME_TIMEOUT",{outcome:"unknown_outcome",retryable:!1}))},M);n.set(h,{child:p,taskId:l.taskId,resolve:a,reject:c,timer:J});try{p.send({...l,id:h},I=>{I&&(clearTimeout(J),n.delete(h),c(I))})}catch(I){clearTimeout(J),n.delete(h),c(I)}})}function C(l,a,c,p=[],h=3e4){return new Promise((M,J)=>{let I=k(),N=`pkg_${++y}`,Q=w(h),ee=setTimeout(()=>{n.delete(N),r.delete(N),u(I,l),J(b(`Package runtime stream timed out after ${Q}ms`,"ERR_PACKAGE_RUNTIME_TIMEOUT",{outcome:"unknown_outcome",retryable:!1}))},Q);n.set(N,{child:I,taskId:l,resolve:M,reject:J,timer:ee}),r.set(N,{onChunk:c});try{I.send({op:"streamHandle",taskId:l,handleId:a,path:p,id:N,timeoutMs:Q},G=>{G&&(clearTimeout(ee),n.delete(N),r.delete(N),J(G))})}catch(G){clearTimeout(ee),n.delete(N),r.delete(N),J(G)}})}function D(l){try{if(!o||!o.connected)return;o.send({...l,id:`pkg_${++y}`,fire:!0})}catch{}}function _(l){try{if(!o||!o.connected)return;u(o,l)}catch{}}async function H(l,a){let c=s.get(l);if(!c)throw new Error("Package context is not available");if(a.handleId)return P({op:a.kind==="get"?"handleGet":"handleCall",taskId:l,handleId:a.handleId,path:a.path||[],argsJson:a.argsJson||"[]",timeoutMs:a.timeoutMs});let p=c.get(a.packageName);if(!p)throw new Error(`Package "${a.packageName}" is not available`);return P({op:a.kind==="construct"?"construct":"call",taskId:l,packageName:a.packageName,package:{name:p.name,fileUrl:p.fileUrl},path:a.path||[],argsJson:a.argsJson||"[]",timeoutMs:a.timeoutMs})}function g(l,a){s.set(l,a)}function x(l){s.delete(l),D({op:"releaseTask",taskId:l})}function $(){if(o){try{o.kill()}catch{}o=null}}return{cleanupTaskPackages:x,cancelTask:_,executePackageRuntimeCall:H,setTaskPackages:g,streamPackageHandle:C,shutdownPackageRuntime:$}}re.exports={createPackageRuntimeBridge:xe}});var oe=ne((Ze,se)=>{"use strict";var Pe=`
1
+ "use strict";var xe=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ir=Object.prototype.hasOwnProperty;var lr=(e,t)=>()=>(e&&(t=e(e=0)),t);var A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),cr=(e,t)=>{for(var n in t)xe(e,n,{get:t[n],enumerable:!0})},ur=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sr(t))!ir.call(e,i)&&i!==n&&xe(e,i,{get:()=>t[i],enumerable:!(r=or(t,i))||r.enumerable});return e};var $e=e=>ur(xe({},"__esModule",{value:!0}),e);var ie=A((Tn,ze)=>{"use strict";function dr(e){if(e instanceof Error)return e;if(e===null)return new Error("Script threw null");if(e===void 0)return new Error("Script threw undefined");let t;if(typeof e=="string")t=e;else{try{let r=JSON.stringify(e);typeof r=="string"&&(t=r)}catch{}if(t===void 0)try{t=String(e)}catch{t="Script threw a non-Error value"}}let n=new Error(t);if(e&&typeof e=="object"){for(let r of["code","statusCode","errorPath","details","executionStage"])try{e[r]!==void 0&&(n[r]=e[r])}catch{}try{typeof e.stack=="string"&&(n.stack=e.stack)}catch{}}return n}function Be(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var fr=3;function De(e){if(typeof e!="string"||!e)return null;let t=e.split(`
2
+ `);for(let n of t){let r=n.match(/(?:\(|\bat\s+)((?:handler|preHook #\d+|postHook #\d+)\.js):(\d+):(\d+)\)?\s*$/);if(!r)continue;let i=r[1],c=parseInt(r[2])-fr;if(!(c<=0))return{line:c,column:parseInt(r[3]),phase:i.replace(".js","")}}return null}function Le(e,t,n){if(!e||!t)return;let r=String(e).split(/\r?\n/),i=Math.max(1,t-1),s=Math.min(r.length,t+1),c=String(s).length,_=[];for(let m=i;m<=s;m++){let l=m===t?">":" ";_.push(`${l} ${String(m).padStart(c," ")}. ${r[m-1]??""}`),m===t&&n&&n>0&&_.push(` ${" ".repeat(c)} ${" ".repeat(Math.max(0,Math.min(r[m-1]?.length||0,n-1)))}^`)}return _.join(`
3
+ `)}function Fe(e,t){if(!(!e||!t)){if(t[e.phase])return t[e.phase];if(e.phase?.startsWith("preHook"))return t.preHook;if(e.phase?.startsWith("postHook"))return t.postHook}}function _r(e,t){let n=Be(e);if(n)return{message:n.message,statusCode:n.statusCode,errorPath:n.errorPath,code:n.code??(Number.isInteger(n.statusCode)?`HTTP_${n.statusCode}`:void 0),details:n.details};let r=De(e.stack),i=e.message||"Unknown error",s=r?`${i} (${r.phase}, line ${r.line})`:i,c=Fe(r,t),_=r?Le(c,r.line,r.column):void 0;return{message:s,statusCode:e.statusCode||null,code:e.code,errorPath:e.errorPath,details:{...e.details&&typeof e.details=="object"?e.details:{},errorName:e.name||null,executionStage:e.executionStage||"runtime",...r?{...r,codeFrame:_}:{}}}}function Je(e){return e?.message==="Script execution timed out."}function je(e){return e?.message==="Isolate was disposed during execution due to memory limit"}function pr(e){Je(e)&&e?.code==null&&(e.code="ERR_SCRIPT_EXECUTION_TIMEOUT"),je(e)&&e?.code==null&&(e.code="ERR_ISOLATE_MEMORY_LIMIT",e.details={outcome:"unknown_outcome",retryable:!1})}ze.exports={normalizeThrownValue:dr,extractThrowInfo:Be,parseUserCodeLocation:De,formatCodeFrame:Le,findSourceForLocation:Fe,buildErrorPayload:_r,isNativeExecutionTimeout:Je,isIsolateMemoryLimit:je,normalizeNativeExecutionError:pr}});var Se=A((En,qe)=>{"use strict";var{createHash:mr}=require("crypto"),He=new WeakMap,yr=500,ve=4*1024*1024,hr=32*1024*1024;async function gr(e,t,n){let r=He.get(e);r||(r={entries:new Map,bytes:0},He.set(e,r));let i=Buffer.byteLength(t,"utf8");if(i>ve)throw new Error(`Executor script exceeds ${ve} bytes`);let s=mr("sha256").update(JSON.stringify([n,t])).digest("hex"),c=r.entries.get(s);if(c)return r.entries.delete(s),r.entries.set(s,c),c.script;let _;try{_=await e.compileScript(t,{filename:n})}catch(l){throw l&&typeof l=="object"&&(l.executionStage="compile"),l}if(r.entries.get(s))return _;for(r.entries.set(s,{script:_,bytes:i}),r.bytes+=i;r.entries.size>0&&(r.entries.size>yr||r.bytes>hr);){let l=r.entries.keys().next().value,p=r.entries.get(l);r.entries.delete(l),r.bytes-=p?.bytes||0}return _}qe.exports={getCachedScript:gr,SCRIPT_MAX_BYTES:ve}});var Ge=A((Mn,Ve)=>{"use strict";var{open:wr}=require("fs/promises"),{fileURLToPath:br}=require("url"),z=require("typescript"),{SCRIPT_MAX_BYTES:re}=Se(),{isNativeExecutionTimeout:kr,isIsolateMemoryLimit:xr}=ie();function vr(e){let t=Symbol("packageProxyFallback");async function n(c){if(typeof c.sourceCode=="string"&&c.sourceCode.length>0){if(Buffer.byteLength(c.sourceCode,"utf8")>re)throw new Error(`Package source exceeds ${re} bytes`);return c.sourceCode}let _=c.filePath;if(!_&&typeof c.fileUrl=="string"&&c.fileUrl.startsWith("file://")&&(_=br(c.fileUrl)),!_)return null;let m;try{if(m=await wr(_,"r"),(await m.stat()).size>re)throw new Error(`Package source exceeds ${re} bytes`);let p=Buffer.allocUnsafe(re+1),w=0;for(;w<p.length;){let{bytesRead:d}=await m.read(p,w,p.length-w,w);if(d===0)break;w+=d}if(w>re)throw new Error(`Package source exceeds ${re} bytes`);return p.subarray(0,w).toString("utf8")}catch(l){if(l?.code==="ENOENT")return null;throw l}finally{try{await m?.close()}catch{}}}async function r(c,_,m,l){let p=await n(m);if(p===null||z.createSourceFile(`pkg:${m.safeName}`,p,z.ScriptTarget.Latest,!1,z.ScriptKind.JS).statements.some(y=>z.isImportDeclaration(y)||z.isExportDeclaration(y)&&y.moduleSpecifier!==void 0))return t;let d;try{d=await c.compileModule(p,{filename:`pkg:${m.safeName}`}),await d.instantiate(_,y=>{throw new Error(`Unresolved import in package ${m.safeName}: ${y}`)})}catch(y){try{d?.release()}catch{}if(c.isDisposed||kr(y)||xr(y))throw y;return t}await d.evaluate({timeout:e(l)});let h=await d.namespace.get("default");return h!==void 0?typeof h?.derefInto=="function"?h.derefInto({release:!1}):h:d.namespace.derefInto({release:!1})}function i(c){if(c==null)return[];if(!Array.isArray(c))throw new Error("Executor pkgSources must be an array");let _=new Set,m=new Set;for(let l of c){if(!l||typeof l!="object")throw new Error("Executor package entries must be objects");if(typeof l.name!="string"||l.name.length===0)throw new Error("Executor package name must be a non-empty string");if(_.has(l.name))throw new Error(`Duplicate executor package name: ${l.name}`);if(typeof l.safeName!="string"||!/^[A-Za-z_$][\w$]*$/.test(l.safeName))throw new Error(`Invalid package safeName: ${l.safeName}`);if(m.has(l.safeName))throw new Error(`Duplicate executor package safeName: ${l.safeName}`);_.add(l.name),m.add(l.safeName)}return c}function s(c,_){let m=new Set(_.map(d=>d.name)),l=new Set,p=z.createSourceFile("package-references.js",String(c||""),z.ScriptTarget.Latest,!1,z.ScriptKind.JS),w=d=>{z.isCallExpression(d)&&z.isIdentifier(d.expression)&&d.expression.text==="require"&&d.arguments.length===1&&z.isStringLiteralLike(d.arguments[0])&&m.has(d.arguments[0].text)&&l.add(d.arguments[0].text),z.forEachChild(d,w)};return w(p),l}return{PACKAGE_PROXY_FALLBACK:t,loadEsmPackageIntoContext:r,validatePackageSources:i,collectIsolatePackageNames:s}}Ve.exports={createWorkerPackages:vr}});var We=A((Cn,Ke)=>{"use strict";Ke.exports=`
2
4
  "use strict";
3
5
  let $ctx = {};
4
6
  let $pkgs = {};
@@ -9,76 +11,208 @@ let __logBytes = 0;
9
11
  let __runtimeCallbackCounter = 0;
10
12
  let __runtimeCallbacks = new Map();
11
13
  let __pendingRuntimeTasks = [];
14
+ let __streamTimerCounter = 0;
12
15
 
16
+ const __trustedNow = Date.now.bind(Date);
13
17
  const __applyOpts = { result: { promise: true, copy: true } };
14
18
 
19
+ const __typedArrayConstructors = Object.freeze(Object.assign(Object.create(null), {
20
+ Int8Array,
21
+ Uint8Array,
22
+ Uint8ClampedArray,
23
+ Int16Array,
24
+ Uint16Array,
25
+ Int32Array,
26
+ Uint32Array,
27
+ ...(typeof Float16Array === 'undefined' ? {} : { Float16Array }),
28
+ Float32Array,
29
+ Float64Array,
30
+ ...(typeof BigInt64Array === 'undefined' ? {} : { BigInt64Array }),
31
+ ...(typeof BigUint64Array === 'undefined' ? {} : { BigUint64Array }),
32
+ }));
33
+ const __typedArrayTagGetter = Object.getOwnPropertyDescriptor(
34
+ Object.getPrototypeOf(Uint8Array.prototype),
35
+ Symbol.toStringTag,
36
+ )?.get;
37
+ const __dataViewByteLengthGetter = Object.getOwnPropertyDescriptor(
38
+ DataView.prototype,
39
+ 'byteLength',
40
+ )?.get;
41
+
42
+ function __decodeTypedArray(payload) {
43
+ const name = String(payload.__typedArray || '');
44
+ const bytes = payload.bytes;
45
+ if (name === 'DataView') {
46
+ const buffer = Uint8Array.from(bytes || payload.data || []).buffer;
47
+ return new DataView(buffer);
48
+ }
49
+ const Ctor = __typedArrayConstructors[name];
50
+ if (typeof Ctor !== 'function') {
51
+ throw new TypeError('Unsupported typed array: ' + name);
52
+ }
53
+ if (Array.isArray(bytes)) {
54
+ const buffer = Uint8Array.from(bytes).buffer;
55
+ return new Ctor(buffer);
56
+ }
57
+ return new Ctor(payload.data || []);
58
+ }
59
+
60
+ function __isEnvelope(value, requiredKey, allowedKeys) {
61
+ if (value === null || (typeof value !== 'object' && typeof value !== 'function')) return false;
62
+ if (!Object.prototype.hasOwnProperty.call(value, requiredKey)) return false;
63
+ const allowed = new Set(allowedKeys);
64
+ return Object.keys(value).every((key) => allowed.has(key));
65
+ }
66
+
67
+ function __decodeNumber(value) {
68
+ if (value === 'nan') return NaN;
69
+ if (value === 'infinity') return Infinity;
70
+ if (value === '-infinity') return -Infinity;
71
+ if (value === '-0') return -0;
72
+ throw new TypeError('Unsupported encoded number: ' + value);
73
+ }
74
+
75
+ function __encodeNumber(value) {
76
+ if (Number.isNaN(value)) return { __number: 'nan' };
77
+ if (value === Infinity) return { __number: 'infinity' };
78
+ if (value === -Infinity) return { __number: '-infinity' };
79
+ if (Object.is(value, -0)) return { __number: '-0' };
80
+ return value;
81
+ }
82
+
83
+ function __collidesWithEnvelope(value) {
84
+ return (
85
+ __isEnvelope(value, '__plainObject', ['__plainObject'])
86
+ || __isEnvelope(value, '__number', ['__number'])
87
+ || __isEnvelope(value, '__bigint', ['__bigint'])
88
+ || __isEnvelope(value, '__nullPrototype', ['__nullPrototype'])
89
+ || (__isEnvelope(value, '__e', ['__e']) && value.__e === 'u')
90
+ || (__isEnvelope(value, '__e', ['__e', 'd']) && value.__e === 'v')
91
+ || __isEnvelope(value, '__fnRef', ['__fnRef'])
92
+ || __isEnvelope(value, '__pkgHandleArg', ['__pkgHandleArg'])
93
+ || __isEnvelope(value, '__pkgHandle', ['__pkgHandle'])
94
+ || __isEnvelope(value, '__date', ['__date'])
95
+ || __isEnvelope(value, '__set', ['__set'])
96
+ || __isEnvelope(value, '__map', ['__map'])
97
+ || __isEnvelope(value, '__regexp', ['__regexp'])
98
+ || __isEnvelope(value, '__error', ['__error'])
99
+ || __isEnvelope(value, '__url', ['__url'])
100
+ || __isEnvelope(value, '__urlSearchParams', ['__urlSearchParams'])
101
+ || __isEnvelope(value, '__blob', ['__blob'])
102
+ || __isEnvelope(value, '__file', ['__file'])
103
+ || __isEnvelope(value, '__formData', ['__formData'])
104
+ || __isEnvelope(value, '__typedArray', ['__typedArray', 'bytes', 'data'])
105
+ || __isEnvelope(value, '__arrayBuffer', ['__arrayBuffer'])
106
+ );
107
+ }
108
+
109
+ function __defineDataProperty(target, key, value) {
110
+ Object.defineProperty(target, key, {
111
+ value,
112
+ enumerable: true,
113
+ configurable: true,
114
+ writable: true,
115
+ });
116
+ }
117
+
15
118
  function __unwrapMainThreadPayload(v) {
16
- if (v !== null && typeof v === 'object' && v.__e === 'u') return undefined;
17
- if (v !== null && typeof v === 'object' && v.__e === 'v') return __unwrapMainThreadPayload(v.d);
18
- if (v !== null && typeof v === 'object' && v.__date) return new Date(v.__date);
19
- if (v !== null && typeof v === 'object' && v.__set) {
119
+ if (v === null || typeof v !== 'object') return v;
120
+ if (__isEnvelope(v, '__plainObject', ['__plainObject'])) {
121
+ const out = {};
122
+ for (const [key, value] of Object.entries(v.__plainObject || {})) {
123
+ __defineDataProperty(out, key, __unwrapMainThreadPayload(value));
124
+ }
125
+ return out;
126
+ }
127
+ if (__isEnvelope(v, '__number', ['__number'])) {
128
+ return __decodeNumber(v.__number);
129
+ }
130
+ if (__isEnvelope(v, '__bigint', ['__bigint'])) {
131
+ return BigInt(v.__bigint);
132
+ }
133
+ if (__isEnvelope(v, '__nullPrototype', ['__nullPrototype'])) {
134
+ const out = Object.create(null);
135
+ for (const [key, value] of Object.entries(v.__nullPrototype || {})) {
136
+ __defineDataProperty(out, key, __unwrapMainThreadPayload(value));
137
+ }
138
+ return out;
139
+ }
140
+ if (__isEnvelope(v, '__e', ['__e']) && v.__e === 'u') return undefined;
141
+ if (__isEnvelope(v, '__e', ['__e', 'd']) && v.__e === 'v') {
142
+ return __unwrapMainThreadPayload(v.d);
143
+ }
144
+ if (__isEnvelope(v, '__date', ['__date'])) return new Date(v.__date);
145
+ if (__isEnvelope(v, '__set', ['__set'])) {
20
146
  return new Set(v.__set.map(__unwrapMainThreadPayload));
21
147
  }
22
- if (v !== null && typeof v === 'object' && v.__map) {
148
+ if (__isEnvelope(v, '__map', ['__map'])) {
23
149
  return new Map(v.__map.map(([key, value]) => [
24
150
  __unwrapMainThreadPayload(key),
25
151
  __unwrapMainThreadPayload(value),
26
152
  ]));
27
153
  }
28
- if (v !== null && typeof v === 'object' && v.__regexp) {
154
+ if (__isEnvelope(v, '__regexp', ['__regexp'])) {
29
155
  return new RegExp(v.__regexp.source, v.__regexp.flags || '');
30
156
  }
31
- if (v !== null && typeof v === 'object' && v.__error) {
157
+ if (__isEnvelope(v, '__error', ['__error'])) {
32
158
  const error = new Error(v.__error.message || '');
33
159
  error.name = v.__error.name || 'Error';
34
160
  if (v.__error.stack) error.stack = v.__error.stack;
35
161
  return error;
36
162
  }
37
- if (v !== null && typeof v === 'object' && v.__url) return new URL(v.__url);
38
- if (v !== null && typeof v === 'object' && v.__urlSearchParams) {
163
+ if (__isEnvelope(v, '__url', ['__url'])) return new URL(v.__url);
164
+ if (__isEnvelope(v, '__urlSearchParams', ['__urlSearchParams'])) {
39
165
  return new URLSearchParams(v.__urlSearchParams);
40
166
  }
41
- if (v !== null && typeof v === 'object' && v.__blob) {
167
+ if (__isEnvelope(v, '__blob', ['__blob'])) {
42
168
  return new Blob([Uint8Array.from(v.__blob.data || [])], {
43
169
  type: v.__blob.type || '',
44
170
  });
45
171
  }
46
- if (v !== null && typeof v === 'object' && v.__file) {
172
+ if (__isEnvelope(v, '__file', ['__file'])) {
47
173
  const parts = [Uint8Array.from(v.__file.data || [])];
48
174
  const options = {
49
175
  type: v.__file.type || '',
50
176
  lastModified: v.__file.lastModified,
51
177
  };
52
- return typeof File !== 'undefined'
53
- ? new File(parts, v.__file.name || 'file', options)
54
- : new Blob(parts, options);
178
+ if (typeof File !== 'undefined') {
179
+ return new File(parts, v.__file.name || 'file', options);
180
+ }
181
+ const blob = new Blob(parts, options);
182
+ __defineDataProperty(blob, 'name', v.__file.name || 'file');
183
+ __defineDataProperty(blob, 'lastModified', v.__file.lastModified);
184
+ return blob;
55
185
  }
56
- if (v !== null && typeof v === 'object' && v.__formData) {
186
+ if (__isEnvelope(v, '__formData', ['__formData'])) {
57
187
  const form = new FormData();
58
188
  for (const [key, value] of v.__formData) {
59
- form.append(key, __unwrapMainThreadPayload(value));
189
+ const decoded = __unwrapMainThreadPayload(value);
190
+ if (
191
+ __isEnvelope(value, '__file', ['__file'])
192
+ && typeof File === 'undefined'
193
+ ) {
194
+ form.append(key, decoded, value.__file.name || 'file');
195
+ } else {
196
+ form.append(key, decoded);
197
+ }
60
198
  }
61
199
  return form;
62
200
  }
63
- if (v !== null && typeof v === 'object' && v.__typedArray) {
64
- const Ctor = globalThis[v.__typedArray] || Uint8Array;
65
- return new Ctor(v.data || []);
201
+ if (__isEnvelope(v, '__typedArray', ['__typedArray', 'bytes', 'data'])) {
202
+ return __decodeTypedArray(v);
66
203
  }
67
- if (v !== null && typeof v === 'object' && v.__arrayBuffer) {
204
+ if (__isEnvelope(v, '__arrayBuffer', ['__arrayBuffer'])) {
68
205
  return Uint8Array.from(v.__arrayBuffer).buffer;
69
206
  }
70
- if (v !== null && typeof v === 'object' && v.__pkgHandle) {
207
+ if (__isEnvelope(v, '__pkgHandle', ['__pkgHandle'])) {
71
208
  return __createPkgHandleProxy(Promise.resolve(v.__pkgHandle), []);
72
209
  }
73
210
  if (Array.isArray(v)) return v.map(__unwrapMainThreadPayload);
74
- if (v !== null && typeof v === 'object' && !v.__pkgHandle) {
75
- const out = {};
76
- for (const [key, value] of Object.entries(v)) {
77
- out[key] = __unwrapMainThreadPayload(value);
78
- }
79
- return out;
211
+ const out = {};
212
+ for (const [key, value] of Object.entries(v)) {
213
+ __defineDataProperty(out, key, __unwrapMainThreadPayload(value));
80
214
  }
81
- return v;
215
+ return out;
82
216
  }
83
217
 
84
218
  function __parseMainThreadResult(s) {
@@ -86,18 +220,84 @@ function __parseMainThreadResult(s) {
86
220
  return __unwrapMainThreadPayload(w);
87
221
  }
88
222
 
223
+ `});var Ye=A((Rn,Xe)=>{"use strict";Xe.exports=`// A script may call the host without awaiting the result, and a host call
224
+ // outlives the script that made it: a fire-and-forget call is still pending when
225
+ // the task finishes, and the lifecycle rejects it then. V8 reports that
226
+ // rejection as an unhandled rejection of the isolate, which the next script run
227
+ // on the same lane inherits and fails with \u2014 one task killing another. Every
228
+ // host-call promise is therefore marked handled where it is handed to the
229
+ // script: awaiting the call still observes the rejection, while a call the
230
+ // script ignores can no longer fail a different task.
231
+ function __hostCallAsync(fn) {
232
+ return (...args) => {
233
+ const promise = fn(...args);
234
+ if (promise && typeof promise.catch === 'function') promise.catch(() => {});
235
+ return promise;
236
+ };
237
+ }
238
+
89
239
  async function __call(type, dataJson) {
90
- const r = await __callRef.apply(undefined, [__taskId, type, dataJson], __applyOpts);
240
+ const r = await __callRef.apply(undefined, [type, dataJson], __applyOpts);
91
241
  return __parseMainThreadResult(r);
92
242
  }
93
243
 
94
244
  function __remainingTaskTimeoutMs() {
95
245
  if (!__taskDeadlineMs) return 30000;
96
- return Math.max(1, Math.ceil(__taskDeadlineMs - Date.now()));
246
+ const remainingMs = Math.ceil(__taskDeadlineMs - __trustedNow());
247
+ if (remainingMs <= 0) {
248
+ const error = new Error('Script execution timed out.');
249
+ error.code = 'ERR_SCRIPT_EXECUTION_TIMEOUT';
250
+ throw error;
251
+ }
252
+ return remainingMs;
253
+ }
254
+
255
+ async function __awaitBeforeDeadline(value, deadlineMs, timeoutError) {
256
+ const remainingMs = Math.ceil(deadlineMs - __trustedNow());
257
+ if (remainingMs <= 0) throw timeoutError();
258
+ const timerId = 'deadline_timer_' + (++__streamTimerCounter);
259
+ try {
260
+ const result = await Promise.race([
261
+ Promise.resolve(value),
262
+ __waitForStreamTimer(timerId, remainingMs).then((fired) => {
263
+ if (fired) throw timeoutError();
264
+ const error = new Error('Task is no longer active');
265
+ error.code = 'ERR_EXECUTION_ABORTED';
266
+ throw error;
267
+ }),
268
+ ]);
269
+ if (__trustedNow() >= deadlineMs) throw timeoutError();
270
+ return result;
271
+ } finally {
272
+ void __clearStreamTimer(timerId).catch(() => {});
273
+ }
274
+ }
275
+
276
+ function __taskTimeoutError() {
277
+ const error = new Error('Script execution timed out.');
278
+ error.code = 'ERR_SCRIPT_EXECUTION_TIMEOUT';
279
+ return error;
280
+ }
281
+
282
+ function __awaitTaskDeadline(value) {
283
+ return __awaitBeforeDeadline(value, __innerGuardDeadlineMs(), __taskTimeoutError);
284
+ }
285
+
286
+ // The host supplies task tolerance plus backstop grace; the V8 watchdog keeps
287
+ // the original execution budget.
288
+ let __innerGuardGraceMs = 500;
289
+
290
+ function __innerGuardDeadlineMs() {
291
+ if (!__taskDeadlineMs) return __trustedNow() + 30000 + __innerGuardGraceMs;
292
+ return __taskDeadlineMs + __innerGuardGraceMs;
293
+ }
294
+
295
+ function __innerGuardTimeoutMs() {
296
+ return Math.max(1, Math.ceil(__innerGuardDeadlineMs() - __trustedNow()));
97
297
  }
98
298
 
99
299
  function __encodePkgCallPayload(payload) {
100
- return JSON.stringify({ ...payload, timeoutMs: __remainingTaskTimeoutMs() });
300
+ return JSON.stringify({ ...payload, timeoutMs: __innerGuardTimeoutMs() });
101
301
  }
102
302
 
103
303
  function __bytesToBase64(bytes) {
@@ -118,6 +318,29 @@ function __bytesToBase64(bytes) {
118
318
  return out;
119
319
  }
120
320
 
321
+ function __base64ToBytes(value) {
322
+ const encoded = String(value || '');
323
+ if (encoded.length % 4 !== 0) throw new TypeError('Invalid Base64 payload');
324
+ const padding = encoded.endsWith('==') ? 2 : encoded.endsWith('=') ? 1 : 0;
325
+ const length = encoded.length - padding;
326
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
327
+ const out = new Uint8Array(encoded.length / 4 * 3 - padding);
328
+ let bits = 0;
329
+ let bitCount = 0;
330
+ let offset = 0;
331
+ for (let i = 0; i < length; i++) {
332
+ const index = chars.indexOf(encoded[i]);
333
+ if (index < 0) throw new TypeError('Invalid Base64 payload');
334
+ bits = (bits << 6) | index;
335
+ bitCount += 6;
336
+ if (bitCount >= 8) {
337
+ bitCount -= 8;
338
+ out[offset++] = (bits >> bitCount) & 255;
339
+ }
340
+ }
341
+ return out;
342
+ }
343
+
121
344
  function __streamChunkToBytes(chunk) {
122
345
  if (chunk === undefined || chunk === null) return new Uint8Array();
123
346
  if (typeof chunk === 'string') return new TextEncoder().encode(chunk);
@@ -128,105 +351,214 @@ function __streamChunkToBytes(chunk) {
128
351
  return new TextEncoder().encode(String(chunk));
129
352
  }
130
353
 
354
+ function __responseBodyToBytes(value) {
355
+ if (typeof value === 'string') return new TextEncoder().encode(value);
356
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
357
+ if (ArrayBuffer.isView(value)) {
358
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
359
+ }
360
+ throw new TypeError('@RES.bytes requires a string, ArrayBuffer, or ArrayBuffer view');
361
+ }
362
+
363
+ function __encodeTypedArray(value) {
364
+ let name;
365
+ try {
366
+ __dataViewByteLengthGetter.call(value);
367
+ name = 'DataView';
368
+ } catch {
369
+ try { name = __typedArrayTagGetter.call(value); } catch {}
370
+ }
371
+ if (!name || (name !== 'DataView' && !__typedArrayConstructors[name])) {
372
+ throw new TypeError('Unsupported ArrayBuffer view');
373
+ }
374
+ return {
375
+ __typedArray: name,
376
+ bytes: Array.from(
377
+ new Uint8Array(value.buffer, value.byteOffset, value.byteLength),
378
+ ),
379
+ };
380
+ }
381
+
131
382
  async function __encodeRuntimeArg(value, seen) {
383
+ if (value === undefined) return { __e: 'u' };
384
+ if (typeof value === 'number') return __encodeNumber(value);
385
+ if (typeof value === 'bigint') return { __bigint: value.toString() };
386
+ if (typeof value === 'function' && value.__pkgHandlePromise) {
387
+ return {
388
+ __pkgHandleArg: await __awaitTaskDeadline(value.__pkgHandlePromise),
389
+ };
390
+ }
391
+ if (
392
+ value !== null
393
+ && (typeof value === 'object' || typeof value === 'function')
394
+ && typeof value.then === 'function'
395
+ ) {
396
+ return __encodeRuntimeArg(await __awaitTaskDeadline(value), seen);
397
+ }
132
398
  if (typeof value === 'function') {
133
- if (value.__pkgHandlePromise) {
134
- return { __pkgHandleArg: await value.__pkgHandlePromise };
135
- }
136
- if (typeof value.then === 'function') {
137
- return __encodeRuntimeArg(await value, seen);
138
- }
139
399
  const id = 'fn_' + (++__runtimeCallbackCounter);
140
400
  __runtimeCallbacks.set(id, value);
141
401
  return { __fnRef: id };
142
402
  }
143
403
  if (!seen) seen = new WeakSet();
404
+ let tracked = false;
144
405
  if (value && typeof value === 'object') {
145
406
  if (seen.has(value)) return null;
146
407
  seen.add(value);
408
+ tracked = true;
147
409
  }
148
- if (value instanceof Date) return { __date: value.toISOString() };
149
- if (value instanceof Set) {
150
- const items = [];
151
- for (const item of value.values()) items.push(await __encodeRuntimeArg(item, seen));
152
- return { __set: items };
153
- }
154
- if (value instanceof Map) {
155
- const entries = [];
156
- for (const [key, item] of value.entries()) {
157
- entries.push([
158
- await __encodeRuntimeArg(key, seen),
159
- await __encodeRuntimeArg(item, seen),
160
- ]);
410
+ try {
411
+ if (value instanceof Date) {
412
+ return {
413
+ __date: Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString(),
414
+ };
161
415
  }
162
- return { __map: entries };
163
- }
164
- if (value instanceof RegExp) {
165
- return { __regexp: { source: value.source, flags: value.flags } };
166
- }
167
- if (value instanceof Error) {
168
- return {
169
- __error: {
170
- name: value.name,
171
- message: value.message,
172
- stack: value.stack,
173
- },
174
- };
175
- }
176
- if (typeof URL !== 'undefined' && value instanceof URL) return { __url: value.href };
177
- if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
178
- return { __urlSearchParams: value.toString() };
179
- }
180
- if (typeof File !== 'undefined' && value instanceof File) {
181
- return {
182
- __file: {
183
- name: value.name,
184
- type: value.type,
185
- lastModified: value.lastModified,
186
- data: Array.from(new Uint8Array(await value.arrayBuffer())),
187
- },
188
- };
189
- }
190
- if (typeof Blob !== 'undefined' && value instanceof Blob) {
191
- return {
192
- __blob: {
193
- type: value.type,
194
- data: Array.from(new Uint8Array(await value.arrayBuffer())),
195
- },
196
- };
197
- }
198
- if (typeof FormData !== 'undefined' && value instanceof FormData) {
199
- const entries = [];
200
- for (const [key, item] of value.entries()) {
201
- entries.push([key, await __encodeRuntimeArg(item, seen)]);
416
+ if (value instanceof Set) {
417
+ const items = [];
418
+ for (const item of value.values()) {
419
+ items.push(await __encodeRuntimeArg(item, seen));
420
+ }
421
+ return { __set: items };
202
422
  }
203
- return { __formData: entries };
204
- }
205
- if (ArrayBuffer.isView(value)) {
206
- return {
207
- __typedArray: value.constructor?.name || 'Uint8Array',
208
- data: Array.from(value),
209
- };
210
- }
211
- if (value instanceof ArrayBuffer) {
212
- return { __arrayBuffer: Array.from(new Uint8Array(value)) };
213
- }
214
- if (Array.isArray(value)) return Promise.all(value.map((item) => __encodeRuntimeArg(item, seen)));
215
- if (value && typeof value === 'object') {
216
- const out = {};
217
- for (const key of Object.keys(value)) {
218
- out[key] = await __encodeRuntimeArg(value[key], seen);
423
+ if (value instanceof Map) {
424
+ const entries = [];
425
+ for (const [key, item] of value.entries()) {
426
+ entries.push([
427
+ await __encodeRuntimeArg(key, seen),
428
+ await __encodeRuntimeArg(item, seen),
429
+ ]);
430
+ }
431
+ return { __map: entries };
219
432
  }
220
- return out;
433
+ if (value instanceof RegExp) {
434
+ return { __regexp: { source: value.source, flags: value.flags } };
435
+ }
436
+ if (value instanceof Error) {
437
+ return {
438
+ __error: {
439
+ name: value.name,
440
+ message: value.message,
441
+ stack: value.stack,
442
+ },
443
+ };
444
+ }
445
+ if (typeof URL !== 'undefined' && value instanceof URL) {
446
+ return { __url: value.href };
447
+ }
448
+ if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
449
+ return { __urlSearchParams: value.toString() };
450
+ }
451
+ if (
452
+ typeof Blob !== 'undefined'
453
+ && value instanceof Blob
454
+ && (
455
+ (typeof File !== 'undefined' && value instanceof File)
456
+ || (
457
+ typeof File === 'undefined'
458
+ && typeof value.name === 'string'
459
+ && typeof value.lastModified === 'number'
460
+ )
461
+ )
462
+ ) {
463
+ return {
464
+ __file: {
465
+ name: value.name,
466
+ type: value.type,
467
+ lastModified: value.lastModified,
468
+ data: Array.from(new Uint8Array(
469
+ await __awaitTaskDeadline(value.arrayBuffer()),
470
+ )),
471
+ },
472
+ };
473
+ }
474
+ if (typeof Blob !== 'undefined' && value instanceof Blob) {
475
+ return {
476
+ __blob: {
477
+ type: value.type,
478
+ data: Array.from(new Uint8Array(
479
+ await __awaitTaskDeadline(value.arrayBuffer()),
480
+ )),
481
+ },
482
+ };
483
+ }
484
+ if (typeof FormData !== 'undefined' && value instanceof FormData) {
485
+ const entries = [];
486
+ for (const [key, item] of value.entries()) {
487
+ entries.push([key, await __encodeRuntimeArg(item, seen)]);
488
+ }
489
+ return { __formData: entries };
490
+ }
491
+ if (ArrayBuffer.isView(value)) return __encodeTypedArray(value);
492
+ if (value instanceof ArrayBuffer) {
493
+ return { __arrayBuffer: Array.from(new Uint8Array(value)) };
494
+ }
495
+ if (Array.isArray(value)) {
496
+ const items = [];
497
+ for (const item of value) {
498
+ items.push(await __encodeRuntimeArg(item, seen));
499
+ }
500
+ return items;
501
+ }
502
+ if (value && typeof value === 'object') {
503
+ const out = {};
504
+ for (const key of Object.keys(value)) {
505
+ __defineDataProperty(
506
+ out,
507
+ key,
508
+ await __encodeRuntimeArg(value[key], seen),
509
+ );
510
+ }
511
+ if (Object.getPrototypeOf(value) === null) {
512
+ return { __nullPrototype: out };
513
+ }
514
+ return __collidesWithEnvelope(out) ? { __plainObject: out } : out;
515
+ }
516
+ return value;
517
+ } finally {
518
+ if (tracked) seen.delete(value);
221
519
  }
222
- return value;
223
520
  }
224
521
 
225
522
  async function __stringifyRuntimeArgs(args) {
226
- return JSON.stringify(await Promise.all(args.map((arg) => __encodeRuntimeArg(arg))));
523
+ const encoded = [];
524
+ const seen = new WeakSet();
525
+ for (const arg of args) {
526
+ encoded.push(await __encodeRuntimeArg(arg, seen));
527
+ }
528
+ return JSON.stringify(encoded);
529
+ }
530
+
531
+ `});var Ze=A((An,Qe)=>{"use strict";Qe.exports=`function __utf8IncompleteSuffixLength(bytes) {
532
+ if (bytes.byteLength === 0) return 0;
533
+ let start = bytes.byteLength - 1;
534
+ while (start > 0 && (bytes[start] & 0xc0) === 0x80) start--;
535
+ const lead = bytes[start];
536
+ const available = bytes.byteLength - start;
537
+ let expected = 0;
538
+ if (lead >= 0xc2 && lead <= 0xdf) expected = 2;
539
+ else if (lead >= 0xe0 && lead <= 0xef) expected = 3;
540
+ else if (lead >= 0xf0 && lead <= 0xf4) expected = 4;
541
+ else return 0;
542
+ if (available >= expected) return 0;
543
+ for (let index = start + 1; index < bytes.byteLength; index++) {
544
+ if ((bytes[index] & 0xc0) !== 0x80) return 0;
545
+ }
546
+ if (available >= 2) {
547
+ const second = bytes[start + 1];
548
+ if (lead === 0xe0 && second < 0xa0) return 0;
549
+ if (lead === 0xed && second > 0x9f) return 0;
550
+ if (lead === 0xf0 && second < 0x90) return 0;
551
+ if (lead === 0xf4 && second > 0x8f) return 0;
552
+ }
553
+ return available;
227
554
  }
228
555
 
229
556
  async function __streamResponseFromLocalReadable(stream, options) {
557
+ const { timeoutMs, idleTimeoutMs } = __normalizeStreamOptions(options);
558
+ const deadlineMs = __trustedNow() + Math.min(
559
+ timeoutMs,
560
+ __innerGuardTimeoutMs(),
561
+ );
230
562
  const observer = typeof options?.observer === 'function'
231
563
  ? options.observer
232
564
  : null;
@@ -234,35 +566,78 @@ async function __streamResponseFromLocalReadable(stream, options) {
234
566
  ? options.transform
235
567
  : null;
236
568
  const decoder = observer || transform ? new TextDecoder('utf-8') : null;
569
+ let pendingTransformBytes = new Uint8Array();
237
570
  const relayOptions = { ...(options || {}) };
238
571
  delete relayOptions.observer;
239
572
  delete relayOptions.transform;
573
+ const timeoutError = () => __streamTimeoutError(
574
+ timeoutMs,
575
+ { timeoutKind: 'total' },
576
+ );
577
+ const awaitStage = (value) => __awaitBeforeDeadline(
578
+ value,
579
+ deadlineMs,
580
+ timeoutError,
581
+ );
240
582
  const notifyObserver = async (text, kind) => {
241
583
  if (!observer) return;
242
584
  try {
243
- await observer(text, kind);
244
- } catch {}
585
+ await awaitStage(observer(text, kind));
586
+ } catch (error) {
587
+ if (
588
+ __trustedNow() >= deadlineMs
589
+ || error?.code === 'ERR_PACKAGE_STREAM_TIMEOUT'
590
+ || error?.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT'
591
+ || error?.code === 'ERR_EXECUTION_ABORTED'
592
+ ) {
593
+ throw error;
594
+ }
595
+ }
245
596
  };
246
597
  const relayChunk = async (chunk, kind, text) => {
247
598
  let output = chunk;
248
599
  if (transform) {
249
- const transformed = await transform(text, kind);
600
+ const chunkBytes = __streamChunkToBytes(chunk);
601
+ const combined = new Uint8Array(
602
+ pendingTransformBytes.byteLength + chunkBytes.byteLength,
603
+ );
604
+ combined.set(pendingTransformBytes);
605
+ combined.set(chunkBytes, pendingTransformBytes.byteLength);
606
+ const suffixLength = kind === 'end'
607
+ ? 0
608
+ : __utf8IncompleteSuffixLength(combined);
609
+ const completedBytes = suffixLength === 0
610
+ ? combined
611
+ : combined.slice(0, combined.byteLength - suffixLength);
612
+ pendingTransformBytes = suffixLength === 0
613
+ ? new Uint8Array()
614
+ : combined.slice(combined.byteLength - suffixLength);
615
+ if (kind !== 'end' && text === '' && completedBytes.byteLength === 0) return;
616
+ const transformed = await awaitStage(transform(text, kind));
250
617
  if (transformed === null) return;
251
- if (transformed !== undefined) output = String(transformed);
618
+ if (transformed === undefined) {
619
+ output = completedBytes;
620
+ } else {
621
+ output = String(transformed);
622
+ }
252
623
  }
253
624
  const bytes = __streamChunkToBytes(output);
254
625
  if (bytes.byteLength === 0) return;
255
- await __call('resCall', JSON.stringify({
626
+ await awaitStage(__call('resCall', JSON.stringify({
256
627
  method: 'streamChunk',
257
628
  chunk: __bytesToBase64(bytes),
258
- }));
629
+ })));
259
630
  };
260
- await __call('resCall', JSON.stringify({
261
- method: 'streamStart',
262
- argsJson: JSON.stringify([null, relayOptions]),
263
- }));
631
+ const iterator = __getStreamIterator(stream);
264
632
  try {
265
- for await (const chunk of stream) {
633
+ await awaitStage(__call('resCall', JSON.stringify({
634
+ method: 'streamStart',
635
+ argsJson: JSON.stringify([null, relayOptions]),
636
+ })));
637
+ while (true) {
638
+ const next = await __nextStreamChunk(iterator, deadlineMs, idleTimeoutMs, timeoutMs);
639
+ if (next.done) break;
640
+ const chunk = next.value;
266
641
  let text = '';
267
642
  try { text = decoder ? decoder.decode(__streamChunkToBytes(chunk), { stream: true }) : ''; } catch {}
268
643
  await notifyObserver(text, 'chunk');
@@ -272,28 +647,38 @@ async function __streamResponseFromLocalReadable(stream, options) {
272
647
  try { endText = decoder ? decoder.decode() : ''; } catch {}
273
648
  await notifyObserver(endText, 'end');
274
649
  await relayChunk('', 'end', endText);
275
- await __call('resCall', JSON.stringify({ method: 'streamEnd' }));
650
+ await awaitStage(__call('resCall', JSON.stringify({ method: 'streamEnd' })));
276
651
  } catch (error) {
277
- try {
278
- await __call('resCall', JSON.stringify({
652
+ const cleanup = Promise.allSettled([
653
+ __closeStreamIterator(iterator),
654
+ __call('resCall', JSON.stringify({
279
655
  method: 'streamError',
280
656
  error: {
281
657
  message: error && error.message ? error.message : String(error),
282
658
  },
283
- }));
284
- } catch {}
285
- await notifyObserver('', 'error');
659
+ })),
660
+ notifyObserver('', 'error'),
661
+ ]);
662
+ if (__trustedNow() < deadlineMs) {
663
+ try { await awaitStage(cleanup); } catch {}
664
+ } else {
665
+ void cleanup;
666
+ }
286
667
  throw error;
287
668
  }
288
669
  }
289
670
 
290
671
  async function __drainPendingRuntimeTasks() {
672
+ let firstFailure;
291
673
  while (__pendingRuntimeTasks.length > 0) {
292
674
  const tasks = __pendingRuntimeTasks.splice(0, __pendingRuntimeTasks.length);
293
- const results = await Promise.allSettled(tasks);
294
- const failed = results.find((result) => result.status === 'rejected');
295
- if (failed) throw failed.reason;
675
+ const results = await __awaitTaskDeadline(Promise.allSettled(tasks));
676
+ if (firstFailure === undefined) {
677
+ const failed = results.find((result) => result.status === 'rejected');
678
+ if (failed) firstFailure = { reason: failed.reason };
679
+ }
296
680
  }
681
+ if (firstFailure !== undefined) throw firstFailure.reason;
297
682
  }
298
683
 
299
684
  async function __invokeRuntimeCallback(id, argsJson) {
@@ -302,26 +687,38 @@ async function __invokeRuntimeCallback(id, argsJson) {
302
687
  return JSON.stringify({ error: 'Package callback not found: ' + id });
303
688
  }
304
689
  try {
305
- const value = await fn(...JSON.parse(argsJson || '[]').map(__unwrapMainThreadPayload));
306
- return JSON.stringify({ value: await __encodeRuntimeArg(value) });
690
+ const value = await __awaitTaskDeadline(
691
+ fn(...JSON.parse(argsJson || '[]').map(__unwrapMainThreadPayload)),
692
+ );
693
+ return JSON.stringify({
694
+ value: await __awaitTaskDeadline(__encodeRuntimeArg(value)),
695
+ });
307
696
  } catch (error) {
697
+ if (
698
+ error?.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT'
699
+ || error?.code === 'ERR_EXECUTION_ABORTED'
700
+ ) {
701
+ throw error;
702
+ }
308
703
  return JSON.stringify({ error: error && error.message ? error.message : String(error) });
309
704
  }
310
705
  }
311
706
 
312
- const __safeCloneFailed = Symbol('__safeCloneFailed');
707
+ `});var tt=A((Nn,et)=>{"use strict";et.exports=`const __safeCloneFailed = Symbol('__safeCloneFailed');
313
708
 
314
709
  async function __safeClone(v, seen, cyclic) {
315
710
  if (!seen) {
316
711
  const cloned = await __safeClone(v, new WeakSet(), new WeakSet());
317
712
  return cloned === __safeCloneFailed ? null : cloned;
318
713
  }
319
- if (v === undefined) return undefined;
714
+ if (v === undefined) return { __e: 'u' };
715
+ if (typeof v === 'bigint') return { __bigint: v.toString() };
320
716
  let tracked = false;
321
717
  try {
322
718
  if (v && typeof v.then === 'function') {
323
- return await __safeClone(await v, seen, cyclic);
719
+ return await __safeClone(await __awaitTaskDeadline(v), seen, cyclic);
324
720
  }
721
+
325
722
  if (v && typeof v === 'object') {
326
723
  if (seen.has(v)) {
327
724
  cyclic.add(v);
@@ -331,6 +728,10 @@ async function __safeClone(v, seen, cyclic) {
331
728
  tracked = true;
332
729
  }
333
730
  if (v instanceof Date) return v.toISOString();
731
+ if (ArrayBuffer.isView(v)) return __encodeTypedArray(v);
732
+ if (v instanceof ArrayBuffer) {
733
+ return { __arrayBuffer: Array.from(new Uint8Array(v)) };
734
+ }
334
735
  if (v instanceof Set) {
335
736
  const out = [];
336
737
  for (const item of v.values()) {
@@ -340,12 +741,16 @@ async function __safeClone(v, seen, cyclic) {
340
741
  return cyclic.has(v) ? __safeCloneFailed : out;
341
742
  }
342
743
  if (v instanceof Map) {
343
- const out = {};
744
+ const entries = [];
344
745
  for (const [key, item] of v.entries()) {
345
- const cloned = await __safeClone(item, seen, cyclic);
346
- out[String(key)] = cloned === __safeCloneFailed ? null : cloned;
746
+ const clonedKey = await __safeClone(key, seen, cyclic);
747
+ const clonedValue = await __safeClone(item, seen, cyclic);
748
+ entries.push([
749
+ clonedKey === __safeCloneFailed ? null : clonedKey,
750
+ clonedValue === __safeCloneFailed ? null : clonedValue,
751
+ ]);
347
752
  }
348
- return cyclic.has(v) ? __safeCloneFailed : out;
753
+ return cyclic.has(v) ? __safeCloneFailed : { __map: entries };
349
754
  }
350
755
  if (Array.isArray(v)) {
351
756
  const out = [];
@@ -359,16 +764,32 @@ async function __safeClone(v, seen, cyclic) {
359
764
  const out = {};
360
765
  for (const key of Object.keys(v)) {
361
766
  const cloned = await __safeClone(v[key], seen, cyclic);
362
- out[key] = cloned === __safeCloneFailed ? null : cloned;
767
+ __defineDataProperty(
768
+ out,
769
+ key,
770
+ cloned === __safeCloneFailed ? null : cloned,
771
+ );
363
772
  }
364
- return cyclic.has(v) ? __safeCloneFailed : out;
773
+ if (cyclic.has(v)) return __safeCloneFailed;
774
+ if (Object.getPrototypeOf(v) === null) {
775
+ return { __nullPrototype: out };
776
+ }
777
+ return __collidesWithEnvelope(out) ? { __plainObject: out } : out;
365
778
  }
366
779
  if (typeof v === 'function' && v.__pkgHandlePromise) {
367
780
  return undefined;
368
781
  }
369
782
  return JSON.parse(JSON.stringify(v));
370
783
  }
371
- catch { return null; }
784
+ catch (error) {
785
+ if (
786
+ error?.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT'
787
+ || error?.code === 'ERR_EXECUTION_ABORTED'
788
+ ) {
789
+ throw error;
790
+ }
791
+ return null;
792
+ }
372
793
  finally {
373
794
  if (tracked) seen.delete(v);
374
795
  }
@@ -377,6 +798,7 @@ async function __safeClone(v, seen, cyclic) {
377
798
  const __ctxChangeProtectedKeys = new Set([
378
799
  '$helpers',
379
800
  '$cache',
801
+ '$transaction',
380
802
  '$repos',
381
803
  '$req',
382
804
  '$res',
@@ -386,6 +808,7 @@ const __ctxChangeProtectedKeys = new Set([
386
808
  '$throw',
387
809
  '$trigger',
388
810
  '$pkgs',
811
+ '$streams',
389
812
  '$env',
390
813
  ]);
391
814
 
@@ -413,42 +836,294 @@ async function __extractResult(result, isAbsent) {
413
836
 
414
837
  const __throwDefaults = { 400: 'Bad request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not found', 409: 'Conflict', 422: 'Validation failed', 429: 'Too many requests', 500: 'Internal server error', 503: 'Service unavailable' };
415
838
 
416
- if (typeof TextEncoder === 'undefined') {
839
+ `});var nt=A((On,rt)=>{"use strict";rt.exports=`if (typeof TextEncoder === 'undefined') {
417
840
  globalThis.TextEncoder = class TextEncoder {
841
+ get encoding() { return 'utf-8'; }
842
+
418
843
  encode(input = '') {
419
- const encoded = unescape(encodeURIComponent(String(input)));
420
- const out = new Uint8Array(encoded.length);
421
- for (let i = 0; i < encoded.length; i++) out[i] = encoded.charCodeAt(i);
422
- return out;
844
+ const text = String(input);
845
+ const bytes = [];
846
+ for (let i = 0; i < text.length; i++) {
847
+ let codePoint = text.charCodeAt(i);
848
+ if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
849
+ const next = text.charCodeAt(i + 1);
850
+ if (next >= 0xdc00 && next <= 0xdfff) {
851
+ codePoint = 0x10000 + ((codePoint - 0xd800) << 10) + (next - 0xdc00);
852
+ i++;
853
+ } else {
854
+ codePoint = 0xfffd;
855
+ }
856
+ } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
857
+ codePoint = 0xfffd;
858
+ }
859
+ if (codePoint <= 0x7f) {
860
+ bytes.push(codePoint);
861
+ } else if (codePoint <= 0x7ff) {
862
+ bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
863
+ } else if (codePoint <= 0xffff) {
864
+ bytes.push(
865
+ 0xe0 | (codePoint >> 12),
866
+ 0x80 | ((codePoint >> 6) & 0x3f),
867
+ 0x80 | (codePoint & 0x3f),
868
+ );
869
+ } else {
870
+ bytes.push(
871
+ 0xf0 | (codePoint >> 18),
872
+ 0x80 | ((codePoint >> 12) & 0x3f),
873
+ 0x80 | ((codePoint >> 6) & 0x3f),
874
+ 0x80 | (codePoint & 0x3f),
875
+ );
876
+ }
877
+ }
878
+ return Uint8Array.from(bytes);
879
+ }
880
+
881
+ encodeInto(input = '', destination) {
882
+ if (!(destination instanceof Uint8Array)) {
883
+ throw new TypeError('TextEncoder.encodeInto requires a Uint8Array destination');
884
+ }
885
+ const text = String(input);
886
+ let read = 0;
887
+ let written = 0;
888
+ for (const character of text) {
889
+ const encoded = this.encode(character);
890
+ if (written + encoded.byteLength > destination.byteLength) break;
891
+ destination.set(encoded, written);
892
+ written += encoded.byteLength;
893
+ read += character.length;
894
+ }
895
+ return { read, written };
423
896
  }
424
897
  };
425
898
  }
426
899
 
427
900
  if (typeof TextDecoder === 'undefined') {
428
901
  globalThis.TextDecoder = class TextDecoder {
429
- constructor() {
902
+ constructor(label = 'utf-8', options = {}) {
903
+ const normalizedLabel = String(label)
904
+ .replace(/^[\\t\\n\\f\\r ]+|[\\t\\n\\f\\r ]+$/g, '')
905
+ .toLowerCase();
906
+ if (![
907
+ 'utf-8',
908
+ 'utf8',
909
+ 'unicode-1-1-utf-8',
910
+ 'unicode11utf8',
911
+ 'unicode20utf8',
912
+ 'x-unicode20utf8',
913
+ ].includes(normalizedLabel)) {
914
+ throw new RangeError('Unsupported TextDecoder encoding: ' + label);
915
+ }
916
+ const normalizedOptions = options == null ? {} : options;
430
917
  this.__pending = new Uint8Array();
918
+ this.__fatal = Boolean(normalizedOptions.fatal);
919
+ this.__ignoreBOM = Boolean(normalizedOptions.ignoreBOM);
920
+ this.__atStart = true;
431
921
  }
432
922
 
923
+ get encoding() { return 'utf-8'; }
924
+ get fatal() { return this.__fatal; }
925
+ get ignoreBOM() { return this.__ignoreBOM; }
926
+
433
927
  decode(input = new Uint8Array(), options = {}) {
928
+ const normalizedOptions = options == null ? {} : options;
929
+ const stream = Boolean(normalizedOptions.stream);
930
+ if (!(input instanceof ArrayBuffer) && !ArrayBuffer.isView(input)) {
931
+ throw new TypeError('TextDecoder.decode requires an ArrayBuffer or ArrayBuffer view');
932
+ }
434
933
  const source = ArrayBuffer.isView(input) ? input : new Uint8Array(input);
435
934
  const bytes = new Uint8Array(this.__pending.length + source.byteLength);
436
935
  bytes.set(this.__pending);
437
- bytes.set(new Uint8Array(source.buffer, source.byteOffset, source.byteLength), this.__pending.length);
438
- let completeLength = bytes.length;
439
- if (options.stream) {
440
- let leadIndex = bytes.length - 1;
441
- while (leadIndex >= 0 && bytes[leadIndex] >= 0x80 && bytes[leadIndex] <= 0xbf) leadIndex--;
442
- if (leadIndex >= 0) {
443
- const lead = bytes[leadIndex];
444
- const expectedLength = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1;
445
- if (expectedLength > bytes.length - leadIndex) completeLength = leadIndex;
936
+ bytes.set(
937
+ new Uint8Array(source.buffer, source.byteOffset, source.byteLength),
938
+ this.__pending.length,
939
+ );
940
+ const output = [];
941
+ const emitReplacement = () => {
942
+ if (this.__fatal) {
943
+ if (!stream) { this.__pending = new Uint8Array(); this.__atStart = true; }
944
+ throw new TypeError('The encoded data was not valid UTF-8');
945
+ }
946
+ output.push('\uFFFD');
947
+ this.__atStart = false;
948
+ };
949
+ let index = 0;
950
+ while (index < bytes.length) {
951
+ const first = bytes[index];
952
+ let expectedLength = 0;
953
+ let codePoint = 0;
954
+ let minimum = 0;
955
+ if (first <= 0x7f) {
956
+ codePoint = first;
957
+ expectedLength = 1;
958
+ } else if (first >= 0xc2 && first <= 0xdf) {
959
+ expectedLength = 2;
960
+ codePoint = first & 0x1f;
961
+ minimum = 0x80;
962
+ } else if (first >= 0xe0 && first <= 0xef) {
963
+ expectedLength = 3;
964
+ codePoint = first & 0x0f;
965
+ minimum = 0x800;
966
+ } else if (first >= 0xf0 && first <= 0xf4) {
967
+ expectedLength = 4;
968
+ codePoint = first & 0x07;
969
+ minimum = 0x10000;
970
+ } else {
971
+ emitReplacement();
972
+ index++;
973
+ continue;
974
+ }
975
+ let availableLength = Math.min(expectedLength, bytes.length - index);
976
+ let validPrefixLength = 1;
977
+ let validPrefix = true;
978
+ for (let offset = 1; offset < availableLength; offset++) {
979
+ const continuation = bytes[index + offset];
980
+ if (continuation < 0x80 || continuation > 0xbf || (offset === 1 && (
981
+ (first === 0xe0 && continuation < 0xa0)
982
+ || (first === 0xed && continuation > 0x9f)
983
+ || (first === 0xf0 && continuation < 0x90)
984
+ || (first === 0xf4 && continuation > 0x8f)
985
+ ))) {
986
+ validPrefix = false;
987
+ break;
988
+ }
989
+ validPrefixLength++;
990
+ }
991
+ if (!validPrefix) {
992
+ emitReplacement();
993
+ index += validPrefixLength;
994
+ continue;
995
+ }
996
+ const second = availableLength > 1 ? bytes[index + 1] : 0;
997
+ if (
998
+ availableLength > 1
999
+ && (
1000
+ (first === 0xe0 && second < 0xa0)
1001
+ || (first === 0xed && second > 0x9f)
1002
+ || (first === 0xf0 && second < 0x90)
1003
+ || (first === 0xf4 && second > 0x8f)
1004
+ )
1005
+ ) {
1006
+ emitReplacement();
1007
+ index++;
1008
+ continue;
1009
+ }
1010
+ if (availableLength < expectedLength) {
1011
+ if (stream) break;
1012
+ emitReplacement();
1013
+ index += availableLength;
1014
+ continue;
446
1015
  }
1016
+ for (let offset = 1; offset < expectedLength; offset++) {
1017
+ codePoint = (codePoint << 6) | (bytes[index + offset] & 0x3f);
1018
+ }
1019
+ if (
1020
+ codePoint < minimum
1021
+ || codePoint > 0x10ffff
1022
+ || (codePoint >= 0xd800 && codePoint <= 0xdfff)
1023
+ ) {
1024
+ emitReplacement();
1025
+ index++;
1026
+ continue;
1027
+ }
1028
+ if (!(this.__atStart && !this.__ignoreBOM && codePoint === 0xfeff)) {
1029
+ output.push(String.fromCodePoint(codePoint));
1030
+ }
1031
+ this.__atStart = false;
1032
+ index += expectedLength;
447
1033
  }
448
- let binary = '';
449
- for (let i = 0; i < completeLength; i++) binary += String.fromCharCode(bytes[i]);
450
- this.__pending = options.stream ? bytes.slice(completeLength) : new Uint8Array();
451
- return decodeURIComponent(escape(binary));
1034
+ this.__pending = stream
1035
+ ? bytes.slice(index)
1036
+ : new Uint8Array();
1037
+ if (!stream) this.__atStart = true;
1038
+ return output.join('');
1039
+ }
1040
+ };
1041
+ }
1042
+
1043
+ `});var ot=A((In,at)=>{"use strict";at.exports=`const __blobStates = new WeakMap();
1044
+ const __fallbackFiles = new WeakSet();
1045
+
1046
+ function __normalizeBlobType(value) {
1047
+ const text = String(value === undefined ? '' : value);
1048
+ for (let index = 0; index < text.length; index++) {
1049
+ const code = text.charCodeAt(index);
1050
+ if (code < 0x20 || code > 0x7e) return '';
1051
+ }
1052
+ return text.toLowerCase();
1053
+ }
1054
+
1055
+ if (typeof Blob === 'undefined') {
1056
+ globalThis.Blob = class Blob {
1057
+ constructor(parts = [], options = {}) {
1058
+ const chunks = [];
1059
+ let totalBytes = 0;
1060
+ for (const part of parts) {
1061
+ let bytes;
1062
+ if (part instanceof Blob) {
1063
+ bytes = __blobStates.get(part).bytes;
1064
+ } else if (part instanceof ArrayBuffer) {
1065
+ bytes = new Uint8Array(part);
1066
+ } else if (ArrayBuffer.isView(part)) {
1067
+ bytes = new Uint8Array(part.buffer, part.byteOffset, part.byteLength);
1068
+ } else {
1069
+ bytes = new TextEncoder().encode(String(part));
1070
+ }
1071
+ const snapshot = new Uint8Array(bytes);
1072
+ chunks.push(snapshot);
1073
+ totalBytes += snapshot.byteLength;
1074
+ }
1075
+ const bytes = new Uint8Array(totalBytes);
1076
+ let offset = 0;
1077
+ for (const chunk of chunks) {
1078
+ bytes.set(chunk, offset);
1079
+ offset += chunk.byteLength;
1080
+ }
1081
+ __blobStates.set(this, {
1082
+ bytes,
1083
+ type: __normalizeBlobType(options?.type),
1084
+ });
1085
+ }
1086
+
1087
+ get size() {
1088
+ return __blobStates.get(this).bytes.byteLength;
1089
+ }
1090
+
1091
+ get type() {
1092
+ return __blobStates.get(this).type;
1093
+ }
1094
+
1095
+ async arrayBuffer() {
1096
+ return new Uint8Array(__blobStates.get(this).bytes).buffer;
1097
+ }
1098
+
1099
+ async text() {
1100
+ return new TextDecoder('utf-8').decode(__blobStates.get(this).bytes);
1101
+ }
1102
+
1103
+ slice(start = 0, end = this.size, contentType = '') {
1104
+ const size = this.size;
1105
+ const normalizeIndex = (value, fallback) => {
1106
+ const number = Number(value);
1107
+ if (Number.isNaN(number)) return 0;
1108
+ if (number === Infinity) return size;
1109
+ if (number === -Infinity) return 0;
1110
+ const integer = Math.trunc(number);
1111
+ return integer < 0
1112
+ ? Math.max(size + integer, 0)
1113
+ : Math.min(integer, size);
1114
+ };
1115
+ const relativeStart = normalizeIndex(start, 0);
1116
+ const relativeEnd = normalizeIndex(end, size);
1117
+ const span = Math.max(relativeEnd - relativeStart, 0);
1118
+ const bytes = __blobStates.get(this).bytes.slice(
1119
+ relativeStart,
1120
+ relativeStart + span,
1121
+ );
1122
+ return new Blob([bytes], { type: contentType });
1123
+ }
1124
+
1125
+ get [Symbol.toStringTag]() {
1126
+ return 'Blob';
452
1127
  }
453
1128
  };
454
1129
  }
@@ -459,8 +1134,41 @@ if (typeof FormData === 'undefined') {
459
1134
  this.__entries = [];
460
1135
  }
461
1136
 
462
- append(name, value) {
463
- this.__entries.push([String(name), value]);
1137
+ __normalizeValue(value, filename) {
1138
+ const isBlob = typeof Blob !== 'undefined' && value instanceof Blob;
1139
+ if (filename !== undefined && !isBlob) {
1140
+ throw new TypeError('FormData filename requires a Blob value');
1141
+ }
1142
+ if (!isBlob) return String(value);
1143
+ const resolvedFilename = filename === undefined ? 'blob' : String(filename);
1144
+ if (typeof File !== 'undefined') {
1145
+ if (value instanceof File && filename === undefined) return value;
1146
+ return new File([value], resolvedFilename, { type: value.type });
1147
+ }
1148
+ if (filename === undefined && __fallbackFiles.has(value)) return value;
1149
+ const blob = new Blob([value], { type: value.type });
1150
+ __fallbackFiles.add(blob);
1151
+ __defineDataProperty(blob, 'name', resolvedFilename);
1152
+ __defineDataProperty(
1153
+ blob,
1154
+ 'lastModified',
1155
+ value.lastModified === undefined ? 0 : value.lastModified,
1156
+ );
1157
+ return blob;
1158
+ }
1159
+
1160
+ append(name, value, filename) {
1161
+ this.__entries.push([
1162
+ String(name),
1163
+ this.__normalizeValue(value, filename),
1164
+ ]);
1165
+ }
1166
+
1167
+ delete(name) {
1168
+ const key = String(name);
1169
+ for (let index = this.__entries.length - 1; index >= 0; index--) {
1170
+ if (this.__entries[index][0] === key) this.__entries.splice(index, 1);
1171
+ }
464
1172
  }
465
1173
 
466
1174
  get(name) {
@@ -469,8 +1177,51 @@ if (typeof FormData === 'undefined') {
469
1177
  return match ? match[1] : null;
470
1178
  }
471
1179
 
472
- entries() {
473
- return this.__entries[Symbol.iterator]();
1180
+ getAll(name) {
1181
+ const key = String(name);
1182
+ return this.__entries
1183
+ .filter(([entryName]) => entryName === key)
1184
+ .map(([, value]) => value);
1185
+ }
1186
+
1187
+ has(name) {
1188
+ const key = String(name);
1189
+ return this.__entries.some(([entryName]) => entryName === key);
1190
+ }
1191
+
1192
+ set(name, value, filename) {
1193
+ const key = String(name);
1194
+ const normalized = this.__normalizeValue(value, filename);
1195
+ const next = [];
1196
+ let replaced = false;
1197
+ for (const entry of this.__entries) {
1198
+ if (entry[0] !== key) next.push(entry);
1199
+ else if (!replaced) {
1200
+ next.push([key, normalized]);
1201
+ replaced = true;
1202
+ }
1203
+ }
1204
+ if (!replaced) next.push([key, normalized]);
1205
+ this.__entries.length = 0;
1206
+ for (const entry of next) this.__entries.push(entry);
1207
+ }
1208
+
1209
+ *entries() {
1210
+ for (const [key, value] of this.__entries) yield [key, value];
1211
+ }
1212
+
1213
+ *keys() {
1214
+ for (const [key] of this.__entries) yield key;
1215
+ }
1216
+
1217
+ *values() {
1218
+ for (const [, value] of this.__entries) yield value;
1219
+ }
1220
+
1221
+ forEach(callback, thisArg) {
1222
+ for (const [key, value] of this.__entries) {
1223
+ callback.call(thisArg, value, key, this);
1224
+ }
474
1225
  }
475
1226
 
476
1227
  [Symbol.iterator]() {
@@ -479,38 +1230,216 @@ if (typeof FormData === 'undefined') {
479
1230
  };
480
1231
  }
481
1232
 
1233
+ `});var it=A((Un,st)=>{"use strict";st.exports=`function __decodeFormComponent(value) {
1234
+ const text = String(value).replace(/\\+/g, ' ');
1235
+ const bytes = [];
1236
+ for (let index = 0; index < text.length;) {
1237
+ if (
1238
+ text[index] === '%'
1239
+ && /^[0-9A-Fa-f]{2}$/.test(text.slice(index + 1, index + 3))
1240
+ ) {
1241
+ bytes.push(parseInt(text.slice(index + 1, index + 3), 16));
1242
+ index += 3;
1243
+ continue;
1244
+ }
1245
+ const codePoint = text.codePointAt(index);
1246
+ const encoded = new TextEncoder().encode(String.fromCodePoint(codePoint));
1247
+ bytes.push(...encoded);
1248
+ index += codePoint > 0xffff ? 2 : 1;
1249
+ }
1250
+ return new TextDecoder('utf-8', { ignoreBOM: true }).decode(Uint8Array.from(bytes));
1251
+ }
1252
+
1253
+ function __toUSVString(value) {
1254
+ const text = String(value);
1255
+ let output = '';
1256
+ for (let index = 0; index < text.length; index++) {
1257
+ const codeUnit = text.charCodeAt(index);
1258
+ if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {
1259
+ const next = text.charCodeAt(index + 1);
1260
+ if (next >= 0xdc00 && next <= 0xdfff) {
1261
+ output += text[index] + text[index + 1];
1262
+ index++;
1263
+ } else {
1264
+ output += '\uFFFD';
1265
+ }
1266
+ } else if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {
1267
+ output += '\uFFFD';
1268
+ } else {
1269
+ output += text[index];
1270
+ }
1271
+ }
1272
+ return output;
1273
+ }
1274
+
1275
+ function __encodeFormComponent(value) {
1276
+ return encodeURIComponent(__toUSVString(value))
1277
+ .replace(/[!'()~]/g, (character) =>
1278
+ '%' + character.charCodeAt(0).toString(16).toUpperCase(),
1279
+ )
1280
+ .replace(/%20/g, '+');
1281
+ }
1282
+
482
1283
  if (typeof URLSearchParams === 'undefined') {
483
1284
  globalThis.URLSearchParams = class URLSearchParams {
484
- constructor(input = '') {
1285
+ constructor(input = '', onChange) {
485
1286
  this.__entries = [];
486
- const inputText = String(input);
1287
+ this.__onChange = typeof onChange === 'function' ? onChange : null;
1288
+ if (input && typeof input !== 'string' && typeof input[Symbol.iterator] === 'function') {
1289
+ for (const entry of input) {
1290
+ if (!entry || typeof entry[Symbol.iterator] !== 'function') {
1291
+ throw new TypeError('URLSearchParams entry must be iterable');
1292
+ }
1293
+ const pair = Array.from(entry);
1294
+ if (pair.length !== 2) {
1295
+ throw new TypeError('URLSearchParams entry must contain two values');
1296
+ }
1297
+ this.__entries.push([
1298
+ __toUSVString(pair[0]),
1299
+ __toUSVString(pair[1]),
1300
+ ]);
1301
+ }
1302
+ return;
1303
+ }
1304
+ if (input && typeof input === 'object') {
1305
+ for (const [key, value] of Object.entries(input)) {
1306
+ this.__entries.push([
1307
+ __toUSVString(key),
1308
+ __toUSVString(value),
1309
+ ]);
1310
+ }
1311
+ return;
1312
+ }
1313
+ const inputText = input === null ? '' : String(input);
487
1314
  const text = inputText.startsWith('?') ? inputText.slice(1) : inputText;
488
1315
  if (!text) return;
489
1316
  for (const part of text.split('&')) {
490
1317
  if (!part) continue;
491
- const [key, value = ''] = part.split('=');
492
- this.append(decodeURIComponent(key), decodeURIComponent(value));
1318
+ const separator = part.indexOf('=');
1319
+ const key = separator >= 0 ? part.slice(0, separator) : part;
1320
+ const value = separator >= 0 ? part.slice(separator + 1) : '';
1321
+ this.__entries.push([
1322
+ __decodeFormComponent(key),
1323
+ __decodeFormComponent(value),
1324
+ ]);
493
1325
  }
494
1326
  }
495
1327
 
496
- append(name, value) {
497
- this.__entries.push([String(name), String(value)]);
1328
+ __changed() {
1329
+ this.__onChange?.(this.toString());
1330
+ }
1331
+
1332
+ __setChangeHandler(handler) {
1333
+ this.__onChange = typeof handler === 'function' ? handler : null;
1334
+ }
1335
+
1336
+ append(name, value) {
1337
+ this.__entries.push([
1338
+ __toUSVString(name),
1339
+ __toUSVString(value),
1340
+ ]);
1341
+ this.__changed();
1342
+ }
1343
+
1344
+ delete(name, value) {
1345
+ const key = __toUSVString(name);
1346
+ const normalizedValue = value === undefined ? null : __toUSVString(value);
1347
+ for (let index = this.__entries.length - 1; index >= 0; index--) {
1348
+ const [entryName, entryValue] = this.__entries[index];
1349
+ if (
1350
+ entryName === key
1351
+ && (normalizedValue === null || entryValue === normalizedValue)
1352
+ ) {
1353
+ this.__entries.splice(index, 1);
1354
+ }
1355
+ }
1356
+ this.__changed();
1357
+ }
1358
+
1359
+ set(name, value) {
1360
+ const key = __toUSVString(name);
1361
+ const normalizedValue = __toUSVString(value);
1362
+ const next = [];
1363
+ let replaced = false;
1364
+ for (const entry of this.__entries) {
1365
+ if (entry[0] !== key) {
1366
+ next.push(entry);
1367
+ } else if (!replaced) {
1368
+ next.push([key, normalizedValue]);
1369
+ replaced = true;
1370
+ }
1371
+ }
1372
+ if (!replaced) next.push([key, normalizedValue]);
1373
+ this.__entries.length = 0;
1374
+ for (const entry of next) this.__entries.push(entry);
1375
+ this.__changed();
1376
+ }
1377
+
1378
+ get(name) {
1379
+ const key = __toUSVString(name);
1380
+ const match = this.__entries.find(([entryName]) => entryName === key);
1381
+ return match ? match[1] : null;
1382
+ }
1383
+
1384
+ getAll(name) {
1385
+ const key = __toUSVString(name);
1386
+ return this.__entries
1387
+ .filter(([entryName]) => entryName === key)
1388
+ .map(([, value]) => value);
1389
+ }
1390
+
1391
+ has(name, value) {
1392
+ const key = __toUSVString(name);
1393
+ const normalizedValue = value === undefined ? null : __toUSVString(value);
1394
+ return this.__entries.some(([entryName, entryValue]) =>
1395
+ entryName === key
1396
+ && (normalizedValue === null || entryValue === normalizedValue),
1397
+ );
1398
+ }
1399
+
1400
+ sort() {
1401
+ const sorted = this.__entries
1402
+ .map((entry, index) => ({ entry, index }))
1403
+ .sort((left, right) => {
1404
+ let order = 0;
1405
+ if (left.entry[0] < right.entry[0]) order = -1;
1406
+ else if (left.entry[0] > right.entry[0]) order = 1;
1407
+ return order || left.index - right.index;
1408
+ })
1409
+ .map(({ entry }) => entry);
1410
+ this.__entries.length = 0;
1411
+ for (const entry of sorted) this.__entries.push(entry);
1412
+ this.__changed();
498
1413
  }
499
1414
 
500
- get(name) {
501
- const key = String(name);
502
- const match = this.__entries.find(([entryName]) => entryName === key);
503
- return match ? match[1] : null;
1415
+ get size() {
1416
+ return this.__entries.length;
504
1417
  }
505
1418
 
506
1419
  toString() {
507
1420
  return this.__entries
508
- .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))
1421
+ .map(([key, value]) =>
1422
+ __encodeFormComponent(key) + '=' + __encodeFormComponent(value),
1423
+ )
509
1424
  .join('&');
510
1425
  }
511
1426
 
512
- entries() {
513
- return this.__entries[Symbol.iterator]();
1427
+ *entries() {
1428
+ for (const [key, value] of this.__entries) yield [key, value];
1429
+ }
1430
+
1431
+ *keys() {
1432
+ for (const [key] of this.__entries) yield key;
1433
+ }
1434
+
1435
+ *values() {
1436
+ for (const [, value] of this.__entries) yield value;
1437
+ }
1438
+
1439
+ forEach(callback, thisArg) {
1440
+ for (const [key, value] of this.__entries) {
1441
+ callback.call(thisArg, value, key, this);
1442
+ }
514
1443
  }
515
1444
 
516
1445
  [Symbol.iterator]() {
@@ -519,49 +1448,176 @@ if (typeof URLSearchParams === 'undefined') {
519
1448
  };
520
1449
  }
521
1450
 
1451
+ `});var ct=A(($n,lt)=>{"use strict";lt.exports=`function __parseNativeUrl(input, base, mutation) {
1452
+ const result = __urlParseRef.applySync(
1453
+ undefined,
1454
+ [
1455
+ String(input),
1456
+ base === undefined ? undefined : String(base),
1457
+ mutation ? JSON.stringify(mutation) : null,
1458
+ ],
1459
+ { arguments: { copy: true }, result: { copy: true } },
1460
+ );
1461
+ return JSON.parse(result);
1462
+ }
1463
+
1464
+ const __urlStates = new WeakMap();
1465
+ const __urlSearchParamsOwners = new WeakMap();
1466
+ if (typeof URL === 'undefined' && typeof URLSearchParams.prototype.__setChangeHandler !== 'function') {
1467
+ for (const method of ['append', 'delete', 'set', 'sort']) {
1468
+ const intrinsic = URLSearchParams.prototype[method];
1469
+ Object.defineProperty(URLSearchParams.prototype, method, {
1470
+ value: function (...args) {
1471
+ const result = intrinsic.apply(this, args);
1472
+ const record = __urlSearchParamsOwners.get(this);
1473
+ if (record && !record.muted) {
1474
+ const serialized = record.serializeIntrinsic();
1475
+ record.state = __parseNativeUrl(record.state.href, undefined, {
1476
+ property: 'search', value: serialized ? '?' + serialized : '',
1477
+ });
1478
+ record.paramsSerialized = serialized;
1479
+ }
1480
+ return result;
1481
+ }, writable: true, configurable: true,
1482
+ });
1483
+ }
1484
+ }
1485
+
1486
+ function __getUrlState(url) {
1487
+ const record = __urlStates.get(url);
1488
+ if (!record) throw new TypeError('Illegal URL invocation');
1489
+ return record;
1490
+ }
1491
+
1492
+ function __replaceUrlSearchParams(url, search) {
1493
+ const record = __getUrlState(url);
1494
+ record.muted = true;
1495
+ try {
1496
+ const keys = Array.from(new Set(record.target.keys()));
1497
+ for (const key of keys) record.deleteIntrinsic(key);
1498
+ for (const [key, value] of new URLSearchParams(search)) {
1499
+ record.appendIntrinsic(key, value);
1500
+ }
1501
+ } finally {
1502
+ record.muted = false;
1503
+ }
1504
+ record.paramsSerialized = record.serializeIntrinsic();
1505
+ }
1506
+
1507
+ function __syncUrlSearchParams(url) {
1508
+ const record = __getUrlState(url);
1509
+ if (record.muted) return record;
1510
+ const serialized = record.serializeIntrinsic();
1511
+ if (record.paramsSerialized !== serialized) {
1512
+ const search = serialized ? '?' + serialized : '';
1513
+ record.state = __parseNativeUrl(record.state.href, undefined, {
1514
+ property: 'search',
1515
+ value: search,
1516
+ });
1517
+ record.paramsSerialized = serialized;
1518
+ }
1519
+ return record;
1520
+ }
1521
+
1522
+ function __applyUrlMutation(url, property, value) {
1523
+ const record = __syncUrlSearchParams(url);
1524
+ record.state = __parseNativeUrl(record.state.href, undefined, {
1525
+ property,
1526
+ value: __toUSVString(value),
1527
+ });
1528
+ __replaceUrlSearchParams(url, record.state.search);
1529
+ }
1530
+
522
1531
  if (typeof URL === 'undefined') {
523
1532
  globalThis.URL = class URL {
524
- constructor(input) {
525
- this.href = String(input);
526
- const schemeIndex = this.href.indexOf('://');
527
- if (schemeIndex >= 0) {
528
- const hostStart = schemeIndex + 3;
529
- const hostEndCandidates = ['/', '?', '#']
530
- .map((token) => this.href.indexOf(token, hostStart))
531
- .filter((index) => index >= 0);
532
- const hostEnd = hostEndCandidates.length ? Math.min(...hostEndCandidates) : this.href.length;
533
- this.host = this.href.slice(hostStart, hostEnd);
1533
+ constructor(input, base) {
1534
+ const state = __parseNativeUrl(input, base);
1535
+ const target = new URLSearchParams();
1536
+ const record = {
1537
+ state,
1538
+ target,
1539
+ muted: false,
1540
+ paramsSerialized: '',
1541
+ deleteIntrinsic: target.delete.bind(target),
1542
+ appendIntrinsic: target.append.bind(target),
1543
+ serializeIntrinsic: target.toString.bind(target),
1544
+ };
1545
+ __urlStates.set(this, record);
1546
+ if (typeof target.__setChangeHandler === 'function') {
1547
+ target.__setChangeHandler((serialized) => {
1548
+ if (record.muted) return;
1549
+ record.state = __parseNativeUrl(record.state.href, undefined, {
1550
+ property: 'search',
1551
+ value: serialized ? '?' + serialized : '',
1552
+ });
1553
+ record.paramsSerialized = serialized;
1554
+ });
534
1555
  } else {
535
- this.host = '';
1556
+ __urlSearchParamsOwners.set(target, record);
536
1557
  }
537
- const query = this.href.includes('?') ? this.href.slice(this.href.indexOf('?') + 1).split('#')[0] : '';
538
- this.search = query ? '?' + query : '';
539
- this.searchParams = new URLSearchParams(query);
1558
+ Object.defineProperty(this, 'searchParams', {
1559
+ value: target,
1560
+ writable: false,
1561
+ configurable: false,
1562
+ enumerable: true,
1563
+ });
1564
+ __replaceUrlSearchParams(this, state.search);
540
1565
  }
541
1566
 
542
- toString() {
543
- return this.href;
1567
+ get href() { return __syncUrlSearchParams(this).state.href; }
1568
+ set href(value) {
1569
+ const record = __getUrlState(this);
1570
+ record.state = __parseNativeUrl(value, undefined);
1571
+ __replaceUrlSearchParams(this, record.state.search);
544
1572
  }
1573
+ get origin() { return __syncUrlSearchParams(this).state.origin; }
1574
+ get protocol() { return __syncUrlSearchParams(this).state.protocol; }
1575
+ set protocol(value) { __applyUrlMutation(this, 'protocol', value); }
1576
+ get username() { return __syncUrlSearchParams(this).state.username; }
1577
+ set username(value) { __applyUrlMutation(this, 'username', value); }
1578
+ get password() { return __syncUrlSearchParams(this).state.password; }
1579
+ set password(value) { __applyUrlMutation(this, 'password', value); }
1580
+ get host() { return __syncUrlSearchParams(this).state.host; }
1581
+ set host(value) { __applyUrlMutation(this, 'host', value); }
1582
+ get hostname() { return __syncUrlSearchParams(this).state.hostname; }
1583
+ set hostname(value) { __applyUrlMutation(this, 'hostname', value); }
1584
+ get port() { return __syncUrlSearchParams(this).state.port; }
1585
+ set port(value) { __applyUrlMutation(this, 'port', value); }
1586
+ get pathname() { return __syncUrlSearchParams(this).state.pathname; }
1587
+ set pathname(value) { __applyUrlMutation(this, 'pathname', value); }
1588
+ get search() { return __syncUrlSearchParams(this).state.search; }
1589
+ set search(value) { __applyUrlMutation(this, 'search', value); }
1590
+ get hash() { return __syncUrlSearchParams(this).state.hash; }
1591
+ set hash(value) { __applyUrlMutation(this, 'hash', value); }
1592
+
1593
+ toString() { return this.href; }
1594
+ toJSON() { return this.href; }
545
1595
  };
546
1596
  }
547
1597
 
548
- function __createPkgHandleProxy(handlePromise, path) {
549
- const fn = function (...args) {
550
- return __createAsyncPkgResultProxy(
551
- handlePromise.then((handleId) =>
552
- __stringifyRuntimeArgs(args).then((argsJson) =>
553
- __call('pkgCall', __encodePkgCallPayload({ handleId, path, argsJson, kind: 'call' })),
554
- ),
555
- ),
556
- [],
557
- );
558
- };
1598
+ `});var dt=A((Bn,ut)=>{"use strict";ut.exports=`function __createPkgHandleProxy(handlePromise, path) {
1599
+ // The handle promise is created eagerly by the caller, so a script that drops
1600
+ // this proxy without awaiting it would leave the rejection unobserved and V8
1601
+ // would report it against the isolate, failing the next task on the lane.
1602
+ if (handlePromise && typeof handlePromise.catch === 'function') {
1603
+ handlePromise.catch(() => {});
1604
+ }
1605
+ const fn = () => {};
559
1606
  return new Proxy(fn, {
560
1607
  get: (_, prop) => {
1608
+ if (prop === Symbol.asyncIterator) {
1609
+ return () => __createPkgStreamIterator(
1610
+ handlePromise.then((handleId) => ({ handleId, path })),
1611
+ );
1612
+ }
561
1613
  if (typeof prop === 'symbol') return undefined;
562
1614
  if (prop === 'then') return undefined;
1615
+ if (prop === '$property') {
1616
+ return (key) => __createPkgHandleProxy(handlePromise, path.concat(key));
1617
+ }
563
1618
  if (prop === '__pkgHandle') return undefined;
564
1619
  if (prop === '__pkgHandlePromise') return handlePromise;
1620
+ if (prop === '__pkgHandlePath') return path;
565
1621
  if (prop === '__enfyraLocalReadable') return undefined;
566
1622
  return __createAsyncPkgResultProxy(
567
1623
  handlePromise.then((handleId) =>
@@ -586,12 +1642,16 @@ function __createPkgHandleProxy(handlePromise, path) {
586
1642
  });
587
1643
  }
588
1644
 
1645
+ function __formatResultPath(path) {
1646
+ return path.map((key) => String(key)).join('.');
1647
+ }
1648
+
589
1649
  function __resolvePkgResultPath(base, path) {
590
1650
  let current = base;
591
1651
  let receiver = undefined;
592
1652
  for (const key of path) {
593
1653
  if (current === undefined || current === null) {
594
- throw new Error('Package result property not found: ' + path.join('.'));
1654
+ throw new Error('Package result property not found: ' + __formatResultPath(path));
595
1655
  }
596
1656
  receiver = current;
597
1657
  current = current[key];
@@ -600,26 +1660,35 @@ function __resolvePkgResultPath(base, path) {
600
1660
  }
601
1661
 
602
1662
  function __createAsyncPkgResultProxy(valuePromise, path) {
1663
+ // Same reason as the main-result proxy: the host call behind this proxy is
1664
+ // issued eagerly, so a script that drops the proxy without reading it would
1665
+ // leave the rejection unobserved and V8 would report it against the isolate,
1666
+ // failing whichever task runs next on the lane.
1667
+ if (valuePromise && typeof valuePromise.catch === 'function') {
1668
+ valuePromise.catch(() => {});
1669
+ }
603
1670
  const resolveValue = () => valuePromise.then(__wrapPkgValue);
604
1671
  const resolvePath = () =>
605
1672
  resolveValue().then((base) => __resolvePkgResultPath(base, path));
606
1673
  const promiseForPath = () =>
607
1674
  path.length === 0 ? resolveValue() : resolvePath().then(({ target }) => target);
608
1675
 
609
- const fn = function (...args) {
610
- return __createAsyncPkgResultProxy(
611
- resolvePath().then(({ target, receiver }) => {
612
- if (typeof target !== 'function') {
613
- throw new Error('Package result is not callable: ' + (path.join('.') || '<root>'));
614
- }
615
- return Reflect.apply(target, receiver, args);
616
- }),
617
- [],
618
- );
619
- };
1676
+ const fn = () => {};
620
1677
 
621
1678
  return new Proxy(fn, {
622
1679
  get: (_target, prop) => {
1680
+ if (prop === Symbol.asyncIterator) {
1681
+ return () => __createPkgStreamIterator(
1682
+ promiseForPath().then(async (value) => {
1683
+ const handlePromise = value && value.__pkgHandlePromise;
1684
+ if (!handlePromise) throw new Error('Package result is not an async iterable');
1685
+ return {
1686
+ handleId: await handlePromise,
1687
+ path: value.__pkgHandlePath || [],
1688
+ };
1689
+ }),
1690
+ );
1691
+ }
623
1692
  if (typeof prop === 'symbol') return undefined;
624
1693
  if (prop === '__pkgHandle') return undefined;
625
1694
  if (prop === '__enfyraLocalReadable') return undefined;
@@ -646,13 +1715,19 @@ function __createAsyncPkgResultProxy(valuePromise, path) {
646
1715
  const promise = promiseForPath();
647
1716
  return promise.finally.bind(promise);
648
1717
  }
1718
+ if (prop === '$property') {
1719
+ return (key) => __createAsyncPkgResultProxy(
1720
+ valuePromise,
1721
+ path.concat(key),
1722
+ );
1723
+ }
649
1724
  return __createAsyncPkgResultProxy(valuePromise, path.concat(String(prop)));
650
1725
  },
651
1726
  apply: (_target, _thisArg, args) =>
652
1727
  __createAsyncPkgResultProxy(
653
1728
  resolvePath().then(({ target, receiver }) => {
654
1729
  if (typeof target !== 'function') {
655
- throw new Error('Package result is not callable: ' + (path.join('.') || '<root>'));
1730
+ throw new Error('Package result is not callable: ' + (__formatResultPath(path) || '<root>'));
656
1731
  }
657
1732
  return Reflect.apply(target, receiver, args);
658
1733
  }),
@@ -661,24 +1736,536 @@ function __createAsyncPkgResultProxy(valuePromise, path) {
661
1736
  });
662
1737
  }
663
1738
 
664
- function __createAsyncMainResultProxy(valuePromise, path) {
1739
+ `});var _t=A((Dn,ft)=>{"use strict";ft.exports=`const __pkgStreamNextWithTimeout = Symbol('enfyra.packageStreamNextWithTimeout');
1740
+ const __trustedStreamCleanupIterators = new WeakSet();
1741
+
1742
+ function __createPackageStreamError(message, code, details) {
1743
+ const error = new Error(message);
1744
+ if (code) error.code = code;
1745
+ if (details !== undefined) error.details = details;
1746
+ return error;
1747
+ }
1748
+
1749
+ function __unwrapPackageStreamResult(result) {
1750
+ if (result && result.__pkgStreamError) {
1751
+ const payload = result.__pkgStreamError;
1752
+ throw __createPackageStreamError(payload.message, payload.code, payload.details);
1753
+ }
1754
+ return result;
1755
+ }
1756
+
1757
+ function __createPkgStreamIterator(descriptorPromise) {
1758
+ let sessionPromise = null;
1759
+ let cleanupPromise = null;
1760
+ let closed = false;
1761
+ let pending = false;
1762
+
1763
+ const call = async (method, data) => {
1764
+ const result = await __call('pkgStreamCall', JSON.stringify({
1765
+ method,
1766
+ ...(data || {}),
1767
+ timeoutMs: __innerGuardTimeoutMs(),
1768
+ }));
1769
+ return __unwrapPackageStreamResult(result);
1770
+ };
1771
+ const open = () => {
1772
+ if (!sessionPromise) {
1773
+ sessionPromise = descriptorPromise.then(({ handleId, path }) =>
1774
+ call('open', { handleId, path: path || [] }).then((value) => value.streamId),
1775
+ );
1776
+ }
1777
+ return sessionPromise;
1778
+ };
1779
+
1780
+ const iterator = {
1781
+ async next() {
1782
+ return iterator[__pkgStreamNextWithTimeout]();
1783
+ },
1784
+ async [__pkgStreamNextWithTimeout](timeoutMs) {
1785
+ if (closed) return { done: true, value: undefined };
1786
+ if (pending) {
1787
+ throw __createPackageStreamError(
1788
+ 'Concurrent package stream next() calls are not supported',
1789
+ 'ERR_PACKAGE_STREAM_CONCURRENT_NEXT',
1790
+ );
1791
+ }
1792
+ pending = true;
1793
+ try {
1794
+ const streamId = await open();
1795
+ if (closed) return { done: true, value: undefined };
1796
+ const result = await call('next', {
1797
+ streamId,
1798
+ streamTimeoutMs: timeoutMs,
1799
+ });
1800
+ if (closed || result.done) {
1801
+ closed = true;
1802
+ return { done: true, value: undefined };
1803
+ }
1804
+ return { done: false, value: __base64ToBytes(result.chunk) };
1805
+ } catch (error) {
1806
+ try { await iterator.return(); } catch {}
1807
+ throw error;
1808
+ } finally {
1809
+ pending = false;
1810
+ }
1811
+ },
1812
+ return() {
1813
+ if (cleanupPromise) return cleanupPromise;
1814
+ closed = true;
1815
+ cleanupPromise = sessionPromise
1816
+ ? sessionPromise.then(
1817
+ (streamId) => call('return', { streamId }),
1818
+ () => undefined,
1819
+ ).then(() => ({ done: true, value: undefined }))
1820
+ : Promise.resolve({ done: true, value: undefined });
1821
+ cleanupPromise.catch(() => {});
1822
+ return cleanupPromise;
1823
+ },
1824
+ [Symbol.asyncIterator]() {
1825
+ return this;
1826
+ },
1827
+ };
1828
+ __trustedStreamCleanupIterators.add(iterator);
1829
+ return iterator;
1830
+ }
1831
+
1832
+ function __getStreamIterator(readable) {
1833
+ const iteratorMethod = readable?.[Symbol.asyncIterator];
1834
+ if (typeof iteratorMethod !== 'function') {
1835
+ throw new Error('$streams requires an async iterable readable stream');
1836
+ }
1837
+ return iteratorMethod.call(readable);
1838
+ }
1839
+
1840
+ function __requestStreamReturn(iterator) {
1841
+ try {
1842
+ const result = iterator?.return?.();
1843
+ if (result && typeof result.catch === 'function') result.catch(() => {});
1844
+ } catch {}
1845
+ }
1846
+
1847
+ async function __closeStreamIterator(iterator) {
1848
+ const returnMethod = iterator?.return;
1849
+ if (typeof returnMethod !== 'function') return;
1850
+ if (__trustedStreamCleanupIterators.has(iterator)) {
1851
+ try { await returnMethod.call(iterator); } catch {}
1852
+ return;
1853
+ }
1854
+ __requestStreamReturn(iterator);
1855
+ }
1856
+
1857
+ function __normalizeStreamOptions(options) {
1858
+ const requestedTimeoutMs = Number(options?.timeoutMs);
1859
+ const timeoutMs = Number.isFinite(requestedTimeoutMs)
1860
+ ? Math.max(1, Math.trunc(requestedTimeoutMs))
1861
+ : 30000;
1862
+ const requestedIdleTimeoutMs = Number(options?.idleTimeoutMs);
1863
+ const idleTimeoutMs = Number.isFinite(requestedIdleTimeoutMs) && requestedIdleTimeoutMs > 0
1864
+ ? Math.max(1, Math.trunc(requestedIdleTimeoutMs))
1865
+ : null;
1866
+ const requestedMaxBytes = Number(options?.maxBytes);
1867
+ const maxBytes = Number.isFinite(requestedMaxBytes) && requestedMaxBytes > 0
1868
+ ? Math.max(1, Math.trunc(requestedMaxBytes))
1869
+ : 8 * 1024 * 1024;
1870
+ return { timeoutMs, idleTimeoutMs, maxBytes };
1871
+ }
1872
+
1873
+ function __streamTimeoutError(timeoutMs, details) {
1874
+ return __createPackageStreamError(
1875
+ 'Package stream timed out after ' + Math.max(1, Math.trunc(timeoutMs)) + 'ms',
1876
+ 'ERR_PACKAGE_STREAM_TIMEOUT',
1877
+ { streamScoped: true, retryable: true, ...(details || {}) },
1878
+ );
1879
+ }
1880
+
1881
+ async function __waitForStreamTimer(timerId, timeoutMs) {
1882
+ return await __streamTimerRef.apply(
1883
+ undefined,
1884
+ ['wait', timerId, timeoutMs],
1885
+ __applyOpts,
1886
+ );
1887
+ }
1888
+
1889
+ async function __clearStreamTimer(timerId) {
1890
+ return await __streamTimerRef.apply(
1891
+ undefined,
1892
+ ['clear', timerId, 0],
1893
+ __applyOpts,
1894
+ );
1895
+ }
1896
+
1897
+ async function __nextStreamChunk(
1898
+ iterator,
1899
+ deadlineMs,
1900
+ idleTimeoutMs,
1901
+ totalTimeoutMs,
1902
+ ) {
1903
+ const remainingMs = Math.ceil(deadlineMs - __trustedNow());
1904
+ if (remainingMs <= 0) {
1905
+ throw __streamTimeoutError(totalTimeoutMs, { timeoutKind: 'total' });
1906
+ }
1907
+ const nextTimeoutMs = Math.min(
1908
+ remainingMs,
1909
+ Number.isFinite(idleTimeoutMs) && idleTimeoutMs > 0
1910
+ ? Math.max(1, Math.trunc(idleTimeoutMs))
1911
+ : remainingMs,
1912
+ );
1913
+ const timerId = 'stream_timer_' + (++__streamTimerCounter);
1914
+ try {
1915
+ const result = await Promise.race([
1916
+ Promise.resolve().then(() => typeof iterator[__pkgStreamNextWithTimeout] === 'function'
1917
+ ? iterator[__pkgStreamNextWithTimeout](nextTimeoutMs)
1918
+ : iterator.next()),
1919
+ __waitForStreamTimer(timerId, nextTimeoutMs).then((fired) => {
1920
+ if (!fired) {
1921
+ const error = new Error('Task is no longer active');
1922
+ error.code = 'ERR_EXECUTION_ABORTED';
1923
+ throw error;
1924
+ }
1925
+ throw __streamTimeoutError(
1926
+ nextTimeoutMs < remainingMs ? nextTimeoutMs : totalTimeoutMs,
1927
+ { timeoutKind: nextTimeoutMs < remainingMs ? 'idle' : 'total' },
1928
+ );
1929
+ }),
1930
+ ]);
1931
+ if (__trustedNow() >= deadlineMs) {
1932
+ throw __streamTimeoutError(totalTimeoutMs, { timeoutKind: 'total' });
1933
+ }
1934
+ return result;
1935
+ } catch (error) {
1936
+ __requestStreamReturn(iterator);
1937
+ throw error;
1938
+ } finally {
1939
+ void __clearStreamTimer(timerId).catch(() => {});
1940
+ }
1941
+ }
1942
+
1943
+ `});var mt=A((Ln,pt)=>{"use strict";pt.exports=`async function __preflightStream(readable, options) {
1944
+ const iterator = __getStreamIterator(readable);
1945
+ const { timeoutMs, idleTimeoutMs } = __normalizeStreamOptions(options);
1946
+ const requestedMaxFirstChunkBytes = Number(options?.maxFirstChunkBytes);
1947
+ const maxFirstChunkBytes = Number.isFinite(requestedMaxFirstChunkBytes)
1948
+ && requestedMaxFirstChunkBytes > 0
1949
+ ? Math.max(1, Math.trunc(requestedMaxFirstChunkBytes))
1950
+ : null;
1951
+ const deadlineMs = __trustedNow() + Math.min(timeoutMs, __innerGuardTimeoutMs());
1952
+ let firstChunk;
1953
+ try {
1954
+ while (firstChunk === undefined) {
1955
+ const next = await __nextStreamChunk(
1956
+ iterator,
1957
+ deadlineMs,
1958
+ idleTimeoutMs,
1959
+ timeoutMs,
1960
+ );
1961
+ if (next.done) {
1962
+ throw __createPackageStreamError(
1963
+ 'Package stream ended before yielding bytes',
1964
+ 'ERR_PACKAGE_STREAM_EMPTY',
1965
+ );
1966
+ }
1967
+ const bytes = __streamChunkToBytes(next.value);
1968
+ if (bytes.byteLength > 0) {
1969
+ if (maxFirstChunkBytes !== null && bytes.byteLength > maxFirstChunkBytes) {
1970
+ throw __createPackageStreamError(
1971
+ 'Package stream first chunk exceeded maxFirstChunkBytes (' + maxFirstChunkBytes + ')',
1972
+ 'ERR_PACKAGE_STREAM_MAX_BYTES',
1973
+ { maxBytes: maxFirstChunkBytes, firstChunk: true },
1974
+ );
1975
+ }
1976
+ firstChunk = bytes;
1977
+ }
1978
+ }
1979
+ } catch (error) {
1980
+ await __closeStreamIterator(iterator);
1981
+ throw error;
1982
+ }
1983
+
1984
+ let consumed = false;
1985
+ let closed = false;
1986
+ let cleanupPromise = null;
1987
+ let nextQueue = Promise.resolve();
1988
+ let firstPending = true;
1989
+ const close = () => {
1990
+ if (cleanupPromise) return cleanupPromise;
1991
+ closed = true;
1992
+ cleanupPromise = (async () => {
1993
+ await __closeStreamIterator(iterator);
1994
+ return { done: true, value: undefined };
1995
+ })();
1996
+ return cleanupPromise;
1997
+ };
1998
+ const replayIterator = {
1999
+ next() {
2000
+ const operation = nextQueue.then(async () => {
2001
+ if (closed) return { done: true, value: undefined };
2002
+ if (firstPending) {
2003
+ firstPending = false;
2004
+ return { done: false, value: firstChunk };
2005
+ }
2006
+ try {
2007
+ const next = await __nextStreamChunk(iterator, deadlineMs, idleTimeoutMs, timeoutMs);
2008
+ if (closed || next.done) {
2009
+ closed = true;
2010
+ return { done: true, value: undefined };
2011
+ }
2012
+ return { done: false, value: __streamChunkToBytes(next.value) };
2013
+ } catch (error) {
2014
+ await close();
2015
+ throw error;
2016
+ }
2017
+ });
2018
+ nextQueue = operation.catch(() => {});
2019
+ return operation;
2020
+ },
2021
+ return: close,
2022
+ [Symbol.asyncIterator]() { return this; },
2023
+ };
2024
+ if (__trustedStreamCleanupIterators.has(iterator)) {
2025
+ __trustedStreamCleanupIterators.add(replayIterator);
2026
+ }
2027
+ const stream = {
2028
+ __enfyraLocalReadable: true,
2029
+ __enfyraCancel: close,
2030
+ [Symbol.asyncIterator]() {
2031
+ if (consumed) {
2032
+ throw __createPackageStreamError(
2033
+ 'Preflight stream already has a consumer',
2034
+ 'ERR_PACKAGE_STREAM_ALREADY_CONSUMED',
2035
+ );
2036
+ }
2037
+ consumed = true;
2038
+ return replayIterator;
2039
+ },
2040
+ };
2041
+ return {
2042
+ stream,
2043
+ firstChunk: new Uint8Array(firstChunk),
2044
+ cancel: close,
2045
+ };
2046
+ }
2047
+
2048
+ async function __readStream(readable, options, asText) {
2049
+ const iterator = __getStreamIterator(readable);
2050
+ const { timeoutMs, idleTimeoutMs, maxBytes } = __normalizeStreamOptions(options);
2051
+ const deadlineMs = __trustedNow() + Math.min(timeoutMs, __innerGuardTimeoutMs());
2052
+ const chunks = [];
2053
+ const text = [];
2054
+ const decoder = asText ? new TextDecoder('utf-8') : null;
2055
+ let totalBytes = 0;
2056
+ try {
2057
+ while (true) {
2058
+ const next = await __nextStreamChunk(iterator, deadlineMs, idleTimeoutMs, timeoutMs);
2059
+ if (next.done) break;
2060
+ const bytes = __streamChunkToBytes(next.value);
2061
+ if (bytes.byteLength === 0) continue;
2062
+ totalBytes += bytes.byteLength;
2063
+ if (totalBytes > maxBytes) {
2064
+ throw __createPackageStreamError(
2065
+ 'Package stream exceeded maxBytes (' + maxBytes + ')',
2066
+ 'ERR_PACKAGE_STREAM_MAX_BYTES',
2067
+ { maxBytes },
2068
+ );
2069
+ }
2070
+ if (decoder) {
2071
+ text.push(decoder.decode(bytes, { stream: true }));
2072
+ } else {
2073
+ chunks.push(new Uint8Array(bytes));
2074
+ }
2075
+ }
2076
+ } catch (error) {
2077
+ await __closeStreamIterator(iterator);
2078
+ throw error;
2079
+ }
2080
+ if (decoder) {
2081
+ text.push(decoder.decode());
2082
+ return text.join('');
2083
+ }
2084
+ const output = new Uint8Array(totalBytes);
2085
+ let offset = 0;
2086
+ for (const chunk of chunks) {
2087
+ output.set(chunk, offset);
2088
+ offset += chunk.byteLength;
2089
+ }
2090
+ return output;
2091
+ }
2092
+
2093
+ function __guardStream(readable, options) {
2094
+ const { timeoutMs, idleTimeoutMs, maxBytes } = __normalizeStreamOptions(options);
2095
+ let consumed = false;
2096
+ const iterator = __getStreamIterator(readable);
2097
+ let closed = false;
2098
+ let cleanupPromise = null;
2099
+ const close = () => {
2100
+ if (cleanupPromise) return cleanupPromise;
2101
+ closed = true;
2102
+ cleanupPromise = (async () => {
2103
+ await __closeStreamIterator(iterator);
2104
+ return { done: true, value: undefined };
2105
+ })();
2106
+ return cleanupPromise;
2107
+ };
2108
+ return {
2109
+ __enfyraLocalReadable: true,
2110
+ __enfyraCancel: close,
2111
+ [Symbol.asyncIterator]() {
2112
+ if (consumed) {
2113
+ throw __createPackageStreamError(
2114
+ 'Guarded stream already has a consumer',
2115
+ 'ERR_PACKAGE_STREAM_ALREADY_CONSUMED',
2116
+ );
2117
+ }
2118
+ consumed = true;
2119
+ const deadlineMs = __trustedNow() + Math.min(timeoutMs, __innerGuardTimeoutMs());
2120
+ let totalBytes = 0;
2121
+ let nextQueue = Promise.resolve();
2122
+ const guardedIterator = {
2123
+ next() {
2124
+ const operation = nextQueue.then(async () => {
2125
+ if (closed) return { done: true, value: undefined };
2126
+ try {
2127
+ const next = await __nextStreamChunk(iterator, deadlineMs, idleTimeoutMs, timeoutMs);
2128
+ if (closed || next.done) {
2129
+ closed = true;
2130
+ return { done: true, value: undefined };
2131
+ }
2132
+ const bytes = __streamChunkToBytes(next.value);
2133
+ totalBytes += bytes.byteLength;
2134
+ if (totalBytes > maxBytes) {
2135
+ throw __createPackageStreamError(
2136
+ 'Package stream exceeded maxBytes (' + maxBytes + ')',
2137
+ 'ERR_PACKAGE_STREAM_MAX_BYTES',
2138
+ { maxBytes },
2139
+ );
2140
+ }
2141
+ return { done: false, value: next.value };
2142
+ } catch (error) {
2143
+ await close();
2144
+ throw error;
2145
+ }
2146
+ });
2147
+ nextQueue = operation.catch(() => {});
2148
+ return operation;
2149
+ },
2150
+ return: close,
2151
+ [Symbol.asyncIterator]() { return this; },
2152
+ };
2153
+ if (__trustedStreamCleanupIterators.has(iterator)) {
2154
+ __trustedStreamCleanupIterators.add(guardedIterator);
2155
+ }
2156
+ return guardedIterator;
2157
+ },
2158
+ };
2159
+ }
2160
+
2161
+ async function __cancelStream(readable) {
2162
+ if (!readable) return;
2163
+ if (readable.__enfyraLocalReadable && typeof readable.__enfyraCancel === 'function') {
2164
+ await readable.__enfyraCancel();
2165
+ return;
2166
+ }
2167
+ const iterator = __getStreamIterator(readable);
2168
+ await __closeStreamIterator(iterator);
2169
+ }
2170
+
2171
+ function __tapStream(readable, options) {
2172
+ const onChunk = typeof options?.onChunk === 'function' ? options.onChunk : null;
2173
+ const { timeoutMs } = __normalizeStreamOptions(options);
2174
+ let consumed = false;
2175
+ let closed = false;
2176
+ let cleanupPromise = null;
2177
+ let iterator = null;
2178
+ let totalBytes = 0;
2179
+ let nextQueue = Promise.resolve();
2180
+ const close = () => {
2181
+ if (cleanupPromise) return cleanupPromise;
2182
+ closed = true;
2183
+ cleanupPromise = (async () => {
2184
+ if (iterator) await __closeStreamIterator(iterator);
2185
+ else await __cancelStream(readable);
2186
+ return { done: true, value: undefined };
2187
+ })();
2188
+ return cleanupPromise;
2189
+ };
2190
+ return {
2191
+ __enfyraLocalReadable: true,
2192
+ __enfyraCancel: close,
2193
+ [Symbol.asyncIterator]() {
2194
+ if (consumed) {
2195
+ throw __createPackageStreamError(
2196
+ 'Tapped stream already has a consumer',
2197
+ 'ERR_PACKAGE_STREAM_ALREADY_CONSUMED',
2198
+ );
2199
+ }
2200
+ consumed = true;
2201
+ if (!closed) {
2202
+ const guarded = __guardStream(readable, options);
2203
+ iterator = __getStreamIterator(guarded);
2204
+ }
2205
+ const deadlineMs = __trustedNow() + Math.min(
2206
+ timeoutMs,
2207
+ __innerGuardTimeoutMs(),
2208
+ );
2209
+ const tappedIterator = {
2210
+ next() {
2211
+ const operation = nextQueue.then(async () => {
2212
+ if (closed) return { done: true, value: undefined };
2213
+ try {
2214
+ const next = await iterator.next();
2215
+ if (closed || next.done) {
2216
+ closed = true;
2217
+ return { done: true, value: undefined };
2218
+ }
2219
+ const bytes = __streamChunkToBytes(next.value);
2220
+ totalBytes += bytes.byteLength;
2221
+ if (onChunk) {
2222
+ await __awaitBeforeDeadline(
2223
+ onChunk(new Uint8Array(bytes), totalBytes),
2224
+ deadlineMs,
2225
+ () => __streamTimeoutError(
2226
+ timeoutMs,
2227
+ { timeoutKind: 'total' },
2228
+ ),
2229
+ );
2230
+ }
2231
+ if (closed) return { done: true, value: undefined };
2232
+ return next;
2233
+ } catch (error) {
2234
+ await close();
2235
+ throw error;
2236
+ }
2237
+ });
2238
+ nextQueue = operation.catch(() => {});
2239
+ return operation;
2240
+ },
2241
+ return: close,
2242
+ [Symbol.asyncIterator]() { return this; },
2243
+ };
2244
+ if (__trustedStreamCleanupIterators.has(iterator)) {
2245
+ __trustedStreamCleanupIterators.add(tappedIterator);
2246
+ }
2247
+ return tappedIterator;
2248
+ },
2249
+ };
2250
+ }
2251
+
2252
+ `});var ht=A((Fn,yt)=>{"use strict";yt.exports=`function __createAsyncMainResultProxy(valuePromise, path) {
2253
+ // The proxy is lazy: a script that ignores a package/helper call never reads
2254
+ // its then method, so nothing would observe a rejection here and V8 would
2255
+ // report it as an unhandled rejection of the isolate, failing whichever task
2256
+ // runs next on the lane. Marking the source promise keeps the rejection
2257
+ // observable for a script that awaits the proxy without letting an ignored
2258
+ // call escape.
2259
+ if (valuePromise && typeof valuePromise.catch === 'function') {
2260
+ valuePromise.catch(() => {});
2261
+ }
665
2262
  const resolveValue = () => valuePromise;
666
2263
  const resolvePath = () =>
667
2264
  resolveValue().then((base) => __resolvePkgResultPath(base, path));
668
2265
  const promiseForPath = () =>
669
2266
  path.length === 0 ? resolveValue() : resolvePath().then(({ target }) => target);
670
2267
 
671
- const fn = function (...args) {
672
- return __createAsyncMainResultProxy(
673
- resolvePath().then(({ target, receiver }) => {
674
- if (typeof target !== 'function') {
675
- throw new Error('Async result is not callable: ' + (path.join('.') || '<root>'));
676
- }
677
- return Reflect.apply(target, receiver, args);
678
- }),
679
- [],
680
- );
681
- };
2268
+ const fn = () => {};
682
2269
 
683
2270
  return new Proxy(fn, {
684
2271
  get: (_target, prop) => {
@@ -694,13 +2281,19 @@ function __createAsyncMainResultProxy(valuePromise, path) {
694
2281
  const promise = promiseForPath();
695
2282
  return promise.finally.bind(promise);
696
2283
  }
697
- return __createAsyncMainResultProxy(valuePromise, path.concat(String(prop)));
2284
+ if (prop === '$property') {
2285
+ return (key) => __createAsyncMainResultProxy(
2286
+ valuePromise,
2287
+ path.concat(key),
2288
+ );
2289
+ }
2290
+ return __createAsyncMainResultProxy(valuePromise, path.concat(prop));
698
2291
  },
699
2292
  apply: (_target, _thisArg, args) =>
700
2293
  __createAsyncMainResultProxy(
701
2294
  resolvePath().then(({ target, receiver }) => {
702
2295
  if (typeof target !== 'function') {
703
- throw new Error('Async result is not callable: ' + (path.join('.') || '<root>'));
2296
+ throw new Error('Async result is not callable: ' + (__formatResultPath(path) || '<root>'));
704
2297
  }
705
2298
  return Reflect.apply(target, receiver, args);
706
2299
  }),
@@ -717,14 +2310,14 @@ function __wrapPkgValue(value) {
717
2310
  }
718
2311
 
719
2312
  function __createPkgProxy(packageName, path) {
720
- const fn = function (...args) {
2313
+ const fn = (function (...args) {
721
2314
  return __createAsyncPkgResultProxy(
722
2315
  __stringifyRuntimeArgs(args).then((argsJson) =>
723
2316
  __call('pkgCall', __encodePkgCallPayload({ packageName, path, argsJson, kind: 'call' })),
724
2317
  ),
725
2318
  [],
726
2319
  );
727
- };
2320
+ }).bind(null);
728
2321
  return new Proxy(fn, {
729
2322
  get: (_, prop) => {
730
2323
  if (prop === 'then') return undefined;
@@ -753,35 +2346,112 @@ function __createPkgProxy(packageName, path) {
753
2346
  }
754
2347
 
755
2348
  function __createReadableFrom(input) {
2349
+ let consumed = false;
2350
+ let sourceIterator = null;
2351
+ let closed = false;
2352
+ let cleanupPromise = null;
2353
+ let nextQueue = Promise.resolve();
2354
+ const close = () => {
2355
+ if (cleanupPromise) return cleanupPromise;
2356
+ closed = true;
2357
+ cleanupPromise = (async () => {
2358
+ if (sourceIterator) await __closeStreamIterator(sourceIterator);
2359
+ return { done: true, value: undefined };
2360
+ })();
2361
+ return cleanupPromise;
2362
+ };
756
2363
  const stream = {
757
2364
  __enfyraLocalReadable: true,
758
- async *[Symbol.asyncIterator]() {
759
- if (input && typeof input[Symbol.asyncIterator] === 'function') {
760
- for await (const chunk of input) yield chunk;
761
- return;
2365
+ __enfyraCancel: close,
2366
+ [Symbol.asyncIterator]() {
2367
+ if (consumed) {
2368
+ throw __createPackageStreamError(
2369
+ 'Readable.from stream already has a consumer',
2370
+ 'ERR_PACKAGE_STREAM_ALREADY_CONSUMED',
2371
+ );
762
2372
  }
763
- if (input && typeof input[Symbol.iterator] === 'function' && typeof input !== 'string') {
764
- for (const chunk of input) yield chunk;
765
- return;
2373
+ consumed = true;
2374
+ if (!closed) {
2375
+ if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) {
2376
+ let pending = true;
2377
+ sourceIterator = {
2378
+ next() {
2379
+ if (!pending) return { done: true, value: undefined };
2380
+ pending = false;
2381
+ return { done: false, value: input };
2382
+ },
2383
+ };
2384
+ } else if (input && typeof input[Symbol.asyncIterator] === 'function') {
2385
+ sourceIterator = input[Symbol.asyncIterator]();
2386
+ } else if (
2387
+ input
2388
+ && typeof input[Symbol.iterator] === 'function'
2389
+ && typeof input !== 'string'
2390
+ ) {
2391
+ sourceIterator = input[Symbol.iterator]();
2392
+ } else {
2393
+ let pending = true;
2394
+ sourceIterator = {
2395
+ next() {
2396
+ if (!pending) return { done: true, value: undefined };
2397
+ pending = false;
2398
+ return { done: false, value: input };
2399
+ },
2400
+ };
2401
+ }
766
2402
  }
767
- yield input;
2403
+ const iterator = {
2404
+ next() {
2405
+ const operation = nextQueue.then(async () => {
2406
+ if (closed || !sourceIterator) {
2407
+ return { done: true, value: undefined };
2408
+ }
2409
+ try {
2410
+ const next = await sourceIterator.next();
2411
+ if (closed || next.done) {
2412
+ closed = true;
2413
+ return { done: true, value: undefined };
2414
+ }
2415
+ const value = await next.value;
2416
+ if (closed) return { done: true, value: undefined };
2417
+ return { done: false, value };
2418
+ } catch (error) {
2419
+ await close();
2420
+ throw error;
2421
+ }
2422
+ });
2423
+ nextQueue = operation.catch(() => {});
2424
+ return operation;
2425
+ },
2426
+ return: close,
2427
+ [Symbol.asyncIterator]() { return this; },
2428
+ };
2429
+ if (__trustedStreamCleanupIterators.has(sourceIterator)) {
2430
+ __trustedStreamCleanupIterators.add(iterator);
2431
+ }
2432
+ return iterator;
768
2433
  },
769
2434
  };
770
2435
  return stream;
771
2436
  }
772
2437
 
773
- const __builtinModules = {
2438
+ const __builtinModules = Object.create(null);
2439
+ Object.assign(__builtinModules, {
774
2440
  stream: {
775
2441
  Readable: {
776
2442
  from: __createReadableFrom,
777
2443
  },
778
2444
  },
779
- };
2445
+ });
780
2446
  __builtinModules['node:stream'] = __builtinModules.stream;
781
2447
 
782
2448
  const require = (name) => {
783
- if (__builtinModules[name] !== undefined) return __builtinModules[name];
784
- if ($pkgs[name] === undefined) throw new Error('Module "' + name + '" is not available. Install it via Settings \\u2192 Packages');
2449
+ if (Object.prototype.hasOwnProperty.call(__builtinModules, name)) {
2450
+ return __builtinModules[name];
2451
+ }
2452
+ if (!Object.prototype.hasOwnProperty.call($pkgs, name)) {
2453
+ throw new Error('Module "' + name + '" is not available. Install it via Settings \\u2192 Packages');
2454
+ }
785
2455
  return $pkgs[name];
786
2456
  };
787
2457
 
@@ -792,104 +2462,281 @@ const console = {
792
2462
  info: (...a) => $ctx.$logs(...a),
793
2463
  };
794
2464
 
795
- function __resetTask(snapshot, taskId, timeoutMs, deadlineMs) {
2465
+ `});var wt=A((Jn,gt)=>{"use strict";gt.exports=`function __resetTask(snapshot, taskId, timeoutMs, deadlineMs, innerGuardGraceMs = 500) {
796
2466
  $ctx = snapshot || {};
797
2467
  $pkgs = {};
798
2468
  __taskId = taskId;
2469
+ __innerGuardGraceMs = innerGuardGraceMs;
799
2470
  const providedDeadlineMs = Number(deadlineMs);
2471
+ const requestedTimeoutMs = Number(timeoutMs);
2472
+ const normalizedTimeoutMs = Number.isFinite(requestedTimeoutMs)
2473
+ ? Math.max(1, Math.trunc(requestedTimeoutMs))
2474
+ : 30000;
800
2475
  __taskDeadlineMs = Number.isFinite(providedDeadlineMs) && providedDeadlineMs > 0
801
2476
  ? providedDeadlineMs
802
- : Date.now() + Math.max(1, Math.trunc(Number(timeoutMs) || 30000));
2477
+ : __trustedNow() + normalizedTimeoutMs;
803
2478
  __logs = [];
804
2479
  __logBytes = 0;
805
2480
  __runtimeCallbackCounter = 0;
806
2481
  __runtimeCallbacks = new Map();
807
2482
  __pendingRuntimeTasks = [];
2483
+ __streamTimerCounter = 0;
808
2484
  %%PKG_SETUP%%
809
2485
  $ctx.$pkgs = $pkgs;
2486
+ $ctx.$streams = {
2487
+ preflight: __preflightStream,
2488
+ readBytes: (readable, options) => __readStream(readable, options, false),
2489
+ readText: (readable, options) => __readStream(readable, options, true),
2490
+ guard: __guardStream,
2491
+ tap: __tapStream,
2492
+ cancel: __cancelStream,
2493
+ };
810
2494
  $ctx.$share = $ctx.$share || {};
811
2495
  $ctx.$share.$logs = __logs;
812
2496
  const __createRepoProxy = (table, access) => new Proxy({}, {
813
- get: (_, method) => async (...args) =>
814
- __call('repoCall', JSON.stringify({ table: String(table), access, method: String(method), argsJson: JSON.stringify(args) }))
2497
+ get: (_, method) => {
2498
+ if (method === 'then') return undefined;
2499
+ return __hostCallAsync(async (...args) =>
2500
+ __call('repoCall', JSON.stringify({
2501
+ table: String(table),
2502
+ access,
2503
+ method: String(method),
2504
+ argsJson: await __stringifyRuntimeArgs(args),
2505
+ })));
2506
+ }
815
2507
  });
816
2508
  const __secureRepos = new Proxy({}, {
817
- get: (_, table) => __createRepoProxy(table, 'secure')
2509
+ get: (_, table) => {
2510
+ if (table === 'then') return undefined;
2511
+ return __createRepoProxy(table, 'secure');
2512
+ }
818
2513
  });
819
2514
  $ctx.$repos = new Proxy({}, {
820
- get: (_, table) => String(table) === 'secure' ? __secureRepos : __createRepoProxy(table)
2515
+ get: (_, table) => {
2516
+ if (table === 'then') return undefined;
2517
+ return String(table) === 'secure' ? __secureRepos : __createRepoProxy(table);
2518
+ }
821
2519
  });
822
2520
  $ctx.$helpers = new Proxy({}, {
823
2521
  get: (_, name) => {
2522
+ if (name === 'then') return undefined;
824
2523
  const basePath = String(name);
825
2524
  const fn = (...args) =>
826
2525
  __createAsyncMainResultProxy(
827
- __call('helpersCall', JSON.stringify({ name: basePath, argsJson: JSON.stringify(args) })),
2526
+ __stringifyRuntimeArgs(args).then((argsJson) =>
2527
+ __call('helpersCall', JSON.stringify({ name: basePath, argsJson })),
2528
+ ),
828
2529
  [],
829
2530
  );
830
2531
  return new Proxy(fn, {
831
- get: (_, subName) => (...args) =>
832
- __createAsyncMainResultProxy(
833
- __call('helpersCall', JSON.stringify({ name: basePath + '.' + String(subName), argsJson: JSON.stringify(args) })),
834
- [],
835
- )
2532
+ get: (_, subName) => {
2533
+ if (subName === 'then') return undefined;
2534
+ return (...args) =>
2535
+ __createAsyncMainResultProxy(
2536
+ __stringifyRuntimeArgs(args).then((argsJson) =>
2537
+ __call('helpersCall', JSON.stringify({
2538
+ name: basePath + '.' + String(subName),
2539
+ argsJson,
2540
+ })),
2541
+ ),
2542
+ [],
2543
+ );
2544
+ }
836
2545
  });
837
2546
  }
838
2547
  });
839
2548
  $ctx.$socket = new Proxy({}, {
840
- get: (_, method) => async (...args) =>
841
- __call('socketCall', JSON.stringify({ method: String(method), argsJson: JSON.stringify(args) }))
2549
+ get: (_, method) => {
2550
+ if (method === 'then') return undefined;
2551
+ return __hostCallAsync(async (...args) =>
2552
+ __call('socketCall', JSON.stringify({
2553
+ method: String(method),
2554
+ argsJson: await __stringifyRuntimeArgs(args),
2555
+ })));
2556
+ }
842
2557
  });
843
2558
  $ctx.$cache = new Proxy({}, {
844
- get: (_, method) => async (...args) =>
845
- __call('cacheCall', JSON.stringify({ method: String(method), argsJson: JSON.stringify(args) }))
2559
+ get: (_, method) => {
2560
+ if (method === 'then') return undefined;
2561
+ return __hostCallAsync(async (...args) =>
2562
+ __call('cacheCall', JSON.stringify({
2563
+ method: String(method),
2564
+ argsJson: await __stringifyRuntimeArgs(args),
2565
+ })));
2566
+ }
846
2567
  });
847
2568
  $ctx.$transaction = {
848
- run: async (...args) =>
2569
+ run: __hostCallAsync(async (...args) =>
849
2570
  __call('transactionCall', JSON.stringify({
850
2571
  argsJson: await __stringifyRuntimeArgs(args)
851
- }))
2572
+ })))
852
2573
  };
853
2574
  $ctx.$storage = new Proxy({}, {
854
- get: (_, method) => async (...args) =>
855
- __call('storageCall', JSON.stringify({ method: String(method), argsJson: await __stringifyRuntimeArgs(args) }))
2575
+ get: (_, method) => {
2576
+ if (method === 'then') return undefined;
2577
+ return __hostCallAsync(async (...args) =>
2578
+ __call('storageCall', JSON.stringify({ method: String(method), argsJson: await __stringifyRuntimeArgs(args) })));
2579
+ }
856
2580
  });
857
2581
  $ctx.$res = new Proxy({}, {
858
- get: (_, method) => async (...args) => {
2582
+ get: (_, method) => {
2583
+ if (method === 'then') return undefined;
2584
+ return __hostCallAsync(async (...args) => {
859
2585
  const methodName = String(method);
860
2586
  if (methodName === 'stream' && args[0]?.__enfyraLocalReadable) {
861
2587
  const task = __streamResponseFromLocalReadable(args[0], args[1]);
862
2588
  __pendingRuntimeTasks.push(task);
863
2589
  return task;
864
2590
  }
2591
+ if (methodName === 'json') {
2592
+ const jsonText = JSON.stringify(args[0]);
2593
+ if (jsonText === undefined) {
2594
+ throw new TypeError('@RES.json requires a JSON-serializable value');
2595
+ }
2596
+ return __call('resCall', JSON.stringify({
2597
+ method: 'json',
2598
+ jsonText,
2599
+ options: args[1] || {},
2600
+ }));
2601
+ }
2602
+ if (methodName === 'bytes') {
2603
+ return __call('resCall', JSON.stringify({
2604
+ method: 'bytes',
2605
+ bytes: __bytesToBase64(__responseBodyToBytes(args[0])),
2606
+ options: args[1] || {},
2607
+ }));
2608
+ }
865
2609
  return __call('resCall', JSON.stringify({ method: methodName, argsJson: await __stringifyRuntimeArgs(args) }));
2610
+ });
866
2611
  }
867
2612
  });
868
- $ctx.$trigger = async (...args) =>
869
- __call('dispatchCall', JSON.stringify({ method: 'trigger', argsJson: JSON.stringify(args) }));
2613
+ $ctx.$trigger = __hostCallAsync(async (...args) =>
2614
+ __call('dispatchCall', JSON.stringify({
2615
+ method: 'trigger',
2616
+ argsJson: await __stringifyRuntimeArgs(args),
2617
+ })));
2618
+ const safeDiagnosticString = (value) => {
2619
+ try { return String(value); } catch { return '[Unserializable]'; }
2620
+ };
2621
+ const safeDiagnosticValue = (value, seen = new WeakSet(), depth = 0) => {
2622
+ if (
2623
+ value === null
2624
+ || typeof value === 'string'
2625
+ || typeof value === 'boolean'
2626
+ || typeof value === 'number'
2627
+ ) {
2628
+ return value;
2629
+ }
2630
+ if (value === undefined) return undefined;
2631
+ if (typeof value === 'bigint') return safeDiagnosticString(value);
2632
+ if (typeof value === 'symbol') return safeDiagnosticString(value);
2633
+ if (typeof value === 'function') return '[Function]';
2634
+ if (depth >= 12) return '[MaxDepth]';
2635
+ if (seen.has(value)) return '[Circular]';
2636
+ seen.add(value);
2637
+ try {
2638
+ if (value instanceof Date) {
2639
+ try { return value.toISOString(); } catch { return safeDiagnosticString(value); }
2640
+ }
2641
+ if (value instanceof Error) {
2642
+ return {
2643
+ name: safeDiagnosticString(value.name),
2644
+ message: safeDiagnosticString(value.message),
2645
+ stack: typeof value.stack === 'string' ? value.stack : undefined,
2646
+ };
2647
+ }
2648
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
2649
+ const bytes = value instanceof ArrayBuffer
2650
+ ? new Uint8Array(value)
2651
+ : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
2652
+ const output = Array.from(bytes.subarray(0, 1000));
2653
+ if (bytes.byteLength > output.length) output.push('[Truncated]');
2654
+ return output;
2655
+ }
2656
+ if (Array.isArray(value)) {
2657
+ const output = [];
2658
+ const length = Math.min(value.length, 1000);
2659
+ for (let index = 0; index < length; index += 1) {
2660
+ let descriptor;
2661
+ try { descriptor = Object.getOwnPropertyDescriptor(value, String(index)); } catch {}
2662
+ output.push(
2663
+ descriptor && Object.prototype.hasOwnProperty.call(descriptor, 'value')
2664
+ ? safeDiagnosticValue(descriptor.value, seen, depth + 1)
2665
+ : descriptor
2666
+ ? '[Accessor]'
2667
+ : null,
2668
+ );
2669
+ }
2670
+ if (value.length > length) output.push('[Truncated]');
2671
+ return output;
2672
+ }
2673
+ const output = {};
2674
+ let descriptors;
2675
+ try { descriptors = Object.getOwnPropertyDescriptors(value); } catch {
2676
+ return '[Unserializable]';
2677
+ }
2678
+ let count = 0;
2679
+ for (const key of Object.keys(descriptors)) {
2680
+ if (count >= 1000) {
2681
+ output.__truncated = true;
2682
+ break;
2683
+ }
2684
+ const descriptor = descriptors[key];
2685
+ if (!descriptor.enumerable) continue;
2686
+ __defineDataProperty(
2687
+ output,
2688
+ key,
2689
+ Object.prototype.hasOwnProperty.call(descriptor, 'value')
2690
+ ? safeDiagnosticValue(descriptor.value, seen, depth + 1)
2691
+ : '[Accessor]',
2692
+ );
2693
+ count += 1;
2694
+ }
2695
+ return output;
2696
+ } catch {
2697
+ return '[Unserializable]';
2698
+ } finally {
2699
+ seen.delete(value);
2700
+ }
2701
+ };
2702
+ const safeDiagnosticJson = (value) => {
2703
+ try {
2704
+ const text = JSON.stringify(safeDiagnosticValue(value));
2705
+ return text === undefined
2706
+ ? JSON.stringify(safeDiagnosticString(value))
2707
+ : text;
2708
+ } catch {
2709
+ return '"[Unserializable]"';
2710
+ }
2711
+ };
870
2712
  $ctx.$throw = new Proxy({}, {
871
- get: (_, status) => (...args) => {
2713
+ get: (_, status) => {
2714
+ if (status === 'then') return undefined;
2715
+ return (...args) => {
872
2716
  const key = String(status);
873
2717
  const throwPayload = (payload) => {
874
- throw new Error(JSON.stringify({ __userThrow: true, ...payload }));
2718
+ throw new Error(safeDiagnosticJson({ __userThrow: true, ...payload }));
875
2719
  };
876
2720
 
877
2721
  if (key === 'http') {
878
2722
  const code = Number(args[0]);
2723
+ if (!Number.isInteger(code) || code < 400 || code > 599) {
2724
+ throw new TypeError('$throw.http requires an integer HTTP status from 400 to 599');
2725
+ }
879
2726
  const message = args[1] !== undefined && args[1] !== null && args[1] !== ''
880
- ? String(args[1])
2727
+ ? safeDiagnosticString(args[1])
881
2728
  : (__throwDefaults[code] || 'Error');
882
2729
  throwPayload({
883
2730
  errorPath: '$throw.http',
884
2731
  statusCode: code,
885
2732
  message,
886
- details: args[2] || null,
2733
+ details: args[2] ?? null,
887
2734
  });
888
2735
  }
889
2736
 
890
2737
  if (key === 'notFound') {
891
- const resource = args[0] !== undefined && args[0] !== null && args[0] !== '' ? String(args[0]) : 'Resource';
892
- const identifier = args[1] !== undefined && args[1] !== null ? String(args[1]) : undefined;
2738
+ const resource = args[0] !== undefined && args[0] !== null && args[0] !== '' ? safeDiagnosticString(args[0]) : 'Resource';
2739
+ const identifier = args[1] !== undefined && args[1] !== null ? safeDiagnosticString(args[1]) : undefined;
893
2740
  throwPayload({
894
2741
  errorPath: '$throw.notFound',
895
2742
  statusCode: 404,
@@ -899,9 +2746,9 @@ function __resetTask(snapshot, taskId, timeoutMs, deadlineMs) {
899
2746
  }
900
2747
 
901
2748
  if (key === 'duplicate') {
902
- const resource = args[0] !== undefined && args[0] !== null && args[0] !== '' ? String(args[0]) : 'Resource';
903
- const field = args[1] !== undefined && args[1] !== null && args[1] !== '' ? String(args[1]) : 'field';
904
- const value = args[2] !== undefined && args[2] !== null ? String(args[2]) : 'value';
2749
+ const resource = args[0] !== undefined && args[0] !== null && args[0] !== '' ? safeDiagnosticString(args[0]) : 'Resource';
2750
+ const field = args[1] !== undefined && args[1] !== null && args[1] !== '' ? safeDiagnosticString(args[1]) : 'field';
2751
+ const value = args[2] !== undefined && args[2] !== null ? safeDiagnosticString(args[2]) : 'value';
905
2752
  throwPayload({
906
2753
  errorPath: '$throw.duplicate',
907
2754
  statusCode: 409,
@@ -910,24 +2757,58 @@ function __resetTask(snapshot, taskId, timeoutMs, deadlineMs) {
910
2757
  });
911
2758
  }
912
2759
 
913
- const code = parseInt(key);
914
- const msg = (args[0] !== undefined && args[0] !== null && args[0] !== '') ? String(args[0]) : (__throwDefaults[code] || 'Error');
2760
+ if (!/^\\d+$/.test(key)) {
2761
+ throw new TypeError('$throw status must be an integer HTTP status');
2762
+ }
2763
+ const code = Number(key);
2764
+ if (!Number.isInteger(code) || code < 400 || code > 599) {
2765
+ throw new TypeError('$throw status must be from 400 to 599');
2766
+ }
2767
+ const msg = (args[0] !== undefined && args[0] !== null && args[0] !== '') ? safeDiagnosticString(args[0]) : (__throwDefaults[code] || 'Error');
915
2768
  throwPayload({
916
2769
  errorPath: Number.isFinite(code) ? '$throw.' + code : '$throw.' + key,
917
2770
  statusCode: code,
918
2771
  message: msg,
919
- details: args[1] || null,
2772
+ details: args[1] ?? null,
920
2773
  });
2774
+ };
921
2775
  }
922
2776
  });
2777
+ const truncateLogText = (text, maxBytes) => {
2778
+ const suffix = '[Truncated]';
2779
+ let low = 0;
2780
+ let high = text.length;
2781
+ let result = JSON.stringify(suffix);
2782
+ while (low <= high) {
2783
+ const mid = Math.floor((low + high) / 2);
2784
+ const candidate = JSON.stringify(text.slice(0, mid) + suffix);
2785
+ if (new TextEncoder().encode(candidate).byteLength <= maxBytes) {
2786
+ result = candidate;
2787
+ low = mid + 1;
2788
+ } else {
2789
+ high = mid - 1;
2790
+ }
2791
+ }
2792
+ return result;
2793
+ };
923
2794
  $ctx.$logs = (...args) => {
924
2795
  for (const a of args) {
925
- if (__logs.length >= 200 || __logBytes >= 40000) { $ctx.$share.$logsTruncated = true; break; }
926
- let text;
927
- try { text = JSON.stringify(a); } catch { text = String(a); }
928
- text = text === undefined ? String(a) : text;
929
- if (text.length > 8192) { text = JSON.stringify(text.slice(0, 8192) + '[Truncated]'); $ctx.$share.$logsTruncated = true; }
930
- __logBytes += text.length;
2796
+ if (__logs.length >= 200 || __logBytes >= 40000) {
2797
+ $ctx.$share.$logsTruncated = true;
2798
+ break;
2799
+ }
2800
+ let text = safeDiagnosticJson(a);
2801
+ let textBytes = new TextEncoder().encode(text).byteLength;
2802
+ if (textBytes > 8192) {
2803
+ text = truncateLogText(text, 8192);
2804
+ textBytes = new TextEncoder().encode(text).byteLength;
2805
+ $ctx.$share.$logsTruncated = true;
2806
+ }
2807
+ if (__logBytes + textBytes > 40000) {
2808
+ $ctx.$share.$logsTruncated = true;
2809
+ break;
2810
+ }
2811
+ __logBytes += textBytes;
931
2812
  try { __logs.push(JSON.parse(text)); } catch { __logs.push(text); }
932
2813
  }
933
2814
  };
@@ -958,50 +2839,49 @@ function __cleanupTask() {
958
2839
  __runtimeCallbackCounter = 0;
959
2840
  __runtimeCallbacks = new Map();
960
2841
  __pendingRuntimeTasks = [];
2842
+ __streamTimerCounter = 0;
961
2843
  return true;
962
2844
  }
963
- `;function Se(e){return Pe.replace("%%PKG_SETUP%%",e)}se.exports={buildSetupCode:Se}});var{parentPort:Ce}=require("worker_threads"),S=Ce||{on(e,t){e==="message"&&process.on("message",t)},postMessage(e){process.send?.(e)}},ie=require("fs"),{fileURLToPath:Re}=require("url"),{createPackageRuntimeBridge:$e}=ae(),{buildSetupCode:Te}=oe(),q;try{q=require("isolated-vm")}catch(e){S.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var K=new Map,pe=0,O=new Map,E=new Map,j=new Map,U=$e({workerDir:__dirname,activeTaskContexts:O}),Me=500,Ne=5e3,ce=new WeakMap,_e=new WeakMap,W={created:0,reused:0,released:0,evicted:0,scrubFailed:0};function B(e){let t=j.get(e);return Math.max(1,Math.ceil((t??Date.now()+3e4)-Date.now()))}var A=null,le=0,ue=0,de=0;async function Ae(){let e=Date.now();if(e-ue<Ne)return de;if(ue=e,!A)return 0;let t=0;for(let s of A){let n=s?.isolate;if(!(!n||n.isDisposed))try{let r=await n.getHeapStatistics(),i=r.heap_size_limit||1,o=r.used_heap_size/i;o>t&&(t=o)}catch{}}return de=t,t}async function F(e){e.heapRatio=await Ae(),e.runnerRssBytes=process.memoryUsage().rss,e.contextStats=Ee(),S.postMessage(e)}function Ee(){return{...W,idle:0}}function ge(e,t,s){if(!A){let n=Math.max(1,Math.trunc(Number(t)||8));A=new Array(n).fill(null)}for(let n=0;n<A.length;n++){let r=(le+n)%A.length,i=A[r];if((!i||!i.isolate||i.isolate.isDisposed)&&(i={isolate:new q.Isolate({memoryLimit:e}),taskIds:new Set},A[r]=i),i.taskIds.size<s)return le=(r+1)%A.length,i}throw new Error("No isolate lane is available")}function z(e,t,s){for(let n of[...e.taskIds])n!==t&&(e.taskIds.delete(n),E.delete(n),O.delete(n),j.delete(n),U.cancelTask(n),V(n),S.postMessage({type:"result",id:n,success:!1,error:{message:"Isolate was disposed because a sibling task could not continue",code:"ERR_EXECUTOR_ISOLATE_LOST",details:{outcome:"unknown_outcome",retryable:!1,reason:s}}}),S.postMessage({type:"taskReleased",id:n}));try{e.isolate.dispose()}catch{}}function Oe(e){let t=E.get(e);if(!t){S.postMessage({type:"taskCancelled",id:e});return}z(t,e,"sibling_cancelled"),U.cancelTask(e),E.delete(e),O.delete(e),j.delete(e),t.taskIds.delete(e),V(e),S.postMessage({type:"taskCancelled",id:e})}function ye(e,t){t.taskIds.delete(e)&&(O.delete(e),E.delete(e),j.delete(e),V(e),S.postMessage({type:"taskReleased",id:e}))}async function T(e,t,s){let n=ce.get(e);n||(n=new Map,ce.set(e,n));let r=n.get(t);if(r)return r;let i;try{i=await e.compileScript(t,{filename:s})}catch(o){throw o&&typeof o=="object"&&(o.executionStage="compile"),o}if(n.set(t,i),n.size>Me){let o=n.keys().next().value;n.delete(o)}return i}S.on("message",async e=>{if(e.type==="execute")Ge(e).catch(async t=>{await F({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")We(e).catch(async t=>{await F({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="invokeRuntimeCallback")Je(e).catch(t=>{S.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:t?.message||String(t)})});else if(e.type==="callResult"){let t=K.get(e.callId);t&&(K.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=K.get(e.callId);t&&(K.delete(e.callId),t.reject(new Error(e.error)))}else e.type==="cancelTask"&&Oe(e.id)});async function Je(e){let t=O.get(e.id);if(!t){S.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:`Runtime callback context not found: ${e.id}`});return}let s=await t.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(e.callbackId)}, ${JSON.stringify(e.argsJson||"[]")});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),n=JSON.parse(s);S.postMessage({type:"runtimeCallbackResult",callId:e.callId,...n})}function L(e,t,s){return new Promise((n,r)=>{let i=`cb_${++pe}`;K.set(i,{resolve:n,reject:r}),S.postMessage({type:t,id:e,callId:i,...s})})}function Ie(e,t,s){S.postMessage({type:t,id:e,callId:`f_${++pe}`,...s})}async function je(e,t){if(t?.method!=="stream")return L(e,"resCall",t);let s=JSON.parse(t.argsJson||"[]"),n=s[0],r=s[1]||{},i=n?.__pkgHandleArg;if(!i)return L(e,"resCall",t);let o=r.observer&&typeof r.observer=="object"?r.observer.__fnRef:null,y=r.transform&&typeof r.transform=="object"?r.transform.__fnRef:null,f=o||y?new TextDecoder("utf-8"):null;delete r.observer,delete r.transform;let w={...r};await L(e,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,w])});let b=async(u,m,v)=>{if(!u)return;let k=O.get(e);if(!k)return;let P=await k.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(u)}, ${JSON.stringify(JSON.stringify([m,v]))});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),C=JSON.parse(P);if(C?.error)throw new Error(C.error);if(C?.value?.__e!=="u")return C?.value},R=async(u,m)=>{if(o)try{await b(o,u,m)}catch{}},d=async(u,m,v)=>{let k=u;if(y){let C=await b(y,v,m);if(C===null)return;C!==void 0&&(k=Buffer.from(String(C)))}let P=Buffer.from(k);P.length!==0&&await L(e,"resCall",{method:"streamChunk",chunk:P.toString("base64")})};try{await U.streamPackageHandle(e,i,async m=>{let v="";try{v=f?f.decode(Buffer.from(m),{stream:!0}):""}catch{}await R(v,"chunk"),await d(m,"chunk",v)},[],B(e));let u="";try{u=f?f.decode():""}catch{}await R(u,"end"),await d("","end",u),await L(e,"resCall",{method:"streamEnd"})}catch(u){try{await L(e,"resCall",{method:"streamError",error:{message:u.message,stack:u.stack}})}catch{}throw await R("","error"),u}return JSON.stringify({__e:"u"})}function Ue(e){if(typeof e.sourceCode=="string"&&e.sourceCode.length>0)return e.sourceCode;let t=e.filePath;return!t&&typeof e.fileUrl=="string"&&e.fileUrl.startsWith("file://")&&(t=Re(e.fileUrl)),!t||!ie.existsSync(t)?null:ie.readFileSync(t,"utf8")}async function He(e,t,s){try{let n=Ue(s);if(!n)return null;let r=await e.compileModule(n,{filename:`pkg:${s.safeName}`});await r.instantiate(t,o=>{throw new Error(`Unresolved import in package ${s.safeName}: ${o}`)}),await r.evaluate({timeout:1e4});let i=await r.namespace.get("default");return i!==void 0&&i.typeof!=="undefined"?i.derefInto({release:!1}):r.namespace.derefInto({release:!1})}catch{return null}}function he(e,t){let s=new Set(t.map(f=>f.name)),n=new Set,r=String(e||""),i=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,o=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,y=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let f of[i,o])for(let w of r.matchAll(f)){let b=w[2];s.has(b)&&n.add(b)}for(let f of r.matchAll(y)){let w=f[1];s.has(w)&&n.add(w)}return n}async function Le(e,t,s,n){let r=await e.createContext(),i=r.global;await i.set("global",i.derefInto());let o=[],y=[],f=new Map;for(let d of s){f.set(d.name,d);let u=n.has(d.name)?await He(e,r,d):null;u!==null?(await i.set(`__pkg_${d.safeName}`,u),o.push(d)):y.push(d)}U.setTaskPackages(t,f),await i.set("__callRef",new q.Reference(async(d,u,m)=>{let v=JSON.parse(m);if(u==="pkgCall")try{return JSON.stringify(await U.executePackageRuntimeCall(d,v))}catch(k){throw new Error(JSON.stringify({__userThrow:!0,message:k.message,code:k.code,details:k.details}))}return u==="resCall"?je(d,v):L(d,u,v)})),await i.set("__fireRef",new q.Reference((d,u,m)=>{let v=JSON.parse(m);Ie(d,u,v)}));let w=o.map(d=>`$pkgs[${JSON.stringify(d.name)}] = __pkg_${d.safeName};`).concat(y.map(d=>`$pkgs[${JSON.stringify(d.name)}] = __createPkgProxy(${JSON.stringify(d.name)}, []);`)).join(`
964
- `),b=Te(w);return await(await T(e,b,"setup.js")).run(r,{timeout:B(t)}),_e.set(r,f),r}async function me(e,t,s,n,r,i,o){let y=e.isolate,f=await Le(y,t,s,r);W.created++,U.setTaskPackages(t,_e.get(f)||new Map);let w=f.global;return await w.set("__snapshot",new q.ExternalCopy(n).copyInto()),await w.set("__nextTaskId",t),await w.set("__nextTaskTimeoutMs",i),await w.set("__nextTaskDeadlineMs",o),await(await T(y,"__resetTask(__snapshot, __nextTaskId, __nextTaskTimeoutMs, __nextTaskDeadlineMs);","reset-task.js")).run(f,{timeout:B(t)}),f}async function ke(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await T(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{W.scrubFailed++;try{t.release()}catch{}return}try{t.release()}catch{}W.released++}}function Fe(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var De=3,Be=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function Ke(e){if(!e)return null;let t=e.split(`
965
- `);for(let s of t){let n=s.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!n)continue;let r=n[1].trim();if(Be.includes(r)||r!=="handler.js"&&!r.startsWith("preHook #")&&!r.startsWith("postHook #"))continue;let o=parseInt(n[2])-De;if(!(o<=0))return{line:o,column:parseInt(n[3]),phase:r.replace(".js","")}}return null}function qe(e,t,s){if(!e||!t)return;let n=String(e).split(/\r?\n/),r=Math.max(1,t-1),i=Math.min(n.length,t+1),o=String(i).length,y=[];for(let f=r;f<=i;f++){let w=f===t?">":" ";y.push(`${w} ${String(f).padStart(o," ")}. ${n[f-1]??""}`),f===t&&s&&s>0&&y.push(` ${" ".repeat(o)} ${" ".repeat(Math.max(0,s-1))}^`)}return y.join(`
966
- `)}function Ve(e,t){if(!(!e||!t)){if(t[e.phase])return t[e.phase];if(e.phase?.startsWith("preHook"))return t.preHook;if(e.phase?.startsWith("postHook"))return t.postHook}}function te(e,t){let s=Fe(e);if(s)return{message:s.message,statusCode:s.statusCode,errorPath:s.errorPath,code:s.code??(Number.isInteger(s.statusCode)?`HTTP_${s.statusCode}`:void 0),details:s.details};let n=Ke(e.stack),r=e.message||"Unknown error",i=n?`${r} (${n.phase}, line ${n.line})`:r,o=Ve(n,t),y=n?qe(o,n.line,n.column):void 0;return{message:i,statusCode:e.statusCode||null,details:{errorName:e.name||null,executionStage:e.executionStage||"runtime",...n?{...n,codeFrame:y}:{}}}}function X(e){return e?.message==="Script execution timed out."}function Y(e){return e?.message==="Isolate was disposed during execution due to memory limit"}function we(e){X(e)&&e?.code==null&&(e.code="ERR_SCRIPT_EXECUTION_TIMEOUT"),Y(e)&&e?.code==null&&(e.code="ERR_ISOLATE_MEMORY_LIMIT",e.details={outcome:"unknown_outcome",retryable:!1})}async function Z(e,t,s){we(t);let n=te(t,s);t.details&&(n.details={...n.details,...t.details});let r,i=O.get(e),o=E.get(e);if(i&&o&&!o.isolate.isDisposed)try{let y=await T(o.isolate,"JSON.stringify({logs: __logs, truncated: $ctx.$share.$logsTruncated === true})","extract-diagnostic-logs.js");r=JSON.parse(await y.run(i,{timeout:100}))}catch{}await F({type:"result",id:e,success:!1,diagnosticLogs:r,error:{...n,stack:t.stack,code:n.code??t.code}})}async function Ge(e){let{id:t,code:s,pkgSources:n,snapshot:r,memoryLimitMb:i,isolatePoolSize:o,tasksPerIsolate:y}=e,f={handler:e.sourceCode||s||""},w=n||[],b=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),R=Date.now()+b;j.set(t,R);let d=he(s,w),u=ge(i,o,Math.max(1,Math.trunc(Number(y)||1)));u.taskIds.add(t),E.set(t,u);let m=u.isolate,v;try{v=await me(u,t,w,r,d,b,R)}catch(k){j.delete(t),E.delete(t),u.taskIds.delete(t),V(t),await Z(t,k,f),S.postMessage({type:"taskReleased",id:t});return}O.set(t,v);try{let k=`
967
- (async () => {
968
- "use strict";
969
- ${s}
970
- })().then((__result) => __extractResult(__result, __result === undefined));
971
- `,C=await(await T(m,k,"handler.js")).run(v,{timeout:B(t),promise:!0}),D=JSON.parse(C);await F({type:"result",id:t,success:!0,...D})}catch(k){u.taskIds.has(t)&&(await Z(t,k,f),(X(k)||Y(k))&&z(u,t,"sibling_execution_failure"))}finally{await ke(u,v),ye(t,u)}}async function We(e){let{id:t,codeBlocks:s,pkgSources:n,snapshot:r,memoryLimitMb:i,isolatePoolSize:o,tasksPerIsolate:y}=e,f=n||[],w=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),b=Date.now()+w;j.set(t,b);let R=he((s||[]).map(_=>_.code||"").join(`
972
- `),f),d=ge(i,o,Math.max(1,Math.trunc(Number(y)||1)));d.taskIds.add(t),E.set(t,d);let u=d.isolate,m;try{m=await me(d,t,f,r,R,w,b)}catch(_){j.delete(t),E.delete(t),d.taskIds.delete(t),V(t),await Z(t,_),S.postMessage({type:"taskReleased",id:t});return}O.set(t,m);let v=[],k=[],P={},C=0,D=0;for(let _ of s){let H=_.type||"handler",g=_.sourceCode||_.code||"";H==="postHook"?(D++,P[`postHook #${D}`]=g,P.postHook=g,k.push(_)):(H==="handler"?P.handler=g:(C++,P[`${H} #${C}`]=g,P.preHook=g),v.push(_))}try{let _=null;for(let g=0;g<v.length;g++){let x=v[g],$=x.type||"handler",l=$==="handler"?"handler":`${$} #${g+1}`,a;$==="preHook"?a=`
2845
+ `});var kt=A((jn,bt)=>{"use strict";var Sr=[We(),Ye(),Ze(),tt(),nt(),ot(),it(),ct(),dt(),_t(),mt(),ht(),wt()].join("");function Pr(e){return Sr.replace("%%PKG_SETUP%%",()=>e)}bt.exports={buildSetupCode:Pr}});var Pe={};cr(Pe,{INNER_GUARD_GRACE_MS:()=>Er,TASK_CANCEL_ACK_GRACE_MS:()=>Tr,TASK_TIMEOUT_TOLERANCE_RATIO:()=>Mr,getTaskCancellationTimeoutMs:()=>xt,getTaskInnerGuardGraceMs:()=>Cr});function xt(e){return Math.min(2147483647,e+Math.ceil(e*.15))}function Cr(e){return xt(e)-e+500}var Tr,Er,Mr,Te=lr(()=>{"use strict";Tr=1e4,Er=500,Mr=.15});var Me=A((zn,vt)=>{"use strict";var{randomUUID:Rr}=require("crypto"),pe=new WeakMap,Ee=new WeakMap;function Ar(e){let t=e.createInspectorSession(),n=new Map,r=new Map,i=new Map,s=0,c,_=Promise.resolve(),m=p=>new Promise((w,d)=>{let h=++s;i.set(h,{resolve:w,reject:d});try{t.dispatchProtocolMessage(JSON.stringify({id:h,method:p}))}catch(y){i.delete(h),d(y)}});t.onResponse=(p,w)=>{let d=JSON.parse(w),h=i.get(d.id);h&&(i.delete(d.id),d.error?h.reject(new Error(d.error.message)):h.resolve(d.result))},t.onNotification=p=>{let w=JSON.parse(p);if(w.method==="Debugger.scriptParsed"){let{scriptId:d,executionContextId:h,url:y}=w.params;n.set(d,h),y.startsWith("enfyra-task-context:")&&r.set(y,h)}else if(w.method==="Runtime.executionContextDestroyed"){let d=w.params.executionContextId;for(let[h,y]of n)y===d&&n.delete(h);for(let[h,y]of r)y===d&&r.delete(h)}else if(w.method==="Debugger.paused"){let d=c;d&&(d.handling=!0),(async()=>{try{let h=w.params.callFrames[0],y=n.get(h?.location?.scriptId),k=d&&r.get(d.marker);if(k!==void 0&&y===k&&d.isCancelling()){let x=m("Runtime.terminateExecution");await m("Debugger.resume").catch(()=>{}),await x}else await m("Debugger.resume")}finally{d?.complete()}})().catch(()=>d?.complete())}};let l=m("Runtime.enable").then(()=>m("Debugger.enable"));return{ready:l,forget(p){let w=pe.get(p),d=r.get(w);r.delete(w);for(let[h,y]of n)y===d&&n.delete(h);pe.delete(p)},interrupt(p,w){let d=_.catch(()=>{}).then(async()=>{if(await l,e.isDisposed||!w())return;let h,y=new Promise(E=>{h=E}),k={marker:pe.get(p),isCancelling:w,complete:h,handling:!1};c=k;let x;try{await m("Debugger.pause"),await Promise.race([y,new Promise(E=>{x=setTimeout(E,250)})]),k.handling&&await y}finally{clearTimeout(x),c===k&&(c=void 0)}});return _=d,d}}}async function Nr(e,t){let n="enfyra-task-context:"+Rr();pe.set(e,n),await e.eval("void 0;",{filename:n,timeout:t})}function Or(e,t){Ee.get(e)?.forget(t)}async function Ir(e,t,n){if(e.isolate.isDisposed||!n())return;let r=Ee.get(e.isolate);r||(r=Ar(e.isolate),Ee.set(e.isolate,r)),await r.interrupt(t,n)}vt.exports={registerTaskContext:Nr,forgetTaskContext:Or,interruptTask:Ir}});var Et=A((Hn,Tt)=>{"use strict";var{URL:St}=require("url"),{buildSetupCode:Ur}=kt(),{normalizeThrownValue:Pt}=ie(),{getTaskInnerGuardGraceMs:$r}=(Te(),$e(Pe)),{registerTaskContext:Br,forgetTaskContext:Dr}=Me();function Lr({ivm:e,packageRuntimeBridge:t,contextStats:n,getCachedScript:r,getTaskRemainingTimeoutMs:i,loadEsmPackageIntoContext:s,PACKAGE_PROXY_FALLBACK:c,executeResCall:_,callMain:m,waitForStreamTimer:l,clearStreamTimer:p,cleanupTaskPackages:w,isTaskCancelled:d}){let h=new WeakMap,y=new WeakMap;async function k(g,f,C,P){let S=await g.createContext({inspector:!0});try{let M=S.global;await M.set("global",M.derefInto());let U=[],q=[],D=new Map;for(let T of C){D.set(T.name,T);let F=P.has(T.name)?await s(g,S,T,f):c;F!==c?(await M.set(`__pkg_${T.safeName}`,F),U.push(T)):q.push(T)}t.setTaskPackages(f,D);let L=new Set(["pkgCall","pkgStreamCall","resCall","repoCall","helpersCall","socketCall","cacheCall","transactionCall","storageCall","dispatchCall"]);await M.set("__callRef",new e.Reference(async(T,F)=>{if(d(f))throw new Error("Task was cancelled");if(!L.has(T))throw new Error(`Unsupported host call type: ${T}`);let o=JSON.parse(F);if(T==="pkgCall")try{return JSON.stringify(await t.executePackageRuntimeCall(f,o))}catch(a){let u=Pt(a);throw new Error(JSON.stringify({__userThrow:!0,message:u.message,code:u.code,details:u.details}))}if(T==="pkgStreamCall")try{return JSON.stringify(await t.executePackageStreamCall(f,o))}catch(a){let u=Pt(a);return JSON.stringify({__pkgStreamError:{message:u.message,code:u.code,details:u.details}})}return T==="resCall"?_(f,o):m(f,T,o)})),await M.set("__urlParseRef",new e.Reference((T,F,o)=>{let a=F==null?new St(String(T)):new St(String(T),String(F));if(o){let u=JSON.parse(o),b=String(u.property);if(!["href","protocol","username","password","host","hostname","port","pathname","search","hash"].includes(b))throw new TypeError(`Unsupported URL property: ${b}`);a[b]=String(u.value)}return JSON.stringify({href:a.href,origin:a.origin,protocol:a.protocol,username:a.username,password:a.password,host:a.host,hostname:a.hostname,port:a.port,pathname:a.pathname,search:a.search,hash:a.hash})})),await M.set("__streamTimerRef",new e.Reference(async(T,F,o)=>T==="wait"?await l(f,F,o):T==="clear"?p(f,F):!1));let fe=U.map(T=>`$pkgs[${JSON.stringify(T.name)}] = __pkg_${T.safeName};`).concat(q.map(T=>`$pkgs[${JSON.stringify(T.name)}] = __createPkgProxy(${JSON.stringify(T.name)}, []);`)).join(`
2846
+ `),we=Ur(fe);return await(await r(g,we,"setup.js")).run(S,{timeout:i(f)}),h.set(S,D),S}catch(M){t.cancelTask(f),w(f);try{S.release()}catch{}throw M}}async function x(g,f,C,P,S,M,U){let q=g.isolate,D=await k(q,f,C,S);n.created++;try{t.setTaskPackages(f,h.get(D)||new Map);let L=D.global;return await L.set("__snapshot",new e.ExternalCopy(P).copyInto()),await L.set("__nextTaskId",f),await L.set("__nextTaskTimeoutMs",M),await L.set("__nextTaskDeadlineMs",U),await L.set("__nextTaskInnerGuardGraceMs",$r(M)),await(await r(q,"__resetTask(__snapshot, __nextTaskId, __nextTaskTimeoutMs, __nextTaskDeadlineMs, __nextTaskInnerGuardGraceMs);","reset-task.js")).run(D,{timeout:i(f)}),await Br(D,i(f)),D}catch(L){try{D.release()}catch{}throw L}}function E(g,f){if(!f)return Promise.resolve();let C=y.get(f);if(C)return C;let P=O(g,f).finally(()=>{Dr(g.isolate,f)});return y.set(f,P),P}async function O(g,f){if(g.isolate.isDisposed){try{f.release()}catch{}return}try{await(await r(g.isolate,"__cleanupTask();","cleanup-task.js")).run(f,{timeout:5e3})}catch{n.scrubFailed++;try{f.release()}catch{}return}try{f.release()}catch{}n.released++}async function v(g,f,C,P){if(P!==void 0){let q=`__extractResult(JSON.parse(${JSON.stringify(JSON.stringify(P))}), false)`,L=await(await g.compileScript(q,{filename:"extract.js"})).run(f,{timeout:i(C),promise:!0});return JSON.parse(L)}let U=await(await r(g,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(f,{timeout:i(C),promise:!0});return JSON.parse(U)}return{prepareContext:x,releaseContext:E,extractFinalResult:v}}Tt.exports={createWorkerContext:Lr}});var Ct=A((qn,Mt)=>{"use strict";function Fr({callMain:e,activeTaskContexts:t,getTaskRemainingTimeoutMs:n,getTaskInnerGuardTimeoutMs:r=n,packageRuntimeBridge:i}){async function s(c,_){if(_?.method!=="stream")return e(c,"resCall",_);let m=JSON.parse(_.argsJson||"[]"),l=m[0],p=m[1]||{},w=l?.__pkgHandleArg;if(!w)return e(c,"resCall",_);let d=p.observer&&typeof p.observer=="object"?p.observer.__fnRef:null,h=p.transform&&typeof p.transform=="object"?p.transform.__fnRef:null,y=d||h?new TextDecoder("utf-8"):null;delete p.observer,delete p.transform;let k={...p};await e(c,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,k])});let x=async(v,g,f)=>{if(!v)return;let C=t.get(c);if(!C)throw new Error("Response callback task is no longer active");let P=await C.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(v)}, ${JSON.stringify(JSON.stringify([g,f]))});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0},timeout:n(c)}),S=JSON.parse(P);if(S?.error)throw new Error(S.error);if(S?.value?.__e!=="u")return S?.value},E=async(v,g)=>{if(d)try{await x(d,v,g)}catch{}},O=async(v,g,f)=>{let C=v;if(h){let S=await x(h,f,g);if(S===null)return;S!==void 0&&(C=Buffer.from(String(S)))}let P=Buffer.from(C);P.length!==0&&await e(c,"resCall",{method:"streamChunk",chunk:P.toString("base64")})};try{await i.streamPackageHandle(c,w,async g=>{let f="";try{f=y?y.decode(Buffer.from(g),{stream:!0}):""}catch{}await E(f,"chunk"),await O(g,"chunk",f)},[],r(c));let v="";try{v=y?y.decode():""}catch{}await E(v,"end"),await O("","end",v),await e(c,"resCall",{method:"streamEnd"})}catch(v){try{await e(c,"resCall",{method:"streamError",error:{message:v.message,stack:v.stack}})}catch{}throw await E("","error"),v}return JSON.stringify({__e:"u"})}return{executeResCall:s}}Mt.exports={createWorkerResponse:Fr}});var Ut=A((Vn,It)=>{"use strict";var{normalizeThrownValue:Rt,normalizeNativeExecutionError:Ce,isNativeExecutionTimeout:At,isIsolateMemoryLimit:Nt,buildErrorPayload:Ot}=ie();function Jr(e){if(!Array.isArray(e))throw new Error("Executor codeBlocks must be an array");let t=new Set(["preHook","handler","postHook"]),n=0;for(let m of e){if(!m||typeof m!="object")throw new Error("Executor codeBlocks entries must be objects");let l=m.type||"handler";if(!t.has(l))throw new Error(`Unsupported executor code block type: ${l}`);l==="handler"&&n++}if(n>1)throw new Error("Executor batch may contain at most one handler block");let r=[],i=[],s={},c=0,_=0;for(let m of e){let l=m.type||"handler",p=m.sourceCode||m.code||"";l==="postHook"?(_++,s[`postHook #${_}`]=p,s.postHook=p,i.push(m)):(l==="handler"?s.handler=p:(c++,s[`${l} #${c}`]=p,s.preHook=p),r.push(m))}return{preHooksAndHandler:r,postHooks:i,sourceByPhase:s}}function jr({getCachedScript:e,getTaskRemainingTimeoutMs:t,extractFinalResult:n,postResultMessage:r,reportTaskFailure:i,runnerPort:s,failIsolateSiblings:c,isLaneUnusable:_}){async function m({id:l,isolate:p,context:w,entry:d,preHooksAndHandler:h,postHooks:y,sourceByPhase:k}){let x=null,E=0;for(let g of h){let f=g.type||"handler";f!=="handler"&&E++;let C=f==="handler"?"handler":`${f} #${E}`,P;f==="preHook"?P=`
973
2847
  (async () => {
974
2848
  "use strict";
975
- ${x.code}
2849
+ ${g.code}
976
2850
  })().then((__r) => {
977
2851
  if (__r !== undefined) return JSON.stringify({ __shortCircuit: true, value: __r });
978
2852
  return JSON.stringify({ __shortCircuit: false });
979
- });`:a=`
2853
+ });`:P=`
980
2854
  (async () => {
981
2855
  "use strict";
982
- ${x.code}
2856
+ ${g.code}
983
2857
  })().then((__r) => {
984
2858
  $ctx.$data = __r;
985
2859
  return "__handler_done__";
986
- });`;try{let p=await(await T(u,a,`${l}.js`)).run(m,{timeout:B(t),promise:!0});if($==="preHook"&&typeof p=="string"){let h=JSON.parse(p);if(h.__shortCircuit){let M=await fe(u,m,h.value);await F({type:"result",id:t,success:!0,...M,shortCircuit:!0});return}}}catch(c){_=c;break}}if(!_&&k.length>0&&await(await T(u,'$ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(m,{timeout:5e3}),_&&k.length>0){let g=te(_,P),x={message:g.message||"Unknown error",name:_.constructor?.name||"Error",stack:_.stack||"",statusCode:g.statusCode||500,details:g.details||{},timestamp:new Date().toISOString()},$=`
987
- $ctx.$error = ${JSON.stringify(x)};
2860
+ });`;try{let M=await(await e(p,P,`${C}.js`)).run(w,{timeout:t(l),promise:!0});if(f==="preHook"&&typeof M=="string"){let U=JSON.parse(M);if(U.__shortCircuit){let q=await n(p,w,l,U.value);await r({...q,type:"result",id:l,success:!0,shortCircuit:!0});return}}}catch(S){x=Rt(S);break}}x&&Ce(x);let O=!!(x&&(p.isDisposed||At(x)||Nt(x)));if(!x&&y.length>0&&await(await e(p,'if ($ctx.$statusCode === undefined || $ctx.$statusCode === null) $ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(w,{timeout:t(l)}),x&&y.length>0&&!O){let g=Ot(x,k),f=Number(g.statusCode),C=Number.isInteger(f)&&f>=100&&f<=599?f:500,P={message:g.message||"Unknown error",name:x.constructor?.name||"Error",stack:x.stack||"",statusCode:C,details:g.details||{},timestamp:new Date().toISOString()},S=`
2861
+ $ctx.$error = ${JSON.stringify(P)};
988
2862
  $ctx.$data = null;
989
- $ctx.$statusCode = ${x.statusCode};
2863
+ $ctx.$statusCode = ${JSON.stringify(P.statusCode)};
990
2864
  if ($ctx.$api) {
991
- $ctx.$api.error = ${JSON.stringify(x)};
2865
+ $ctx.$api.error = ${JSON.stringify(P)};
992
2866
  $ctx.$api.response = {
993
- statusCode: ${x.statusCode},
2867
+ statusCode: ${P.statusCode},
994
2868
  responseTime: $ctx.$api.request && $ctx.$api.request.timestamp
995
2869
  ? Date.now() - new Date($ctx.$api.request.timestamp).getTime()
996
2870
  : 0,
997
- timestamp: ${JSON.stringify(x.timestamp)},
2871
+ timestamp: ${JSON.stringify(P.timestamp)},
998
2872
  };
999
2873
  }
1000
- "__error_populated__";`;await(await u.compileScript($,{filename:"populate-error.js"})).run(m,{timeout:5e3})}for(let g=0;g<k.length;g++){let x=k[g],$=`postHook #${g+1}`,l=`
2874
+ "__error_populated__";`;await(await p.compileScript(S,{filename:"populate-error.js"})).run(w,{timeout:t(l)})}for(let g=0;g<y.length&&!O;g++){let f=y[g],C=`postHook #${g+1}`,P=`
1001
2875
  (async () => {
1002
2876
  "use strict";
1003
- ${x.code}
2877
+ ${f.code}
1004
2878
  })().then((__r) => {
1005
2879
  if (__r !== undefined) $ctx.$data = __r;
1006
2880
  return "__posthook_done__";
1007
- });`;try{await(await T(u,l,`${$}.js`)).run(m,{timeout:B(t),promise:!0})}catch(a){S.postMessage({type:"executionError",id:t,sourceKind:"postHook",scriptId:x.scriptId,error:{message:a.message,stack:a.stack,code:a.code}})}}if(_){we(_);let g=te(_,P);_.details&&(g.details={...g.details,..._.details});let x;try{let a=await(await T(u,"(async () => JSON.stringify(await __extractCtxChanges()))()","extract-error-ctx.js")).run(m,{timeout:5e3,promise:!0});x=JSON.parse(a)}catch{}await F({type:"result",id:t,success:!1,error:{message:g.message,statusCode:g.statusCode,errorPath:g.errorPath,stack:_.stack,code:g.code??_.code,details:g.details},ctxChanges:x}),(X(_)||Y(_))&&z(d,t,"sibling_execution_failure");return}let H=await fe(u,m);await F({type:"result",id:t,success:!0,...H})}catch(_){d.taskIds.has(t)&&(await Z(t,_),(X(_)||Y(_))&&z(d,t,"sibling_execution_failure"))}finally{await ke(d,m),ye(t,d)}}function V(e){U.cleanupTaskPackages(e)}function ze(){U.shutdownPackageRuntime()}process.on("exit",ze);async function fe(e,t,s){if(s!==void 0){let o=`__extractResult(${JSON.stringify(s)}, false)`,f=await(await e.compileScript(o,{filename:"extract.js"})).run(t,{timeout:5e3,promise:!0});return JSON.parse(f)}let i=await(await T(e,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(t,{timeout:5e3,promise:!0});return JSON.parse(i)}
2881
+ });`;try{await(await e(p,P,`${C}.js`)).run(w,{timeout:t(l),promise:!0})}catch(S){let M=Rt(S);if(Ce(M),p.isDisposed||At(M)||Nt(M)){x=M,O=!0;break}s.postMessage({type:"executionError",id:l,sourceKind:"postHook",scriptId:f.scriptId,error:{message:M.message,stack:M.stack,code:M.code}})}}if(x){Ce(x),i(l,x,k);let g=Ot(x,k);x.details&&(g.details={...g.details,...x.details});let f;try{let S=await(await e(p,"(async () => JSON.stringify(await __extractCtxChanges()))()","extract-error-ctx.js")).run(w,{timeout:t(l),promise:!0});f=JSON.parse(S)}catch{}await r({type:"result",id:l,success:!1,error:{message:g.message,statusCode:g.statusCode,errorPath:g.errorPath,stack:x.stack,code:g.code??x.code,details:g.details},ctxChanges:f}),_(d,x)&&c(d,l,"sibling_execution_failure");return}let v=await n(p,w,l);await r({...v,type:"result",id:l,success:!0})}return{executeWorkerBatch:m}}It.exports={prepareWorkerBatch:Jr,createWorkerBatch:jr}});var Bt=A((Gn,$t)=>{"use strict";var{fork:zr}=require("child_process"),Hr=require("path"),Re=3e4,qr=2147483647,Vr=1e3;function Gr({workerDir:e,activeTaskContexts:t,getTaskRemainingTimeoutMs:n=()=>Re}){let r=new Map,i=new Map,s=new Map,c=new Map,_=new Map,m=new WeakSet,l=null,p=0,w=!1,d=1e3;function h(o){let a=Number(o);return Number.isFinite(a)?Math.max(1,Math.min(qr,Math.trunc(a))):Re}function y(o,a,u){let b=new Error(o);return b.code=a,b.details=u,b}function k(o){try{if(o instanceof Error)return o}catch{}if(o===null)return new Error("Operation rejected with null");if(o===void 0)return new Error("Operation rejected with undefined");try{return new Error(typeof o=="string"?o:String(o))}catch{return new Error("Operation rejected with a non-Error value")}}function x(o,a){for(let[u,b]of i)b.child===o&&(clearTimeout(b.timer),i.delete(u),s.delete(u),b.reject(a))}function E(o){for(let[a,u]of c)u.child===o&&(clearTimeout(u.timer),c.delete(a))}function O(o,a){if(!o||m.has(o))return;m.add(o),l===o&&(l=null),E(o),x(o,a);try{o.disconnect()}catch{}try{o.kill("SIGTERM")}catch{}let u=setTimeout(()=>{if(!(o.exitCode!==null||o.signalCode!==null))try{o.kill("SIGKILL")}catch{}},Vr);u.unref?.(),o.once("exit",()=>clearTimeout(u))}function v(o,a){if(!o.connected)return;let u=`cancel_${++p}`,b=setTimeout(()=>{c.delete(u),O(o,y("Package runtime did not acknowledge task cancellation","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))},d);b.unref?.(),c.set(u,{child:o,timer:b});try{o.send({op:"cancelTask",taskId:a,id:u})}catch{clearTimeout(b),c.delete(u);try{o.kill()}catch{}}}function g(o,a){if(!o.connected){O(o,y("Package runtime IPC is closed","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}));return}try{o.send(a,u=>{u&&O(o,y(u.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))})}catch(u){let b=k(u);O(o,y(b.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}}function f(o,a,u=0){if(!(u>=128||!o||typeof o!="object")){if(Object.keys(o).length===1&&typeof o.__fnRef=="string"){a.add(o.__fnRef);return}if(Array.isArray(o)){for(let b of o)f(b,a,u+1);return}for(let b of Object.values(o))f(b,a,u+1)}}function C(o,a){let u;try{u=JSON.parse(a||"[]")}catch{return}let b=_.get(o);b||(b=new Set,_.set(o,b)),f(u,b)}function P(o){let a=typeof o=="string"?JSON.parse(o):o;if(a?.error)throw new Error(a.error);return a?.value}async function S(o,a){if(o!==l||m.has(o))throw new Error("Package callback runtime is no longer active");if(!_.get(a.taskId)?.has(a.callbackId))throw new Error("Package callback is not authorized for this task");let b=t.get(a.taskId);if(!b)throw new Error(`Package callback context not found: ${a.taskId}`);let R=JSON.stringify(a.callbackId),j=JSON.stringify(a.argsJson||"[]"),J=await b.evalClosure(`return __invokeRuntimeCallback(${R}, ${j});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0},timeout:n(a.taskId)});return P(J)}function M(){if(w)throw y("Package runtime is shut down","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1});if(l&&l.connected)return l;let o=Hr.join(e,"package-runtime.child.js"),a=zr(o,[],{stdio:["ignore","ignore","ignore","ipc"],env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_ENV:process.env.NODE_ENV||"production",TMPDIR:process.env.TMPDIR||"",LANG:process.env.LANG||""}});return l=a,a.on("message",u=>{if(!u||!u.id)return;if(u.type==="pkgStreamChunk"){let R=s.get(u.id);if(!R)return;Promise.resolve().then(()=>R.onChunk(Buffer.from(u.chunk||"","base64"))).then(()=>{try{a.send({type:"pkgStreamAck",ackId:u.ackId})}catch{}}).catch(j=>{let J=k(j);try{a.send({type:"pkgStreamError",ackId:u.ackId,error:{message:J.message,stack:J.stack}})}catch{}});return}if(u.type==="taskCancelled"){let R=c.get(u.id);if(!R||R.child!==a)return;clearTimeout(R.timer),c.delete(u.id);return}if(u.type==="pkgCallbackCall"){S(a,u).then(R=>{g(a,{type:"pkgCallbackResult",id:u.id,value:R})}).catch(R=>{let j=k(R);g(a,{type:"pkgCallbackError",id:u.id,error:{message:j.message,stack:j.stack}})});return}let b=i.get(u.id);if(b)if(clearTimeout(b.timer),i.delete(u.id),s.delete(u.id),u.ok)b.resolve(u.value);else{u.error?.code==="ERR_PACKAGE_RUNTIME_TIMEOUT"&&v(a,b.taskId);let R=y(u.error?.message||"Package runtime call failed",u.error?.code,u.error?.details);R.stack=u.error?.stack||R.stack,b.reject(R)}}),a.on("exit",(u,b)=>{O(a,y(`Package runtime exited${b?` with signal ${b}`:` with code ${u}`}`,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),a.on("disconnect",()=>{O(a,y("Package runtime disconnected","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),a.on("error",u=>{O(a,y(u.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),a}function U(o){return new Promise((a,u)=>{let b=M();C(o.taskId,o.argsJson);let R=`pkg_${++p}`,j=h(o.timeoutMs),J=setTimeout(()=>{i.delete(R),s.delete(R),v(b,o.taskId),u(y(`Package runtime call timed out after ${j}ms`,"ERR_PACKAGE_RUNTIME_TIMEOUT",{outcome:"unknown_outcome",retryable:!1}))},j);i.set(R,{child:b,taskId:o.taskId,resolve:a,reject:u,timer:J});try{b.send({...o,timeoutMs:j,id:R},Z=>{Z&&(clearTimeout(J),i.delete(R),u(Z))})}catch(Z){clearTimeout(J),i.delete(R),u(Z)}})}function q(o,a,u,b=[],R=Re){return new Promise((j,J)=>{let Z=M(),W=`pkg_${++p}`,be=h(R),ke=setTimeout(()=>{i.delete(W),s.delete(W),v(Z,o),J(y(`Package runtime stream timed out after ${be}ms`,"ERR_PACKAGE_RUNTIME_TIMEOUT",{outcome:"unknown_outcome",retryable:!1}))},be);i.set(W,{child:Z,taskId:o,resolve:j,reject:J,timer:ke}),s.set(W,{onChunk:u});try{Z.send({op:"streamHandle",taskId:o,handleId:a,path:b,id:W,timeoutMs:be},_e=>{_e&&(clearTimeout(ke),i.delete(W),s.delete(W),J(_e))})}catch(_e){clearTimeout(ke),i.delete(W),s.delete(W),J(_e)}})}function D(o){try{if(!l||!l.connected)return;l.send({...o,id:`pkg_${++p}`,fire:!0})}catch{}}function L(o){try{if(!l||!l.connected)return;v(l,o)}catch{}}async function fe(o,a){let u=r.get(o);if(!u)throw new Error("Package context is not available");if(a.handleId!==null&&a.handleId!==void 0){if(a.kind!=="get"&&a.kind!=="call")throw new Error(`Unsupported package handle call kind: ${a.kind}`);return U({op:a.kind==="get"?"handleGet":"handleCall",taskId:o,handleId:a.handleId,path:a.path||[],argsJson:a.argsJson||"[]",timeoutMs:a.timeoutMs})}let b=u.get(a.packageName);if(!b)throw new Error(`Package "${a.packageName}" is not available`);if(a.kind!=="construct"&&a.kind!=="call")throw new Error(`Unsupported package call kind: ${a.kind}`);return U({op:a.kind==="construct"?"construct":"call",taskId:o,packageName:a.packageName,package:{name:b.name,fileUrl:b.fileUrl},path:a.path||[],argsJson:a.argsJson||"[]",timeoutMs:a.timeoutMs})}async function we(o,a){if(!r.get(o))throw new Error("Package context is not available");if(a.method==="open")return U({op:"streamIteratorOpen",taskId:o,handleId:a.handleId,path:a.path||[],timeoutMs:a.timeoutMs});if(a.method==="next")return U({op:"streamIteratorNext",taskId:o,streamId:a.streamId,streamTimeoutMs:a.streamTimeoutMs,timeoutMs:a.timeoutMs});if(a.method==="return")return U({op:"streamIteratorReturn",taskId:o,streamId:a.streamId,timeoutMs:a.timeoutMs});throw new Error(`Unsupported package stream method: ${a.method}`)}function Ue(o,a){r.set(o,a)}function T(o){r.delete(o),_.delete(o),D({op:"releaseTask",taskId:o})}function F(){w=!0;let o=l;o&&O(o,y("Package runtime was shut down","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}return{cleanupTaskPackages:T,cancelTask:L,executePackageRuntimeCall:fe,executePackageStreamCall:we,setTaskPackages:Ue,streamPackageHandle:q,shutdownPackageRuntime:F}}$t.exports={createPackageRuntimeBridge:Gr}});var{normalizeThrownValue:me,buildErrorPayload:jt,isNativeExecutionTimeout:Kn,isIsolateMemoryLimit:Kr,normalizeNativeExecutionError:zt}=ie(),{getCachedScript:ye}=Se(),{createWorkerPackages:Wr}=Ge(),{createWorkerContext:Xr}=Et(),{createWorkerResponse:Yr}=Ct(),{prepareWorkerBatch:Qr,createWorkerBatch:Zr}=Ut(),{getTaskInnerGuardGraceMs:en}=(Te(),$e(Pe)),{interruptTask:tn}=Me(),{parentPort:Ht}=require("worker_threads"),N=Ht||{on(e,t){e==="message"&&process.on("message",t)},postMessage(e){process.send?.(e)}},{createPackageRuntimeBridge:rn}=Bt(),Ae;try{Ae=require("isolated-vm")}catch(e){N.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var Y=new Map,nn=0,V=new Map,I=new Map,B=new Map,ee=new Map,X=new Map,H=new Set,ae=new Set,K=new Set,te=new Set,le=new Set,G=rn({workerDir:__dirname,activeTaskContexts:V,getTaskRemainingTimeoutMs:ne}),an=1e5,on=128,sn=5e3,ln=25,qt={created:0,reused:0,released:0,evicted:0,scrubFailed:0},{PACKAGE_PROXY_FALLBACK:cn,loadEsmPackageIntoContext:un,validatePackageSources:Vt,collectIsolatePackageNames:Gt}=Wr(ne),{executeResCall:dn}=Yr({callMain:tr,activeTaskContexts:V,getTaskRemainingTimeoutMs:ne,getTaskInnerGuardTimeoutMs:Oe,packageRuntimeBridge:G}),{prepareContext:Kt,releaseContext:Ne,extractFinalResult:fn}=Xr({ivm:Ae,packageRuntimeBridge:G,contextStats:qt,getCachedScript:ye,getTaskRemainingTimeoutMs:ne,loadEsmPackageIntoContext:un,PACKAGE_PROXY_FALLBACK:cn,executeResCall:dn,callMain:tr,waitForStreamTimer:mn,clearStreamTimer:pn,cleanupTaskPackages:Q,isTaskCancelled:e=>K.has(e)}),{executeWorkerBatch:_n}=Zr({getCachedScript:ye,getTaskRemainingTimeoutMs:ne,extractFinalResult:fn,postResultMessage:he,reportTaskFailure:ge,runnerPort:N,failIsolateSiblings:de,isLaneUnusable:ue});function ne(e){let t=B.get(e);return Math.max(1,Math.ceil((t??Date.now()+3e4)-Date.now()))}function Oe(e){let t=B.get(e)??Date.now()+3e4,n=en(ee.get(e)??3e4);return Math.min(2147483647,Math.max(1,Math.ceil(t+n-Date.now())))}function pn(e,t){let n=X.get(e),r=n?.get(t);return r?(clearTimeout(r.timer),n.delete(t),n.size===0&&X.delete(e),r.resolve(!1),!0):!1}function oe(e){let t=X.get(e);if(t){X.delete(e);for(let n of t.values())clearTimeout(n.timer),n.resolve(!1)}}function se(e,t="Task is no longer active"){for(let[n,r]of Y)r.taskId===e&&(Y.delete(n),clearTimeout(r.timer),r.reject(new Error(t)))}function Wt(e){for(le.add(e);le.size>an;)le.delete(le.values().next().value)}function mn(e,t,n){let r=X.get(e)?.get(t);r&&(clearTimeout(r.timer),X.get(e).delete(t),r.resolve(!1));let i=Math.max(1,Math.min(Math.trunc(Number(n)||1),Oe(e))),s=X.get(e);return s||(s=new Map,X.set(e,s)),new Promise(c=>{let _=setTimeout(()=>{s.delete(t),s.size===0&&X.delete(e),c(!0)},i);s.set(t,{timer:_,resolve:c})})}var $=null,ce=null,Dt=0,Lt=0,Ft=0;async function yn(){let e=Date.now();if(e-Lt<sn)return Ft;if(Lt=e,!$)return 0;let t=$.map(s=>s?.isolate).filter(s=>s&&!s.isDisposed),n,r=await Promise.race([Promise.allSettled(t.map(s=>s.getHeapStatistics())),new Promise(s=>{n=setTimeout(()=>s([]),ln)})]);clearTimeout(n);let i=0;for(let s of r){if(s.status!=="fulfilled")continue;let c=s.value.heap_size_limit||1,_=s.value.used_heap_size/c;_>i&&(i=_)}return Ft=i,i}async function he(e,t={}){let n=e?.id;if(n){if(H.has(n)||ae.has(n)||K.has(n)||!t.allowInactive&&!I.has(n))return!1;ae.add(n)}try{if(e.heapRatio=await yn(),e.runnerRssBytes=process.memoryUsage().rss,e.contextStats=hn(),n){if(!t.allowInactive&&!I.has(n))return!1;H.add(n)}return N.postMessage(e),!0}finally{n&&ae.delete(n)}}function hn(){return{...qt,idle:0}}function Xt(e,t,n){if(!$)ce={memoryLimitMb:e,poolSize:t,tasksPerIsolate:n},$=new Array(t).fill(null);else if(ce.memoryLimitMb!==e||ce.poolSize!==t||ce.tasksPerIsolate!==n)throw new Error("Executor isolate pool configuration cannot change at runtime");for(let r=0;r<$.length;r++){let i=(Dt+r)%$.length,s=$[i];if((!s||!s.isolate||s.isolate.isDisposed)&&(s={isolate:new Ae.Isolate({memoryLimit:e,inspector:!0}),taskIds:new Set},$[i]=s),s.taskIds.size<n)return Dt=(i+1)%$.length,s}throw new Error("No isolate lane is available")}function Yt(e){return`${Array.isArray($)?$.indexOf(e):-1}`}function ue(e,t){return!!e?.isolate?.isDisposed||Kr(t)}function de(e,t,n){for(let r of[...e.taskIds]){if(r===t||ae.has(r))continue;e.taskIds.delete(r),I.delete(r),V.delete(r),B.delete(r),ee.delete(r),oe(r),se(r,n),G.cancelTask(r),Q(r),H.has(r)||(ge(r,Object.assign(new Error("Isolate was disposed because a sibling task could not continue"),{code:"ERR_EXECUTOR_ISOLATE_LOST",details:{outcome:"unknown_outcome",retryable:!1,reason:n}}),{}),H.add(r),N.postMessage({type:"result",id:r,success:!1,error:{message:"Isolate was disposed because a sibling task could not continue",code:"ERR_EXECUTOR_ISOLATE_LOST",details:{outcome:"unknown_outcome",retryable:!1,reason:n}}})),N.postMessage({type:"taskReleased",id:r}),H.delete(r),te.delete(r)}try{e.isolate.dispose()}catch{}}async function gn(e){if(H.has(e)||ae.has(e)||te.has(e)||K.has(e))return;let t=I.get(e);if(!t){N.postMessage({type:"taskCancelled",id:e});return}K.add(e);try{ue(t,null)&&de(t,e,"sibling_cancelled"),G.cancelTask(e),oe(e),se(e,"Task was cancelled"),Q(e);let n=V.get(e),r=!1,i=Ne(t,n).then(()=>{r=!0}),s;for(await Promise.race([i,new Promise(c=>{s=setTimeout(c,25)})]),clearTimeout(s);!r&&n&&!t.isolate.isDisposed;)await tn(t,n,()=>K.has(e)&&!r),r||await new Promise(c=>setTimeout(c,100));await i,I.delete(e),V.delete(e),B.delete(e),ee.delete(e),t.taskIds.delete(e),N.postMessage({type:"taskCancelled",id:e}),H.delete(e)}finally{K.delete(e),te.delete(e)}}function Qt(e,t){K.has(e)||I.get(e)!==t||!t.taskIds.has(e)||(t.taskIds.delete(e),V.delete(e),I.delete(e),B.delete(e),ee.delete(e),oe(e),se(e),Q(e),N.postMessage({type:"taskReleased",id:e}),H.delete(e),te.delete(e))}function Zt(e,t){return t.taskIds.has(e)&&!K.has(e)&&I.get(e)===t&&!t.isolate.isDisposed}function er(e,t,n,r){return!t.taskIds.has(e)||I.get(e)!==t?(B.delete(e),oe(e),se(e,"Task was cancelled during preparation"),G.cancelTask(e),Q(e),Promise.resolve()):(zt(n),ue(t,n)&&de(t,e,"sibling_preparation_failure"),B.delete(e),oe(e),se(e,"Task preparation failed"),I.delete(e),t.taskIds.delete(e),G.cancelTask(e),Q(e),Ie(e,n,r,{allowInactive:!0}).then(()=>{N.postMessage({type:"taskReleased",id:e}),H.delete(e),te.delete(e)}))}function wn(e){if(!e)return;let t=I.get(e);t&&t.taskIds.delete(e),I.delete(e),V.delete(e),B.delete(e),oe(e),se(e,"Task setup failed");try{G.cancelTask(e)}catch{}try{Q(e)}catch{}try{N.postMessage({type:"taskReleased",id:e})}catch{}H.delete(e),ae.delete(e),te.delete(e)}async function bn(e,t){let n=me(t);if(n.code==="ERR_EXECUTOR_DUPLICATE_TASK_ID"||n.code==="ERR_EXECUTOR_INVALID_TASK_ID"){N.postMessage({type:"protocolError",code:n.code,message:n.message});return}try{ge(e?.id,n,{}),await he({type:"result",id:e?.id,success:!1,error:{message:n.message,stack:n.stack,code:n.code}},{allowInactive:!0})}finally{wn(e?.id)}}function Jt(e,t){bn(e,t).catch(n=>{let r=me(n);try{N.postMessage({type:"protocolError",code:"ERR_EXECUTOR_RECOVERY_FAILED",message:r.message})}catch{}})}N.on("message",async e=>{if(!e||typeof e!="object"){N.postMessage({type:"protocolError",code:"ERR_EXECUTOR_INVALID_MESSAGE",message:"Executor message must be an object"});return}if(e.type==="execute")xn(e).catch(t=>Jt(e,t));else if(e.type==="executeBatch")vn(e).catch(t=>Jt(e,t));else if(e.type==="invokeRuntimeCallback")kn(e).catch(t=>{let n=me(t);try{N.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:n.message})}catch{}});else if(e.type==="callResult"){let t=Y.get(e.callId);t&&(Y.delete(e.callId),clearTimeout(t.timer),t.resolve(e.result))}else if(e.type==="callError"){let t=Y.get(e.callId);t&&(Y.delete(e.callId),clearTimeout(t.timer),t.reject(new Error(e.error)))}else e.type==="cancelTask"?gn(e.id).catch(()=>{}):e.type==="shutdown"&&Sn()});async function kn(e){let t=V.get(e.id);if(!t){N.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:`Runtime callback context not found: ${e.id}`});return}let n=await t.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(e.callbackId)}, ${JSON.stringify(e.argsJson||"[]")});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0},timeout:ne(e.id)}),r=JSON.parse(n);N.postMessage({...r,type:"runtimeCallbackResult",callId:e.callId})}function tr(e,t,n){return H.has(e)||K.has(e)||!I.has(e)||!B.has(e)?Promise.reject(new Error("Task is no longer active")):new Promise((r,i)=>{let s=`cb_${++nn}`,c=setTimeout(()=>{let _=Y.get(s);_&&(Y.delete(s),_.reject(new Error(`Host callback timed out: ${t}`)))},Oe(e));Y.set(s,{taskId:e,timer:c,resolve:r,reject:i}),N.postMessage({...n,type:t,id:e,callId:s})})}function ge(e,t,n){if(te.has(e)||K.has(e))return;te.add(e);let r=jt(t,n);N.postMessage({type:"taskFailure",id:e,error:{...r,stack:t.stack,code:r.code??t.code}})}async function Ie(e,t,n,r={}){t=me(t),zt(t),ge(e,t,n);let i=jt(t,n);t.details&&(i.details={...i.details,...t.details});let s,c=V.get(e),_=I.get(e);if(c&&_&&!_.isolate.isDisposed)try{let m=await ye(_.isolate,"JSON.stringify({logs: __logs, truncated: $ctx.$share.$logsTruncated === true})","extract-diagnostic-logs.js");s=JSON.parse(await m.run(c,{timeout:100}))}catch{}await he({type:"result",id:e,success:!1,diagnosticLogs:s,error:{...i,stack:t.stack,code:i.code??t.code}},{allowInactive:r.allowInactive===!0})}function rr(e){if(!e||typeof e!="string"){let t=new Error("Executor task id must be a non-empty string");throw t.code="ERR_EXECUTOR_INVALID_TASK_ID",t}if(I.has(e)||B.has(e)||H.has(e)||le.has(e)){let t=new Error(`Executor task id cannot be reused: ${e}`);throw t.code="ERR_EXECUTOR_DUPLICATE_TASK_ID",t}}function nr(e){let t=Number(e.timeoutMs??3e4),n=Number(e.memoryLimitMb??128),r=Number(e.isolatePoolSize??8),i=Number(e.tasksPerIsolate??1);if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0||t>2147483647)throw new Error("Invalid executor timeoutMs");if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>on)throw new Error("Invalid executor memoryLimitMb");if(!Number.isFinite(r)||!Number.isInteger(r)||r<1||r>128)throw new Error("Invalid executor isolatePoolSize");if(!Number.isFinite(i)||!Number.isInteger(i)||i<1||i>64)throw new Error("Invalid executor tasksPerIsolate");return{timeoutMs:Math.trunc(t),memoryLimitMb:Math.trunc(n),isolatePoolSize:Math.trunc(r),tasksPerIsolate:Math.trunc(i)}}async function xn(e){let{id:t,code:n,pkgSources:r,snapshot:i}=e;rr(t),Wt(t);let{timeoutMs:s,memoryLimitMb:c,isolatePoolSize:_,tasksPerIsolate:m}=nr(e),l={handler:e.sourceCode||n||""},p=Vt(r),w=Date.now()+s;B.set(t,w),ee.set(t,s);let d=Gt(n,p),h=Xt(c,_,m);h.taskIds.add(t),I.set(t,h);let y=h.isolate,k;try{k=await Kt(h,t,p,i,d,s,w)}catch(E){await er(t,h,E,l);return}if(!Zt(t,h)){try{k.release()}catch{}G.cancelTask(t),Q(t);return}V.set(t,k);let x=ee.get(t);x!==void 0&&B.set(t,Date.now()+x),N.postMessage({type:"taskLane",id:t,laneKey:Yt(h)});try{let E=`
2882
+ (async () => {
2883
+ "use strict";
2884
+ ${n}
2885
+ })().then((__result) => __extractResult(__result, __result === undefined));
2886
+ `,v=await(await ye(y,E,"handler.js")).run(k,{timeout:ne(t),promise:!0}),g=JSON.parse(v);await he({...g,type:"result",id:t,success:!0})}catch(E){h.taskIds.has(t)&&(await Ie(t,E,l),ue(h,E)&&de(h,t,"sibling_execution_failure"))}finally{try{await Ne(h,k)}finally{Qt(t,h)}}}async function vn(e){let{id:t,codeBlocks:n,pkgSources:r,snapshot:i}=e;rr(t),Wt(t);let{preHooksAndHandler:s,postHooks:c,sourceByPhase:_}=Qr(n),{timeoutMs:m,memoryLimitMb:l,isolatePoolSize:p,tasksPerIsolate:w}=nr(e),d=Vt(r),h=Date.now()+m;B.set(t,h),ee.set(t,m);let y=Gt((n||[]).map(v=>v.code||"").join(`
2887
+ `),d),k=Xt(l,p,w);k.taskIds.add(t),I.set(t,k);let x=k.isolate,E;try{E=await Kt(k,t,d,i,y,m,h)}catch(v){await er(t,k,v,_);return}if(!Zt(t,k)){try{E.release()}catch{}G.cancelTask(t),Q(t);return}V.set(t,E);let O=ee.get(t);O!==void 0&&B.set(t,Date.now()+O),N.postMessage({type:"taskLane",id:t,laneKey:Yt(k)});try{await _n({id:t,isolate:x,context:E,entry:k,preHooksAndHandler:s,postHooks:c,sourceByPhase:_})}catch(v){k.taskIds.has(t)&&(await Ie(t,v,_),ue(k,v)&&de(k,t,"sibling_execution_failure"))}finally{try{await Ne(k,E)}finally{Qt(t,k)}}}function Q(e){G.cleanupTaskPackages(e)}function ar(){G.shutdownPackageRuntime()}function Sn(){if(ar(),$){for(let e of $)if(!(!e?.isolate||e.isolate.isDisposed))try{e.isolate.dispose()}catch{}$=null,ce=null}try{N.postMessage({type:"shutdownComplete"})}catch{}Ht?.close()}process.on("exit",ar);