@enfyra/kernel 1.0.4

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.
@@ -0,0 +1,682 @@
1
+ "use strict";var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var I=T((Ae,j)=>{"use strict";var{fork:re}=require("child_process"),ae=require("path");function ne({workerDir:e,activeTaskContexts:t}){let s=new Map,a=new Map,r=null,i=0;function l(u){for(let n of a.values())n.reject(u);a.clear()}function _(u){let n=typeof u=="string"?JSON.parse(u):u;if(n?.error)throw new Error(n.error);return n?.value}async function d(u){let n=t.get(u.taskId);if(!n)throw new Error(`Package callback context not found: ${u.taskId}`);let o=JSON.stringify(u.callbackId),f=JSON.stringify(u.argsJson||"[]"),g=await n.evalClosure(`return __invokeRuntimeCallback(${o}, ${f});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}});return _(g)}function k(){if(r&&r.connected)return r;let u=ae.join(e,"package-runtime.child.js"),n=re(u,[],{stdio:["ignore","ignore","ignore","ipc"]});return r=n,n.on("message",o=>{if(!o||!o.id)return;if(o.type==="pkgCallbackCall"){d(o).then(g=>{try{n.send({type:"pkgCallbackResult",id:o.id,value:g})}catch{}}).catch(g=>{try{n.send({type:"pkgCallbackError",id:o.id,error:{message:g.message,stack:g.stack}})}catch{}});return}let f=a.get(o.id);if(f)if(a.delete(o.id),o.ok)f.resolve(o.value);else{let g=new Error(o.error?.message||"Package runtime call failed");g.stack=o.error?.stack||g.stack,f.reject(g)}}),n.on("exit",(o,f)=>{r===n&&(r=null),l(new Error(`Package runtime exited${f?` with signal ${f}`:` with code ${o}`}`))}),n.on("error",o=>{r===n&&(r=null),l(o)}),n}function y(u){return new Promise((n,o)=>{let f=k(),g=`pkg_${++i}`;a.set(g,{resolve:n,reject:o});try{f.send({...u,id:g},w=>{w&&(a.delete(g),o(w))})}catch(w){a.delete(g),o(w)}})}function m(u){try{if(!r||!r.connected)return;r.send({...u,id:`pkg_${++i}`,fire:!0})}catch{}}async function c(u,n){let o=s.get(u);if(!o)throw new Error("Package context is not available");if(n.handleId)return y({op:n.kind==="get"?"handleGet":"handleCall",taskId:u,handleId:n.handleId,path:n.path||[],argsJson:n.argsJson||"[]"});let f=o.get(n.packageName);if(!f)throw new Error(`Package "${n.packageName}" is not available`);return y({op:n.kind==="construct"?"construct":"call",taskId:u,packageName:n.packageName,package:{name:f.name,fileUrl:f.fileUrl},path:n.path||[],argsJson:n.argsJson||"[]"})}function h(u,n){s.set(u,n)}function v(u){s.delete(u),m({op:"releaseTask",taskId:u})}function p(){if(r){try{r.kill()}catch{}r=null}}return{cleanupTaskPackages:v,executePackageRuntimeCall:c,setTaskPackages:h,shutdownPackageRuntime:p}}j.exports={createPackageRuntimeBridge:ne}});var H=T((Ne,U)=>{"use strict";var se=`
2
+ "use strict";
3
+ let $ctx = {};
4
+ let $pkgs = {};
5
+ let __taskId = null;
6
+ let __logs = [];
7
+ let __runtimeCallbackCounter = 0;
8
+ let __runtimeCallbacks = new Map();
9
+
10
+ const __applyOpts = { result: { promise: true, copy: true } };
11
+
12
+ function __unwrapMainThreadPayload(v) {
13
+ if (v !== null && typeof v === 'object' && v.__e === 'u') return undefined;
14
+ if (v !== null && typeof v === 'object' && v.__e === 'v') return __unwrapMainThreadPayload(v.d);
15
+ if (v !== null && typeof v === 'object' && v.__date) return new Date(v.__date);
16
+ if (v !== null && typeof v === 'object' && v.__set) {
17
+ return new Set(v.__set.map(__unwrapMainThreadPayload));
18
+ }
19
+ if (v !== null && typeof v === 'object' && v.__map) {
20
+ return new Map(v.__map.map(([key, value]) => [
21
+ __unwrapMainThreadPayload(key),
22
+ __unwrapMainThreadPayload(value),
23
+ ]));
24
+ }
25
+ if (v !== null && typeof v === 'object' && v.__regexp) {
26
+ return new RegExp(v.__regexp.source, v.__regexp.flags || '');
27
+ }
28
+ if (v !== null && typeof v === 'object' && v.__error) {
29
+ const error = new Error(v.__error.message || '');
30
+ error.name = v.__error.name || 'Error';
31
+ if (v.__error.stack) error.stack = v.__error.stack;
32
+ return error;
33
+ }
34
+ if (v !== null && typeof v === 'object' && v.__url) return new URL(v.__url);
35
+ if (v !== null && typeof v === 'object' && v.__urlSearchParams) {
36
+ return new URLSearchParams(v.__urlSearchParams);
37
+ }
38
+ if (v !== null && typeof v === 'object' && v.__blob) {
39
+ return new Blob([Uint8Array.from(v.__blob.data || [])], {
40
+ type: v.__blob.type || '',
41
+ });
42
+ }
43
+ if (v !== null && typeof v === 'object' && v.__file) {
44
+ const parts = [Uint8Array.from(v.__file.data || [])];
45
+ const options = {
46
+ type: v.__file.type || '',
47
+ lastModified: v.__file.lastModified,
48
+ };
49
+ return typeof File !== 'undefined'
50
+ ? new File(parts, v.__file.name || 'file', options)
51
+ : new Blob(parts, options);
52
+ }
53
+ if (v !== null && typeof v === 'object' && v.__formData) {
54
+ const form = new FormData();
55
+ for (const [key, value] of v.__formData) {
56
+ form.append(key, __unwrapMainThreadPayload(value));
57
+ }
58
+ return form;
59
+ }
60
+ if (v !== null && typeof v === 'object' && v.__typedArray) {
61
+ const Ctor = globalThis[v.__typedArray] || Uint8Array;
62
+ return new Ctor(v.data || []);
63
+ }
64
+ if (v !== null && typeof v === 'object' && v.__arrayBuffer) {
65
+ return Uint8Array.from(v.__arrayBuffer).buffer;
66
+ }
67
+ if (v !== null && typeof v === 'object' && v.__pkgHandle) {
68
+ return __createPkgHandleProxy(Promise.resolve(v.__pkgHandle), []);
69
+ }
70
+ if (Array.isArray(v)) return v.map(__unwrapMainThreadPayload);
71
+ if (v !== null && typeof v === 'object' && !v.__pkgHandle) {
72
+ const out = {};
73
+ for (const [key, value] of Object.entries(v)) {
74
+ out[key] = __unwrapMainThreadPayload(value);
75
+ }
76
+ return out;
77
+ }
78
+ return v;
79
+ }
80
+
81
+ function __parseMainThreadResult(s) {
82
+ const w = typeof s === 'string' ? JSON.parse(s) : s;
83
+ return __unwrapMainThreadPayload(w);
84
+ }
85
+
86
+ async function __call(type, dataJson) {
87
+ const r = await __callRef.apply(undefined, [__taskId, type, dataJson], __applyOpts);
88
+ return __parseMainThreadResult(r);
89
+ }
90
+
91
+ async function __encodeRuntimeArg(value) {
92
+ if (typeof value === 'function') {
93
+ if (value.__pkgHandlePromise) {
94
+ return { __pkgHandleArg: await value.__pkgHandlePromise };
95
+ }
96
+ if (typeof value.then === 'function') {
97
+ return __encodeRuntimeArg(await value);
98
+ }
99
+ const id = 'fn_' + (++__runtimeCallbackCounter);
100
+ __runtimeCallbacks.set(id, value);
101
+ return { __fnRef: id };
102
+ }
103
+ if (value instanceof Date) return { __date: value.toISOString() };
104
+ if (value instanceof Set) {
105
+ const items = [];
106
+ for (const item of value.values()) items.push(await __encodeRuntimeArg(item));
107
+ return { __set: items };
108
+ }
109
+ if (value instanceof Map) {
110
+ const entries = [];
111
+ for (const [key, item] of value.entries()) {
112
+ entries.push([
113
+ await __encodeRuntimeArg(key),
114
+ await __encodeRuntimeArg(item),
115
+ ]);
116
+ }
117
+ return { __map: entries };
118
+ }
119
+ if (value instanceof RegExp) {
120
+ return { __regexp: { source: value.source, flags: value.flags } };
121
+ }
122
+ if (value instanceof Error) {
123
+ return {
124
+ __error: {
125
+ name: value.name,
126
+ message: value.message,
127
+ stack: value.stack,
128
+ },
129
+ };
130
+ }
131
+ if (typeof URL !== 'undefined' && value instanceof URL) return { __url: value.href };
132
+ if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
133
+ return { __urlSearchParams: value.toString() };
134
+ }
135
+ if (typeof File !== 'undefined' && value instanceof File) {
136
+ return {
137
+ __file: {
138
+ name: value.name,
139
+ type: value.type,
140
+ lastModified: value.lastModified,
141
+ data: Array.from(new Uint8Array(await value.arrayBuffer())),
142
+ },
143
+ };
144
+ }
145
+ if (typeof Blob !== 'undefined' && value instanceof Blob) {
146
+ return {
147
+ __blob: {
148
+ type: value.type,
149
+ data: Array.from(new Uint8Array(await value.arrayBuffer())),
150
+ },
151
+ };
152
+ }
153
+ if (typeof FormData !== 'undefined' && value instanceof FormData) {
154
+ const entries = [];
155
+ for (const [key, item] of value.entries()) {
156
+ entries.push([key, await __encodeRuntimeArg(item)]);
157
+ }
158
+ return { __formData: entries };
159
+ }
160
+ if (ArrayBuffer.isView(value)) {
161
+ return {
162
+ __typedArray: value.constructor?.name || 'Uint8Array',
163
+ data: Array.from(value),
164
+ };
165
+ }
166
+ if (value instanceof ArrayBuffer) {
167
+ return { __arrayBuffer: Array.from(new Uint8Array(value)) };
168
+ }
169
+ if (Array.isArray(value)) return Promise.all(value.map(__encodeRuntimeArg));
170
+ if (value && typeof value === 'object') {
171
+ const out = {};
172
+ for (const key of Object.keys(value)) {
173
+ out[key] = await __encodeRuntimeArg(value[key]);
174
+ }
175
+ return out;
176
+ }
177
+ return value;
178
+ }
179
+
180
+ async function __stringifyRuntimeArgs(args) {
181
+ return JSON.stringify(await Promise.all(args.map(__encodeRuntimeArg)));
182
+ }
183
+
184
+ async function __invokeRuntimeCallback(id, argsJson) {
185
+ const fn = __runtimeCallbacks.get(id);
186
+ if (typeof fn !== 'function') {
187
+ return JSON.stringify({ error: 'Package callback not found: ' + id });
188
+ }
189
+ try {
190
+ const value = await fn(...JSON.parse(argsJson || '[]').map(__unwrapMainThreadPayload));
191
+ return JSON.stringify({ value: await __encodeRuntimeArg(value) });
192
+ } catch (error) {
193
+ return JSON.stringify({ error: error && error.message ? error.message : String(error) });
194
+ }
195
+ }
196
+
197
+ function __safeClone(v) {
198
+ if (v === undefined) return undefined;
199
+ try { return JSON.parse(JSON.stringify(v)); }
200
+ catch { return null; }
201
+ }
202
+
203
+ function __extractResult(result, isAbsent) {
204
+ const valueAbsent = isAbsent === true;
205
+ const out = {
206
+ valueAbsent,
207
+ ctxChanges: {
208
+ $body: __safeClone($ctx.$body),
209
+ $query: __safeClone($ctx.$query),
210
+ $params: __safeClone($ctx.$params),
211
+ $data: __safeClone($ctx.$data),
212
+ $share: __safeClone($ctx.$share),
213
+ $flow: __safeClone($ctx.$flow),
214
+ $error: __safeClone($ctx.$error),
215
+ $api: __safeClone($ctx.$api),
216
+ $statusCode: $ctx.$statusCode,
217
+ }
218
+ };
219
+ if (!valueAbsent) out.value = __safeClone(result);
220
+ return JSON.stringify(out);
221
+ }
222
+
223
+ 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' };
224
+
225
+ if (typeof TextEncoder === 'undefined') {
226
+ globalThis.TextEncoder = class TextEncoder {
227
+ encode(input = '') {
228
+ const encoded = unescape(encodeURIComponent(String(input)));
229
+ const out = new Uint8Array(encoded.length);
230
+ for (let i = 0; i < encoded.length; i++) out[i] = encoded.charCodeAt(i);
231
+ return out;
232
+ }
233
+ };
234
+ }
235
+
236
+ if (typeof TextDecoder === 'undefined') {
237
+ globalThis.TextDecoder = class TextDecoder {
238
+ decode(input = new Uint8Array()) {
239
+ const bytes = ArrayBuffer.isView(input) ? input : new Uint8Array(input);
240
+ let binary = '';
241
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
242
+ return decodeURIComponent(escape(binary));
243
+ }
244
+ };
245
+ }
246
+
247
+ if (typeof FormData === 'undefined') {
248
+ globalThis.FormData = class FormData {
249
+ constructor() {
250
+ this.__entries = [];
251
+ }
252
+
253
+ append(name, value) {
254
+ this.__entries.push([String(name), value]);
255
+ }
256
+
257
+ get(name) {
258
+ const key = String(name);
259
+ const match = this.__entries.find(([entryName]) => entryName === key);
260
+ return match ? match[1] : null;
261
+ }
262
+
263
+ entries() {
264
+ return this.__entries[Symbol.iterator]();
265
+ }
266
+
267
+ [Symbol.iterator]() {
268
+ return this.entries();
269
+ }
270
+ };
271
+ }
272
+
273
+ if (typeof URLSearchParams === 'undefined') {
274
+ globalThis.URLSearchParams = class URLSearchParams {
275
+ constructor(input = '') {
276
+ this.__entries = [];
277
+ const inputText = String(input);
278
+ const text = inputText.startsWith('?') ? inputText.slice(1) : inputText;
279
+ if (!text) return;
280
+ for (const part of text.split('&')) {
281
+ if (!part) continue;
282
+ const [key, value = ''] = part.split('=');
283
+ this.append(decodeURIComponent(key), decodeURIComponent(value));
284
+ }
285
+ }
286
+
287
+ append(name, value) {
288
+ this.__entries.push([String(name), String(value)]);
289
+ }
290
+
291
+ get(name) {
292
+ const key = String(name);
293
+ const match = this.__entries.find(([entryName]) => entryName === key);
294
+ return match ? match[1] : null;
295
+ }
296
+
297
+ toString() {
298
+ return this.__entries
299
+ .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))
300
+ .join('&');
301
+ }
302
+
303
+ entries() {
304
+ return this.__entries[Symbol.iterator]();
305
+ }
306
+
307
+ [Symbol.iterator]() {
308
+ return this.entries();
309
+ }
310
+ };
311
+ }
312
+
313
+ if (typeof URL === 'undefined') {
314
+ globalThis.URL = class URL {
315
+ constructor(input) {
316
+ this.href = String(input);
317
+ const schemeIndex = this.href.indexOf('://');
318
+ if (schemeIndex >= 0) {
319
+ const hostStart = schemeIndex + 3;
320
+ const hostEndCandidates = ['/', '?', '#']
321
+ .map((token) => this.href.indexOf(token, hostStart))
322
+ .filter((index) => index >= 0);
323
+ const hostEnd = hostEndCandidates.length ? Math.min(...hostEndCandidates) : this.href.length;
324
+ this.host = this.href.slice(hostStart, hostEnd);
325
+ } else {
326
+ this.host = '';
327
+ }
328
+ const query = this.href.includes('?') ? this.href.slice(this.href.indexOf('?') + 1).split('#')[0] : '';
329
+ this.search = query ? '?' + query : '';
330
+ this.searchParams = new URLSearchParams(query);
331
+ }
332
+
333
+ toString() {
334
+ return this.href;
335
+ }
336
+ };
337
+ }
338
+
339
+ function __createPkgHandleProxy(handlePromise, path) {
340
+ const fn = function (...args) {
341
+ return __createAsyncPkgResultProxy(
342
+ handlePromise.then((handleId) =>
343
+ __stringifyRuntimeArgs(args).then((argsJson) =>
344
+ __call('pkgCall', JSON.stringify({ handleId, path, argsJson, kind: 'call' })),
345
+ ),
346
+ ),
347
+ [],
348
+ );
349
+ };
350
+ return new Proxy(fn, {
351
+ get: (_, prop) => {
352
+ if (prop === 'then') return undefined;
353
+ if (prop === '__pkgHandle') return undefined;
354
+ if (prop === '__pkgHandlePromise') return handlePromise;
355
+ return __createAsyncPkgResultProxy(
356
+ handlePromise.then((handleId) =>
357
+ __call('pkgCall', JSON.stringify({
358
+ handleId,
359
+ path: path.concat(String(prop)),
360
+ kind: 'get',
361
+ })),
362
+ ),
363
+ [],
364
+ );
365
+ },
366
+ apply: (_target, _thisArg, args) =>
367
+ __createAsyncPkgResultProxy(
368
+ handlePromise.then((handleId) =>
369
+ __stringifyRuntimeArgs(args).then((argsJson) =>
370
+ __call('pkgCall', JSON.stringify({ handleId, path, argsJson, kind: 'call' })),
371
+ ),
372
+ ),
373
+ [],
374
+ )
375
+ });
376
+ }
377
+
378
+ function __resolvePkgResultPath(base, path) {
379
+ let current = base;
380
+ let receiver = undefined;
381
+ for (const key of path) {
382
+ if (current === undefined || current === null) {
383
+ throw new Error('Package result property not found: ' + path.join('.'));
384
+ }
385
+ receiver = current;
386
+ current = current[key];
387
+ }
388
+ return { target: current, receiver };
389
+ }
390
+
391
+ function __createAsyncPkgResultProxy(valuePromise, path) {
392
+ const resolveValue = () => valuePromise.then(__wrapPkgValue);
393
+ const resolvePath = () =>
394
+ resolveValue().then((base) => __resolvePkgResultPath(base, path));
395
+ const promiseForPath = () =>
396
+ path.length === 0 ? resolveValue() : resolvePath().then(({ target }) => target);
397
+
398
+ const fn = function (...args) {
399
+ return __createAsyncPkgResultProxy(
400
+ resolvePath().then(({ target, receiver }) => {
401
+ if (typeof target !== 'function') {
402
+ throw new Error('Package result is not callable: ' + (path.join('.') || '<root>'));
403
+ }
404
+ return Reflect.apply(target, receiver, args);
405
+ }),
406
+ [],
407
+ );
408
+ };
409
+
410
+ return new Proxy(fn, {
411
+ get: (_target, prop) => {
412
+ if (prop === '__pkgHandle') return undefined;
413
+ if (prop === '__pkgHandlePromise') return undefined;
414
+ if (prop === 'then') {
415
+ const promise = promiseForPath();
416
+ return promise.then.bind(promise);
417
+ }
418
+ if (prop === 'catch') {
419
+ const promise = promiseForPath();
420
+ return promise.catch.bind(promise);
421
+ }
422
+ if (prop === 'finally') {
423
+ const promise = promiseForPath();
424
+ return promise.finally.bind(promise);
425
+ }
426
+ return __createAsyncPkgResultProxy(valuePromise, path.concat(String(prop)));
427
+ },
428
+ apply: (_target, _thisArg, args) =>
429
+ __createAsyncPkgResultProxy(
430
+ resolvePath().then(({ target, receiver }) => {
431
+ if (typeof target !== 'function') {
432
+ throw new Error('Package result is not callable: ' + (path.join('.') || '<root>'));
433
+ }
434
+ return Reflect.apply(target, receiver, args);
435
+ }),
436
+ [],
437
+ )
438
+ });
439
+ }
440
+
441
+ function __createAsyncMainResultProxy(valuePromise, path) {
442
+ const resolveValue = () => valuePromise;
443
+ const resolvePath = () =>
444
+ resolveValue().then((base) => __resolvePkgResultPath(base, path));
445
+ const promiseForPath = () =>
446
+ path.length === 0 ? resolveValue() : resolvePath().then(({ target }) => target);
447
+
448
+ const fn = function (...args) {
449
+ return __createAsyncMainResultProxy(
450
+ resolvePath().then(({ target, receiver }) => {
451
+ if (typeof target !== 'function') {
452
+ throw new Error('Async result is not callable: ' + (path.join('.') || '<root>'));
453
+ }
454
+ return Reflect.apply(target, receiver, args);
455
+ }),
456
+ [],
457
+ );
458
+ };
459
+
460
+ return new Proxy(fn, {
461
+ get: (_target, prop) => {
462
+ if (prop === 'then') {
463
+ const promise = promiseForPath();
464
+ return promise.then.bind(promise);
465
+ }
466
+ if (prop === 'catch') {
467
+ const promise = promiseForPath();
468
+ return promise.catch.bind(promise);
469
+ }
470
+ if (prop === 'finally') {
471
+ const promise = promiseForPath();
472
+ return promise.finally.bind(promise);
473
+ }
474
+ return __createAsyncMainResultProxy(valuePromise, path.concat(String(prop)));
475
+ },
476
+ apply: (_target, _thisArg, args) =>
477
+ __createAsyncMainResultProxy(
478
+ resolvePath().then(({ target, receiver }) => {
479
+ if (typeof target !== 'function') {
480
+ throw new Error('Async result is not callable: ' + (path.join('.') || '<root>'));
481
+ }
482
+ return Reflect.apply(target, receiver, args);
483
+ }),
484
+ [],
485
+ )
486
+ });
487
+ }
488
+
489
+ function __wrapPkgValue(value) {
490
+ if (value && typeof value === 'object' && value.__pkgHandle) {
491
+ return __createPkgHandleProxy(Promise.resolve(value.__pkgHandle), []);
492
+ }
493
+ return value;
494
+ }
495
+
496
+ function __createPkgProxy(packageName, path) {
497
+ const fn = function (...args) {
498
+ return __createAsyncPkgResultProxy(
499
+ __stringifyRuntimeArgs(args).then((argsJson) =>
500
+ __call('pkgCall', JSON.stringify({ packageName, path, argsJson, kind: 'call' })),
501
+ ),
502
+ [],
503
+ );
504
+ };
505
+ return new Proxy(fn, {
506
+ get: (_, prop) => {
507
+ if (prop === 'then') return undefined;
508
+ return __createPkgProxy(packageName, path.concat(String(prop)));
509
+ },
510
+ apply: (_target, _thisArg, args) =>
511
+ __createAsyncPkgResultProxy(
512
+ __stringifyRuntimeArgs(args).then((argsJson) =>
513
+ __call('pkgCall', JSON.stringify({ packageName, path, argsJson, kind: 'call' })),
514
+ ),
515
+ [],
516
+ ),
517
+ construct: (_target, args) => {
518
+ const handlePromise = __stringifyRuntimeArgs(args)
519
+ .then((argsJson) =>
520
+ __call('pkgCall', JSON.stringify({ packageName, path, argsJson, kind: 'construct' })),
521
+ )
522
+ .then((value) => {
523
+ if (value && value.__pkgHandlePromise) return value.__pkgHandlePromise;
524
+ if (!value || !value.__pkgHandle) throw new Error('Package constructor did not return a handle');
525
+ return value.__pkgHandle;
526
+ });
527
+ return __createPkgHandleProxy(handlePromise, []);
528
+ }
529
+ });
530
+ }
531
+
532
+ const require = (name) => {
533
+ if ($pkgs[name] === undefined) throw new Error('Module "' + name + '" is not available. Install it via Settings \\u2192 Packages');
534
+ return $pkgs[name];
535
+ };
536
+
537
+ const console = {
538
+ log: (...a) => $ctx.$logs(...a),
539
+ warn: (...a) => $ctx.$logs(...a),
540
+ error: (...a) => $ctx.$logs(...a),
541
+ info: (...a) => $ctx.$logs(...a),
542
+ };
543
+
544
+ function __resetTask(snapshot, taskId) {
545
+ $ctx = snapshot || {};
546
+ $pkgs = {};
547
+ __taskId = taskId;
548
+ __logs = [];
549
+ __runtimeCallbackCounter = 0;
550
+ __runtimeCallbacks = new Map();
551
+ %%PKG_SETUP%%
552
+ $ctx.$pkgs = $pkgs;
553
+ $ctx.$share = $ctx.$share || {};
554
+ $ctx.$share.$logs = __logs;
555
+ $ctx.$repos = new Proxy({}, {
556
+ get: (_, table) => new Proxy({}, {
557
+ get: (_, method) => async (...args) =>
558
+ __call('repoCall', JSON.stringify({ table: String(table), method: String(method), argsJson: JSON.stringify(args) }))
559
+ })
560
+ });
561
+ $ctx.$helpers = new Proxy({}, {
562
+ get: (_, name) => {
563
+ const basePath = String(name);
564
+ const fn = (...args) =>
565
+ __createAsyncMainResultProxy(
566
+ __call('helpersCall', JSON.stringify({ name: basePath, argsJson: JSON.stringify(args) })),
567
+ [],
568
+ );
569
+ return new Proxy(fn, {
570
+ get: (_, subName) => (...args) =>
571
+ __createAsyncMainResultProxy(
572
+ __call('helpersCall', JSON.stringify({ name: basePath + '.' + String(subName), argsJson: JSON.stringify(args) })),
573
+ [],
574
+ )
575
+ });
576
+ }
577
+ });
578
+ $ctx.$socket = new Proxy({}, {
579
+ get: (_, method) => async (...args) =>
580
+ __call('socketCall', JSON.stringify({ method: String(method), argsJson: JSON.stringify(args) }))
581
+ });
582
+ $ctx.$cache = new Proxy({}, {
583
+ get: (_, method) => async (...args) =>
584
+ __call('cacheCall', JSON.stringify({ method: String(method), argsJson: JSON.stringify(args) }))
585
+ });
586
+ $ctx.$trigger = async (...args) =>
587
+ __call('dispatchCall', JSON.stringify({ method: 'trigger', argsJson: JSON.stringify(args) }));
588
+ $ctx.$throw = new Proxy({}, {
589
+ get: (_, status) => (message, details) => {
590
+ const code = parseInt(String(status));
591
+ const msg = (message !== undefined && message !== null && message !== '') ? String(message) : (__throwDefaults[code] || 'Error');
592
+ const payload = JSON.stringify({ __userThrow: true, statusCode: code, message: msg, details: details || null });
593
+ throw new Error(payload);
594
+ }
595
+ });
596
+ $ctx.$logs = (...args) => {
597
+ for (const a of args) {
598
+ try { __logs.push(JSON.parse(JSON.stringify(a))); }
599
+ catch { __logs.push(String(a)); }
600
+ }
601
+ };
602
+ }
603
+
604
+ const __baselineGlobalKeys = new Set(Reflect.ownKeys(globalThis));
605
+ const __baselineObjectPrototypeKeys = new Set(Reflect.ownKeys(Object.prototype));
606
+ const __baselineArrayPrototypeKeys = new Set(Reflect.ownKeys(Array.prototype));
607
+ const __baselineFunctionPrototypeKeys = new Set(Reflect.ownKeys(Function.prototype));
608
+
609
+ function __deleteExtraKeys(target, baseline) {
610
+ for (const key of Reflect.ownKeys(target)) {
611
+ if (baseline.has(key)) continue;
612
+ try { delete target[key]; } catch {}
613
+ }
614
+ }
615
+
616
+ function __cleanupTask() {
617
+ __deleteExtraKeys(globalThis, __baselineGlobalKeys);
618
+ __deleteExtraKeys(Object.prototype, __baselineObjectPrototypeKeys);
619
+ __deleteExtraKeys(Array.prototype, __baselineArrayPrototypeKeys);
620
+ __deleteExtraKeys(Function.prototype, __baselineFunctionPrototypeKeys);
621
+ $ctx = {};
622
+ $pkgs = {};
623
+ __taskId = null;
624
+ __logs = [];
625
+ __runtimeCallbackCounter = 0;
626
+ __runtimeCallbacks = new Map();
627
+ return true;
628
+ }
629
+ `;function oe(e){return se.replace("%%PKG_SETUP%%",e)}U.exports={buildSetupCode:oe}});var{parentPort:N}=require("worker_threads"),F=require("fs"),{fileURLToPath:ie}=require("url"),{createPackageRuntimeBridge:ce}=I(),{buildSetupCode:le}=H(),C;try{C=require("isolated-vm")}catch(e){N.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var S=new Map,B=0,R=new Map,A=ce({workerDir:__dirname,activeTaskContexts:R}),ue=500,pe=5e3,fe=32,L=new WeakMap,V=new WeakMap,z=new WeakMap,b={created:0,reused:0,released:0,evicted:0,scrubFailed:0},P=null,_e=0,K=0,D=0;async function de(){let e=Date.now();if(e-K<pe)return D;if(K=e,!P)return 0;let t=0;for(let s of P){let a=s?.isolate;if(!(!a||a.isDisposed))try{let r=await a.getHeapStatistics(),i=r.heap_size_limit||1,l=r.used_heap_size/i;l>t&&(t=l)}catch{}}return D=t,t}async function $(e){e.heapRatio=await de(),e.contextStats=ge(),N.postMessage(e)}function ge(){let e=0;if(P)for(let t of P)e+=t?.idleContexts?.length||0;return{...b,idle:e}}function W(e,t){if(!P){let r=Math.max(1,Math.trunc(Number(t)||8));P=new Array(r).fill(null)}let s=_e++%P.length,a=P[s];return(!a||!a.isolate||a.isolate.isDisposed)&&(a={isolate:new C.Isolate({memoryLimit:e}),idleContexts:[]},P[s]=a),a}async function x(e,t,s){let a=L.get(e);a||(a=new Map,L.set(e,a));let r=a.get(t);if(r)return r;let i=await e.compileScript(t,{filename:s});if(a.set(t,i),a.size>ue){let l=a.keys().next().value;a.delete(l)}return i}N.on("message",async e=>{if(e.type==="execute")be(e).catch(async t=>{await $({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Se(e).catch(async t=>{await $({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="callResult"){let t=S.get(e.callId);t&&(S.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=S.get(e.callId);t&&(S.delete(e.callId),t.reject(new Error(e.error)))}});function ye(e,t,s){return new Promise((a,r)=>{let i=`cb_${++B}`;S.set(i,{resolve:a,reject:r}),N.postMessage({type:t,id:e,callId:i,...s})})}function he(e,t,s){N.postMessage({type:t,id:e,callId:`f_${++B}`,...s})}function me(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=ie(e.fileUrl)),!t||!F.existsSync(t)?null:F.readFileSync(t,"utf8")}async function ke(e,t,s){try{let a=me(s);if(!a)return null;let r=await e.compileModule(a,{filename:`pkg:${s.safeName}`});await r.instantiate(t,l=>{throw new Error(`Unresolved import in package ${s.safeName}: ${l}`)}),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 G(e,t){let s=r=>{let i=2166136261;for(let l=0;l<r.length;l++)i^=r.charCodeAt(l),i=Math.imul(i,16777619);return(i>>>0).toString(36)},a=new Set(t||[]);return e.map(r=>{let i=r.cacheKey||`${r.filePath||""}:${r.fileUrl||""}:${r.mtimeMs||""}:${r.size||""}:${s(r.sourceCode||"")}`,l=a.has(r.name)?"isolate":"proxy";return`${r.name}:${r.version||""}:${i}:${l}`}).join("|")}function X(e,t){let s=new Set(t.map(d=>d.name)),a=new Set,r=String(e||""),i=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,l=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,_=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let d of[i,l])for(let k of r.matchAll(d)){let y=k[2];s.has(y)&&a.add(y)}for(let d of r.matchAll(_)){let k=d[1];s.has(k)&&a.add(k)}return a}async function ve(e,t,s,a){let r=await e.createContext(),i=r.global;await i.set("global",i.derefInto());let l=[],_=[],d=new Map;for(let c of s){d.set(c.name,c);let h=a.has(c.name)?await ke(e,r,c):null;h!==null?(await i.set(`__pkg_${c.safeName}`,h),l.push(c)):_.push(c)}A.setTaskPackages(t,d),await i.set("__callRef",new C.Reference(async(c,h,v)=>{let p=JSON.parse(v);return h==="pkgCall"?JSON.stringify(await A.executePackageRuntimeCall(c,p)):ye(c,h,p)})),await i.set("__fireRef",new C.Reference((c,h,v)=>{let p=JSON.parse(v);he(c,h,p)}));let k=l.map(c=>`$pkgs[${JSON.stringify(c.name)}] = __pkg_${c.safeName};`).concat(_.map(c=>`$pkgs[${JSON.stringify(c.name)}] = __createPkgProxy(${JSON.stringify(c.name)}, []);`)).join(`
630
+ `),y=le(k);return await(await x(e,y,"setup.js")).run(r,{timeout:5e3}),V.set(r,G(s,a)),z.set(r,d),r}async function Z(e,t,s,a,r){let i=e.isolate,l=G(s,r),_=null;for(let y=e.idleContexts.length-1;y>=0;y--){let m=e.idleContexts[y];if(e.idleContexts.splice(y,1),V.get(m)===l){_=m,b.reused++;break}try{m.release()}catch{}}_||(_=await ve(i,t,s,r),b.created++),A.setTaskPackages(t,z.get(_)||new Map);let d=_.global;return await d.set("__snapshot",new C.ExternalCopy(a).copyInto()),await d.set("__nextTaskId",t),await(await x(i,"__resetTask(__snapshot, __nextTaskId);","reset-task.js")).run(_,{timeout:5e3}),_}async function Q(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await x(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{b.scrubFailed++;try{t.release()}catch{}return}if(e.idleContexts.length>=fe){try{t.release()}catch{}b.evicted++;return}e.idleContexts.push(t),b.released++}}function we(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var Pe=3,xe=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function $e(e){if(!e)return null;let t=e.split(`
631
+ `);for(let s of t){let a=s.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!a)continue;let r=a[1].trim();if(xe.includes(r))continue;let l=parseInt(a[2])-Pe;if(!(l<=0))return{line:l,column:parseInt(a[3]),phase:r.replace(".js","")}}return null}function J(e){let t=we(e);if(t)return{message:t.message,statusCode:t.statusCode,details:t.details};let s=$e(e.stack),a=e.message||"Unknown error";return{message:s?`${a} (${s.phase}, line ${s.line})`:a,statusCode:e.statusCode||null,details:s||void 0}}async function Y(e,t){let s=J(t);await $({type:"result",id:e,success:!1,error:{...s,stack:t.stack,code:t.code}})}async function be(e){let{id:t,code:s,pkgSources:a,snapshot:r,memoryLimitMb:i,isolatePoolSize:l}=e,_=a||[],d=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),k=X(s,_),y=W(i,l),m=y.isolate,c=await Z(y,t,_,r,k);R.set(t,c);try{let h=`
632
+ (async () => {
633
+ "use strict";
634
+ ${s}
635
+ })().then((__result) => __extractResult(__result, __result === undefined));
636
+ `,p=await(await x(m,h,"handler.js")).run(c,{timeout:d,promise:!0}),u=JSON.parse(p);await $({type:"result",id:t,success:!0,...u})}catch(h){await Y(t,h)}finally{R.delete(t),await Q(y,c),ee(t)}}async function Se(e){let{id:t,codeBlocks:s,pkgSources:a,snapshot:r,memoryLimitMb:i,isolatePoolSize:l}=e,_=a||[],d=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),k=X((s||[]).map(p=>p.code||"").join(`
637
+ `),_),y=W(i,l),m=y.isolate,c=await Z(y,t,_,r,k);R.set(t,c);let h=[],v=[];for(let p of s)(p.type||"handler")==="postHook"?v.push(p):h.push(p);try{let p=null;for(let n=0;n<h.length;n++){let o=h[n],f=o.type||"handler",g=f==="handler"?"handler":`${f} #${n+1}`,w;f==="preHook"?w=`
638
+ (async () => {
639
+ "use strict";
640
+ ${o.code}
641
+ })().then((__r) => {
642
+ if (__r !== undefined) return JSON.stringify({ __shortCircuit: true, value: __r });
643
+ return JSON.stringify({ __shortCircuit: false });
644
+ });`:w=`
645
+ (async () => {
646
+ "use strict";
647
+ ${o.code}
648
+ })().then((__r) => {
649
+ $ctx.$data = __r;
650
+ return "__handler_done__";
651
+ });`;try{let M=await(await x(m,w,`${g}.js`)).run(c,{timeout:d,promise:!0});if(f==="preHook"&&typeof M=="string"){let E=JSON.parse(M);if(E.__shortCircuit){let te=await q(m,c,E.value);await $({type:"result",id:t,success:!0,...te,shortCircuit:!0});return}}}catch(O){p=O;break}}if(!p&&v.length>0&&await(await x(m,'$ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(c,{timeout:5e3}),p&&v.length>0){let n=J(p),o={message:n.message||"Unknown error",name:p.constructor?.name||"Error",stack:p.stack||"",statusCode:n.statusCode||500,details:n.details||{},timestamp:new Date().toISOString()},f=`
652
+ $ctx.$error = ${JSON.stringify(o)};
653
+ $ctx.$data = null;
654
+ $ctx.$statusCode = ${o.statusCode};
655
+ if ($ctx.$api) {
656
+ $ctx.$api.error = ${JSON.stringify(o)};
657
+ $ctx.$api.response = {
658
+ statusCode: ${o.statusCode},
659
+ responseTime: $ctx.$api.request && $ctx.$api.request.timestamp
660
+ ? Date.now() - new Date($ctx.$api.request.timestamp).getTime()
661
+ : 0,
662
+ timestamp: ${JSON.stringify(o.timestamp)},
663
+ };
664
+ }
665
+ "__error_populated__";`;await(await m.compileScript(f,{filename:"populate-error.js"})).run(c,{timeout:5e3})}for(let n=0;n<v.length;n++){let o=v[n],f=`postHook #${n+1}`,g=`
666
+ (async () => {
667
+ "use strict";
668
+ ${o.code}
669
+ })().then((__r) => {
670
+ if (__r !== undefined) $ctx.$data = __r;
671
+ return "__posthook_done__";
672
+ });`;try{await(await x(m,g,`${f}.js`)).run(c,{timeout:d,promise:!0})}catch{}}if(p){let n=J(p),o;try{let w=await(await x(m,`JSON.stringify({
673
+ $body: __safeClone($ctx.$body),
674
+ $query: __safeClone($ctx.$query),
675
+ $params: __safeClone($ctx.$params),
676
+ $data: __safeClone($ctx.$data),
677
+ $share: __safeClone($ctx.$share),
678
+ $flow: __safeClone($ctx.$flow),
679
+ $error: __safeClone($ctx.$error),
680
+ $api: __safeClone($ctx.$api),
681
+ $statusCode: $ctx.$statusCode,
682
+ })`,"extract-error-ctx.js")).run(c,{timeout:5e3});o=JSON.parse(w)}catch{}await $({type:"result",id:t,success:!1,error:{message:n.message,statusCode:n.statusCode,stack:p.stack,code:p.code,details:n.details},ctxChanges:o});return}let u=await q(m,c);await $({type:"result",id:t,success:!0,...u})}catch(p){await Y(t,p)}finally{R.delete(t),await Q(y,c),ee(t)}}function ee(e){A.cleanupTaskPackages(e)}function Ce(){A.shutdownPackageRuntime()}process.on("exit",Ce);async function q(e,t,s){if(s!==void 0){let l=`__extractResult(${JSON.stringify(s)}, false)`,d=await(await e.compileScript(l,{filename:"extract.js"})).run(t,{timeout:5e3});return JSON.parse(d)}let i=await(await x(e,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(t,{timeout:5e3});return JSON.parse(i)}