@ricsam/isolate-fetch 0.0.1 → 0.1.2

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,1759 @@
1
+ // @bun
2
+ // packages/fetch/src/index.ts
3
+ import ivm from "isolated-vm";
4
+ import { setupCore, clearAllInstanceState } from "@ricsam/isolate-core";
5
+ import {
6
+ getStreamRegistryForContext,
7
+ startNativeStreamReader
8
+ } from "./stream-state.mjs";
9
+ var instanceStateMap = new WeakMap;
10
+ var nextInstanceId = 1;
11
+ function getInstanceStateMapForContext(context) {
12
+ let map = instanceStateMap.get(context);
13
+ if (!map) {
14
+ map = new Map;
15
+ instanceStateMap.set(context, map);
16
+ }
17
+ return map;
18
+ }
19
+ var headersCode = `
20
+ (function() {
21
+ class Headers {
22
+ #headers = new Map(); // lowercase key -> [originalCase, values[]]
23
+
24
+ constructor(init) {
25
+ if (init instanceof Headers) {
26
+ init.forEach((value, key) => this.append(key, value));
27
+ } else if (Array.isArray(init)) {
28
+ for (const pair of init) {
29
+ if (Array.isArray(pair) && pair.length >= 2) {
30
+ this.append(pair[0], pair[1]);
31
+ }
32
+ }
33
+ } else if (init && typeof init === 'object') {
34
+ for (const [key, value] of Object.entries(init)) {
35
+ this.append(key, value);
36
+ }
37
+ }
38
+ }
39
+
40
+ append(name, value) {
41
+ const key = String(name).toLowerCase();
42
+ const valueStr = String(value);
43
+ const existing = this.#headers.get(key);
44
+ if (existing) {
45
+ existing[1].push(valueStr);
46
+ } else {
47
+ this.#headers.set(key, [String(name), [valueStr]]);
48
+ }
49
+ }
50
+
51
+ delete(name) {
52
+ this.#headers.delete(String(name).toLowerCase());
53
+ }
54
+
55
+ get(name) {
56
+ const entry = this.#headers.get(String(name).toLowerCase());
57
+ return entry ? entry[1].join(', ') : null;
58
+ }
59
+
60
+ getSetCookie() {
61
+ const entry = this.#headers.get('set-cookie');
62
+ return entry ? [...entry[1]] : [];
63
+ }
64
+
65
+ has(name) {
66
+ return this.#headers.has(String(name).toLowerCase());
67
+ }
68
+
69
+ set(name, value) {
70
+ const key = String(name).toLowerCase();
71
+ this.#headers.set(key, [String(name), [String(value)]]);
72
+ }
73
+
74
+ forEach(callback, thisArg) {
75
+ for (const [key, [originalName, values]] of this.#headers) {
76
+ callback.call(thisArg, values.join(', '), originalName, this);
77
+ }
78
+ }
79
+
80
+ *entries() {
81
+ for (const [key, [name, values]] of this.#headers) {
82
+ yield [name, values.join(', ')];
83
+ }
84
+ }
85
+
86
+ *keys() {
87
+ for (const [key, [name]] of this.#headers) {
88
+ yield name;
89
+ }
90
+ }
91
+
92
+ *values() {
93
+ for (const [key, [name, values]] of this.#headers) {
94
+ yield values.join(', ');
95
+ }
96
+ }
97
+
98
+ [Symbol.iterator]() {
99
+ return this.entries();
100
+ }
101
+ }
102
+
103
+ globalThis.Headers = Headers;
104
+ })();
105
+ `;
106
+ var formDataCode = `
107
+ (function() {
108
+ class FormData {
109
+ #entries = []; // Array of [name, value]
110
+
111
+ append(name, value, filename) {
112
+ let finalValue = value;
113
+ if (value instanceof Blob && !(value instanceof File)) {
114
+ if (filename !== undefined) {
115
+ finalValue = new File([value], String(filename), { type: value.type });
116
+ }
117
+ } else if (value instanceof File && filename !== undefined) {
118
+ finalValue = new File([value], String(filename), {
119
+ type: value.type,
120
+ lastModified: value.lastModified
121
+ });
122
+ }
123
+ this.#entries.push([String(name), finalValue]);
124
+ }
125
+
126
+ delete(name) {
127
+ const nameStr = String(name);
128
+ this.#entries = this.#entries.filter(([n]) => n !== nameStr);
129
+ }
130
+
131
+ get(name) {
132
+ const nameStr = String(name);
133
+ const entry = this.#entries.find(([n]) => n === nameStr);
134
+ return entry ? entry[1] : null;
135
+ }
136
+
137
+ getAll(name) {
138
+ const nameStr = String(name);
139
+ return this.#entries.filter(([n]) => n === nameStr).map(([, v]) => v);
140
+ }
141
+
142
+ has(name) {
143
+ return this.#entries.some(([n]) => n === String(name));
144
+ }
145
+
146
+ set(name, value, filename) {
147
+ const nameStr = String(name);
148
+ this.delete(nameStr);
149
+ this.append(nameStr, value, filename);
150
+ }
151
+
152
+ *entries() {
153
+ for (const [name, value] of this.#entries) {
154
+ yield [name, value];
155
+ }
156
+ }
157
+
158
+ *keys() {
159
+ for (const [name] of this.#entries) {
160
+ yield name;
161
+ }
162
+ }
163
+
164
+ *values() {
165
+ for (const [, value] of this.#entries) {
166
+ yield value;
167
+ }
168
+ }
169
+
170
+ forEach(callback, thisArg) {
171
+ for (const [name, value] of this.#entries) {
172
+ callback.call(thisArg, value, name, this);
173
+ }
174
+ }
175
+
176
+ [Symbol.iterator]() {
177
+ return this.entries();
178
+ }
179
+ }
180
+
181
+ globalThis.FormData = FormData;
182
+ })();
183
+ `;
184
+ var multipartCode = `
185
+ (function() {
186
+ // Find byte sequence in Uint8Array
187
+ function findSequence(haystack, needle, start = 0) {
188
+ outer: for (let i = start; i <= haystack.length - needle.length; i++) {
189
+ for (let j = 0; j < needle.length; j++) {
190
+ if (haystack[i + j] !== needle[j]) continue outer;
191
+ }
192
+ return i;
193
+ }
194
+ return -1;
195
+ }
196
+
197
+ // Parse header lines into object
198
+ function parseHeaders(text) {
199
+ const headers = {};
200
+ for (const line of text.split(/\\r?\\n/)) {
201
+ const colonIdx = line.indexOf(':');
202
+ if (colonIdx > 0) {
203
+ const name = line.slice(0, colonIdx).trim().toLowerCase();
204
+ const value = line.slice(colonIdx + 1).trim();
205
+ headers[name] = value;
206
+ }
207
+ }
208
+ return headers;
209
+ }
210
+
211
+ // Parse multipart/form-data body into FormData
212
+ globalThis.__parseMultipartFormData = function(bodyBytes, contentType) {
213
+ const formData = new FormData();
214
+
215
+ // Extract boundary from Content-Type
216
+ const boundaryMatch = contentType.match(/boundary=([^;]+)/i);
217
+ if (!boundaryMatch) return formData;
218
+
219
+ const boundary = boundaryMatch[1].replace(/^["']|["']$/g, '');
220
+ const encoder = new TextEncoder();
221
+ const decoder = new TextDecoder();
222
+ const boundaryBytes = encoder.encode('--' + boundary);
223
+
224
+ // Find first boundary
225
+ let pos = findSequence(bodyBytes, boundaryBytes, 0);
226
+ if (pos === -1) return formData;
227
+ pos += boundaryBytes.length;
228
+
229
+ while (pos < bodyBytes.length) {
230
+ // Skip CRLF after boundary
231
+ if (bodyBytes[pos] === 0x0d && bodyBytes[pos + 1] === 0x0a) pos += 2;
232
+ else if (bodyBytes[pos] === 0x0a) pos += 1;
233
+
234
+ // Check for closing boundary (--)
235
+ if (bodyBytes[pos] === 0x2d && bodyBytes[pos + 1] === 0x2d) break;
236
+
237
+ // Find header/body separator (CRLFCRLF)
238
+ const crlfcrlf = encoder.encode('\\r\\n\\r\\n');
239
+ const headersEnd = findSequence(bodyBytes, crlfcrlf, pos);
240
+ if (headersEnd === -1) break;
241
+
242
+ // Parse headers
243
+ const headersText = decoder.decode(bodyBytes.slice(pos, headersEnd));
244
+ const headers = parseHeaders(headersText);
245
+ pos = headersEnd + 4;
246
+
247
+ // Find next boundary
248
+ const nextBoundary = findSequence(bodyBytes, boundaryBytes, pos);
249
+ if (nextBoundary === -1) break;
250
+
251
+ // Extract content (minus trailing CRLF)
252
+ let contentEnd = nextBoundary;
253
+ if (contentEnd > 0 && bodyBytes[contentEnd - 1] === 0x0a) contentEnd--;
254
+ if (contentEnd > 0 && bodyBytes[contentEnd - 1] === 0x0d) contentEnd--;
255
+ const content = bodyBytes.slice(pos, contentEnd);
256
+
257
+ // Parse Content-Disposition
258
+ const disposition = headers['content-disposition'] || '';
259
+ const nameMatch = disposition.match(/name="([^"]+)"/);
260
+ const filenameMatch = disposition.match(/filename="([^"]+)"/);
261
+
262
+ if (nameMatch) {
263
+ const name = nameMatch[1];
264
+ if (filenameMatch) {
265
+ const filename = filenameMatch[1];
266
+ const mimeType = headers['content-type'] || 'application/octet-stream';
267
+ const file = new File([content], filename, { type: mimeType });
268
+ formData.append(name, file);
269
+ } else {
270
+ formData.append(name, decoder.decode(content));
271
+ }
272
+ }
273
+
274
+ pos = nextBoundary + boundaryBytes.length;
275
+ }
276
+
277
+ return formData;
278
+ };
279
+
280
+ // Serialize FormData to multipart/form-data format
281
+ globalThis.__serializeFormData = function(formData) {
282
+ const boundary = '----FormDataBoundary' + Math.random().toString(36).slice(2) +
283
+ Math.random().toString(36).slice(2);
284
+ const encoder = new TextEncoder();
285
+ const parts = [];
286
+
287
+ for (const [name, value] of formData.entries()) {
288
+ if (value instanceof File) {
289
+ const header = [
290
+ '--' + boundary,
291
+ 'Content-Disposition: form-data; name="' + name + '"; filename="' + value.name + '"',
292
+ 'Content-Type: ' + (value.type || 'application/octet-stream'),
293
+ '',
294
+ ''
295
+ ].join('\\r\\n');
296
+ parts.push(encoder.encode(header));
297
+ // Use existing __Blob_bytes callback (File extends Blob)
298
+ parts.push(__Blob_bytes(value._getInstanceId()));
299
+ parts.push(encoder.encode('\\r\\n'));
300
+ } else if (value instanceof Blob) {
301
+ const header = [
302
+ '--' + boundary,
303
+ 'Content-Disposition: form-data; name="' + name + '"; filename="blob"',
304
+ 'Content-Type: ' + (value.type || 'application/octet-stream'),
305
+ '',
306
+ ''
307
+ ].join('\\r\\n');
308
+ parts.push(encoder.encode(header));
309
+ parts.push(__Blob_bytes(value._getInstanceId()));
310
+ parts.push(encoder.encode('\\r\\n'));
311
+ } else {
312
+ const header = [
313
+ '--' + boundary,
314
+ 'Content-Disposition: form-data; name="' + name + '"',
315
+ '',
316
+ ''
317
+ ].join('\\r\\n');
318
+ parts.push(encoder.encode(header));
319
+ parts.push(encoder.encode(String(value)));
320
+ parts.push(encoder.encode('\\r\\n'));
321
+ }
322
+ }
323
+
324
+ // Closing boundary
325
+ parts.push(encoder.encode('--' + boundary + '--\\r\\n'));
326
+
327
+ // Concatenate all parts
328
+ const totalLength = parts.reduce((sum, p) => sum + p.length, 0);
329
+ const body = new Uint8Array(totalLength);
330
+ let offset = 0;
331
+ for (const part of parts) {
332
+ body.set(part, offset);
333
+ offset += part.length;
334
+ }
335
+
336
+ return {
337
+ body: body,
338
+ contentType: 'multipart/form-data; boundary=' + boundary
339
+ };
340
+ };
341
+ })();
342
+ `;
343
+ function setupStreamCallbacks(context, streamRegistry) {
344
+ const global = context.global;
345
+ global.setSync("__Stream_create", new ivm.Callback(() => {
346
+ return streamRegistry.create();
347
+ }));
348
+ global.setSync("__Stream_push", new ivm.Callback((streamId, chunkArray) => {
349
+ const chunk = new Uint8Array(chunkArray);
350
+ return streamRegistry.push(streamId, chunk);
351
+ }));
352
+ global.setSync("__Stream_close", new ivm.Callback((streamId) => {
353
+ streamRegistry.close(streamId);
354
+ }));
355
+ global.setSync("__Stream_error", new ivm.Callback((streamId, message) => {
356
+ streamRegistry.error(streamId, new Error(message));
357
+ }));
358
+ global.setSync("__Stream_isQueueFull", new ivm.Callback((streamId) => {
359
+ return streamRegistry.isQueueFull(streamId);
360
+ }));
361
+ const pullRef = new ivm.Reference(async (streamId) => {
362
+ const result = await streamRegistry.pull(streamId);
363
+ if (result.done) {
364
+ return JSON.stringify({ done: true });
365
+ }
366
+ return JSON.stringify({ done: false, value: Array.from(result.value) });
367
+ });
368
+ global.setSync("__Stream_pull_ref", pullRef);
369
+ }
370
+ var hostBackedStreamCode = `
371
+ (function() {
372
+ const _streamIds = new WeakMap();
373
+
374
+ class HostBackedReadableStream {
375
+ constructor(streamId) {
376
+ if (streamId === undefined) {
377
+ streamId = __Stream_create();
378
+ }
379
+ _streamIds.set(this, streamId);
380
+ }
381
+
382
+ _getStreamId() {
383
+ return _streamIds.get(this);
384
+ }
385
+
386
+ getReader() {
387
+ const streamId = this._getStreamId();
388
+ let released = false;
389
+
390
+ return {
391
+ read: async () => {
392
+ if (released) {
393
+ throw new TypeError("Reader has been released");
394
+ }
395
+ const resultJson = __Stream_pull_ref.applySyncPromise(undefined, [streamId]);
396
+ const result = JSON.parse(resultJson);
397
+
398
+ if (result.done) {
399
+ return { done: true, value: undefined };
400
+ }
401
+ return { done: false, value: new Uint8Array(result.value) };
402
+ },
403
+
404
+ releaseLock: () => {
405
+ released = true;
406
+ },
407
+
408
+ get closed() {
409
+ return new Promise(() => {});
410
+ },
411
+
412
+ cancel: async (reason) => {
413
+ __Stream_error(streamId, String(reason || "cancelled"));
414
+ }
415
+ };
416
+ }
417
+
418
+ async cancel(reason) {
419
+ __Stream_error(this._getStreamId(), String(reason || "cancelled"));
420
+ }
421
+
422
+ get locked() {
423
+ return false;
424
+ }
425
+
426
+ // Static method to create from existing stream ID
427
+ static _fromStreamId(streamId) {
428
+ return new HostBackedReadableStream(streamId);
429
+ }
430
+ }
431
+
432
+ globalThis.HostBackedReadableStream = HostBackedReadableStream;
433
+ })();
434
+ `;
435
+ function setupResponse(context, stateMap) {
436
+ const global = context.global;
437
+ global.setSync("__Response_construct", new ivm.Callback((bodyBytes, status, statusText, headers) => {
438
+ const instanceId = nextInstanceId++;
439
+ const body = bodyBytes ? new Uint8Array(bodyBytes) : null;
440
+ const state = {
441
+ status,
442
+ statusText,
443
+ headers,
444
+ body,
445
+ bodyUsed: false,
446
+ type: "default",
447
+ url: "",
448
+ redirected: false,
449
+ streamId: null
450
+ };
451
+ stateMap.set(instanceId, state);
452
+ return instanceId;
453
+ }));
454
+ global.setSync("__Response_constructStreaming", new ivm.Callback((streamId, status, statusText, headers) => {
455
+ const instanceId = nextInstanceId++;
456
+ const state = {
457
+ status,
458
+ statusText,
459
+ headers,
460
+ body: null,
461
+ bodyUsed: false,
462
+ type: "default",
463
+ url: "",
464
+ redirected: false,
465
+ streamId
466
+ };
467
+ stateMap.set(instanceId, state);
468
+ return instanceId;
469
+ }));
470
+ global.setSync("__Response_constructFromFetch", new ivm.Callback((bodyBytes, status, statusText, headers, url, redirected) => {
471
+ const instanceId = nextInstanceId++;
472
+ const body = bodyBytes ? new Uint8Array(bodyBytes) : null;
473
+ const state = {
474
+ status,
475
+ statusText,
476
+ headers,
477
+ body,
478
+ bodyUsed: false,
479
+ type: "default",
480
+ url,
481
+ redirected,
482
+ streamId: null
483
+ };
484
+ stateMap.set(instanceId, state);
485
+ return instanceId;
486
+ }));
487
+ global.setSync("__Response_get_status", new ivm.Callback((instanceId) => {
488
+ const state = stateMap.get(instanceId);
489
+ return state?.status ?? 200;
490
+ }));
491
+ global.setSync("__Response_get_statusText", new ivm.Callback((instanceId) => {
492
+ const state = stateMap.get(instanceId);
493
+ return state?.statusText ?? "";
494
+ }));
495
+ global.setSync("__Response_get_headers", new ivm.Callback((instanceId) => {
496
+ const state = stateMap.get(instanceId);
497
+ return state?.headers ?? [];
498
+ }));
499
+ global.setSync("__Response_get_bodyUsed", new ivm.Callback((instanceId) => {
500
+ const state = stateMap.get(instanceId);
501
+ return state?.bodyUsed ?? false;
502
+ }));
503
+ global.setSync("__Response_get_url", new ivm.Callback((instanceId) => {
504
+ const state = stateMap.get(instanceId);
505
+ return state?.url ?? "";
506
+ }));
507
+ global.setSync("__Response_get_redirected", new ivm.Callback((instanceId) => {
508
+ const state = stateMap.get(instanceId);
509
+ return state?.redirected ?? false;
510
+ }));
511
+ global.setSync("__Response_get_type", new ivm.Callback((instanceId) => {
512
+ const state = stateMap.get(instanceId);
513
+ return state?.type ?? "default";
514
+ }));
515
+ global.setSync("__Response_setType", new ivm.Callback((instanceId, type) => {
516
+ const state = stateMap.get(instanceId);
517
+ if (state) {
518
+ state.type = type;
519
+ }
520
+ }));
521
+ global.setSync("__Response_markBodyUsed", new ivm.Callback((instanceId) => {
522
+ const state = stateMap.get(instanceId);
523
+ if (state) {
524
+ if (state.bodyUsed) {
525
+ throw new Error("[TypeError]Body has already been consumed");
526
+ }
527
+ state.bodyUsed = true;
528
+ }
529
+ }));
530
+ global.setSync("__Response_text", new ivm.Callback((instanceId) => {
531
+ const state = stateMap.get(instanceId);
532
+ if (!state || !state.body)
533
+ return "";
534
+ return new TextDecoder().decode(state.body);
535
+ }));
536
+ global.setSync("__Response_arrayBuffer", new ivm.Callback((instanceId) => {
537
+ const state = stateMap.get(instanceId);
538
+ if (!state || !state.body) {
539
+ return new ivm.ExternalCopy(new ArrayBuffer(0)).copyInto();
540
+ }
541
+ return new ivm.ExternalCopy(state.body.buffer.slice(state.body.byteOffset, state.body.byteOffset + state.body.byteLength)).copyInto();
542
+ }));
543
+ global.setSync("__Response_clone", new ivm.Callback((instanceId) => {
544
+ const state = stateMap.get(instanceId);
545
+ if (!state) {
546
+ throw new Error("[TypeError]Cannot clone invalid Response");
547
+ }
548
+ const newId = nextInstanceId++;
549
+ const newState = {
550
+ ...state,
551
+ body: state.body ? new Uint8Array(state.body) : null,
552
+ bodyUsed: false
553
+ };
554
+ stateMap.set(newId, newState);
555
+ return newId;
556
+ }));
557
+ global.setSync("__Response_getStreamId", new ivm.Callback((instanceId) => {
558
+ const state = stateMap.get(instanceId);
559
+ return state?.streamId ?? null;
560
+ }));
561
+ const responseCode = `
562
+ (function() {
563
+ const _responseInstanceIds = new WeakMap();
564
+
565
+ function __decodeError(err) {
566
+ if (!(err instanceof Error)) return err;
567
+ const match = err.message.match(/^\\[(TypeError|RangeError|SyntaxError|ReferenceError|URIError|EvalError|Error)\\](.*)$/);
568
+ if (match) {
569
+ const ErrorType = globalThis[match[1]] || Error;
570
+ return new ErrorType(match[2]);
571
+ }
572
+ return err;
573
+ }
574
+
575
+ function __prepareBody(body) {
576
+ if (body === null || body === undefined) return null;
577
+ if (typeof body === 'string') {
578
+ const encoder = new TextEncoder();
579
+ return Array.from(encoder.encode(body));
580
+ }
581
+ if (body instanceof ArrayBuffer) {
582
+ return Array.from(new Uint8Array(body));
583
+ }
584
+ if (body instanceof Uint8Array) {
585
+ return Array.from(body);
586
+ }
587
+ if (ArrayBuffer.isView(body)) {
588
+ return Array.from(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
589
+ }
590
+ if (body instanceof Blob) {
591
+ // Mark as needing async Blob handling - will be read in constructor
592
+ return { __isBlob: true, blob: body };
593
+ }
594
+ // Handle ReadableStream (both native and host-backed)
595
+ if (body instanceof ReadableStream || body instanceof HostBackedReadableStream) {
596
+ return { __isStream: true, stream: body };
597
+ }
598
+ // Try to convert to string
599
+ return Array.from(new TextEncoder().encode(String(body)));
600
+ }
601
+
602
+ class Response {
603
+ #instanceId;
604
+ #headers;
605
+ #streamId = null;
606
+ #blobInitPromise = null; // For async Blob body initialization
607
+
608
+ constructor(body, init = {}) {
609
+ // Handle internal construction from instance ID
610
+ if (typeof body === 'number' && init === null) {
611
+ this.#instanceId = body;
612
+ this.#headers = new Headers(__Response_get_headers(body));
613
+ this.#streamId = __Response_getStreamId(body);
614
+ return;
615
+ }
616
+
617
+ const preparedBody = __prepareBody(body);
618
+
619
+ // Handle Blob body - create streaming response and push blob data
620
+ if (preparedBody && preparedBody.__isBlob) {
621
+ this.#streamId = __Stream_create();
622
+ const status = init.status ?? 200;
623
+ const statusText = init.statusText ?? '';
624
+ const headers = new Headers(init.headers);
625
+ const headersArray = Array.from(headers.entries());
626
+
627
+ this.#instanceId = __Response_constructStreaming(
628
+ this.#streamId,
629
+ status,
630
+ statusText,
631
+ headersArray
632
+ );
633
+ this.#headers = headers;
634
+
635
+ // Start async blob initialization and stream pumping
636
+ const streamId = this.#streamId;
637
+ const blob = preparedBody.blob;
638
+ this.#blobInitPromise = (async () => {
639
+ try {
640
+ const buffer = await blob.arrayBuffer();
641
+ __Stream_push(streamId, Array.from(new Uint8Array(buffer)));
642
+ __Stream_close(streamId);
643
+ } catch (error) {
644
+ __Stream_error(streamId, String(error));
645
+ }
646
+ })();
647
+ return;
648
+ }
649
+
650
+ // Handle streaming body
651
+ if (preparedBody && preparedBody.__isStream) {
652
+ this.#streamId = __Stream_create();
653
+ const status = init.status ?? 200;
654
+ const statusText = init.statusText ?? '';
655
+ const headers = new Headers(init.headers);
656
+ const headersArray = Array.from(headers.entries());
657
+
658
+ this.#instanceId = __Response_constructStreaming(
659
+ this.#streamId,
660
+ status,
661
+ statusText,
662
+ headersArray
663
+ );
664
+ this.#headers = headers;
665
+
666
+ // Start pumping the source stream to host queue (fire-and-forget)
667
+ this._startStreamPump(preparedBody.stream);
668
+ return;
669
+ }
670
+
671
+ // Existing buffered body handling
672
+ const bodyBytes = preparedBody;
673
+ const status = init.status ?? 200;
674
+ const statusText = init.statusText ?? '';
675
+ const headersInit = init.headers;
676
+ const headers = new Headers(headersInit);
677
+ const headersArray = Array.from(headers.entries());
678
+
679
+ this.#instanceId = __Response_construct(bodyBytes, status, statusText, headersArray);
680
+ this.#headers = headers;
681
+ }
682
+
683
+ async _startStreamPump(sourceStream) {
684
+ const streamId = this.#streamId;
685
+ try {
686
+ const reader = sourceStream.getReader();
687
+ while (true) {
688
+ // Check backpressure - wait if queue is full
689
+ while (__Stream_isQueueFull(streamId)) {
690
+ await new Promise(r => setTimeout(r, 1));
691
+ }
692
+
693
+ const { done, value } = await reader.read();
694
+ if (done) {
695
+ __Stream_close(streamId);
696
+ break;
697
+ }
698
+ if (value) {
699
+ __Stream_push(streamId, Array.from(value));
700
+ }
701
+ }
702
+ } catch (error) {
703
+ __Stream_error(streamId, String(error));
704
+ }
705
+ }
706
+
707
+ _getInstanceId() {
708
+ return this.#instanceId;
709
+ }
710
+
711
+ static _fromInstanceId(instanceId) {
712
+ return new Response(instanceId, null);
713
+ }
714
+
715
+ get status() {
716
+ return __Response_get_status(this.#instanceId);
717
+ }
718
+
719
+ get statusText() {
720
+ return __Response_get_statusText(this.#instanceId);
721
+ }
722
+
723
+ get ok() {
724
+ const status = this.status;
725
+ return status >= 200 && status < 300;
726
+ }
727
+
728
+ get headers() {
729
+ return this.#headers;
730
+ }
731
+
732
+ get bodyUsed() {
733
+ return __Response_get_bodyUsed(this.#instanceId);
734
+ }
735
+
736
+ get url() {
737
+ return __Response_get_url(this.#instanceId);
738
+ }
739
+
740
+ get redirected() {
741
+ return __Response_get_redirected(this.#instanceId);
742
+ }
743
+
744
+ get type() {
745
+ return __Response_get_type(this.#instanceId);
746
+ }
747
+
748
+ get body() {
749
+ const streamId = __Response_getStreamId(this.#instanceId);
750
+ if (streamId !== null) {
751
+ return HostBackedReadableStream._fromStreamId(streamId);
752
+ }
753
+
754
+ // Fallback: create host-backed stream from buffered body
755
+ const instanceId = this.#instanceId;
756
+ const newStreamId = __Stream_create();
757
+ const buffer = __Response_arrayBuffer(instanceId);
758
+
759
+ if (buffer.byteLength > 0) {
760
+ __Stream_push(newStreamId, Array.from(new Uint8Array(buffer)));
761
+ }
762
+ __Stream_close(newStreamId);
763
+
764
+ return HostBackedReadableStream._fromStreamId(newStreamId);
765
+ }
766
+
767
+ async text() {
768
+ try {
769
+ __Response_markBodyUsed(this.#instanceId);
770
+ } catch (err) {
771
+ throw __decodeError(err);
772
+ }
773
+ return __Response_text(this.#instanceId);
774
+ }
775
+
776
+ async json() {
777
+ const text = await this.text();
778
+ return JSON.parse(text);
779
+ }
780
+
781
+ async arrayBuffer() {
782
+ try {
783
+ __Response_markBodyUsed(this.#instanceId);
784
+ } catch (err) {
785
+ throw __decodeError(err);
786
+ }
787
+
788
+ // For streaming responses (including Blob bodies), consume the stream
789
+ if (this.#streamId !== null) {
790
+ // Wait for blob init to complete if needed
791
+ if (this.#blobInitPromise) {
792
+ await this.#blobInitPromise;
793
+ this.#blobInitPromise = null;
794
+ }
795
+
796
+ const reader = this.body.getReader();
797
+ const chunks = [];
798
+ while (true) {
799
+ const { done, value } = await reader.read();
800
+ if (done) break;
801
+ if (value) chunks.push(value);
802
+ }
803
+ // Concatenate all chunks
804
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
805
+ const result = new Uint8Array(totalLength);
806
+ let offset = 0;
807
+ for (const chunk of chunks) {
808
+ result.set(chunk, offset);
809
+ offset += chunk.length;
810
+ }
811
+ return result.buffer;
812
+ }
813
+
814
+ return __Response_arrayBuffer(this.#instanceId);
815
+ }
816
+
817
+ async blob() {
818
+ const buffer = await this.arrayBuffer();
819
+ const contentType = this.headers.get('content-type') || '';
820
+ return new Blob([buffer], { type: contentType });
821
+ }
822
+
823
+ async formData() {
824
+ const contentType = this.headers.get('content-type') || '';
825
+
826
+ // Parse multipart/form-data
827
+ if (contentType.includes('multipart/form-data')) {
828
+ const buffer = await this.arrayBuffer();
829
+ return __parseMultipartFormData(new Uint8Array(buffer), contentType);
830
+ }
831
+
832
+ // Parse application/x-www-form-urlencoded
833
+ if (contentType.includes('application/x-www-form-urlencoded')) {
834
+ const text = await this.text();
835
+ const formData = new FormData();
836
+ const params = new URLSearchParams(text);
837
+ for (const [key, value] of params) {
838
+ formData.append(key, value);
839
+ }
840
+ return formData;
841
+ }
842
+
843
+ throw new TypeError('Unsupported content type for formData()');
844
+ }
845
+
846
+ clone() {
847
+ if (this.bodyUsed) {
848
+ throw new TypeError('Cannot clone a Response that has already been used');
849
+ }
850
+ const newId = __Response_clone(this.#instanceId);
851
+ const cloned = Response._fromInstanceId(newId);
852
+ return cloned;
853
+ }
854
+
855
+ static json(data, init = {}) {
856
+ const body = JSON.stringify(data);
857
+ const headers = new Headers(init.headers);
858
+ if (!headers.has('content-type')) {
859
+ headers.set('content-type', 'application/json');
860
+ }
861
+ return new Response(body, { ...init, headers });
862
+ }
863
+
864
+ static redirect(url, status = 302) {
865
+ if (![301, 302, 303, 307, 308].includes(status)) {
866
+ throw new RangeError('Invalid redirect status code');
867
+ }
868
+ const headers = new Headers({ Location: String(url) });
869
+ return new Response(null, { status, headers });
870
+ }
871
+
872
+ static error() {
873
+ const response = new Response(null, { status: 0, statusText: '' });
874
+ __Response_setType(response._getInstanceId(), 'error');
875
+ return response;
876
+ }
877
+ }
878
+
879
+ globalThis.Response = Response;
880
+ })();
881
+ `;
882
+ context.evalSync(responseCode);
883
+ }
884
+ function setupRequest(context, stateMap) {
885
+ const global = context.global;
886
+ global.setSync("__Request_construct", new ivm.Callback((url, method, headers, bodyBytes, mode, credentials, cache, redirect, referrer, integrity) => {
887
+ const instanceId = nextInstanceId++;
888
+ const body = bodyBytes ? new Uint8Array(bodyBytes) : null;
889
+ const state = {
890
+ url,
891
+ method,
892
+ headers,
893
+ body,
894
+ bodyUsed: false,
895
+ streamId: null,
896
+ mode,
897
+ credentials,
898
+ cache,
899
+ redirect,
900
+ referrer,
901
+ integrity
902
+ };
903
+ stateMap.set(instanceId, state);
904
+ return instanceId;
905
+ }));
906
+ global.setSync("__Request_get_method", new ivm.Callback((instanceId) => {
907
+ const state = stateMap.get(instanceId);
908
+ return state?.method ?? "GET";
909
+ }));
910
+ global.setSync("__Request_get_url", new ivm.Callback((instanceId) => {
911
+ const state = stateMap.get(instanceId);
912
+ return state?.url ?? "";
913
+ }));
914
+ global.setSync("__Request_get_headers", new ivm.Callback((instanceId) => {
915
+ const state = stateMap.get(instanceId);
916
+ return state?.headers ?? [];
917
+ }));
918
+ global.setSync("__Request_get_bodyUsed", new ivm.Callback((instanceId) => {
919
+ const state = stateMap.get(instanceId);
920
+ return state?.bodyUsed ?? false;
921
+ }));
922
+ global.setSync("__Request_get_mode", new ivm.Callback((instanceId) => {
923
+ const state = stateMap.get(instanceId);
924
+ return state?.mode ?? "cors";
925
+ }));
926
+ global.setSync("__Request_get_credentials", new ivm.Callback((instanceId) => {
927
+ const state = stateMap.get(instanceId);
928
+ return state?.credentials ?? "same-origin";
929
+ }));
930
+ global.setSync("__Request_get_cache", new ivm.Callback((instanceId) => {
931
+ const state = stateMap.get(instanceId);
932
+ return state?.cache ?? "default";
933
+ }));
934
+ global.setSync("__Request_get_redirect", new ivm.Callback((instanceId) => {
935
+ const state = stateMap.get(instanceId);
936
+ return state?.redirect ?? "follow";
937
+ }));
938
+ global.setSync("__Request_get_referrer", new ivm.Callback((instanceId) => {
939
+ const state = stateMap.get(instanceId);
940
+ return state?.referrer ?? "about:client";
941
+ }));
942
+ global.setSync("__Request_get_integrity", new ivm.Callback((instanceId) => {
943
+ const state = stateMap.get(instanceId);
944
+ return state?.integrity ?? "";
945
+ }));
946
+ global.setSync("__Request_markBodyUsed", new ivm.Callback((instanceId) => {
947
+ const state = stateMap.get(instanceId);
948
+ if (state) {
949
+ if (state.bodyUsed) {
950
+ throw new Error("[TypeError]Body has already been consumed");
951
+ }
952
+ state.bodyUsed = true;
953
+ }
954
+ }));
955
+ global.setSync("__Request_text", new ivm.Callback((instanceId) => {
956
+ const state = stateMap.get(instanceId);
957
+ if (!state || !state.body)
958
+ return "";
959
+ return new TextDecoder().decode(state.body);
960
+ }));
961
+ global.setSync("__Request_arrayBuffer", new ivm.Callback((instanceId) => {
962
+ const state = stateMap.get(instanceId);
963
+ if (!state || !state.body) {
964
+ return new ivm.ExternalCopy(new ArrayBuffer(0)).copyInto();
965
+ }
966
+ return new ivm.ExternalCopy(state.body.buffer.slice(state.body.byteOffset, state.body.byteOffset + state.body.byteLength)).copyInto();
967
+ }));
968
+ global.setSync("__Request_getBodyBytes", new ivm.Callback((instanceId) => {
969
+ const state = stateMap.get(instanceId);
970
+ if (!state || !state.body)
971
+ return null;
972
+ return Array.from(state.body);
973
+ }));
974
+ global.setSync("__Request_clone", new ivm.Callback((instanceId) => {
975
+ const state = stateMap.get(instanceId);
976
+ if (!state) {
977
+ throw new Error("[TypeError]Cannot clone invalid Request");
978
+ }
979
+ const newId = nextInstanceId++;
980
+ const newState = {
981
+ ...state,
982
+ body: state.body ? new Uint8Array(state.body) : null,
983
+ bodyUsed: false
984
+ };
985
+ stateMap.set(newId, newState);
986
+ return newId;
987
+ }));
988
+ global.setSync("__Request_getStreamId", new ivm.Callback((instanceId) => {
989
+ const state = stateMap.get(instanceId);
990
+ return state?.streamId ?? null;
991
+ }));
992
+ const requestCode = `
993
+ (function() {
994
+ function __decodeError(err) {
995
+ if (!(err instanceof Error)) return err;
996
+ const match = err.message.match(/^\\[(TypeError|RangeError|SyntaxError|ReferenceError|URIError|EvalError|Error)\\](.*)$/);
997
+ if (match) {
998
+ const ErrorType = globalThis[match[1]] || Error;
999
+ return new ErrorType(match[2]);
1000
+ }
1001
+ return err;
1002
+ }
1003
+
1004
+ function __prepareBody(body) {
1005
+ if (body === null || body === undefined) return null;
1006
+ if (typeof body === 'string') {
1007
+ const encoder = new TextEncoder();
1008
+ return Array.from(encoder.encode(body));
1009
+ }
1010
+ if (body instanceof ArrayBuffer) {
1011
+ return Array.from(new Uint8Array(body));
1012
+ }
1013
+ if (body instanceof Uint8Array) {
1014
+ return Array.from(body);
1015
+ }
1016
+ if (ArrayBuffer.isView(body)) {
1017
+ return Array.from(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
1018
+ }
1019
+ if (body instanceof URLSearchParams) {
1020
+ return Array.from(new TextEncoder().encode(body.toString()));
1021
+ }
1022
+ if (body instanceof FormData) {
1023
+ // Check if FormData has any File/Blob entries
1024
+ let hasFiles = false;
1025
+ for (const [, value] of body.entries()) {
1026
+ if (value instanceof File || value instanceof Blob) {
1027
+ hasFiles = true;
1028
+ break;
1029
+ }
1030
+ }
1031
+
1032
+ if (hasFiles) {
1033
+ // Serialize as multipart/form-data
1034
+ const { body: bytes, contentType } = __serializeFormData(body);
1035
+ globalThis.__pendingFormDataContentType = contentType;
1036
+ return Array.from(bytes);
1037
+ }
1038
+
1039
+ // URL-encoded for string-only FormData
1040
+ const parts = [];
1041
+ body.forEach((value, key) => {
1042
+ if (typeof value === 'string') {
1043
+ parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
1044
+ }
1045
+ });
1046
+ return Array.from(new TextEncoder().encode(parts.join('&')));
1047
+ }
1048
+ // Try to convert to string
1049
+ return Array.from(new TextEncoder().encode(String(body)));
1050
+ }
1051
+
1052
+ // Helper to consume a HostBackedReadableStream and concatenate all chunks
1053
+ async function __consumeStream(stream) {
1054
+ const reader = stream.getReader();
1055
+ const chunks = [];
1056
+ let totalLength = 0;
1057
+
1058
+ while (true) {
1059
+ const { done, value } = await reader.read();
1060
+ if (done) break;
1061
+ chunks.push(value);
1062
+ totalLength += value.length;
1063
+ }
1064
+
1065
+ // Concatenate all chunks
1066
+ const result = new Uint8Array(totalLength);
1067
+ let offset = 0;
1068
+ for (const chunk of chunks) {
1069
+ result.set(chunk, offset);
1070
+ offset += chunk.length;
1071
+ }
1072
+ return result;
1073
+ }
1074
+
1075
+ class Request {
1076
+ #instanceId;
1077
+ #headers;
1078
+ #signal;
1079
+ #streamId;
1080
+ #cachedBody = null;
1081
+
1082
+ constructor(input, init = {}) {
1083
+ // Handle internal construction from instance ID
1084
+ if (typeof input === 'number' && init === null) {
1085
+ this.#instanceId = input;
1086
+ this.#headers = new Headers(__Request_get_headers(input));
1087
+ this.#signal = null;
1088
+ this.#streamId = __Request_getStreamId(input);
1089
+ return;
1090
+ }
1091
+
1092
+ let url;
1093
+ let method = 'GET';
1094
+ let headers;
1095
+ let body = null;
1096
+ let signal = null;
1097
+ let mode = 'cors';
1098
+ let credentials = 'same-origin';
1099
+ let cache = 'default';
1100
+ let redirect = 'follow';
1101
+ let referrer = 'about:client';
1102
+ let integrity = '';
1103
+
1104
+ if (input instanceof Request) {
1105
+ url = input.url;
1106
+ method = input.method;
1107
+ headers = new Headers(input.headers);
1108
+ signal = input.signal;
1109
+ mode = input.mode;
1110
+ credentials = input.credentials;
1111
+ cache = input.cache;
1112
+ redirect = input.redirect;
1113
+ referrer = input.referrer;
1114
+ integrity = input.integrity;
1115
+ // Note: We don't copy the body from the input Request
1116
+ } else {
1117
+ url = String(input);
1118
+ headers = new Headers();
1119
+ }
1120
+
1121
+ // Apply init overrides
1122
+ if (init.method !== undefined) method = String(init.method).toUpperCase();
1123
+ if (init.headers !== undefined) headers = new Headers(init.headers);
1124
+ if (init.body !== undefined) body = init.body;
1125
+ if (init.signal !== undefined) signal = init.signal;
1126
+ if (init.mode !== undefined) mode = init.mode;
1127
+ if (init.credentials !== undefined) credentials = init.credentials;
1128
+ if (init.cache !== undefined) cache = init.cache;
1129
+ if (init.redirect !== undefined) redirect = init.redirect;
1130
+ if (init.referrer !== undefined) referrer = init.referrer;
1131
+ if (init.integrity !== undefined) integrity = init.integrity;
1132
+
1133
+ // Validate: body with GET/HEAD
1134
+ if (body !== null && (method === 'GET' || method === 'HEAD')) {
1135
+ throw new TypeError('Request with GET/HEAD method cannot have body');
1136
+ }
1137
+
1138
+ const bodyBytes = __prepareBody(body);
1139
+
1140
+ // Handle Content-Type for FormData
1141
+ if (globalThis.__pendingFormDataContentType) {
1142
+ headers.set('content-type', globalThis.__pendingFormDataContentType);
1143
+ delete globalThis.__pendingFormDataContentType;
1144
+ } else if (body instanceof FormData && !headers.has('content-type')) {
1145
+ headers.set('content-type', 'application/x-www-form-urlencoded');
1146
+ }
1147
+
1148
+ const headersArray = Array.from(headers.entries());
1149
+
1150
+ this.#instanceId = __Request_construct(
1151
+ url, method, headersArray, bodyBytes,
1152
+ mode, credentials, cache, redirect, referrer, integrity
1153
+ );
1154
+ this.#headers = headers;
1155
+ this.#signal = signal;
1156
+ this.#streamId = null;
1157
+ }
1158
+
1159
+ _getInstanceId() {
1160
+ return this.#instanceId;
1161
+ }
1162
+
1163
+ static _fromInstanceId(instanceId) {
1164
+ return new Request(instanceId, null);
1165
+ }
1166
+
1167
+ get method() {
1168
+ return __Request_get_method(this.#instanceId);
1169
+ }
1170
+
1171
+ get url() {
1172
+ return __Request_get_url(this.#instanceId);
1173
+ }
1174
+
1175
+ get headers() {
1176
+ return this.#headers;
1177
+ }
1178
+
1179
+ get bodyUsed() {
1180
+ return __Request_get_bodyUsed(this.#instanceId);
1181
+ }
1182
+
1183
+ get signal() {
1184
+ return this.#signal;
1185
+ }
1186
+
1187
+ get mode() {
1188
+ return __Request_get_mode(this.#instanceId);
1189
+ }
1190
+
1191
+ get credentials() {
1192
+ return __Request_get_credentials(this.#instanceId);
1193
+ }
1194
+
1195
+ get cache() {
1196
+ return __Request_get_cache(this.#instanceId);
1197
+ }
1198
+
1199
+ get redirect() {
1200
+ return __Request_get_redirect(this.#instanceId);
1201
+ }
1202
+
1203
+ get referrer() {
1204
+ return __Request_get_referrer(this.#instanceId);
1205
+ }
1206
+
1207
+ get integrity() {
1208
+ return __Request_get_integrity(this.#instanceId);
1209
+ }
1210
+
1211
+ get body() {
1212
+ // Return cached body if available
1213
+ if (this.#cachedBody !== null) {
1214
+ return this.#cachedBody;
1215
+ }
1216
+
1217
+ // If we have a stream ID, create and cache the stream
1218
+ if (this.#streamId !== null) {
1219
+ this.#cachedBody = HostBackedReadableStream._fromStreamId(this.#streamId);
1220
+ return this.#cachedBody;
1221
+ }
1222
+
1223
+ // Create stream from buffered body
1224
+ const newStreamId = __Stream_create();
1225
+ const buffer = __Request_arrayBuffer(this.#instanceId);
1226
+ if (buffer.byteLength > 0) {
1227
+ __Stream_push(newStreamId, Array.from(new Uint8Array(buffer)));
1228
+ }
1229
+ __Stream_close(newStreamId);
1230
+
1231
+ this.#cachedBody = HostBackedReadableStream._fromStreamId(newStreamId);
1232
+ return this.#cachedBody;
1233
+ }
1234
+
1235
+ async text() {
1236
+ try {
1237
+ __Request_markBodyUsed(this.#instanceId);
1238
+ } catch (err) {
1239
+ throw __decodeError(err);
1240
+ }
1241
+
1242
+ // If streaming, consume the stream
1243
+ if (this.#streamId !== null) {
1244
+ const bytes = await __consumeStream(this.body);
1245
+ return new TextDecoder().decode(bytes);
1246
+ }
1247
+
1248
+ // Fallback to host callback for buffered body
1249
+ return __Request_text(this.#instanceId);
1250
+ }
1251
+
1252
+ async json() {
1253
+ const text = await this.text();
1254
+ return JSON.parse(text);
1255
+ }
1256
+
1257
+ async arrayBuffer() {
1258
+ try {
1259
+ __Request_markBodyUsed(this.#instanceId);
1260
+ } catch (err) {
1261
+ throw __decodeError(err);
1262
+ }
1263
+
1264
+ // If streaming, consume the stream
1265
+ if (this.#streamId !== null) {
1266
+ const bytes = await __consumeStream(this.body);
1267
+ return bytes.buffer;
1268
+ }
1269
+
1270
+ return __Request_arrayBuffer(this.#instanceId);
1271
+ }
1272
+
1273
+ async blob() {
1274
+ const buffer = await this.arrayBuffer();
1275
+ const contentType = this.headers.get('content-type') || '';
1276
+ return new Blob([buffer], { type: contentType });
1277
+ }
1278
+
1279
+ async formData() {
1280
+ const contentType = this.headers.get('content-type') || '';
1281
+
1282
+ // Parse multipart/form-data
1283
+ if (contentType.includes('multipart/form-data')) {
1284
+ const buffer = await this.arrayBuffer();
1285
+ return __parseMultipartFormData(new Uint8Array(buffer), contentType);
1286
+ }
1287
+
1288
+ // Parse application/x-www-form-urlencoded
1289
+ if (contentType.includes('application/x-www-form-urlencoded')) {
1290
+ const text = await this.text();
1291
+ const formData = new FormData();
1292
+ const params = new URLSearchParams(text);
1293
+ for (const [key, value] of params) {
1294
+ formData.append(key, value);
1295
+ }
1296
+ return formData;
1297
+ }
1298
+
1299
+ throw new TypeError('Unsupported content type for formData()');
1300
+ }
1301
+
1302
+ clone() {
1303
+ if (this.bodyUsed) {
1304
+ throw new TypeError('Cannot clone a Request that has already been used');
1305
+ }
1306
+ const newId = __Request_clone(this.#instanceId);
1307
+ const cloned = Request._fromInstanceId(newId);
1308
+ cloned.#signal = this.#signal;
1309
+ return cloned;
1310
+ }
1311
+
1312
+ _getBodyBytes() {
1313
+ return __Request_getBodyBytes(this.#instanceId);
1314
+ }
1315
+ }
1316
+
1317
+ globalThis.Request = Request;
1318
+ })();
1319
+ `;
1320
+ context.evalSync(requestCode);
1321
+ }
1322
+ function setupFetchFunction(context, stateMap, options) {
1323
+ const global = context.global;
1324
+ const fetchRef = new ivm.Reference(async (url, method, headersJson, bodyJson, signalAborted) => {
1325
+ if (signalAborted) {
1326
+ throw new Error("[AbortError]The operation was aborted.");
1327
+ }
1328
+ const headers = JSON.parse(headersJson);
1329
+ const bodyBytes = bodyJson ? JSON.parse(bodyJson) : null;
1330
+ const body = bodyBytes ? new Uint8Array(bodyBytes) : null;
1331
+ const nativeRequest = new Request(url, {
1332
+ method,
1333
+ headers,
1334
+ body
1335
+ });
1336
+ const onFetch = options?.onFetch ?? fetch;
1337
+ const nativeResponse = await onFetch(nativeRequest);
1338
+ const responseBody = await nativeResponse.arrayBuffer();
1339
+ const responseBodyArray = Array.from(new Uint8Array(responseBody));
1340
+ const instanceId = nextInstanceId++;
1341
+ const state = {
1342
+ status: nativeResponse.status,
1343
+ statusText: nativeResponse.statusText,
1344
+ headers: Array.from(nativeResponse.headers.entries()),
1345
+ body: new Uint8Array(responseBodyArray),
1346
+ bodyUsed: false,
1347
+ type: "default",
1348
+ url: nativeResponse.url,
1349
+ redirected: nativeResponse.redirected,
1350
+ streamId: null
1351
+ };
1352
+ stateMap.set(instanceId, state);
1353
+ return instanceId;
1354
+ });
1355
+ global.setSync("__fetch_ref", fetchRef);
1356
+ const fetchCode = `
1357
+ (function() {
1358
+ function __decodeError(err) {
1359
+ if (!(err instanceof Error)) return err;
1360
+ const match = err.message.match(/^\\[(TypeError|RangeError|AbortError|Error)\\](.*)$/);
1361
+ if (match) {
1362
+ if (match[1] === 'AbortError') {
1363
+ return new DOMException(match[2], 'AbortError');
1364
+ }
1365
+ const ErrorType = globalThis[match[1]] || Error;
1366
+ return new ErrorType(match[2]);
1367
+ }
1368
+ return err;
1369
+ }
1370
+
1371
+ globalThis.fetch = function(input, init = {}) {
1372
+ // Create Request from input
1373
+ const request = input instanceof Request ? input : new Request(input, init);
1374
+
1375
+ // Get signal info
1376
+ const signal = init.signal ?? request.signal;
1377
+ const signalAborted = signal?.aborted ?? false;
1378
+
1379
+ // Serialize headers and body to JSON for transfer
1380
+ const headersJson = JSON.stringify(Array.from(request.headers.entries()));
1381
+ const bodyBytes = request._getBodyBytes();
1382
+ const bodyJson = bodyBytes ? JSON.stringify(bodyBytes) : null;
1383
+
1384
+ // Call host - returns just the response instance ID
1385
+ try {
1386
+ const instanceId = __fetch_ref.applySyncPromise(undefined, [
1387
+ request.url,
1388
+ request.method,
1389
+ headersJson,
1390
+ bodyJson,
1391
+ signalAborted
1392
+ ]);
1393
+
1394
+ // Construct Response from the instance ID
1395
+ return Response._fromInstanceId(instanceId);
1396
+ } catch (err) {
1397
+ throw __decodeError(err);
1398
+ }
1399
+ };
1400
+ })();
1401
+ `;
1402
+ context.evalSync(fetchCode);
1403
+ }
1404
+ function setupServer(context, serveState) {
1405
+ const global = context.global;
1406
+ context.evalSync(`
1407
+ globalThis.__upgradeRegistry__ = new Map();
1408
+ globalThis.__upgradeIdCounter__ = 0;
1409
+ `);
1410
+ global.setSync("__setPendingUpgrade__", new ivm.Callback((connectionId) => {
1411
+ serveState.pendingUpgrade = { requested: true, connectionId };
1412
+ }));
1413
+ context.evalSync(`
1414
+ (function() {
1415
+ class Server {
1416
+ upgrade(request, options) {
1417
+ const data = options?.data;
1418
+ const connectionId = String(++globalThis.__upgradeIdCounter__);
1419
+ globalThis.__upgradeRegistry__.set(connectionId, data);
1420
+ __setPendingUpgrade__(connectionId);
1421
+ return true;
1422
+ }
1423
+ }
1424
+ globalThis.__Server__ = Server;
1425
+ })();
1426
+ `);
1427
+ }
1428
+ function setupServerWebSocket(context, wsCommandCallbacks) {
1429
+ const global = context.global;
1430
+ global.setSync("__ServerWebSocket_send", new ivm.Callback((connectionId, data) => {
1431
+ const cmd = { type: "message", connectionId, data };
1432
+ for (const cb of wsCommandCallbacks)
1433
+ cb(cmd);
1434
+ }));
1435
+ global.setSync("__ServerWebSocket_close", new ivm.Callback((connectionId, code, reason) => {
1436
+ const cmd = { type: "close", connectionId, code, reason };
1437
+ for (const cb of wsCommandCallbacks)
1438
+ cb(cmd);
1439
+ }));
1440
+ context.evalSync(`
1441
+ (function() {
1442
+ const _wsInstanceData = new WeakMap();
1443
+
1444
+ class ServerWebSocket {
1445
+ constructor(connectionId) {
1446
+ _wsInstanceData.set(this, { connectionId, readyState: 1 });
1447
+ }
1448
+
1449
+ get data() {
1450
+ const state = _wsInstanceData.get(this);
1451
+ return globalThis.__upgradeRegistry__.get(state.connectionId);
1452
+ }
1453
+
1454
+ get readyState() {
1455
+ return _wsInstanceData.get(this).readyState;
1456
+ }
1457
+
1458
+ send(message) {
1459
+ const state = _wsInstanceData.get(this);
1460
+ if (state.readyState !== 1) throw new Error("WebSocket is not open");
1461
+ // Convert ArrayBuffer/Uint8Array to string for transfer
1462
+ let data = message;
1463
+ if (message instanceof ArrayBuffer) {
1464
+ data = new TextDecoder().decode(message);
1465
+ } else if (message instanceof Uint8Array) {
1466
+ data = new TextDecoder().decode(message);
1467
+ }
1468
+ __ServerWebSocket_send(state.connectionId, data);
1469
+ }
1470
+
1471
+ close(code, reason) {
1472
+ const state = _wsInstanceData.get(this);
1473
+ if (state.readyState === 3) return;
1474
+ state.readyState = 2; // CLOSING
1475
+ __ServerWebSocket_close(state.connectionId, code, reason);
1476
+ }
1477
+
1478
+ _setReadyState(readyState) {
1479
+ _wsInstanceData.get(this).readyState = readyState;
1480
+ }
1481
+ }
1482
+
1483
+ globalThis.__ServerWebSocket__ = ServerWebSocket;
1484
+ })();
1485
+ `);
1486
+ }
1487
+ function setupServe(context) {
1488
+ context.evalSync(`
1489
+ (function() {
1490
+ globalThis.__serveOptions__ = null;
1491
+
1492
+ function serve(options) {
1493
+ globalThis.__serveOptions__ = options;
1494
+ }
1495
+
1496
+ globalThis.serve = serve;
1497
+ })();
1498
+ `);
1499
+ }
1500
+ async function setupFetch(context, options) {
1501
+ await setupCore(context);
1502
+ const stateMap = getInstanceStateMapForContext(context);
1503
+ const streamRegistry = getStreamRegistryForContext(context);
1504
+ context.evalSync(headersCode);
1505
+ context.evalSync(formDataCode);
1506
+ context.evalSync(multipartCode);
1507
+ setupStreamCallbacks(context, streamRegistry);
1508
+ context.evalSync(hostBackedStreamCode);
1509
+ setupResponse(context, stateMap);
1510
+ setupRequest(context, stateMap);
1511
+ setupFetchFunction(context, stateMap, options);
1512
+ const serveState = {
1513
+ pendingUpgrade: null,
1514
+ activeConnections: new Map
1515
+ };
1516
+ const wsCommandCallbacks = new Set;
1517
+ setupServer(context, serveState);
1518
+ setupServerWebSocket(context, wsCommandCallbacks);
1519
+ setupServe(context);
1520
+ return {
1521
+ dispose() {
1522
+ stateMap.clear();
1523
+ context.evalSync(`globalThis.__upgradeRegistry__.clear()`);
1524
+ serveState.activeConnections.clear();
1525
+ serveState.pendingUpgrade = null;
1526
+ },
1527
+ async dispatchRequest(request, dispatchOptions) {
1528
+ const tick = dispatchOptions?.tick;
1529
+ if (serveState.pendingUpgrade) {
1530
+ const oldConnectionId = serveState.pendingUpgrade.connectionId;
1531
+ context.evalSync(`globalThis.__upgradeRegistry__.delete("${oldConnectionId}")`);
1532
+ serveState.pendingUpgrade = null;
1533
+ }
1534
+ const hasHandler = context.evalSync(`!!globalThis.__serveOptions__?.fetch`);
1535
+ if (!hasHandler) {
1536
+ throw new Error("No serve() handler registered");
1537
+ }
1538
+ let requestStreamId = null;
1539
+ let streamCleanup = null;
1540
+ if (request.body) {
1541
+ requestStreamId = streamRegistry.create();
1542
+ streamCleanup = startNativeStreamReader(request.body, requestStreamId, streamRegistry);
1543
+ }
1544
+ try {
1545
+ const headersArray = Array.from(request.headers.entries());
1546
+ const requestInstanceId = nextInstanceId++;
1547
+ const requestState = {
1548
+ url: request.url,
1549
+ method: request.method,
1550
+ headers: headersArray,
1551
+ body: null,
1552
+ bodyUsed: false,
1553
+ streamId: requestStreamId,
1554
+ mode: request.mode,
1555
+ credentials: request.credentials,
1556
+ cache: request.cache,
1557
+ redirect: request.redirect,
1558
+ referrer: request.referrer,
1559
+ integrity: request.integrity
1560
+ };
1561
+ stateMap.set(requestInstanceId, requestState);
1562
+ const responseInstanceId = await context.eval(`
1563
+ (async function() {
1564
+ const request = Request._fromInstanceId(${requestInstanceId});
1565
+ const server = new __Server__();
1566
+ const response = await Promise.resolve(__serveOptions__.fetch(request, server));
1567
+ return response._getInstanceId();
1568
+ })()
1569
+ `, { promise: true });
1570
+ const responseState = stateMap.get(responseInstanceId);
1571
+ if (!responseState) {
1572
+ throw new Error("Response state not found");
1573
+ }
1574
+ if (responseState.streamId !== null) {
1575
+ const responseStreamId = responseState.streamId;
1576
+ let streamDone = false;
1577
+ const pumpedStream = new ReadableStream({
1578
+ async pull(controller) {
1579
+ if (streamDone)
1580
+ return;
1581
+ while (!streamDone) {
1582
+ if (tick) {
1583
+ await tick();
1584
+ }
1585
+ const state = streamRegistry.get(responseStreamId);
1586
+ if (!state) {
1587
+ controller.close();
1588
+ streamDone = true;
1589
+ return;
1590
+ }
1591
+ if (state.queue.length > 0 || state.closed || state.errored) {
1592
+ break;
1593
+ }
1594
+ await new Promise((r) => setTimeout(r, 1));
1595
+ }
1596
+ try {
1597
+ const result = await streamRegistry.pull(responseStreamId);
1598
+ if (result.done) {
1599
+ controller.close();
1600
+ streamDone = true;
1601
+ streamRegistry.delete(responseStreamId);
1602
+ return;
1603
+ }
1604
+ controller.enqueue(result.value);
1605
+ } catch (error) {
1606
+ controller.error(error);
1607
+ streamDone = true;
1608
+ streamRegistry.delete(responseStreamId);
1609
+ }
1610
+ },
1611
+ cancel() {
1612
+ streamDone = true;
1613
+ streamRegistry.error(responseStreamId, new Error("Stream cancelled"));
1614
+ streamRegistry.delete(responseStreamId);
1615
+ }
1616
+ });
1617
+ const responseHeaders2 = new Headers(responseState.headers);
1618
+ const status2 = responseState.status === 101 ? 200 : responseState.status;
1619
+ const response2 = new Response(pumpedStream, {
1620
+ status: status2,
1621
+ statusText: responseState.statusText,
1622
+ headers: responseHeaders2
1623
+ });
1624
+ response2._originalStatus = responseState.status;
1625
+ return response2;
1626
+ }
1627
+ const responseHeaders = new Headers(responseState.headers);
1628
+ const responseBody = responseState.body;
1629
+ const status = responseState.status === 101 ? 200 : responseState.status;
1630
+ const response = new Response(responseBody, {
1631
+ status,
1632
+ statusText: responseState.statusText,
1633
+ headers: responseHeaders
1634
+ });
1635
+ response._originalStatus = responseState.status;
1636
+ return response;
1637
+ } finally {
1638
+ if (streamCleanup) {
1639
+ await streamCleanup();
1640
+ }
1641
+ if (requestStreamId !== null) {
1642
+ streamRegistry.delete(requestStreamId);
1643
+ }
1644
+ }
1645
+ },
1646
+ getUpgradeRequest() {
1647
+ const result = serveState.pendingUpgrade;
1648
+ return result;
1649
+ },
1650
+ dispatchWebSocketOpen(connectionId) {
1651
+ const hasOpenHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.open`);
1652
+ if (!hasOpenHandler) {
1653
+ context.evalSync(`globalThis.__upgradeRegistry__.delete("${connectionId}")`);
1654
+ return;
1655
+ }
1656
+ serveState.activeConnections.set(connectionId, { connectionId });
1657
+ context.evalSync(`
1658
+ (function() {
1659
+ const ws = new __ServerWebSocket__("${connectionId}");
1660
+ globalThis.__activeWs_${connectionId}__ = ws;
1661
+ __serveOptions__.websocket.open(ws);
1662
+ })()
1663
+ `);
1664
+ if (serveState.pendingUpgrade?.connectionId === connectionId) {
1665
+ serveState.pendingUpgrade = null;
1666
+ }
1667
+ },
1668
+ dispatchWebSocketMessage(connectionId, message) {
1669
+ if (!serveState.activeConnections.has(connectionId)) {
1670
+ return;
1671
+ }
1672
+ const hasMessageHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.message`);
1673
+ if (!hasMessageHandler) {
1674
+ return;
1675
+ }
1676
+ if (typeof message === "string") {
1677
+ context.evalSync(`
1678
+ (function() {
1679
+ const ws = globalThis.__activeWs_${connectionId}__;
1680
+ if (ws) __serveOptions__.websocket.message(ws, "${message.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n")}");
1681
+ })()
1682
+ `);
1683
+ } else {
1684
+ const bytes = Array.from(new Uint8Array(message));
1685
+ context.evalSync(`
1686
+ (function() {
1687
+ const ws = globalThis.__activeWs_${connectionId}__;
1688
+ if (ws) {
1689
+ const bytes = new Uint8Array([${bytes.join(",")}]);
1690
+ __serveOptions__.websocket.message(ws, bytes.buffer);
1691
+ }
1692
+ })()
1693
+ `);
1694
+ }
1695
+ },
1696
+ dispatchWebSocketClose(connectionId, code, reason) {
1697
+ if (!serveState.activeConnections.has(connectionId)) {
1698
+ return;
1699
+ }
1700
+ context.evalSync(`
1701
+ (function() {
1702
+ const ws = globalThis.__activeWs_${connectionId}__;
1703
+ if (ws) ws._setReadyState(3);
1704
+ })()
1705
+ `);
1706
+ const hasCloseHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.close`);
1707
+ if (hasCloseHandler) {
1708
+ const safeReason = reason.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
1709
+ context.evalSync(`
1710
+ (function() {
1711
+ const ws = globalThis.__activeWs_${connectionId}__;
1712
+ if (ws) __serveOptions__.websocket.close(ws, ${code}, "${safeReason}");
1713
+ })()
1714
+ `);
1715
+ }
1716
+ context.evalSync(`
1717
+ delete globalThis.__activeWs_${connectionId}__;
1718
+ globalThis.__upgradeRegistry__.delete("${connectionId}");
1719
+ `);
1720
+ serveState.activeConnections.delete(connectionId);
1721
+ },
1722
+ dispatchWebSocketError(connectionId, error) {
1723
+ if (!serveState.activeConnections.has(connectionId)) {
1724
+ return;
1725
+ }
1726
+ const hasErrorHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.error`);
1727
+ if (!hasErrorHandler) {
1728
+ return;
1729
+ }
1730
+ const safeName = error.name.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
1731
+ const safeMessage = error.message.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
1732
+ context.evalSync(`
1733
+ (function() {
1734
+ const ws = globalThis.__activeWs_${connectionId}__;
1735
+ if (ws) {
1736
+ const error = { name: "${safeName}", message: "${safeMessage}" };
1737
+ __serveOptions__.websocket.error(ws, error);
1738
+ }
1739
+ })()
1740
+ `);
1741
+ },
1742
+ onWebSocketCommand(callback) {
1743
+ wsCommandCallbacks.add(callback);
1744
+ return () => wsCommandCallbacks.delete(callback);
1745
+ },
1746
+ hasServeHandler() {
1747
+ return context.evalSync(`!!globalThis.__serveOptions__?.fetch`);
1748
+ },
1749
+ hasActiveConnections() {
1750
+ return serveState.activeConnections.size > 0;
1751
+ }
1752
+ };
1753
+ }
1754
+ export {
1755
+ setupFetch,
1756
+ clearAllInstanceState
1757
+ };
1758
+
1759
+ //# debugId=30AA5852218E953D64756E2164756E21