@ricsam/isolate 0.0.1 → 0.1.1
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.
- package/README.md +243 -34
- package/dist/cjs/bridge/diagnostics.cjs +58 -0
- package/dist/cjs/bridge/diagnostics.cjs.map +10 -0
- package/dist/cjs/bridge/legacy-adapters.cjs +242 -0
- package/dist/cjs/bridge/legacy-adapters.cjs.map +10 -0
- package/dist/cjs/bridge/request-context.cjs +59 -0
- package/dist/cjs/bridge/request-context.cjs.map +10 -0
- package/dist/cjs/bridge/runtime-bindings.cjs +367 -0
- package/dist/cjs/bridge/runtime-bindings.cjs.map +10 -0
- package/dist/cjs/browser/browser-runtime.cjs +157 -0
- package/dist/cjs/browser/browser-runtime.cjs.map +10 -0
- package/dist/cjs/daemon.cjs +91 -0
- package/dist/cjs/daemon.cjs.map +10 -0
- package/dist/cjs/files/index.cjs +140 -0
- package/dist/cjs/files/index.cjs.map +10 -0
- package/dist/cjs/host/create-isolate-host.cjs +235 -0
- package/dist/cjs/host/create-isolate-host.cjs.map +10 -0
- package/dist/cjs/host/index.cjs +47 -0
- package/dist/cjs/host/index.cjs.map +10 -0
- package/dist/cjs/index.cjs +55 -0
- package/dist/cjs/index.cjs.map +10 -0
- package/dist/cjs/internal/client/connection.cjs +1919 -0
- package/dist/cjs/internal/client/connection.cjs.map +10 -0
- package/dist/cjs/internal/client/index.cjs +48 -0
- package/dist/cjs/internal/client/index.cjs.map +10 -0
- package/dist/cjs/internal/client/types.cjs +30 -0
- package/dist/cjs/internal/client/types.cjs.map +9 -0
- package/dist/cjs/internal/console/index.cjs +506 -0
- package/dist/cjs/internal/console/index.cjs.map +10 -0
- package/dist/cjs/internal/console/utils.cjs +70 -0
- package/dist/cjs/internal/console/utils.cjs.map +10 -0
- package/dist/cjs/internal/core/index.cjs +2745 -0
- package/dist/cjs/internal/core/index.cjs.map +10 -0
- package/dist/cjs/internal/crypto/index.cjs +470 -0
- package/dist/cjs/internal/crypto/index.cjs.map +10 -0
- package/dist/cjs/internal/daemon/callback-fs-handler.cjs +355 -0
- package/dist/cjs/internal/daemon/callback-fs-handler.cjs.map +10 -0
- package/dist/cjs/internal/daemon/connection.cjs +1952 -0
- package/dist/cjs/internal/daemon/connection.cjs.map +10 -0
- package/dist/cjs/internal/daemon/daemon.cjs +98 -0
- package/dist/cjs/internal/daemon/daemon.cjs.map +10 -0
- package/dist/cjs/internal/daemon/index.cjs +145 -0
- package/dist/cjs/internal/daemon/index.cjs.map +10 -0
- package/dist/cjs/internal/daemon/runtime-pool.cjs +106 -0
- package/dist/cjs/internal/daemon/runtime-pool.cjs.map +10 -0
- package/dist/cjs/internal/daemon/types.cjs +30 -0
- package/dist/cjs/internal/daemon/types.cjs.map +9 -0
- package/dist/cjs/internal/encoding/index.cjs +419 -0
- package/dist/cjs/internal/encoding/index.cjs.map +10 -0
- package/dist/cjs/internal/fetch/consistency/origins.cjs +598 -0
- package/dist/cjs/internal/fetch/consistency/origins.cjs.map +10 -0
- package/dist/cjs/internal/fetch/index.cjs +2640 -0
- package/dist/cjs/internal/fetch/index.cjs.map +10 -0
- package/dist/cjs/internal/fetch/stream-state.cjs +256 -0
- package/dist/cjs/internal/fetch/stream-state.cjs.map +10 -0
- package/dist/cjs/internal/fs/index.cjs +847 -0
- package/dist/cjs/internal/fs/index.cjs.map +10 -0
- package/dist/cjs/internal/fs/node-adapter.cjs +254 -0
- package/dist/cjs/internal/fs/node-adapter.cjs.map +10 -0
- package/dist/cjs/internal/module-loader/bundle.cjs +482 -0
- package/dist/cjs/internal/module-loader/bundle.cjs.map +10 -0
- package/dist/cjs/internal/module-loader/index.cjs +240 -0
- package/dist/cjs/internal/module-loader/index.cjs.map +10 -0
- package/dist/cjs/internal/module-loader/mappings.cjs +120 -0
- package/dist/cjs/internal/module-loader/mappings.cjs.map +10 -0
- package/dist/cjs/internal/module-loader/resolve.cjs +177 -0
- package/dist/cjs/internal/module-loader/resolve.cjs.map +10 -0
- package/dist/cjs/internal/module-loader/strip-types.cjs +236 -0
- package/dist/cjs/internal/module-loader/strip-types.cjs.map +10 -0
- package/dist/cjs/internal/path/index.cjs +503 -0
- package/dist/cjs/internal/path/index.cjs.map +10 -0
- package/dist/cjs/internal/playwright/client.cjs +49 -0
- package/dist/cjs/internal/playwright/client.cjs.map +10 -0
- package/dist/cjs/internal/playwright/handler.cjs +1416 -0
- package/dist/cjs/internal/playwright/handler.cjs.map +10 -0
- package/dist/cjs/internal/playwright/index.cjs +1289 -0
- package/dist/cjs/internal/playwright/index.cjs.map +10 -0
- package/dist/cjs/internal/playwright/types.cjs +47 -0
- package/dist/cjs/internal/playwright/types.cjs.map +10 -0
- package/dist/cjs/internal/protocol/codec.cjs +510 -0
- package/dist/cjs/internal/protocol/codec.cjs.map +10 -0
- package/dist/cjs/internal/protocol/framing.cjs +141 -0
- package/dist/cjs/internal/protocol/framing.cjs.map +10 -0
- package/dist/cjs/internal/protocol/index.cjs +110 -0
- package/dist/cjs/internal/protocol/index.cjs.map +10 -0
- package/dist/cjs/internal/protocol/marshalValue.cjs +518 -0
- package/dist/cjs/internal/protocol/marshalValue.cjs.map +10 -0
- package/dist/cjs/internal/protocol/serialization.cjs +109 -0
- package/dist/cjs/internal/protocol/serialization.cjs.map +10 -0
- package/dist/cjs/internal/protocol/types.cjs +181 -0
- package/dist/cjs/internal/protocol/types.cjs.map +10 -0
- package/dist/cjs/internal/runtime/index.cjs +1235 -0
- package/dist/cjs/internal/runtime/index.cjs.map +10 -0
- package/dist/cjs/internal/server/index.cjs +223 -0
- package/dist/cjs/internal/server/index.cjs.map +10 -0
- package/dist/cjs/internal/test-environment/index.cjs +1415 -0
- package/dist/cjs/internal/test-environment/index.cjs.map +10 -0
- package/dist/cjs/internal/timers/index.cjs +200 -0
- package/dist/cjs/internal/timers/index.cjs.map +10 -0
- package/dist/cjs/internal/transform/index.cjs +361 -0
- package/dist/cjs/internal/transform/index.cjs.map +10 -0
- package/dist/cjs/internal/typecheck/index.cjs +60 -0
- package/dist/cjs/internal/typecheck/index.cjs.map +10 -0
- package/dist/cjs/internal/typecheck/isolate-types.cjs +2614 -0
- package/dist/cjs/internal/typecheck/isolate-types.cjs.map +10 -0
- package/dist/cjs/internal/typecheck/typecheck.cjs +131 -0
- package/dist/cjs/internal/typecheck/typecheck.cjs.map +10 -0
- package/dist/cjs/modules/index.cjs +160 -0
- package/dist/cjs/modules/index.cjs.map +10 -0
- package/dist/cjs/package.json +5 -0
- package/dist/cjs/runtime/script-runtime.cjs +97 -0
- package/dist/cjs/runtime/script-runtime.cjs.map +10 -0
- package/dist/cjs/server/app-server.cjs +158 -0
- package/dist/cjs/server/app-server.cjs.map +10 -0
- package/dist/cjs/testing/integration-helpers.cjs +127 -0
- package/dist/cjs/testing/integration-helpers.cjs.map +10 -0
- package/dist/cjs/typecheck/index.cjs +96 -0
- package/dist/cjs/typecheck/index.cjs.map +10 -0
- package/dist/cjs/types.cjs +30 -0
- package/dist/cjs/types.cjs.map +9 -0
- package/dist/mjs/bridge/diagnostics.mjs +18 -0
- package/dist/mjs/bridge/diagnostics.mjs.map +10 -0
- package/dist/mjs/bridge/legacy-adapters.mjs +178 -0
- package/dist/mjs/bridge/legacy-adapters.mjs.map +10 -0
- package/dist/mjs/bridge/request-context.mjs +19 -0
- package/dist/mjs/bridge/request-context.mjs.map +10 -0
- package/dist/mjs/bridge/runtime-bindings.mjs +303 -0
- package/dist/mjs/bridge/runtime-bindings.mjs.map +10 -0
- package/dist/mjs/browser/browser-runtime.mjs +93 -0
- package/dist/mjs/browser/browser-runtime.mjs.map +10 -0
- package/dist/mjs/daemon.mjs +91 -0
- package/dist/mjs/daemon.mjs.map +10 -0
- package/dist/mjs/files/index.mjs +76 -0
- package/dist/mjs/files/index.mjs.map +10 -0
- package/dist/mjs/host/create-isolate-host.mjs +171 -0
- package/dist/mjs/host/create-isolate-host.mjs.map +10 -0
- package/dist/mjs/host/index.mjs +7 -0
- package/dist/mjs/host/index.mjs.map +10 -0
- package/dist/mjs/index.mjs +15 -0
- package/dist/mjs/index.mjs.map +10 -0
- package/dist/mjs/internal/client/connection.mjs +1872 -0
- package/dist/mjs/internal/client/connection.mjs.map +10 -0
- package/dist/mjs/internal/client/index.mjs +8 -0
- package/dist/mjs/internal/client/index.mjs.map +10 -0
- package/dist/mjs/internal/client/types.mjs +2 -0
- package/dist/mjs/internal/client/types.mjs.map +9 -0
- package/dist/mjs/internal/console/index.mjs +442 -0
- package/dist/mjs/internal/console/index.mjs.map +10 -0
- package/dist/mjs/internal/console/utils.mjs +30 -0
- package/dist/mjs/internal/console/utils.mjs.map +10 -0
- package/dist/mjs/internal/core/index.mjs +2681 -0
- package/dist/mjs/internal/core/index.mjs.map +10 -0
- package/dist/mjs/internal/crypto/index.mjs +406 -0
- package/dist/mjs/internal/crypto/index.mjs.map +10 -0
- package/dist/mjs/internal/daemon/callback-fs-handler.mjs +315 -0
- package/dist/mjs/internal/daemon/callback-fs-handler.mjs.map +10 -0
- package/dist/mjs/internal/daemon/connection.mjs +1931 -0
- package/dist/mjs/internal/daemon/connection.mjs.map +10 -0
- package/dist/mjs/internal/daemon/daemon.mjs +98 -0
- package/dist/mjs/internal/daemon/daemon.mjs.map +10 -0
- package/dist/mjs/internal/daemon/index.mjs +105 -0
- package/dist/mjs/internal/daemon/index.mjs.map +10 -0
- package/dist/mjs/internal/daemon/runtime-pool.mjs +66 -0
- package/dist/mjs/internal/daemon/runtime-pool.mjs.map +10 -0
- package/dist/mjs/internal/daemon/types.mjs +2 -0
- package/dist/mjs/internal/daemon/types.mjs.map +9 -0
- package/dist/mjs/internal/encoding/index.mjs +379 -0
- package/dist/mjs/internal/encoding/index.mjs.map +10 -0
- package/dist/mjs/internal/fetch/consistency/origins.mjs +558 -0
- package/dist/mjs/internal/fetch/consistency/origins.mjs.map +10 -0
- package/dist/mjs/internal/fetch/index.mjs +2580 -0
- package/dist/mjs/internal/fetch/index.mjs.map +10 -0
- package/dist/mjs/internal/fetch/stream-state.mjs +216 -0
- package/dist/mjs/internal/fetch/stream-state.mjs.map +10 -0
- package/dist/mjs/internal/fs/index.mjs +783 -0
- package/dist/mjs/internal/fs/index.mjs.map +10 -0
- package/dist/mjs/internal/fs/node-adapter.mjs +190 -0
- package/dist/mjs/internal/fs/node-adapter.mjs.map +10 -0
- package/dist/mjs/internal/module-loader/bundle.mjs +418 -0
- package/dist/mjs/internal/module-loader/bundle.mjs.map +10 -0
- package/dist/mjs/internal/module-loader/index.mjs +185 -0
- package/dist/mjs/internal/module-loader/index.mjs.map +10 -0
- package/dist/mjs/internal/module-loader/mappings.mjs +80 -0
- package/dist/mjs/internal/module-loader/mappings.mjs.map +10 -0
- package/dist/mjs/internal/module-loader/resolve.mjs +113 -0
- package/dist/mjs/internal/module-loader/resolve.mjs.map +10 -0
- package/dist/mjs/internal/module-loader/strip-types.mjs +172 -0
- package/dist/mjs/internal/module-loader/strip-types.mjs.map +10 -0
- package/dist/mjs/internal/path/index.mjs +463 -0
- package/dist/mjs/internal/path/index.mjs.map +10 -0
- package/dist/mjs/internal/playwright/client.mjs +13 -0
- package/dist/mjs/internal/playwright/client.mjs.map +10 -0
- package/dist/mjs/internal/playwright/handler.mjs +1378 -0
- package/dist/mjs/internal/playwright/handler.mjs.map +10 -0
- package/dist/mjs/internal/playwright/index.mjs +1234 -0
- package/dist/mjs/internal/playwright/index.mjs.map +10 -0
- package/dist/mjs/internal/playwright/types.mjs +7 -0
- package/dist/mjs/internal/playwright/types.mjs.map +10 -0
- package/dist/mjs/internal/protocol/codec.mjs +470 -0
- package/dist/mjs/internal/protocol/codec.mjs.map +10 -0
- package/dist/mjs/internal/protocol/framing.mjs +101 -0
- package/dist/mjs/internal/protocol/framing.mjs.map +10 -0
- package/dist/mjs/internal/protocol/index.mjs +98 -0
- package/dist/mjs/internal/protocol/index.mjs.map +10 -0
- package/dist/mjs/internal/protocol/marshalValue.mjs +494 -0
- package/dist/mjs/internal/protocol/marshalValue.mjs.map +10 -0
- package/dist/mjs/internal/protocol/serialization.mjs +69 -0
- package/dist/mjs/internal/protocol/serialization.mjs.map +10 -0
- package/dist/mjs/internal/protocol/types.mjs +141 -0
- package/dist/mjs/internal/protocol/types.mjs.map +10 -0
- package/dist/mjs/internal/runtime/index.mjs +1198 -0
- package/dist/mjs/internal/runtime/index.mjs.map +10 -0
- package/dist/mjs/internal/server/index.mjs +183 -0
- package/dist/mjs/internal/server/index.mjs.map +10 -0
- package/dist/mjs/internal/test-environment/index.mjs +1351 -0
- package/dist/mjs/internal/test-environment/index.mjs.map +10 -0
- package/dist/mjs/internal/timers/index.mjs +136 -0
- package/dist/mjs/internal/timers/index.mjs.map +10 -0
- package/dist/mjs/internal/transform/index.mjs +321 -0
- package/dist/mjs/internal/transform/index.mjs.map +10 -0
- package/dist/mjs/internal/typecheck/index.mjs +35 -0
- package/dist/mjs/internal/typecheck/index.mjs.map +10 -0
- package/dist/mjs/internal/typecheck/isolate-types.mjs +2574 -0
- package/dist/mjs/internal/typecheck/isolate-types.mjs.map +10 -0
- package/dist/mjs/internal/typecheck/typecheck.mjs +91 -0
- package/dist/mjs/internal/typecheck/typecheck.mjs.map +10 -0
- package/dist/mjs/modules/index.mjs +96 -0
- package/dist/mjs/modules/index.mjs.map +10 -0
- package/dist/mjs/package.json +5 -0
- package/dist/mjs/runtime/script-runtime.mjs +57 -0
- package/dist/mjs/runtime/script-runtime.mjs.map +10 -0
- package/dist/mjs/server/app-server.mjs +118 -0
- package/dist/mjs/server/app-server.mjs.map +10 -0
- package/dist/mjs/testing/integration-helpers.mjs +63 -0
- package/dist/mjs/testing/integration-helpers.mjs.map +10 -0
- package/dist/mjs/typecheck/index.mjs +56 -0
- package/dist/mjs/typecheck/index.mjs.map +10 -0
- package/dist/mjs/types.mjs +2 -0
- package/dist/mjs/types.mjs.map +9 -0
- package/dist/types/bridge/diagnostics.d.ts +12 -0
- package/dist/types/bridge/legacy-adapters.d.ts +14 -0
- package/dist/types/bridge/request-context.d.ts +10 -0
- package/dist/types/bridge/runtime-bindings.d.ts +14 -0
- package/dist/types/browser/browser-runtime.d.ts +3 -0
- package/dist/types/daemon.d.ts +2 -0
- package/dist/types/files/index.d.ts +5 -0
- package/dist/types/host/create-isolate-host.d.ts +2 -0
- package/dist/types/host/index.d.ts +1 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/internal/client/connection.d.ts +9 -0
- package/dist/types/internal/client/index.d.ts +8 -0
- package/dist/types/internal/client/types.d.ts +198 -0
- package/dist/types/internal/console/index.d.ts +108 -0
- package/dist/types/internal/console/utils.d.ts +27 -0
- package/dist/types/internal/core/index.d.ts +119 -0
- package/dist/types/internal/crypto/index.d.ts +18 -0
- package/dist/types/internal/daemon/callback-fs-handler.d.ts +28 -0
- package/dist/types/internal/daemon/connection.d.ts +9 -0
- package/dist/types/internal/daemon/daemon.d.ts +2 -0
- package/dist/types/internal/daemon/index.d.ts +14 -0
- package/dist/types/internal/daemon/runtime-pool.d.ts +16 -0
- package/dist/types/internal/daemon/types.d.ts +211 -0
- package/dist/types/internal/encoding/index.d.ts +21 -0
- package/dist/types/internal/fetch/consistency/origins.d.ts +179 -0
- package/dist/types/internal/fetch/index.d.ts +93 -0
- package/dist/types/internal/fetch/stream-state.d.ts +65 -0
- package/dist/types/internal/fs/index.d.ts +70 -0
- package/dist/types/internal/fs/node-adapter.d.ts +24 -0
- package/dist/types/internal/module-loader/bundle.d.ts +33 -0
- package/dist/types/internal/module-loader/index.d.ts +30 -0
- package/dist/types/internal/module-loader/mappings.d.ts +47 -0
- package/dist/types/internal/module-loader/resolve.d.ts +26 -0
- package/dist/types/internal/module-loader/strip-types.d.ts +19 -0
- package/dist/types/internal/path/index.d.ts +23 -0
- package/dist/types/internal/playwright/client.d.ts +7 -0
- package/dist/types/internal/playwright/handler.d.ts +44 -0
- package/dist/types/internal/playwright/index.d.ts +14 -0
- package/dist/types/internal/playwright/types.d.ts +145 -0
- package/dist/types/internal/protocol/codec.d.ts +242 -0
- package/dist/types/internal/protocol/framing.d.ts +89 -0
- package/dist/types/internal/protocol/index.d.ts +10 -0
- package/dist/types/internal/protocol/marshalValue.d.ts +79 -0
- package/dist/types/internal/protocol/serialization.d.ts +23 -0
- package/dist/types/internal/protocol/types.d.ts +996 -0
- package/dist/types/internal/runtime/index.d.ts +200 -0
- package/dist/types/internal/server/index.d.ts +42 -0
- package/dist/types/internal/test-environment/index.d.ts +112 -0
- package/dist/types/internal/timers/index.d.ts +22 -0
- package/dist/types/internal/transform/index.d.ts +36 -0
- package/dist/types/internal/typecheck/index.d.ts +7 -0
- package/dist/types/internal/typecheck/isolate-types.d.ts +94 -0
- package/dist/types/internal/typecheck/typecheck.d.ts +148 -0
- package/dist/types/modules/index.d.ts +2 -0
- package/dist/types/runtime/script-runtime.d.ts +6 -0
- package/dist/types/server/app-server.d.ts +3 -0
- package/dist/types/testing/integration-helpers.d.ts +9 -0
- package/dist/types/typecheck/index.d.ts +8 -0
- package/dist/types/types.d.ts +233 -0
- package/package.json +82 -6
|
@@ -0,0 +1,2640 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
function __accessProp(key) {
|
|
8
|
+
return this[key];
|
|
9
|
+
}
|
|
10
|
+
var __toESMCache_node;
|
|
11
|
+
var __toESMCache_esm;
|
|
12
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
13
|
+
var canCache = mod != null && typeof mod === "object";
|
|
14
|
+
if (canCache) {
|
|
15
|
+
var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
|
|
16
|
+
var cached = cache.get(mod);
|
|
17
|
+
if (cached)
|
|
18
|
+
return cached;
|
|
19
|
+
}
|
|
20
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
21
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
22
|
+
for (let key of __getOwnPropNames(mod))
|
|
23
|
+
if (!__hasOwnProp.call(to, key))
|
|
24
|
+
__defProp(to, key, {
|
|
25
|
+
get: __accessProp.bind(mod, key),
|
|
26
|
+
enumerable: true
|
|
27
|
+
});
|
|
28
|
+
if (canCache)
|
|
29
|
+
cache.set(mod, to);
|
|
30
|
+
return to;
|
|
31
|
+
};
|
|
32
|
+
var __toCommonJS = (from) => {
|
|
33
|
+
var entry = (__moduleCache ??= new WeakMap).get(from), desc;
|
|
34
|
+
if (entry)
|
|
35
|
+
return entry;
|
|
36
|
+
entry = __defProp({}, "__esModule", { value: true });
|
|
37
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
38
|
+
for (var key of __getOwnPropNames(from))
|
|
39
|
+
if (!__hasOwnProp.call(entry, key))
|
|
40
|
+
__defProp(entry, key, {
|
|
41
|
+
get: __accessProp.bind(from, key),
|
|
42
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
__moduleCache.set(from, entry);
|
|
46
|
+
return entry;
|
|
47
|
+
};
|
|
48
|
+
var __moduleCache;
|
|
49
|
+
var __returnValue = (v) => v;
|
|
50
|
+
function __exportSetter(name, newValue) {
|
|
51
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
52
|
+
}
|
|
53
|
+
var __export = (target, all) => {
|
|
54
|
+
for (var name in all)
|
|
55
|
+
__defProp(target, name, {
|
|
56
|
+
get: all[name],
|
|
57
|
+
enumerable: true,
|
|
58
|
+
configurable: true,
|
|
59
|
+
set: __exportSetter.bind(all, name)
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// src/internal/fetch/index.ts
|
|
64
|
+
var exports_fetch = {};
|
|
65
|
+
__export(exports_fetch, {
|
|
66
|
+
setupFetch: () => setupFetch,
|
|
67
|
+
clearAllInstanceState: () => import_core.clearAllInstanceState
|
|
68
|
+
});
|
|
69
|
+
module.exports = __toCommonJS(exports_fetch);
|
|
70
|
+
var import_isolated_vm = __toESM(require("isolated-vm"));
|
|
71
|
+
var import_core = require("../core/index.cjs");
|
|
72
|
+
var import_stream_state = require("./stream-state.cjs");
|
|
73
|
+
var instanceStateMap = new WeakMap;
|
|
74
|
+
var passthruBodies = new WeakMap;
|
|
75
|
+
var trackedGlobalHandles = new WeakMap;
|
|
76
|
+
var nextInstanceId = 1;
|
|
77
|
+
function getInstanceStateMapForContext(context) {
|
|
78
|
+
let map = instanceStateMap.get(context);
|
|
79
|
+
if (!map) {
|
|
80
|
+
map = new Map;
|
|
81
|
+
instanceStateMap.set(context, map);
|
|
82
|
+
}
|
|
83
|
+
return map;
|
|
84
|
+
}
|
|
85
|
+
function getPassthruBodiesForContext(context) {
|
|
86
|
+
let map = passthruBodies.get(context);
|
|
87
|
+
if (!map) {
|
|
88
|
+
map = new Map;
|
|
89
|
+
passthruBodies.set(context, map);
|
|
90
|
+
}
|
|
91
|
+
return map;
|
|
92
|
+
}
|
|
93
|
+
function getTrackedGlobalHandlesForContext(context) {
|
|
94
|
+
let handles = trackedGlobalHandles.get(context);
|
|
95
|
+
if (!handles) {
|
|
96
|
+
handles = new Set;
|
|
97
|
+
trackedGlobalHandles.set(context, handles);
|
|
98
|
+
}
|
|
99
|
+
return handles;
|
|
100
|
+
}
|
|
101
|
+
function setTrackedGlobal(context, name, value) {
|
|
102
|
+
if (value instanceof import_isolated_vm.default.Callback || value instanceof import_isolated_vm.default.Reference) {
|
|
103
|
+
getTrackedGlobalHandlesForContext(context).add(value);
|
|
104
|
+
}
|
|
105
|
+
context.global.setSync(name, value);
|
|
106
|
+
}
|
|
107
|
+
function releaseIfSupported(handle) {
|
|
108
|
+
const maybeHandle = handle;
|
|
109
|
+
if (typeof maybeHandle.release === "function") {
|
|
110
|
+
maybeHandle.release();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function releaseTrackedGlobalHandles(context) {
|
|
114
|
+
const handles = trackedGlobalHandles.get(context);
|
|
115
|
+
if (!handles)
|
|
116
|
+
return;
|
|
117
|
+
for (const handle of handles) {
|
|
118
|
+
try {
|
|
119
|
+
releaseIfSupported(handle);
|
|
120
|
+
} catch {}
|
|
121
|
+
}
|
|
122
|
+
handles.clear();
|
|
123
|
+
}
|
|
124
|
+
function clearPassthruBodiesForContext(context) {
|
|
125
|
+
const map = passthruBodies.get(context);
|
|
126
|
+
if (!map)
|
|
127
|
+
return;
|
|
128
|
+
map.clear();
|
|
129
|
+
passthruBodies.delete(context);
|
|
130
|
+
}
|
|
131
|
+
var headersCode = `
|
|
132
|
+
(function() {
|
|
133
|
+
class Headers {
|
|
134
|
+
#headers = new Map(); // lowercase key -> [originalCase, values[]]
|
|
135
|
+
|
|
136
|
+
constructor(init) {
|
|
137
|
+
if (init instanceof Headers) {
|
|
138
|
+
init.forEach((value, key) => this.append(key, value));
|
|
139
|
+
} else if (Array.isArray(init)) {
|
|
140
|
+
for (const pair of init) {
|
|
141
|
+
if (Array.isArray(pair) && pair.length >= 2) {
|
|
142
|
+
this.append(pair[0], pair[1]);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
} else if (init && typeof init === 'object') {
|
|
146
|
+
for (const [key, value] of Object.entries(init)) {
|
|
147
|
+
this.append(key, value);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
append(name, value) {
|
|
153
|
+
const key = String(name).toLowerCase();
|
|
154
|
+
const valueStr = String(value);
|
|
155
|
+
const existing = this.#headers.get(key);
|
|
156
|
+
if (existing) {
|
|
157
|
+
existing[1].push(valueStr);
|
|
158
|
+
} else {
|
|
159
|
+
this.#headers.set(key, [String(name), [valueStr]]);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
delete(name) {
|
|
164
|
+
this.#headers.delete(String(name).toLowerCase());
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
get(name) {
|
|
168
|
+
const entry = this.#headers.get(String(name).toLowerCase());
|
|
169
|
+
return entry ? entry[1].join(', ') : null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
getSetCookie() {
|
|
173
|
+
const entry = this.#headers.get('set-cookie');
|
|
174
|
+
return entry ? [...entry[1]] : [];
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
has(name) {
|
|
178
|
+
return this.#headers.has(String(name).toLowerCase());
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
set(name, value) {
|
|
182
|
+
const key = String(name).toLowerCase();
|
|
183
|
+
this.#headers.set(key, [String(name), [String(value)]]);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
forEach(callback, thisArg) {
|
|
187
|
+
const sortedKeys = [...this.#headers.keys()].sort();
|
|
188
|
+
for (const key of sortedKeys) {
|
|
189
|
+
const [, values] = this.#headers.get(key);
|
|
190
|
+
if (key === 'set-cookie') {
|
|
191
|
+
for (const value of values) {
|
|
192
|
+
callback.call(thisArg, value, key, this);
|
|
193
|
+
}
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
callback.call(thisArg, values.join(', '), key, this);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
*entries() {
|
|
201
|
+
const sortedKeys = [...this.#headers.keys()].sort();
|
|
202
|
+
for (const key of sortedKeys) {
|
|
203
|
+
const [, values] = this.#headers.get(key);
|
|
204
|
+
if (key === 'set-cookie') {
|
|
205
|
+
for (const value of values) {
|
|
206
|
+
yield [key, value];
|
|
207
|
+
}
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
yield [key, values.join(', ')];
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
*keys() {
|
|
215
|
+
const sortedKeys = [...this.#headers.keys()].sort();
|
|
216
|
+
for (const key of sortedKeys) {
|
|
217
|
+
yield key;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
*values() {
|
|
222
|
+
const sortedKeys = [...this.#headers.keys()].sort();
|
|
223
|
+
for (const key of sortedKeys) {
|
|
224
|
+
const [, values] = this.#headers.get(key);
|
|
225
|
+
if (key === 'set-cookie') {
|
|
226
|
+
for (const value of values) {
|
|
227
|
+
yield value;
|
|
228
|
+
}
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
yield values.join(', ');
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
[Symbol.iterator]() {
|
|
236
|
+
return this.entries();
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
globalThis.Headers = Headers;
|
|
241
|
+
})();
|
|
242
|
+
`;
|
|
243
|
+
var formDataCode = `
|
|
244
|
+
(function() {
|
|
245
|
+
class FormData {
|
|
246
|
+
#entries = []; // Array of [name, value]
|
|
247
|
+
|
|
248
|
+
append(name, value, filename) {
|
|
249
|
+
let finalValue = value;
|
|
250
|
+
if (value instanceof Blob && !(value instanceof File)) {
|
|
251
|
+
if (filename !== undefined) {
|
|
252
|
+
finalValue = new File([value], String(filename), { type: value.type });
|
|
253
|
+
}
|
|
254
|
+
} else if (value instanceof File && filename !== undefined) {
|
|
255
|
+
finalValue = new File([value], String(filename), {
|
|
256
|
+
type: value.type,
|
|
257
|
+
lastModified: value.lastModified
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
this.#entries.push([String(name), finalValue]);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
delete(name) {
|
|
264
|
+
const nameStr = String(name);
|
|
265
|
+
this.#entries = this.#entries.filter(([n]) => n !== nameStr);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
get(name) {
|
|
269
|
+
const nameStr = String(name);
|
|
270
|
+
const entry = this.#entries.find(([n]) => n === nameStr);
|
|
271
|
+
return entry ? entry[1] : null;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
getAll(name) {
|
|
275
|
+
const nameStr = String(name);
|
|
276
|
+
return this.#entries.filter(([n]) => n === nameStr).map(([, v]) => v);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
has(name) {
|
|
280
|
+
return this.#entries.some(([n]) => n === String(name));
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
set(name, value, filename) {
|
|
284
|
+
const nameStr = String(name);
|
|
285
|
+
this.delete(nameStr);
|
|
286
|
+
this.append(nameStr, value, filename);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
*entries() {
|
|
290
|
+
for (const [name, value] of this.#entries) {
|
|
291
|
+
yield [name, value];
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
*keys() {
|
|
296
|
+
for (const [name] of this.#entries) {
|
|
297
|
+
yield name;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
*values() {
|
|
302
|
+
for (const [, value] of this.#entries) {
|
|
303
|
+
yield value;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
forEach(callback, thisArg) {
|
|
308
|
+
for (const [name, value] of this.#entries) {
|
|
309
|
+
callback.call(thisArg, value, name, this);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
[Symbol.iterator]() {
|
|
314
|
+
return this.entries();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
globalThis.FormData = FormData;
|
|
319
|
+
})();
|
|
320
|
+
`;
|
|
321
|
+
var multipartCode = `
|
|
322
|
+
(function() {
|
|
323
|
+
// Find byte sequence in Uint8Array
|
|
324
|
+
function findSequence(haystack, needle, start = 0) {
|
|
325
|
+
outer: for (let i = start; i <= haystack.length - needle.length; i++) {
|
|
326
|
+
for (let j = 0; j < needle.length; j++) {
|
|
327
|
+
if (haystack[i + j] !== needle[j]) continue outer;
|
|
328
|
+
}
|
|
329
|
+
return i;
|
|
330
|
+
}
|
|
331
|
+
return -1;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Parse header lines into object
|
|
335
|
+
function parseHeaders(text) {
|
|
336
|
+
const headers = {};
|
|
337
|
+
for (const line of text.split(/\\r?\\n/)) {
|
|
338
|
+
const colonIdx = line.indexOf(':');
|
|
339
|
+
if (colonIdx > 0) {
|
|
340
|
+
const name = line.slice(0, colonIdx).trim().toLowerCase();
|
|
341
|
+
const value = line.slice(colonIdx + 1).trim();
|
|
342
|
+
headers[name] = value;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return headers;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// Parse multipart/form-data body into FormData
|
|
349
|
+
globalThis.__parseMultipartFormData = function(bodyBytes, contentType) {
|
|
350
|
+
const formData = new FormData();
|
|
351
|
+
|
|
352
|
+
// Extract boundary from Content-Type
|
|
353
|
+
const boundaryMatch = contentType.match(/boundary=([^;]+)/i);
|
|
354
|
+
if (!boundaryMatch) return formData;
|
|
355
|
+
|
|
356
|
+
const boundary = boundaryMatch[1].replace(/^["']|["']$/g, '');
|
|
357
|
+
const encoder = new TextEncoder();
|
|
358
|
+
const decoder = new TextDecoder();
|
|
359
|
+
const boundaryBytes = encoder.encode('--' + boundary);
|
|
360
|
+
|
|
361
|
+
// Find first boundary
|
|
362
|
+
let pos = findSequence(bodyBytes, boundaryBytes, 0);
|
|
363
|
+
if (pos === -1) return formData;
|
|
364
|
+
pos += boundaryBytes.length;
|
|
365
|
+
|
|
366
|
+
while (pos < bodyBytes.length) {
|
|
367
|
+
// Skip CRLF after boundary
|
|
368
|
+
if (bodyBytes[pos] === 0x0d && bodyBytes[pos + 1] === 0x0a) pos += 2;
|
|
369
|
+
else if (bodyBytes[pos] === 0x0a) pos += 1;
|
|
370
|
+
|
|
371
|
+
// Check for closing boundary (--)
|
|
372
|
+
if (bodyBytes[pos] === 0x2d && bodyBytes[pos + 1] === 0x2d) break;
|
|
373
|
+
|
|
374
|
+
// Find header/body separator (CRLFCRLF)
|
|
375
|
+
const crlfcrlf = encoder.encode('\\r\\n\\r\\n');
|
|
376
|
+
const headersEnd = findSequence(bodyBytes, crlfcrlf, pos);
|
|
377
|
+
if (headersEnd === -1) break;
|
|
378
|
+
|
|
379
|
+
// Parse headers
|
|
380
|
+
const headersText = decoder.decode(bodyBytes.slice(pos, headersEnd));
|
|
381
|
+
const headers = parseHeaders(headersText);
|
|
382
|
+
pos = headersEnd + 4;
|
|
383
|
+
|
|
384
|
+
// Find next boundary
|
|
385
|
+
const nextBoundary = findSequence(bodyBytes, boundaryBytes, pos);
|
|
386
|
+
if (nextBoundary === -1) break;
|
|
387
|
+
|
|
388
|
+
// Extract content (minus trailing CRLF)
|
|
389
|
+
let contentEnd = nextBoundary;
|
|
390
|
+
if (contentEnd > 0 && bodyBytes[contentEnd - 1] === 0x0a) contentEnd--;
|
|
391
|
+
if (contentEnd > 0 && bodyBytes[contentEnd - 1] === 0x0d) contentEnd--;
|
|
392
|
+
const content = bodyBytes.slice(pos, contentEnd);
|
|
393
|
+
|
|
394
|
+
// Parse Content-Disposition
|
|
395
|
+
const disposition = headers['content-disposition'] || '';
|
|
396
|
+
const nameMatch = disposition.match(/name="([^"]+)"/);
|
|
397
|
+
const filenameMatch = disposition.match(/filename="([^"]+)"/);
|
|
398
|
+
|
|
399
|
+
if (nameMatch) {
|
|
400
|
+
const name = nameMatch[1];
|
|
401
|
+
if (filenameMatch) {
|
|
402
|
+
const filename = filenameMatch[1];
|
|
403
|
+
const mimeType = headers['content-type'] || 'application/octet-stream';
|
|
404
|
+
const file = new File([content], filename, { type: mimeType });
|
|
405
|
+
formData.append(name, file);
|
|
406
|
+
} else {
|
|
407
|
+
formData.append(name, decoder.decode(content));
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
pos = nextBoundary + boundaryBytes.length;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
return formData;
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
// Serialize FormData to multipart/form-data format
|
|
418
|
+
globalThis.__serializeFormData = function(formData) {
|
|
419
|
+
const boundary = '----FormDataBoundary' + Math.random().toString(36).slice(2) +
|
|
420
|
+
Math.random().toString(36).slice(2);
|
|
421
|
+
const encoder = new TextEncoder();
|
|
422
|
+
const parts = [];
|
|
423
|
+
|
|
424
|
+
for (const [name, value] of formData.entries()) {
|
|
425
|
+
if (value instanceof File) {
|
|
426
|
+
const header = [
|
|
427
|
+
'--' + boundary,
|
|
428
|
+
'Content-Disposition: form-data; name="' + name + '"; filename="' + value.name + '"',
|
|
429
|
+
'Content-Type: ' + (value.type || 'application/octet-stream'),
|
|
430
|
+
'',
|
|
431
|
+
''
|
|
432
|
+
].join('\\r\\n');
|
|
433
|
+
parts.push(encoder.encode(header));
|
|
434
|
+
// Use existing __Blob_bytes callback (File extends Blob)
|
|
435
|
+
parts.push(__Blob_bytes(value._getInstanceId()));
|
|
436
|
+
parts.push(encoder.encode('\\r\\n'));
|
|
437
|
+
} else if (value instanceof Blob) {
|
|
438
|
+
const header = [
|
|
439
|
+
'--' + boundary,
|
|
440
|
+
'Content-Disposition: form-data; name="' + name + '"; filename="blob"',
|
|
441
|
+
'Content-Type: ' + (value.type || 'application/octet-stream'),
|
|
442
|
+
'',
|
|
443
|
+
''
|
|
444
|
+
].join('\\r\\n');
|
|
445
|
+
parts.push(encoder.encode(header));
|
|
446
|
+
parts.push(__Blob_bytes(value._getInstanceId()));
|
|
447
|
+
parts.push(encoder.encode('\\r\\n'));
|
|
448
|
+
} else {
|
|
449
|
+
const header = [
|
|
450
|
+
'--' + boundary,
|
|
451
|
+
'Content-Disposition: form-data; name="' + name + '"',
|
|
452
|
+
'',
|
|
453
|
+
''
|
|
454
|
+
].join('\\r\\n');
|
|
455
|
+
parts.push(encoder.encode(header));
|
|
456
|
+
parts.push(encoder.encode(String(value)));
|
|
457
|
+
parts.push(encoder.encode('\\r\\n'));
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// Closing boundary
|
|
462
|
+
parts.push(encoder.encode('--' + boundary + '--\\r\\n'));
|
|
463
|
+
|
|
464
|
+
// Concatenate all parts
|
|
465
|
+
const totalLength = parts.reduce((sum, p) => sum + p.length, 0);
|
|
466
|
+
const body = new Uint8Array(totalLength);
|
|
467
|
+
let offset = 0;
|
|
468
|
+
for (const part of parts) {
|
|
469
|
+
body.set(part, offset);
|
|
470
|
+
offset += part.length;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
return {
|
|
474
|
+
body: body,
|
|
475
|
+
contentType: 'multipart/form-data; boundary=' + boundary
|
|
476
|
+
};
|
|
477
|
+
};
|
|
478
|
+
})();
|
|
479
|
+
`;
|
|
480
|
+
function setupStreamCallbacks(context, streamRegistry) {
|
|
481
|
+
setTrackedGlobal(context, "__Stream_create", new import_isolated_vm.default.Callback(() => {
|
|
482
|
+
return streamRegistry.create();
|
|
483
|
+
}));
|
|
484
|
+
setTrackedGlobal(context, "__Stream_push", new import_isolated_vm.default.Callback((streamId, chunkArray) => {
|
|
485
|
+
const chunk = new Uint8Array(chunkArray);
|
|
486
|
+
return streamRegistry.push(streamId, chunk);
|
|
487
|
+
}));
|
|
488
|
+
setTrackedGlobal(context, "__Stream_close", new import_isolated_vm.default.Callback((streamId) => {
|
|
489
|
+
streamRegistry.close(streamId);
|
|
490
|
+
}));
|
|
491
|
+
setTrackedGlobal(context, "__Stream_error", new import_isolated_vm.default.Callback((streamId, message) => {
|
|
492
|
+
streamRegistry.error(streamId, new Error(message));
|
|
493
|
+
}));
|
|
494
|
+
setTrackedGlobal(context, "__Stream_isQueueFull", new import_isolated_vm.default.Callback((streamId) => {
|
|
495
|
+
return streamRegistry.isQueueFull(streamId);
|
|
496
|
+
}));
|
|
497
|
+
setTrackedGlobal(context, "__Stream_cancel", new import_isolated_vm.default.Callback((streamId) => {
|
|
498
|
+
streamRegistry.cancel(streamId);
|
|
499
|
+
}));
|
|
500
|
+
const pullRef = new import_isolated_vm.default.Reference(async (streamId) => {
|
|
501
|
+
const result = await streamRegistry.pull(streamId);
|
|
502
|
+
if (result.done) {
|
|
503
|
+
return JSON.stringify({ done: true });
|
|
504
|
+
}
|
|
505
|
+
return JSON.stringify({ done: false, value: Array.from(result.value) });
|
|
506
|
+
});
|
|
507
|
+
setTrackedGlobal(context, "__Stream_pull_ref", pullRef);
|
|
508
|
+
}
|
|
509
|
+
var hostBackedStreamCode = `
|
|
510
|
+
(function() {
|
|
511
|
+
const _streamIds = new WeakMap();
|
|
512
|
+
|
|
513
|
+
// Polyfill values() on ReadableStream if not available (older V8 versions)
|
|
514
|
+
if (typeof ReadableStream.prototype.values !== 'function') {
|
|
515
|
+
ReadableStream.prototype.values = function(options) {
|
|
516
|
+
const reader = this.getReader();
|
|
517
|
+
return {
|
|
518
|
+
async next() {
|
|
519
|
+
const { value, done } = await reader.read();
|
|
520
|
+
if (done) {
|
|
521
|
+
reader.releaseLock();
|
|
522
|
+
return { value: undefined, done: true };
|
|
523
|
+
}
|
|
524
|
+
return { value, done: false };
|
|
525
|
+
},
|
|
526
|
+
async return(value) {
|
|
527
|
+
reader.releaseLock();
|
|
528
|
+
return { value, done: true };
|
|
529
|
+
},
|
|
530
|
+
[Symbol.asyncIterator]() {
|
|
531
|
+
return this;
|
|
532
|
+
}
|
|
533
|
+
};
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// Create a proper ReadableStream subclass that reports as "ReadableStream"
|
|
538
|
+
class HostBackedReadableStream extends ReadableStream {
|
|
539
|
+
constructor(streamId) {
|
|
540
|
+
if (streamId === undefined) {
|
|
541
|
+
streamId = __Stream_create();
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
let closed = false;
|
|
545
|
+
|
|
546
|
+
super({
|
|
547
|
+
async pull(controller) {
|
|
548
|
+
if (closed) return;
|
|
549
|
+
|
|
550
|
+
const resultJson = await __Stream_pull_ref.apply(undefined, [streamId], { result: { promise: true, copy: true } });
|
|
551
|
+
const result = JSON.parse(resultJson);
|
|
552
|
+
|
|
553
|
+
if (result.done) {
|
|
554
|
+
closed = true;
|
|
555
|
+
controller.close();
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
controller.enqueue(new Uint8Array(result.value));
|
|
559
|
+
},
|
|
560
|
+
cancel(reason) {
|
|
561
|
+
closed = true;
|
|
562
|
+
__Stream_cancel(streamId);
|
|
563
|
+
}
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
_streamIds.set(this, streamId);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// Override to report as ReadableStream for spec compliance
|
|
570
|
+
get [Symbol.toStringTag]() {
|
|
571
|
+
return 'ReadableStream';
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
_getStreamId() {
|
|
575
|
+
return _streamIds.get(this);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
static _fromStreamId(streamId) {
|
|
579
|
+
return new HostBackedReadableStream(streamId);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// Make constructor.name return 'ReadableStream' for spec compliance
|
|
584
|
+
Object.defineProperty(HostBackedReadableStream, 'name', { value: 'ReadableStream' });
|
|
585
|
+
|
|
586
|
+
globalThis.HostBackedReadableStream = HostBackedReadableStream;
|
|
587
|
+
})();
|
|
588
|
+
`;
|
|
589
|
+
function setupResponse(context, stateMap, streamRegistry) {
|
|
590
|
+
setTrackedGlobal(context, "__Response_construct", new import_isolated_vm.default.Callback((bodyBytes, status, statusText, headers) => {
|
|
591
|
+
const instanceId = nextInstanceId++;
|
|
592
|
+
const body = bodyBytes ? new Uint8Array(bodyBytes) : null;
|
|
593
|
+
const state = {
|
|
594
|
+
status,
|
|
595
|
+
statusText,
|
|
596
|
+
headers,
|
|
597
|
+
body,
|
|
598
|
+
bodyUsed: false,
|
|
599
|
+
type: "default",
|
|
600
|
+
url: "",
|
|
601
|
+
redirected: false,
|
|
602
|
+
streamId: null
|
|
603
|
+
};
|
|
604
|
+
stateMap.set(instanceId, state);
|
|
605
|
+
return instanceId;
|
|
606
|
+
}));
|
|
607
|
+
setTrackedGlobal(context, "__Response_constructStreaming", new import_isolated_vm.default.Callback((streamId, status, statusText, headers) => {
|
|
608
|
+
const instanceId = nextInstanceId++;
|
|
609
|
+
const state = {
|
|
610
|
+
status,
|
|
611
|
+
statusText,
|
|
612
|
+
headers,
|
|
613
|
+
body: null,
|
|
614
|
+
bodyUsed: false,
|
|
615
|
+
type: "default",
|
|
616
|
+
url: "",
|
|
617
|
+
redirected: false,
|
|
618
|
+
streamId
|
|
619
|
+
};
|
|
620
|
+
stateMap.set(instanceId, state);
|
|
621
|
+
return instanceId;
|
|
622
|
+
}));
|
|
623
|
+
setTrackedGlobal(context, "__Response_constructFromFetch", new import_isolated_vm.default.Callback((bodyBytes, status, statusText, headers, url, redirected) => {
|
|
624
|
+
const instanceId = nextInstanceId++;
|
|
625
|
+
const body = bodyBytes ? new Uint8Array(bodyBytes) : null;
|
|
626
|
+
const state = {
|
|
627
|
+
status,
|
|
628
|
+
statusText,
|
|
629
|
+
headers,
|
|
630
|
+
body,
|
|
631
|
+
bodyUsed: false,
|
|
632
|
+
type: "default",
|
|
633
|
+
url,
|
|
634
|
+
redirected,
|
|
635
|
+
streamId: null
|
|
636
|
+
};
|
|
637
|
+
stateMap.set(instanceId, state);
|
|
638
|
+
return instanceId;
|
|
639
|
+
}));
|
|
640
|
+
setTrackedGlobal(context, "__Response_get_status", new import_isolated_vm.default.Callback((instanceId) => {
|
|
641
|
+
const state = stateMap.get(instanceId);
|
|
642
|
+
return state?.status ?? 200;
|
|
643
|
+
}));
|
|
644
|
+
setTrackedGlobal(context, "__Response_get_statusText", new import_isolated_vm.default.Callback((instanceId) => {
|
|
645
|
+
const state = stateMap.get(instanceId);
|
|
646
|
+
return state?.statusText ?? "";
|
|
647
|
+
}));
|
|
648
|
+
setTrackedGlobal(context, "__Response_get_headers", new import_isolated_vm.default.Callback((instanceId) => {
|
|
649
|
+
const state = stateMap.get(instanceId);
|
|
650
|
+
return state?.headers ?? [];
|
|
651
|
+
}));
|
|
652
|
+
setTrackedGlobal(context, "__Response_get_bodyUsed", new import_isolated_vm.default.Callback((instanceId) => {
|
|
653
|
+
const state = stateMap.get(instanceId);
|
|
654
|
+
return state?.bodyUsed ?? false;
|
|
655
|
+
}));
|
|
656
|
+
setTrackedGlobal(context, "__Response_get_url", new import_isolated_vm.default.Callback((instanceId) => {
|
|
657
|
+
const state = stateMap.get(instanceId);
|
|
658
|
+
return state?.url ?? "";
|
|
659
|
+
}));
|
|
660
|
+
setTrackedGlobal(context, "__Response_get_redirected", new import_isolated_vm.default.Callback((instanceId) => {
|
|
661
|
+
const state = stateMap.get(instanceId);
|
|
662
|
+
return state?.redirected ?? false;
|
|
663
|
+
}));
|
|
664
|
+
setTrackedGlobal(context, "__Response_get_type", new import_isolated_vm.default.Callback((instanceId) => {
|
|
665
|
+
const state = stateMap.get(instanceId);
|
|
666
|
+
return state?.type ?? "default";
|
|
667
|
+
}));
|
|
668
|
+
setTrackedGlobal(context, "__Response_get_nullBody", new import_isolated_vm.default.Callback((instanceId) => {
|
|
669
|
+
const state = stateMap.get(instanceId);
|
|
670
|
+
return state?.nullBody ?? false;
|
|
671
|
+
}));
|
|
672
|
+
setTrackedGlobal(context, "__Response_setType", new import_isolated_vm.default.Callback((instanceId, type) => {
|
|
673
|
+
const state = stateMap.get(instanceId);
|
|
674
|
+
if (state) {
|
|
675
|
+
state.type = type;
|
|
676
|
+
}
|
|
677
|
+
}));
|
|
678
|
+
setTrackedGlobal(context, "__Response_markBodyUsed", new import_isolated_vm.default.Callback((instanceId) => {
|
|
679
|
+
const state = stateMap.get(instanceId);
|
|
680
|
+
if (state) {
|
|
681
|
+
if (state.bodyUsed) {
|
|
682
|
+
throw new Error("[TypeError]Body has already been consumed");
|
|
683
|
+
}
|
|
684
|
+
state.bodyUsed = true;
|
|
685
|
+
}
|
|
686
|
+
}));
|
|
687
|
+
setTrackedGlobal(context, "__Response_text", new import_isolated_vm.default.Callback((instanceId) => {
|
|
688
|
+
const state = stateMap.get(instanceId);
|
|
689
|
+
if (!state || !state.body)
|
|
690
|
+
return "";
|
|
691
|
+
return new TextDecoder().decode(state.body);
|
|
692
|
+
}));
|
|
693
|
+
setTrackedGlobal(context, "__Response_arrayBuffer", new import_isolated_vm.default.Callback((instanceId) => {
|
|
694
|
+
const state = stateMap.get(instanceId);
|
|
695
|
+
if (!state || !state.body) {
|
|
696
|
+
return new import_isolated_vm.default.ExternalCopy(new ArrayBuffer(0)).copyInto();
|
|
697
|
+
}
|
|
698
|
+
return new import_isolated_vm.default.ExternalCopy(state.body.buffer.slice(state.body.byteOffset, state.body.byteOffset + state.body.byteLength)).copyInto();
|
|
699
|
+
}));
|
|
700
|
+
setTrackedGlobal(context, "__Response_clone", new import_isolated_vm.default.Callback((instanceId) => {
|
|
701
|
+
const state = stateMap.get(instanceId);
|
|
702
|
+
if (!state) {
|
|
703
|
+
throw new Error("[TypeError]Cannot clone invalid Response");
|
|
704
|
+
}
|
|
705
|
+
if (state.streamId !== null) {
|
|
706
|
+
const streamId1 = streamRegistry.create();
|
|
707
|
+
const streamId2 = streamRegistry.create();
|
|
708
|
+
const origStreamId = state.streamId;
|
|
709
|
+
(async () => {
|
|
710
|
+
try {
|
|
711
|
+
while (true) {
|
|
712
|
+
const result = await streamRegistry.pull(origStreamId);
|
|
713
|
+
if (result.done) {
|
|
714
|
+
streamRegistry.close(streamId1);
|
|
715
|
+
streamRegistry.close(streamId2);
|
|
716
|
+
break;
|
|
717
|
+
}
|
|
718
|
+
streamRegistry.push(streamId1, new Uint8Array(result.value));
|
|
719
|
+
streamRegistry.push(streamId2, new Uint8Array(result.value));
|
|
720
|
+
}
|
|
721
|
+
} catch (err) {
|
|
722
|
+
streamRegistry.error(streamId1, err);
|
|
723
|
+
streamRegistry.error(streamId2, err);
|
|
724
|
+
}
|
|
725
|
+
})();
|
|
726
|
+
state.streamId = streamId1;
|
|
727
|
+
const newId2 = nextInstanceId++;
|
|
728
|
+
const newState2 = {
|
|
729
|
+
...state,
|
|
730
|
+
streamId: streamId2,
|
|
731
|
+
body: state.body ? new Uint8Array(state.body) : null,
|
|
732
|
+
bodyUsed: false
|
|
733
|
+
};
|
|
734
|
+
stateMap.set(newId2, newState2);
|
|
735
|
+
return newId2;
|
|
736
|
+
}
|
|
737
|
+
const newId = nextInstanceId++;
|
|
738
|
+
const newState = {
|
|
739
|
+
...state,
|
|
740
|
+
body: state.body ? new Uint8Array(state.body) : null,
|
|
741
|
+
bodyUsed: false
|
|
742
|
+
};
|
|
743
|
+
stateMap.set(newId, newState);
|
|
744
|
+
return newId;
|
|
745
|
+
}));
|
|
746
|
+
setTrackedGlobal(context, "__Response_getStreamId", new import_isolated_vm.default.Callback((instanceId) => {
|
|
747
|
+
const state = stateMap.get(instanceId);
|
|
748
|
+
return state?.streamId ?? null;
|
|
749
|
+
}));
|
|
750
|
+
const responseCode = `
|
|
751
|
+
(function() {
|
|
752
|
+
const _responseInstanceIds = new WeakMap();
|
|
753
|
+
|
|
754
|
+
function __decodeError(err) {
|
|
755
|
+
if (!(err instanceof Error)) return err;
|
|
756
|
+
const match = err.message.match(/^\\[(TypeError|RangeError|SyntaxError|ReferenceError|URIError|EvalError|Error)\\](.*)$/);
|
|
757
|
+
if (match) {
|
|
758
|
+
const ErrorType = globalThis[match[1]] || Error;
|
|
759
|
+
return new ErrorType(match[2]);
|
|
760
|
+
}
|
|
761
|
+
return err;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
function __prepareBody(body) {
|
|
765
|
+
if (body === null || body === undefined) return null;
|
|
766
|
+
if (typeof body === 'string') {
|
|
767
|
+
const encoder = new TextEncoder();
|
|
768
|
+
return Array.from(encoder.encode(body));
|
|
769
|
+
}
|
|
770
|
+
if (body instanceof ArrayBuffer) {
|
|
771
|
+
return Array.from(new Uint8Array(body));
|
|
772
|
+
}
|
|
773
|
+
if (body instanceof Uint8Array) {
|
|
774
|
+
return Array.from(body);
|
|
775
|
+
}
|
|
776
|
+
if (ArrayBuffer.isView(body)) {
|
|
777
|
+
return Array.from(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
|
|
778
|
+
}
|
|
779
|
+
if (body instanceof Blob) {
|
|
780
|
+
// Mark as needing async Blob handling - will be read in constructor
|
|
781
|
+
return { __isBlob: true, blob: body };
|
|
782
|
+
}
|
|
783
|
+
// Handle HostBackedReadableStream specially - preserve streamId
|
|
784
|
+
if (body instanceof HostBackedReadableStream) {
|
|
785
|
+
return { __isHostStream: true, stream: body, streamId: body._getStreamId() };
|
|
786
|
+
}
|
|
787
|
+
// Handle native ReadableStream
|
|
788
|
+
if (body instanceof ReadableStream) {
|
|
789
|
+
return { __isStream: true, stream: body };
|
|
790
|
+
}
|
|
791
|
+
// Try to convert to string
|
|
792
|
+
return Array.from(new TextEncoder().encode(String(body)));
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
class Response {
|
|
796
|
+
#instanceId;
|
|
797
|
+
#headers;
|
|
798
|
+
#streamId = null;
|
|
799
|
+
#blobInitPromise = null; // For async Blob body initialization
|
|
800
|
+
#cachedBody = null; // Memoized body stream for spec compliance
|
|
801
|
+
|
|
802
|
+
constructor(body, init = {}) {
|
|
803
|
+
// Handle internal construction from instance ID
|
|
804
|
+
if (typeof body === 'number' && init === null) {
|
|
805
|
+
this.#instanceId = body;
|
|
806
|
+
this.#headers = new Headers(__Response_get_headers(body));
|
|
807
|
+
this.#streamId = __Response_getStreamId(body);
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
const preparedBody = __prepareBody(body);
|
|
812
|
+
|
|
813
|
+
// Handle Blob body - create streaming response and push blob data
|
|
814
|
+
if (preparedBody && preparedBody.__isBlob) {
|
|
815
|
+
this.#streamId = __Stream_create();
|
|
816
|
+
const status = init.status ?? 200;
|
|
817
|
+
const statusText = init.statusText ?? '';
|
|
818
|
+
const headers = new Headers(init.headers);
|
|
819
|
+
const headersArray = Array.from(headers.entries());
|
|
820
|
+
|
|
821
|
+
this.#instanceId = __Response_constructStreaming(
|
|
822
|
+
this.#streamId,
|
|
823
|
+
status,
|
|
824
|
+
statusText,
|
|
825
|
+
headersArray
|
|
826
|
+
);
|
|
827
|
+
this.#headers = headers;
|
|
828
|
+
|
|
829
|
+
// Start async blob initialization and stream pumping
|
|
830
|
+
const streamId = this.#streamId;
|
|
831
|
+
const blob = preparedBody.blob;
|
|
832
|
+
this.#blobInitPromise = (async () => {
|
|
833
|
+
try {
|
|
834
|
+
const buffer = await blob.arrayBuffer();
|
|
835
|
+
__Stream_push(streamId, Array.from(new Uint8Array(buffer)));
|
|
836
|
+
__Stream_close(streamId);
|
|
837
|
+
} catch (error) {
|
|
838
|
+
__Stream_error(streamId, String(error));
|
|
839
|
+
}
|
|
840
|
+
})();
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// Handle HostBackedReadableStream - reuse existing streamId for pass-through
|
|
845
|
+
if (preparedBody && preparedBody.__isHostStream) {
|
|
846
|
+
// Reuse the existing streamId to preserve the pass-through body mapping
|
|
847
|
+
this.#streamId = preparedBody.streamId;
|
|
848
|
+
const status = init.status ?? 200;
|
|
849
|
+
const statusText = init.statusText ?? '';
|
|
850
|
+
const headers = new Headers(init.headers);
|
|
851
|
+
const headersArray = Array.from(headers.entries());
|
|
852
|
+
|
|
853
|
+
this.#instanceId = __Response_constructStreaming(
|
|
854
|
+
this.#streamId,
|
|
855
|
+
status,
|
|
856
|
+
statusText,
|
|
857
|
+
headersArray
|
|
858
|
+
);
|
|
859
|
+
this.#headers = headers;
|
|
860
|
+
// Don't pump - the body is already backed by this streamId
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
// Handle native ReadableStream body
|
|
865
|
+
if (preparedBody && preparedBody.__isStream) {
|
|
866
|
+
this.#streamId = __Stream_create();
|
|
867
|
+
const status = init.status ?? 200;
|
|
868
|
+
const statusText = init.statusText ?? '';
|
|
869
|
+
const headers = new Headers(init.headers);
|
|
870
|
+
const headersArray = Array.from(headers.entries());
|
|
871
|
+
|
|
872
|
+
this.#instanceId = __Response_constructStreaming(
|
|
873
|
+
this.#streamId,
|
|
874
|
+
status,
|
|
875
|
+
statusText,
|
|
876
|
+
headersArray
|
|
877
|
+
);
|
|
878
|
+
this.#headers = headers;
|
|
879
|
+
|
|
880
|
+
// Start pumping the source stream to host queue (fire-and-forget)
|
|
881
|
+
this._startStreamPump(preparedBody.stream);
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// Existing buffered body handling
|
|
886
|
+
const bodyBytes = preparedBody;
|
|
887
|
+
const status = init.status ?? 200;
|
|
888
|
+
const statusText = init.statusText ?? '';
|
|
889
|
+
const headersInit = init.headers;
|
|
890
|
+
const headers = new Headers(headersInit);
|
|
891
|
+
const headersArray = Array.from(headers.entries());
|
|
892
|
+
|
|
893
|
+
this.#instanceId = __Response_construct(bodyBytes, status, statusText, headersArray);
|
|
894
|
+
this.#headers = headers;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
async _startStreamPump(sourceStream) {
|
|
898
|
+
const streamId = this.#streamId;
|
|
899
|
+
try {
|
|
900
|
+
const reader = sourceStream.getReader();
|
|
901
|
+
while (true) {
|
|
902
|
+
// Check backpressure - wait if queue is full
|
|
903
|
+
while (__Stream_isQueueFull(streamId)) {
|
|
904
|
+
await new Promise(r => setTimeout(r, 1));
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
const { done, value } = await reader.read();
|
|
908
|
+
if (done) {
|
|
909
|
+
__Stream_close(streamId);
|
|
910
|
+
break;
|
|
911
|
+
}
|
|
912
|
+
if (value) {
|
|
913
|
+
__Stream_push(streamId, Array.from(value));
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
} catch (error) {
|
|
917
|
+
__Stream_error(streamId, String(error));
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
_getInstanceId() {
|
|
922
|
+
return this.#instanceId;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
static _fromInstanceId(instanceId) {
|
|
926
|
+
return new Response(instanceId, null);
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
get status() {
|
|
930
|
+
return __Response_get_status(this.#instanceId);
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
get statusText() {
|
|
934
|
+
return __Response_get_statusText(this.#instanceId);
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
get ok() {
|
|
938
|
+
const status = this.status;
|
|
939
|
+
return status >= 200 && status < 300;
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
get headers() {
|
|
943
|
+
return this.#headers;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
get bodyUsed() {
|
|
947
|
+
return __Response_get_bodyUsed(this.#instanceId);
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
get url() {
|
|
951
|
+
return __Response_get_url(this.#instanceId);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
get redirected() {
|
|
955
|
+
return __Response_get_redirected(this.#instanceId);
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
get type() {
|
|
959
|
+
return __Response_get_type(this.#instanceId);
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
get body() {
|
|
963
|
+
// Null-body responses (204, 304, HEAD) must return null
|
|
964
|
+
if (__Response_get_nullBody(this.#instanceId)) {
|
|
965
|
+
return null;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// Return cached body if available (WHATWG spec requires same object on repeated access)
|
|
969
|
+
if (this.#cachedBody !== null) {
|
|
970
|
+
return this.#cachedBody;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
const streamId = __Response_getStreamId(this.#instanceId);
|
|
974
|
+
if (streamId !== null) {
|
|
975
|
+
this.#cachedBody = HostBackedReadableStream._fromStreamId(streamId);
|
|
976
|
+
return this.#cachedBody;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
// Fallback: create host-backed stream from buffered body
|
|
980
|
+
const instanceId = this.#instanceId;
|
|
981
|
+
const newStreamId = __Stream_create();
|
|
982
|
+
const buffer = __Response_arrayBuffer(instanceId);
|
|
983
|
+
|
|
984
|
+
if (buffer.byteLength > 0) {
|
|
985
|
+
__Stream_push(newStreamId, Array.from(new Uint8Array(buffer)));
|
|
986
|
+
}
|
|
987
|
+
__Stream_close(newStreamId);
|
|
988
|
+
|
|
989
|
+
this.#cachedBody = HostBackedReadableStream._fromStreamId(newStreamId);
|
|
990
|
+
return this.#cachedBody;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
async text() {
|
|
994
|
+
try {
|
|
995
|
+
__Response_markBodyUsed(this.#instanceId);
|
|
996
|
+
} catch (err) {
|
|
997
|
+
throw __decodeError(err);
|
|
998
|
+
}
|
|
999
|
+
if (__Response_get_nullBody(this.#instanceId)) {
|
|
1000
|
+
return "";
|
|
1001
|
+
}
|
|
1002
|
+
if (this.#streamId !== null) {
|
|
1003
|
+
const reader = this.body.getReader();
|
|
1004
|
+
const chunks = [];
|
|
1005
|
+
while (true) {
|
|
1006
|
+
const { done, value } = await reader.read();
|
|
1007
|
+
if (done) break;
|
|
1008
|
+
if (value) chunks.push(value);
|
|
1009
|
+
}
|
|
1010
|
+
const totalLength = chunks.reduce((acc, c) => acc + c.length, 0);
|
|
1011
|
+
const result = new Uint8Array(totalLength);
|
|
1012
|
+
let offset = 0;
|
|
1013
|
+
for (const chunk of chunks) {
|
|
1014
|
+
result.set(chunk, offset);
|
|
1015
|
+
offset += chunk.length;
|
|
1016
|
+
}
|
|
1017
|
+
return new TextDecoder().decode(result);
|
|
1018
|
+
}
|
|
1019
|
+
return __Response_text(this.#instanceId);
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
async json() {
|
|
1023
|
+
const text = await this.text();
|
|
1024
|
+
return JSON.parse(text);
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
async arrayBuffer() {
|
|
1028
|
+
try {
|
|
1029
|
+
__Response_markBodyUsed(this.#instanceId);
|
|
1030
|
+
} catch (err) {
|
|
1031
|
+
throw __decodeError(err);
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
// For streaming responses (including Blob bodies), consume the stream
|
|
1035
|
+
if (this.#streamId !== null) {
|
|
1036
|
+
// Wait for blob init to complete if needed
|
|
1037
|
+
if (this.#blobInitPromise) {
|
|
1038
|
+
await this.#blobInitPromise;
|
|
1039
|
+
this.#blobInitPromise = null;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
const reader = this.body.getReader();
|
|
1043
|
+
const chunks = [];
|
|
1044
|
+
while (true) {
|
|
1045
|
+
const { done, value } = await reader.read();
|
|
1046
|
+
if (done) break;
|
|
1047
|
+
if (value) chunks.push(value);
|
|
1048
|
+
}
|
|
1049
|
+
// Concatenate all chunks
|
|
1050
|
+
const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
|
|
1051
|
+
const result = new Uint8Array(totalLength);
|
|
1052
|
+
let offset = 0;
|
|
1053
|
+
for (const chunk of chunks) {
|
|
1054
|
+
result.set(chunk, offset);
|
|
1055
|
+
offset += chunk.length;
|
|
1056
|
+
}
|
|
1057
|
+
return result.buffer;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
return __Response_arrayBuffer(this.#instanceId);
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
async blob() {
|
|
1064
|
+
const buffer = await this.arrayBuffer();
|
|
1065
|
+
const contentType = this.headers.get('content-type') || '';
|
|
1066
|
+
return new Blob([buffer], { type: contentType });
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
async formData() {
|
|
1070
|
+
const contentType = this.headers.get('content-type') || '';
|
|
1071
|
+
|
|
1072
|
+
// Parse multipart/form-data
|
|
1073
|
+
if (contentType.includes('multipart/form-data')) {
|
|
1074
|
+
const buffer = await this.arrayBuffer();
|
|
1075
|
+
return __parseMultipartFormData(new Uint8Array(buffer), contentType);
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
// Parse application/x-www-form-urlencoded
|
|
1079
|
+
if (contentType.includes('application/x-www-form-urlencoded')) {
|
|
1080
|
+
const text = await this.text();
|
|
1081
|
+
const formData = new FormData();
|
|
1082
|
+
const params = new URLSearchParams(text);
|
|
1083
|
+
for (const [key, value] of params) {
|
|
1084
|
+
formData.append(key, value);
|
|
1085
|
+
}
|
|
1086
|
+
return formData;
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
throw new TypeError('Unsupported content type for formData()');
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
clone() {
|
|
1093
|
+
if (this.bodyUsed) {
|
|
1094
|
+
throw new TypeError('Cannot clone a Response that has already been used');
|
|
1095
|
+
}
|
|
1096
|
+
const newId = __Response_clone(this.#instanceId);
|
|
1097
|
+
const cloned = Response._fromInstanceId(newId);
|
|
1098
|
+
return cloned;
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
static json(data, init = {}) {
|
|
1102
|
+
const body = JSON.stringify(data);
|
|
1103
|
+
const headers = new Headers(init.headers);
|
|
1104
|
+
if (!headers.has('content-type')) {
|
|
1105
|
+
headers.set('content-type', 'application/json');
|
|
1106
|
+
}
|
|
1107
|
+
return new Response(body, { ...init, headers });
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
static redirect(url, status = 302) {
|
|
1111
|
+
if (![301, 302, 303, 307, 308].includes(status)) {
|
|
1112
|
+
throw new RangeError('Invalid redirect status code');
|
|
1113
|
+
}
|
|
1114
|
+
const headers = new Headers({ Location: String(url) });
|
|
1115
|
+
return new Response(null, { status, headers });
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
static error() {
|
|
1119
|
+
const response = new Response(null, { status: 0, statusText: '' });
|
|
1120
|
+
__Response_setType(response._getInstanceId(), 'error');
|
|
1121
|
+
return response;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
globalThis.Response = Response;
|
|
1126
|
+
})();
|
|
1127
|
+
`;
|
|
1128
|
+
context.evalSync(responseCode);
|
|
1129
|
+
}
|
|
1130
|
+
function setupRequest(context, stateMap) {
|
|
1131
|
+
setTrackedGlobal(context, "__Request_construct", new import_isolated_vm.default.Callback((url, method, headers, bodyBytes, mode, credentials, cache, redirect, referrer, integrity) => {
|
|
1132
|
+
const instanceId = nextInstanceId++;
|
|
1133
|
+
const body = bodyBytes ? new Uint8Array(bodyBytes) : null;
|
|
1134
|
+
const state = {
|
|
1135
|
+
url,
|
|
1136
|
+
method,
|
|
1137
|
+
headers,
|
|
1138
|
+
body,
|
|
1139
|
+
bodyUsed: false,
|
|
1140
|
+
streamId: null,
|
|
1141
|
+
signalAborted: false,
|
|
1142
|
+
mode,
|
|
1143
|
+
credentials,
|
|
1144
|
+
cache,
|
|
1145
|
+
redirect,
|
|
1146
|
+
referrer,
|
|
1147
|
+
integrity
|
|
1148
|
+
};
|
|
1149
|
+
stateMap.set(instanceId, state);
|
|
1150
|
+
return instanceId;
|
|
1151
|
+
}));
|
|
1152
|
+
setTrackedGlobal(context, "__Request_get_method", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1153
|
+
const state = stateMap.get(instanceId);
|
|
1154
|
+
return state?.method ?? "GET";
|
|
1155
|
+
}));
|
|
1156
|
+
setTrackedGlobal(context, "__Request_get_url", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1157
|
+
const state = stateMap.get(instanceId);
|
|
1158
|
+
return state?.url ?? "";
|
|
1159
|
+
}));
|
|
1160
|
+
setTrackedGlobal(context, "__Request_get_headers", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1161
|
+
const state = stateMap.get(instanceId);
|
|
1162
|
+
return state?.headers ?? [];
|
|
1163
|
+
}));
|
|
1164
|
+
setTrackedGlobal(context, "__Request_get_bodyUsed", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1165
|
+
const state = stateMap.get(instanceId);
|
|
1166
|
+
return state?.bodyUsed ?? false;
|
|
1167
|
+
}));
|
|
1168
|
+
setTrackedGlobal(context, "__Request_get_mode", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1169
|
+
const state = stateMap.get(instanceId);
|
|
1170
|
+
return state?.mode ?? "cors";
|
|
1171
|
+
}));
|
|
1172
|
+
setTrackedGlobal(context, "__Request_get_credentials", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1173
|
+
const state = stateMap.get(instanceId);
|
|
1174
|
+
return state?.credentials ?? "same-origin";
|
|
1175
|
+
}));
|
|
1176
|
+
setTrackedGlobal(context, "__Request_get_cache", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1177
|
+
const state = stateMap.get(instanceId);
|
|
1178
|
+
return state?.cache ?? "default";
|
|
1179
|
+
}));
|
|
1180
|
+
setTrackedGlobal(context, "__Request_get_redirect", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1181
|
+
const state = stateMap.get(instanceId);
|
|
1182
|
+
return state?.redirect ?? "follow";
|
|
1183
|
+
}));
|
|
1184
|
+
setTrackedGlobal(context, "__Request_get_referrer", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1185
|
+
const state = stateMap.get(instanceId);
|
|
1186
|
+
return state?.referrer ?? "about:client";
|
|
1187
|
+
}));
|
|
1188
|
+
setTrackedGlobal(context, "__Request_get_integrity", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1189
|
+
const state = stateMap.get(instanceId);
|
|
1190
|
+
return state?.integrity ?? "";
|
|
1191
|
+
}));
|
|
1192
|
+
setTrackedGlobal(context, "__Request_markBodyUsed", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1193
|
+
const state = stateMap.get(instanceId);
|
|
1194
|
+
if (state) {
|
|
1195
|
+
if (state.bodyUsed) {
|
|
1196
|
+
throw new Error("[TypeError]Body has already been consumed");
|
|
1197
|
+
}
|
|
1198
|
+
state.bodyUsed = true;
|
|
1199
|
+
}
|
|
1200
|
+
}));
|
|
1201
|
+
setTrackedGlobal(context, "__Request_text", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1202
|
+
const state = stateMap.get(instanceId);
|
|
1203
|
+
if (!state || !state.body)
|
|
1204
|
+
return "";
|
|
1205
|
+
return new TextDecoder().decode(state.body);
|
|
1206
|
+
}));
|
|
1207
|
+
setTrackedGlobal(context, "__Request_arrayBuffer", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1208
|
+
const state = stateMap.get(instanceId);
|
|
1209
|
+
if (!state || !state.body) {
|
|
1210
|
+
return new import_isolated_vm.default.ExternalCopy(new ArrayBuffer(0)).copyInto();
|
|
1211
|
+
}
|
|
1212
|
+
return new import_isolated_vm.default.ExternalCopy(state.body.buffer.slice(state.body.byteOffset, state.body.byteOffset + state.body.byteLength)).copyInto();
|
|
1213
|
+
}));
|
|
1214
|
+
setTrackedGlobal(context, "__Request_getBodyBytes", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1215
|
+
const state = stateMap.get(instanceId);
|
|
1216
|
+
if (!state || !state.body)
|
|
1217
|
+
return null;
|
|
1218
|
+
return Array.from(state.body);
|
|
1219
|
+
}));
|
|
1220
|
+
setTrackedGlobal(context, "__Request_clone", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1221
|
+
const state = stateMap.get(instanceId);
|
|
1222
|
+
if (!state) {
|
|
1223
|
+
throw new Error("[TypeError]Cannot clone invalid Request");
|
|
1224
|
+
}
|
|
1225
|
+
const newId = nextInstanceId++;
|
|
1226
|
+
const newState = {
|
|
1227
|
+
...state,
|
|
1228
|
+
body: state.body ? new Uint8Array(state.body) : null,
|
|
1229
|
+
bodyUsed: false
|
|
1230
|
+
};
|
|
1231
|
+
stateMap.set(newId, newState);
|
|
1232
|
+
return newId;
|
|
1233
|
+
}));
|
|
1234
|
+
setTrackedGlobal(context, "__Request_getStreamId", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1235
|
+
const state = stateMap.get(instanceId);
|
|
1236
|
+
return state?.streamId ?? null;
|
|
1237
|
+
}));
|
|
1238
|
+
setTrackedGlobal(context, "__Request_get_signalAborted", new import_isolated_vm.default.Callback((instanceId) => {
|
|
1239
|
+
const state = stateMap.get(instanceId);
|
|
1240
|
+
return state?.signalAborted ?? false;
|
|
1241
|
+
}));
|
|
1242
|
+
const requestCode = `
|
|
1243
|
+
(function() {
|
|
1244
|
+
function __decodeError(err) {
|
|
1245
|
+
if (!(err instanceof Error)) return err;
|
|
1246
|
+
const match = err.message.match(/^\\[(TypeError|RangeError|SyntaxError|ReferenceError|URIError|EvalError|Error)\\](.*)$/);
|
|
1247
|
+
if (match) {
|
|
1248
|
+
const ErrorType = globalThis[match[1]] || Error;
|
|
1249
|
+
return new ErrorType(match[2]);
|
|
1250
|
+
}
|
|
1251
|
+
return err;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
function __prepareBody(body) {
|
|
1255
|
+
if (body === null || body === undefined) return null;
|
|
1256
|
+
if (typeof body === 'string') {
|
|
1257
|
+
const encoder = new TextEncoder();
|
|
1258
|
+
return Array.from(encoder.encode(body));
|
|
1259
|
+
}
|
|
1260
|
+
if (body instanceof ArrayBuffer) {
|
|
1261
|
+
return Array.from(new Uint8Array(body));
|
|
1262
|
+
}
|
|
1263
|
+
if (body instanceof Uint8Array) {
|
|
1264
|
+
return Array.from(body);
|
|
1265
|
+
}
|
|
1266
|
+
if (ArrayBuffer.isView(body)) {
|
|
1267
|
+
return Array.from(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
|
|
1268
|
+
}
|
|
1269
|
+
if (body instanceof URLSearchParams) {
|
|
1270
|
+
return Array.from(new TextEncoder().encode(body.toString()));
|
|
1271
|
+
}
|
|
1272
|
+
if (body instanceof FormData) {
|
|
1273
|
+
// Always serialize as multipart/form-data per spec
|
|
1274
|
+
const { body: bytes, contentType } = __serializeFormData(body);
|
|
1275
|
+
globalThis.__pendingFormDataContentType = contentType;
|
|
1276
|
+
return Array.from(bytes);
|
|
1277
|
+
}
|
|
1278
|
+
// Try to convert to string
|
|
1279
|
+
return Array.from(new TextEncoder().encode(String(body)));
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
// Helper to consume a HostBackedReadableStream and concatenate all chunks
|
|
1283
|
+
async function __consumeStream(stream) {
|
|
1284
|
+
const reader = stream.getReader();
|
|
1285
|
+
const chunks = [];
|
|
1286
|
+
let totalLength = 0;
|
|
1287
|
+
|
|
1288
|
+
while (true) {
|
|
1289
|
+
const { done, value } = await reader.read();
|
|
1290
|
+
if (done) break;
|
|
1291
|
+
chunks.push(value);
|
|
1292
|
+
totalLength += value.length;
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
// Concatenate all chunks
|
|
1296
|
+
const result = new Uint8Array(totalLength);
|
|
1297
|
+
let offset = 0;
|
|
1298
|
+
for (const chunk of chunks) {
|
|
1299
|
+
result.set(chunk, offset);
|
|
1300
|
+
offset += chunk.length;
|
|
1301
|
+
}
|
|
1302
|
+
return result;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
const __requestSignalControllers = new Map();
|
|
1306
|
+
|
|
1307
|
+
class Request {
|
|
1308
|
+
#instanceId;
|
|
1309
|
+
#headers;
|
|
1310
|
+
#signal;
|
|
1311
|
+
#streamId;
|
|
1312
|
+
#cachedBody = null;
|
|
1313
|
+
|
|
1314
|
+
constructor(input, init = {}) {
|
|
1315
|
+
// Handle internal construction from instance ID
|
|
1316
|
+
if (typeof input === 'number' && init === null) {
|
|
1317
|
+
const controller = new AbortController();
|
|
1318
|
+
if (__Request_get_signalAborted(input)) {
|
|
1319
|
+
controller.abort();
|
|
1320
|
+
}
|
|
1321
|
+
__requestSignalControllers.set(input, controller);
|
|
1322
|
+
|
|
1323
|
+
this.#instanceId = input;
|
|
1324
|
+
this.#headers = new Headers(__Request_get_headers(input));
|
|
1325
|
+
this.#signal = controller.signal;
|
|
1326
|
+
this.#streamId = __Request_getStreamId(input);
|
|
1327
|
+
return;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
let url;
|
|
1331
|
+
let method = 'GET';
|
|
1332
|
+
let headers;
|
|
1333
|
+
let body = null;
|
|
1334
|
+
let signal = new AbortController().signal;
|
|
1335
|
+
let mode = 'cors';
|
|
1336
|
+
let credentials = 'same-origin';
|
|
1337
|
+
let cache = 'default';
|
|
1338
|
+
let redirect = 'follow';
|
|
1339
|
+
let referrer = 'about:client';
|
|
1340
|
+
let integrity = '';
|
|
1341
|
+
|
|
1342
|
+
if (input instanceof Request) {
|
|
1343
|
+
url = input.url;
|
|
1344
|
+
method = input.method;
|
|
1345
|
+
headers = new Headers(input.headers);
|
|
1346
|
+
signal = input.signal;
|
|
1347
|
+
mode = input.mode;
|
|
1348
|
+
credentials = input.credentials;
|
|
1349
|
+
cache = input.cache;
|
|
1350
|
+
redirect = input.redirect;
|
|
1351
|
+
referrer = input.referrer;
|
|
1352
|
+
integrity = input.integrity;
|
|
1353
|
+
// Note: We don't copy the body from the input Request
|
|
1354
|
+
} else {
|
|
1355
|
+
url = String(input);
|
|
1356
|
+
headers = new Headers();
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
// Apply init overrides
|
|
1360
|
+
if (init.method !== undefined) method = String(init.method).toUpperCase();
|
|
1361
|
+
if (init.headers !== undefined) headers = new Headers(init.headers);
|
|
1362
|
+
if (init.body !== undefined) body = init.body;
|
|
1363
|
+
if (init.signal !== undefined) signal = init.signal;
|
|
1364
|
+
if (init.mode !== undefined) mode = init.mode;
|
|
1365
|
+
if (init.credentials !== undefined) credentials = init.credentials;
|
|
1366
|
+
if (init.cache !== undefined) cache = init.cache;
|
|
1367
|
+
if (init.redirect !== undefined) redirect = init.redirect;
|
|
1368
|
+
if (init.referrer !== undefined) referrer = init.referrer;
|
|
1369
|
+
if (init.integrity !== undefined) integrity = init.integrity;
|
|
1370
|
+
|
|
1371
|
+
// Ensure signal is always a valid AbortSignal
|
|
1372
|
+
if (signal == null) {
|
|
1373
|
+
signal = new AbortController().signal;
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
// Validate: body with GET/HEAD
|
|
1377
|
+
if (body !== null && (method === 'GET' || method === 'HEAD')) {
|
|
1378
|
+
throw new TypeError('Request with GET/HEAD method cannot have body');
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
const bodyBytes = __prepareBody(body);
|
|
1382
|
+
|
|
1383
|
+
// Handle Content-Type for FormData
|
|
1384
|
+
if (globalThis.__pendingFormDataContentType) {
|
|
1385
|
+
headers.set('content-type', globalThis.__pendingFormDataContentType);
|
|
1386
|
+
delete globalThis.__pendingFormDataContentType;
|
|
1387
|
+
} else if (body instanceof URLSearchParams && !headers.has('content-type')) {
|
|
1388
|
+
headers.set('content-type', 'application/x-www-form-urlencoded');
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
const headersArray = Array.from(headers.entries());
|
|
1392
|
+
|
|
1393
|
+
this.#instanceId = __Request_construct(
|
|
1394
|
+
url, method, headersArray, bodyBytes,
|
|
1395
|
+
mode, credentials, cache, redirect, referrer, integrity
|
|
1396
|
+
);
|
|
1397
|
+
this.#headers = headers;
|
|
1398
|
+
this.#signal = signal;
|
|
1399
|
+
this.#streamId = null;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
_getInstanceId() {
|
|
1403
|
+
return this.#instanceId;
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
static _fromInstanceId(instanceId) {
|
|
1407
|
+
return new Request(instanceId, null);
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
get method() {
|
|
1411
|
+
return __Request_get_method(this.#instanceId);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
get url() {
|
|
1415
|
+
return __Request_get_url(this.#instanceId);
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
get headers() {
|
|
1419
|
+
return this.#headers;
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
get bodyUsed() {
|
|
1423
|
+
return __Request_get_bodyUsed(this.#instanceId);
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
get signal() {
|
|
1427
|
+
return this.#signal;
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
get mode() {
|
|
1431
|
+
return __Request_get_mode(this.#instanceId);
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
get credentials() {
|
|
1435
|
+
return __Request_get_credentials(this.#instanceId);
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
get cache() {
|
|
1439
|
+
return __Request_get_cache(this.#instanceId);
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
get redirect() {
|
|
1443
|
+
return __Request_get_redirect(this.#instanceId);
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
get referrer() {
|
|
1447
|
+
return __Request_get_referrer(this.#instanceId);
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
get integrity() {
|
|
1451
|
+
return __Request_get_integrity(this.#instanceId);
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
get body() {
|
|
1455
|
+
// Per WHATWG Fetch spec: GET/HEAD requests cannot have a body
|
|
1456
|
+
const method = __Request_get_method(this.#instanceId);
|
|
1457
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
1458
|
+
return null;
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
// Return cached body if available
|
|
1462
|
+
if (this.#cachedBody !== null) {
|
|
1463
|
+
return this.#cachedBody;
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
// If we have a stream ID, create and cache the stream
|
|
1467
|
+
if (this.#streamId !== null) {
|
|
1468
|
+
this.#cachedBody = HostBackedReadableStream._fromStreamId(this.#streamId);
|
|
1469
|
+
return this.#cachedBody;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
// Check if there's any buffered body data
|
|
1473
|
+
const buffer = __Request_arrayBuffer(this.#instanceId);
|
|
1474
|
+
if (buffer.byteLength === 0) {
|
|
1475
|
+
return null; // Return null per WHATWG Fetch spec for empty body
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
// Create stream from non-empty buffered body
|
|
1479
|
+
const newStreamId = __Stream_create();
|
|
1480
|
+
__Stream_push(newStreamId, Array.from(new Uint8Array(buffer)));
|
|
1481
|
+
__Stream_close(newStreamId);
|
|
1482
|
+
|
|
1483
|
+
this.#cachedBody = HostBackedReadableStream._fromStreamId(newStreamId);
|
|
1484
|
+
return this.#cachedBody;
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
async text() {
|
|
1488
|
+
try {
|
|
1489
|
+
__Request_markBodyUsed(this.#instanceId);
|
|
1490
|
+
} catch (err) {
|
|
1491
|
+
throw __decodeError(err);
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
// If streaming, consume the stream
|
|
1495
|
+
if (this.#streamId !== null) {
|
|
1496
|
+
const bytes = await __consumeStream(this.body);
|
|
1497
|
+
return new TextDecoder().decode(bytes);
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
// Fallback to host callback for buffered body
|
|
1501
|
+
return __Request_text(this.#instanceId);
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
async json() {
|
|
1505
|
+
const text = await this.text();
|
|
1506
|
+
return JSON.parse(text);
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
async arrayBuffer() {
|
|
1510
|
+
try {
|
|
1511
|
+
__Request_markBodyUsed(this.#instanceId);
|
|
1512
|
+
} catch (err) {
|
|
1513
|
+
throw __decodeError(err);
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
// If streaming, consume the stream
|
|
1517
|
+
if (this.#streamId !== null) {
|
|
1518
|
+
const bytes = await __consumeStream(this.body);
|
|
1519
|
+
return bytes.buffer;
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
return __Request_arrayBuffer(this.#instanceId);
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
async blob() {
|
|
1526
|
+
const buffer = await this.arrayBuffer();
|
|
1527
|
+
const contentType = this.headers.get('content-type') || '';
|
|
1528
|
+
return new Blob([buffer], { type: contentType });
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
async formData() {
|
|
1532
|
+
const contentType = this.headers.get('content-type') || '';
|
|
1533
|
+
|
|
1534
|
+
// Parse multipart/form-data
|
|
1535
|
+
if (contentType.includes('multipart/form-data')) {
|
|
1536
|
+
const buffer = await this.arrayBuffer();
|
|
1537
|
+
return __parseMultipartFormData(new Uint8Array(buffer), contentType);
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
// Parse application/x-www-form-urlencoded
|
|
1541
|
+
if (contentType.includes('application/x-www-form-urlencoded')) {
|
|
1542
|
+
const text = await this.text();
|
|
1543
|
+
const formData = new FormData();
|
|
1544
|
+
const params = new URLSearchParams(text);
|
|
1545
|
+
for (const [key, value] of params) {
|
|
1546
|
+
formData.append(key, value);
|
|
1547
|
+
}
|
|
1548
|
+
return formData;
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
throw new TypeError('Unsupported content type for formData()');
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
clone() {
|
|
1555
|
+
if (this.bodyUsed) {
|
|
1556
|
+
throw new TypeError('Cannot clone a Request that has already been used');
|
|
1557
|
+
}
|
|
1558
|
+
const newId = __Request_clone(this.#instanceId);
|
|
1559
|
+
const cloned = Request._fromInstanceId(newId);
|
|
1560
|
+
cloned.#signal = this.#signal;
|
|
1561
|
+
return cloned;
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
_getBodyBytes() {
|
|
1565
|
+
return __Request_getBodyBytes(this.#instanceId);
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
globalThis.__Request_abortSignalByInstanceId = function(instanceId) {
|
|
1570
|
+
const controller = __requestSignalControllers.get(instanceId);
|
|
1571
|
+
if (controller && !controller.signal.aborted) {
|
|
1572
|
+
controller.abort();
|
|
1573
|
+
}
|
|
1574
|
+
};
|
|
1575
|
+
|
|
1576
|
+
globalThis.Request = Request;
|
|
1577
|
+
})();
|
|
1578
|
+
`;
|
|
1579
|
+
context.evalSync(requestCode);
|
|
1580
|
+
return context.evalSync("globalThis.__Request_abortSignalByInstanceId", { reference: true });
|
|
1581
|
+
}
|
|
1582
|
+
var FETCH_STREAM_THRESHOLD = 64 * 1024;
|
|
1583
|
+
function setupFetchFunction(context, stateMap, streamRegistry, options) {
|
|
1584
|
+
const fetchAbortControllers = new Map;
|
|
1585
|
+
setTrackedGlobal(context, "__fetch_abort", new import_isolated_vm.default.Callback((fetchId) => {
|
|
1586
|
+
const controller = fetchAbortControllers.get(fetchId);
|
|
1587
|
+
if (controller) {
|
|
1588
|
+
setImmediate(() => controller.abort());
|
|
1589
|
+
}
|
|
1590
|
+
}));
|
|
1591
|
+
const fetchRef = new import_isolated_vm.default.Reference(async (url, method, headersJson, bodyJson, signalAborted, fetchId) => {
|
|
1592
|
+
if (signalAborted) {
|
|
1593
|
+
throw new Error("[AbortError]The operation was aborted.");
|
|
1594
|
+
}
|
|
1595
|
+
const hostController = new AbortController;
|
|
1596
|
+
fetchAbortControllers.set(fetchId, hostController);
|
|
1597
|
+
const headers = JSON.parse(headersJson);
|
|
1598
|
+
const bodyBytes = bodyJson ? JSON.parse(bodyJson) : null;
|
|
1599
|
+
const rawBody = bodyBytes ? new Uint8Array(bodyBytes) : null;
|
|
1600
|
+
const init = {
|
|
1601
|
+
method,
|
|
1602
|
+
headers,
|
|
1603
|
+
rawBody,
|
|
1604
|
+
body: rawBody,
|
|
1605
|
+
signal: hostController.signal
|
|
1606
|
+
};
|
|
1607
|
+
const onFetch = options?.onFetch ?? ((url2, init2) => fetch(url2, {
|
|
1608
|
+
method: init2.method,
|
|
1609
|
+
headers: init2.headers,
|
|
1610
|
+
body: init2.body,
|
|
1611
|
+
signal: init2.signal
|
|
1612
|
+
}));
|
|
1613
|
+
try {
|
|
1614
|
+
let cleanupAbort;
|
|
1615
|
+
const abortPromise = new Promise((_, reject) => {
|
|
1616
|
+
if (hostController.signal.aborted) {
|
|
1617
|
+
reject(Object.assign(new Error("The operation was aborted."), { name: "AbortError" }));
|
|
1618
|
+
return;
|
|
1619
|
+
}
|
|
1620
|
+
const onAbort = () => {
|
|
1621
|
+
reject(Object.assign(new Error("The operation was aborted."), { name: "AbortError" }));
|
|
1622
|
+
};
|
|
1623
|
+
hostController.signal.addEventListener("abort", onAbort, { once: true });
|
|
1624
|
+
cleanupAbort = () => hostController.signal.removeEventListener("abort", onAbort);
|
|
1625
|
+
});
|
|
1626
|
+
abortPromise.catch(() => {});
|
|
1627
|
+
const nativeResponse = await Promise.race([onFetch(url, init), abortPromise]);
|
|
1628
|
+
cleanupAbort?.();
|
|
1629
|
+
const status = nativeResponse.status;
|
|
1630
|
+
const isNullBody = status === 204 || status === 304 || method.toUpperCase() === "HEAD";
|
|
1631
|
+
const isCallbackStream = nativeResponse.__isCallbackStream;
|
|
1632
|
+
const isNetworkResponse = nativeResponse.url && (nativeResponse.url.startsWith("http://") || nativeResponse.url.startsWith("https://"));
|
|
1633
|
+
const shouldStream = !isNullBody && nativeResponse.body && (isCallbackStream || isNetworkResponse);
|
|
1634
|
+
if (shouldStream && nativeResponse.body) {
|
|
1635
|
+
const streamId = streamRegistry.create();
|
|
1636
|
+
const streamCleanupFn = import_stream_state.startNativeStreamReader(nativeResponse.body, streamId, streamRegistry);
|
|
1637
|
+
streamRegistry.setCleanup(streamId, streamCleanupFn);
|
|
1638
|
+
const instanceId2 = nextInstanceId++;
|
|
1639
|
+
const state2 = {
|
|
1640
|
+
status: nativeResponse.status,
|
|
1641
|
+
statusText: nativeResponse.statusText,
|
|
1642
|
+
headers: Array.from(nativeResponse.headers.entries()),
|
|
1643
|
+
body: new Uint8Array(0),
|
|
1644
|
+
bodyUsed: false,
|
|
1645
|
+
type: "default",
|
|
1646
|
+
url: nativeResponse.url,
|
|
1647
|
+
redirected: nativeResponse.redirected,
|
|
1648
|
+
streamId,
|
|
1649
|
+
nullBody: isNullBody
|
|
1650
|
+
};
|
|
1651
|
+
stateMap.set(instanceId2, state2);
|
|
1652
|
+
return instanceId2;
|
|
1653
|
+
}
|
|
1654
|
+
const responseBody = await nativeResponse.arrayBuffer();
|
|
1655
|
+
const responseBodyArray = Array.from(new Uint8Array(responseBody));
|
|
1656
|
+
const instanceId = nextInstanceId++;
|
|
1657
|
+
const state = {
|
|
1658
|
+
status: nativeResponse.status,
|
|
1659
|
+
statusText: nativeResponse.statusText,
|
|
1660
|
+
headers: Array.from(nativeResponse.headers.entries()),
|
|
1661
|
+
body: new Uint8Array(responseBodyArray),
|
|
1662
|
+
bodyUsed: false,
|
|
1663
|
+
type: "default",
|
|
1664
|
+
url: nativeResponse.url,
|
|
1665
|
+
redirected: nativeResponse.redirected,
|
|
1666
|
+
streamId: null,
|
|
1667
|
+
nullBody: isNullBody
|
|
1668
|
+
};
|
|
1669
|
+
stateMap.set(instanceId, state);
|
|
1670
|
+
return instanceId;
|
|
1671
|
+
} catch (err) {
|
|
1672
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
1673
|
+
throw new Error("[AbortError]The operation was aborted.");
|
|
1674
|
+
}
|
|
1675
|
+
throw err;
|
|
1676
|
+
} finally {
|
|
1677
|
+
fetchAbortControllers.delete(fetchId);
|
|
1678
|
+
}
|
|
1679
|
+
});
|
|
1680
|
+
setTrackedGlobal(context, "__fetch_ref", fetchRef);
|
|
1681
|
+
const fetchCode = `
|
|
1682
|
+
(function() {
|
|
1683
|
+
function __decodeError(err) {
|
|
1684
|
+
if (!(err instanceof Error)) return err;
|
|
1685
|
+
const match = err.message.match(/^\\[(TypeError|RangeError|AbortError|Error)\\](.*)$/);
|
|
1686
|
+
if (match) {
|
|
1687
|
+
if (match[1] === 'AbortError') {
|
|
1688
|
+
return new DOMException(match[2], 'AbortError');
|
|
1689
|
+
}
|
|
1690
|
+
const ErrorType = globalThis[match[1]] || Error;
|
|
1691
|
+
return new ErrorType(match[2]);
|
|
1692
|
+
}
|
|
1693
|
+
return err;
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
let __nextFetchId = 1;
|
|
1697
|
+
|
|
1698
|
+
globalThis.fetch = async function(input, init = {}) {
|
|
1699
|
+
// Handle Blob and ReadableStream bodies before creating Request
|
|
1700
|
+
if (init.body instanceof Blob && !(init.body instanceof File)) {
|
|
1701
|
+
const buf = await init.body.arrayBuffer();
|
|
1702
|
+
init = Object.assign({}, init, { body: new Uint8Array(buf) });
|
|
1703
|
+
} else if (init.body instanceof ReadableStream) {
|
|
1704
|
+
const reader = init.body.getReader();
|
|
1705
|
+
const chunks = [];
|
|
1706
|
+
while (true) {
|
|
1707
|
+
const { done, value } = await reader.read();
|
|
1708
|
+
if (done) break;
|
|
1709
|
+
chunks.push(value);
|
|
1710
|
+
}
|
|
1711
|
+
const total = chunks.reduce((s, c) => s + c.length, 0);
|
|
1712
|
+
const buf = new Uint8Array(total);
|
|
1713
|
+
let off = 0;
|
|
1714
|
+
for (const c of chunks) { buf.set(c, off); off += c.length; }
|
|
1715
|
+
init = Object.assign({}, init, { body: buf });
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
// Create Request from input
|
|
1719
|
+
const request = input instanceof Request ? input : new Request(input, init);
|
|
1720
|
+
|
|
1721
|
+
// Get signal info
|
|
1722
|
+
const signal = init.signal ?? request.signal;
|
|
1723
|
+
const signalAborted = signal?.aborted ?? false;
|
|
1724
|
+
|
|
1725
|
+
// Assign a fetch ID for abort tracking
|
|
1726
|
+
const fetchId = __nextFetchId++;
|
|
1727
|
+
|
|
1728
|
+
// Register abort listener if signal exists
|
|
1729
|
+
if (signal && !signalAborted) {
|
|
1730
|
+
signal.addEventListener('abort', () => { __fetch_abort(fetchId); });
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
// Serialize headers and body to JSON for transfer
|
|
1734
|
+
const headersJson = JSON.stringify(Array.from(request.headers.entries()));
|
|
1735
|
+
const bodyBytes = request._getBodyBytes();
|
|
1736
|
+
const bodyJson = bodyBytes ? JSON.stringify(bodyBytes) : null;
|
|
1737
|
+
|
|
1738
|
+
// Short-circuit: if signal is already aborted, throw without calling host
|
|
1739
|
+
if (signalAborted) {
|
|
1740
|
+
throw new DOMException('The operation was aborted.', 'AbortError');
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
// Call host - returns just the response instance ID
|
|
1744
|
+
try {
|
|
1745
|
+
const instanceId = await __fetch_ref.apply(undefined, [
|
|
1746
|
+
request.url,
|
|
1747
|
+
request.method,
|
|
1748
|
+
headersJson,
|
|
1749
|
+
bodyJson,
|
|
1750
|
+
signalAborted,
|
|
1751
|
+
fetchId
|
|
1752
|
+
], { result: { promise: true, copy: true } });
|
|
1753
|
+
|
|
1754
|
+
// Construct Response from the instance ID
|
|
1755
|
+
return Response._fromInstanceId(instanceId);
|
|
1756
|
+
} catch (err) {
|
|
1757
|
+
throw __decodeError(err);
|
|
1758
|
+
}
|
|
1759
|
+
};
|
|
1760
|
+
})();
|
|
1761
|
+
`;
|
|
1762
|
+
context.evalSync(fetchCode);
|
|
1763
|
+
}
|
|
1764
|
+
function setupServer(context, serveState) {
|
|
1765
|
+
context.evalSync(`
|
|
1766
|
+
globalThis.__upgradeRegistry__ = new Map();
|
|
1767
|
+
globalThis.__upgradeIdCounter__ = 0;
|
|
1768
|
+
`);
|
|
1769
|
+
setTrackedGlobal(context, "__setPendingUpgrade__", new import_isolated_vm.default.Callback((connectionId) => {
|
|
1770
|
+
serveState.pendingUpgrade = { requested: true, connectionId };
|
|
1771
|
+
}));
|
|
1772
|
+
context.evalSync(`
|
|
1773
|
+
(function() {
|
|
1774
|
+
class Server {
|
|
1775
|
+
upgrade(request, options) {
|
|
1776
|
+
const data = options?.data;
|
|
1777
|
+
const connectionId = String(++globalThis.__upgradeIdCounter__);
|
|
1778
|
+
globalThis.__upgradeRegistry__.set(connectionId, data);
|
|
1779
|
+
__setPendingUpgrade__(connectionId);
|
|
1780
|
+
return true;
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
globalThis.__Server__ = Server;
|
|
1784
|
+
})();
|
|
1785
|
+
`);
|
|
1786
|
+
}
|
|
1787
|
+
function setupServerWebSocket(context, wsCommandCallbacks) {
|
|
1788
|
+
setTrackedGlobal(context, "__ServerWebSocket_send", new import_isolated_vm.default.Callback((connectionId, data) => {
|
|
1789
|
+
const cmd = { type: "message", connectionId, data };
|
|
1790
|
+
for (const cb of wsCommandCallbacks)
|
|
1791
|
+
cb(cmd);
|
|
1792
|
+
}));
|
|
1793
|
+
setTrackedGlobal(context, "__ServerWebSocket_close", new import_isolated_vm.default.Callback((connectionId, code, reason) => {
|
|
1794
|
+
const cmd = { type: "close", connectionId, code, reason };
|
|
1795
|
+
for (const cb of wsCommandCallbacks)
|
|
1796
|
+
cb(cmd);
|
|
1797
|
+
}));
|
|
1798
|
+
context.evalSync(`
|
|
1799
|
+
(function() {
|
|
1800
|
+
const _wsInstanceData = new WeakMap();
|
|
1801
|
+
|
|
1802
|
+
class ServerWebSocket {
|
|
1803
|
+
constructor(connectionId) {
|
|
1804
|
+
_wsInstanceData.set(this, { connectionId, readyState: 1 });
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
get data() {
|
|
1808
|
+
const state = _wsInstanceData.get(this);
|
|
1809
|
+
return globalThis.__upgradeRegistry__.get(state.connectionId);
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
get readyState() {
|
|
1813
|
+
return _wsInstanceData.get(this).readyState;
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
send(message) {
|
|
1817
|
+
const state = _wsInstanceData.get(this);
|
|
1818
|
+
if (state.readyState !== 1) throw new Error("WebSocket is not open");
|
|
1819
|
+
// Convert ArrayBuffer/Uint8Array to string for transfer
|
|
1820
|
+
let data = message;
|
|
1821
|
+
if (message instanceof ArrayBuffer) {
|
|
1822
|
+
data = new TextDecoder().decode(message);
|
|
1823
|
+
} else if (message instanceof Uint8Array) {
|
|
1824
|
+
data = new TextDecoder().decode(message);
|
|
1825
|
+
}
|
|
1826
|
+
__ServerWebSocket_send(state.connectionId, data);
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
close(code, reason) {
|
|
1830
|
+
const state = _wsInstanceData.get(this);
|
|
1831
|
+
if (state.readyState === 3) return;
|
|
1832
|
+
state.readyState = 2; // CLOSING
|
|
1833
|
+
__ServerWebSocket_close(state.connectionId, code, reason);
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
_setReadyState(readyState) {
|
|
1837
|
+
_wsInstanceData.get(this).readyState = readyState;
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
globalThis.__ServerWebSocket__ = ServerWebSocket;
|
|
1842
|
+
})();
|
|
1843
|
+
`);
|
|
1844
|
+
}
|
|
1845
|
+
function setupClientWebSocket(context, clientWsCommandCallbacks) {
|
|
1846
|
+
setTrackedGlobal(context, "__WebSocket_connect", new import_isolated_vm.default.Callback((socketId, url, protocols) => {
|
|
1847
|
+
const cmd = {
|
|
1848
|
+
type: "connect",
|
|
1849
|
+
socketId,
|
|
1850
|
+
url,
|
|
1851
|
+
protocols
|
|
1852
|
+
};
|
|
1853
|
+
for (const cb of clientWsCommandCallbacks)
|
|
1854
|
+
cb(cmd);
|
|
1855
|
+
}));
|
|
1856
|
+
setTrackedGlobal(context, "__WebSocket_send", new import_isolated_vm.default.Callback((socketId, data) => {
|
|
1857
|
+
const cmd = { type: "send", socketId, data };
|
|
1858
|
+
for (const cb of clientWsCommandCallbacks)
|
|
1859
|
+
cb(cmd);
|
|
1860
|
+
}));
|
|
1861
|
+
setTrackedGlobal(context, "__WebSocket_close", new import_isolated_vm.default.Callback((socketId, code, reason) => {
|
|
1862
|
+
const cmd = { type: "close", socketId, code, reason };
|
|
1863
|
+
for (const cb of clientWsCommandCallbacks)
|
|
1864
|
+
cb(cmd);
|
|
1865
|
+
}));
|
|
1866
|
+
context.evalSync(`
|
|
1867
|
+
(function() {
|
|
1868
|
+
// Socket ID counter
|
|
1869
|
+
let __nextSocketId = 1;
|
|
1870
|
+
|
|
1871
|
+
// Active sockets registry
|
|
1872
|
+
const __clientWebSockets = new Map();
|
|
1873
|
+
|
|
1874
|
+
// Simple Event class (if not defined globally)
|
|
1875
|
+
const _Event = globalThis.Event || class Event {
|
|
1876
|
+
constructor(type, options = {}) {
|
|
1877
|
+
this.type = type;
|
|
1878
|
+
this.bubbles = options.bubbles || false;
|
|
1879
|
+
this.cancelable = options.cancelable || false;
|
|
1880
|
+
this.defaultPrevented = false;
|
|
1881
|
+
this.timeStamp = Date.now();
|
|
1882
|
+
this.target = null;
|
|
1883
|
+
this.currentTarget = null;
|
|
1884
|
+
}
|
|
1885
|
+
preventDefault() {
|
|
1886
|
+
if (this.cancelable) this.defaultPrevented = true;
|
|
1887
|
+
}
|
|
1888
|
+
stopPropagation() {}
|
|
1889
|
+
stopImmediatePropagation() {}
|
|
1890
|
+
};
|
|
1891
|
+
|
|
1892
|
+
// MessageEvent class for WebSocket messages
|
|
1893
|
+
const _MessageEvent = globalThis.MessageEvent || class MessageEvent extends _Event {
|
|
1894
|
+
constructor(type, options = {}) {
|
|
1895
|
+
super(type, options);
|
|
1896
|
+
this.data = options.data !== undefined ? options.data : null;
|
|
1897
|
+
this.origin = options.origin || '';
|
|
1898
|
+
this.lastEventId = options.lastEventId || '';
|
|
1899
|
+
this.source = options.source || null;
|
|
1900
|
+
this.ports = options.ports || [];
|
|
1901
|
+
}
|
|
1902
|
+
};
|
|
1903
|
+
|
|
1904
|
+
// CloseEvent class for WebSocket close
|
|
1905
|
+
const _CloseEvent = globalThis.CloseEvent || class CloseEvent extends _Event {
|
|
1906
|
+
constructor(type, options = {}) {
|
|
1907
|
+
super(type, options);
|
|
1908
|
+
this.code = options.code !== undefined ? options.code : 0;
|
|
1909
|
+
this.reason = options.reason !== undefined ? options.reason : '';
|
|
1910
|
+
this.wasClean = options.wasClean !== undefined ? options.wasClean : false;
|
|
1911
|
+
}
|
|
1912
|
+
};
|
|
1913
|
+
|
|
1914
|
+
// Helper to dispatch events
|
|
1915
|
+
function dispatchEvent(ws, event) {
|
|
1916
|
+
const listeners = ws._listeners.get(event.type) || [];
|
|
1917
|
+
for (const listener of listeners) {
|
|
1918
|
+
try {
|
|
1919
|
+
listener.call(ws, event);
|
|
1920
|
+
} catch (e) {
|
|
1921
|
+
console.error('WebSocket event listener error:', e);
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
// Also call on* handler if set
|
|
1925
|
+
const handler = ws['on' + event.type];
|
|
1926
|
+
if (typeof handler === 'function') {
|
|
1927
|
+
try {
|
|
1928
|
+
handler.call(ws, event);
|
|
1929
|
+
} catch (e) {
|
|
1930
|
+
console.error('WebSocket handler error:', e);
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
class WebSocket {
|
|
1936
|
+
static CONNECTING = 0;
|
|
1937
|
+
static OPEN = 1;
|
|
1938
|
+
static CLOSING = 2;
|
|
1939
|
+
static CLOSED = 3;
|
|
1940
|
+
|
|
1941
|
+
#socketId;
|
|
1942
|
+
#url;
|
|
1943
|
+
#readyState = WebSocket.CONNECTING;
|
|
1944
|
+
#bufferedAmount = 0;
|
|
1945
|
+
#extensions = '';
|
|
1946
|
+
#protocol = '';
|
|
1947
|
+
#binaryType = 'blob';
|
|
1948
|
+
_listeners = new Map();
|
|
1949
|
+
|
|
1950
|
+
// Event handlers
|
|
1951
|
+
onopen = null;
|
|
1952
|
+
onmessage = null;
|
|
1953
|
+
onerror = null;
|
|
1954
|
+
onclose = null;
|
|
1955
|
+
|
|
1956
|
+
constructor(url, protocols) {
|
|
1957
|
+
// Validate URL
|
|
1958
|
+
let parsedUrl;
|
|
1959
|
+
try {
|
|
1960
|
+
parsedUrl = new URL(url);
|
|
1961
|
+
} catch (e) {
|
|
1962
|
+
throw new DOMException("Failed to construct 'WebSocket': The URL '" + url + "' is invalid.", 'SyntaxError');
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
if (parsedUrl.protocol !== 'ws:' && parsedUrl.protocol !== 'wss:') {
|
|
1966
|
+
throw new DOMException("Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'.", 'SyntaxError');
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
// Per WHATWG spec, fragments must be stripped from WebSocket URLs
|
|
1970
|
+
parsedUrl.hash = '';
|
|
1971
|
+
this.#url = parsedUrl.href;
|
|
1972
|
+
this.#socketId = String(__nextSocketId++);
|
|
1973
|
+
|
|
1974
|
+
// Normalize protocols to array
|
|
1975
|
+
let protocolArray = [];
|
|
1976
|
+
if (protocols !== undefined) {
|
|
1977
|
+
if (typeof protocols === 'string') {
|
|
1978
|
+
protocolArray = [protocols];
|
|
1979
|
+
} else if (Array.isArray(protocols)) {
|
|
1980
|
+
protocolArray = protocols;
|
|
1981
|
+
} else {
|
|
1982
|
+
protocolArray = [String(protocols)];
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
|
|
1986
|
+
// Check for duplicate protocols
|
|
1987
|
+
const seen = new Set();
|
|
1988
|
+
for (const p of protocolArray) {
|
|
1989
|
+
if (seen.has(p)) {
|
|
1990
|
+
throw new DOMException("Failed to construct 'WebSocket': The subprotocol '" + p + "' is duplicated.", 'SyntaxError');
|
|
1991
|
+
}
|
|
1992
|
+
seen.add(p);
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
// Register socket
|
|
1996
|
+
__clientWebSockets.set(this.#socketId, this);
|
|
1997
|
+
|
|
1998
|
+
// Call host to create connection
|
|
1999
|
+
__WebSocket_connect(this.#socketId, this.#url, protocolArray);
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
get url() {
|
|
2003
|
+
return this.#url;
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
get readyState() {
|
|
2007
|
+
return this.#readyState;
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
get bufferedAmount() {
|
|
2011
|
+
return this.#bufferedAmount;
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
get extensions() {
|
|
2015
|
+
return this.#extensions;
|
|
2016
|
+
}
|
|
2017
|
+
|
|
2018
|
+
get protocol() {
|
|
2019
|
+
return this.#protocol;
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
get binaryType() {
|
|
2023
|
+
return this.#binaryType;
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
set binaryType(value) {
|
|
2027
|
+
if (value !== 'blob' && value !== 'arraybuffer') {
|
|
2028
|
+
throw new DOMException("Failed to set the 'binaryType' property: '" + value + "' is not a valid value.", 'SyntaxError');
|
|
2029
|
+
}
|
|
2030
|
+
this.#binaryType = value;
|
|
2031
|
+
}
|
|
2032
|
+
|
|
2033
|
+
// ReadyState constants
|
|
2034
|
+
get CONNECTING() { return WebSocket.CONNECTING; }
|
|
2035
|
+
get OPEN() { return WebSocket.OPEN; }
|
|
2036
|
+
get CLOSING() { return WebSocket.CLOSING; }
|
|
2037
|
+
get CLOSED() { return WebSocket.CLOSED; }
|
|
2038
|
+
|
|
2039
|
+
send(data) {
|
|
2040
|
+
if (this.#readyState === WebSocket.CONNECTING) {
|
|
2041
|
+
throw new DOMException("Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.", 'InvalidStateError');
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
if (this.#readyState !== WebSocket.OPEN) {
|
|
2045
|
+
// Silently discard if not open (per spec)
|
|
2046
|
+
return;
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
// Convert data to string for transfer
|
|
2050
|
+
let dataStr;
|
|
2051
|
+
if (typeof data === 'string') {
|
|
2052
|
+
dataStr = data;
|
|
2053
|
+
} else if (data instanceof ArrayBuffer) {
|
|
2054
|
+
// Convert ArrayBuffer to base64 for transfer
|
|
2055
|
+
const bytes = new Uint8Array(data);
|
|
2056
|
+
let binary = '';
|
|
2057
|
+
for (let i = 0; i < bytes.byteLength; i++) {
|
|
2058
|
+
binary += String.fromCharCode(bytes[i]);
|
|
2059
|
+
}
|
|
2060
|
+
dataStr = '__BINARY__' + btoa(binary);
|
|
2061
|
+
} else if (ArrayBuffer.isView(data)) {
|
|
2062
|
+
const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
2063
|
+
let binary = '';
|
|
2064
|
+
for (let i = 0; i < bytes.byteLength; i++) {
|
|
2065
|
+
binary += String.fromCharCode(bytes[i]);
|
|
2066
|
+
}
|
|
2067
|
+
dataStr = '__BINARY__' + btoa(binary);
|
|
2068
|
+
} else if (data instanceof Blob) {
|
|
2069
|
+
// Blob.arrayBuffer() is async, but send() is sync
|
|
2070
|
+
// For now, throw - this is a limitation
|
|
2071
|
+
throw new DOMException("Failed to execute 'send' on 'WebSocket': Blob data is not supported in this environment.", 'NotSupportedError');
|
|
2072
|
+
} else {
|
|
2073
|
+
dataStr = String(data);
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
__WebSocket_send(this.#socketId, dataStr);
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
close(code, reason) {
|
|
2080
|
+
if (code !== undefined) {
|
|
2081
|
+
if (typeof code !== 'number' || code !== Math.floor(code)) {
|
|
2082
|
+
throw new DOMException("Failed to execute 'close' on 'WebSocket': The code must be an integer.", 'InvalidAccessError');
|
|
2083
|
+
}
|
|
2084
|
+
if (code !== 1000 && (code < 3000 || code > 4999)) {
|
|
2085
|
+
throw new DOMException("Failed to execute 'close' on 'WebSocket': The code must be either 1000, or between 3000 and 4999.", 'InvalidAccessError');
|
|
2086
|
+
}
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
if (reason !== undefined) {
|
|
2090
|
+
const encoder = new TextEncoder();
|
|
2091
|
+
if (encoder.encode(reason).byteLength > 123) {
|
|
2092
|
+
throw new DOMException("Failed to execute 'close' on 'WebSocket': The message must not be greater than 123 bytes.", 'SyntaxError');
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
if (this.#readyState === WebSocket.CLOSING || this.#readyState === WebSocket.CLOSED) {
|
|
2097
|
+
return;
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
this.#readyState = WebSocket.CLOSING;
|
|
2101
|
+
__WebSocket_close(this.#socketId, code ?? 1000, reason ?? '');
|
|
2102
|
+
}
|
|
2103
|
+
|
|
2104
|
+
// EventTarget interface
|
|
2105
|
+
addEventListener(type, listener, options) {
|
|
2106
|
+
if (typeof listener !== 'function') return;
|
|
2107
|
+
let listeners = this._listeners.get(type);
|
|
2108
|
+
if (!listeners) {
|
|
2109
|
+
listeners = [];
|
|
2110
|
+
this._listeners.set(type, listeners);
|
|
2111
|
+
}
|
|
2112
|
+
if (!listeners.includes(listener)) {
|
|
2113
|
+
listeners.push(listener);
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
removeEventListener(type, listener, options) {
|
|
2118
|
+
const listeners = this._listeners.get(type);
|
|
2119
|
+
if (!listeners) return;
|
|
2120
|
+
const index = listeners.indexOf(listener);
|
|
2121
|
+
if (index !== -1) {
|
|
2122
|
+
listeners.splice(index, 1);
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
dispatchEvent(event) {
|
|
2127
|
+
dispatchEvent(this, event);
|
|
2128
|
+
return !event.defaultPrevented;
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
// Internal methods called from host
|
|
2132
|
+
_setProtocol(protocol) {
|
|
2133
|
+
this.#protocol = protocol;
|
|
2134
|
+
}
|
|
2135
|
+
|
|
2136
|
+
_setExtensions(extensions) {
|
|
2137
|
+
this.#extensions = extensions;
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
_setReadyState(state) {
|
|
2141
|
+
this.#readyState = state;
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
_dispatchOpen() {
|
|
2145
|
+
this.#readyState = WebSocket.OPEN;
|
|
2146
|
+
const event = new _Event('open');
|
|
2147
|
+
dispatchEvent(this, event);
|
|
2148
|
+
}
|
|
2149
|
+
|
|
2150
|
+
_dispatchMessage(data) {
|
|
2151
|
+
// Handle binary data
|
|
2152
|
+
let messageData = data;
|
|
2153
|
+
if (typeof data === 'string' && data.startsWith('__BINARY__')) {
|
|
2154
|
+
const base64 = data.slice(10);
|
|
2155
|
+
const binary = atob(base64);
|
|
2156
|
+
const bytes = new Uint8Array(binary.length);
|
|
2157
|
+
for (let i = 0; i < binary.length; i++) {
|
|
2158
|
+
bytes[i] = binary.charCodeAt(i);
|
|
2159
|
+
}
|
|
2160
|
+
if (this.#binaryType === 'arraybuffer') {
|
|
2161
|
+
messageData = bytes.buffer;
|
|
2162
|
+
} else {
|
|
2163
|
+
messageData = new Blob([bytes]);
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
const event = new _MessageEvent('message', { data: messageData });
|
|
2168
|
+
dispatchEvent(this, event);
|
|
2169
|
+
}
|
|
2170
|
+
|
|
2171
|
+
_dispatchError() {
|
|
2172
|
+
const event = new _Event('error');
|
|
2173
|
+
dispatchEvent(this, event);
|
|
2174
|
+
}
|
|
2175
|
+
|
|
2176
|
+
_dispatchClose(code, reason, wasClean) {
|
|
2177
|
+
this.#readyState = WebSocket.CLOSED;
|
|
2178
|
+
const event = new _CloseEvent('close', { code, reason, wasClean });
|
|
2179
|
+
dispatchEvent(this, event);
|
|
2180
|
+
__clientWebSockets.delete(this.#socketId);
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2184
|
+
// Helper to dispatch events from host to a socket by ID
|
|
2185
|
+
globalThis.__dispatchClientWebSocketEvent = function(socketId, eventType, data) {
|
|
2186
|
+
const ws = __clientWebSockets.get(socketId);
|
|
2187
|
+
if (!ws) return;
|
|
2188
|
+
|
|
2189
|
+
switch (eventType) {
|
|
2190
|
+
case 'open':
|
|
2191
|
+
ws._setProtocol(data.protocol || '');
|
|
2192
|
+
ws._setExtensions(data.extensions || '');
|
|
2193
|
+
ws._dispatchOpen();
|
|
2194
|
+
break;
|
|
2195
|
+
case 'message':
|
|
2196
|
+
ws._dispatchMessage(data.data);
|
|
2197
|
+
break;
|
|
2198
|
+
case 'error':
|
|
2199
|
+
ws._dispatchError();
|
|
2200
|
+
break;
|
|
2201
|
+
case 'close':
|
|
2202
|
+
ws._dispatchClose(data.code, data.reason, data.wasClean);
|
|
2203
|
+
break;
|
|
2204
|
+
}
|
|
2205
|
+
};
|
|
2206
|
+
|
|
2207
|
+
globalThis.WebSocket = WebSocket;
|
|
2208
|
+
})();
|
|
2209
|
+
`);
|
|
2210
|
+
}
|
|
2211
|
+
function setupServe(context) {
|
|
2212
|
+
context.evalSync(`
|
|
2213
|
+
(function() {
|
|
2214
|
+
globalThis.__serveOptions__ = null;
|
|
2215
|
+
|
|
2216
|
+
function serve(options) {
|
|
2217
|
+
globalThis.__serveOptions__ = options;
|
|
2218
|
+
}
|
|
2219
|
+
|
|
2220
|
+
globalThis.serve = serve;
|
|
2221
|
+
})();
|
|
2222
|
+
`);
|
|
2223
|
+
}
|
|
2224
|
+
async function setupFetch(context, options) {
|
|
2225
|
+
await import_core.setupCore(context);
|
|
2226
|
+
const stateMap = getInstanceStateMapForContext(context);
|
|
2227
|
+
const streamRegistry = import_stream_state.getStreamRegistryForContext(context);
|
|
2228
|
+
context.evalSync(headersCode);
|
|
2229
|
+
context.evalSync(formDataCode);
|
|
2230
|
+
context.evalSync(multipartCode);
|
|
2231
|
+
setupStreamCallbacks(context, streamRegistry);
|
|
2232
|
+
context.evalSync(hostBackedStreamCode);
|
|
2233
|
+
setupResponse(context, stateMap, streamRegistry);
|
|
2234
|
+
const requestAbortSignalRef = setupRequest(context, stateMap);
|
|
2235
|
+
setupFetchFunction(context, stateMap, streamRegistry, options);
|
|
2236
|
+
const serveState = {
|
|
2237
|
+
pendingUpgrade: null,
|
|
2238
|
+
activeConnections: new Map
|
|
2239
|
+
};
|
|
2240
|
+
const wsCommandCallbacks = new Set;
|
|
2241
|
+
const clientWsCommandCallbacks = new Set;
|
|
2242
|
+
setupServer(context, serveState);
|
|
2243
|
+
setupServerWebSocket(context, wsCommandCallbacks);
|
|
2244
|
+
setupServe(context);
|
|
2245
|
+
setupClientWebSocket(context, clientWsCommandCallbacks);
|
|
2246
|
+
const eventCallbacks = new Set;
|
|
2247
|
+
setTrackedGlobal(context, "__emit", new import_isolated_vm.default.Callback((eventName, payloadJson) => {
|
|
2248
|
+
const payload = JSON.parse(payloadJson);
|
|
2249
|
+
for (const cb of eventCallbacks)
|
|
2250
|
+
cb(eventName, payload);
|
|
2251
|
+
}));
|
|
2252
|
+
context.evalSync(`
|
|
2253
|
+
(function() {
|
|
2254
|
+
const __eventListeners = new Map();
|
|
2255
|
+
|
|
2256
|
+
globalThis.__on = function(event, callback) {
|
|
2257
|
+
let listeners = __eventListeners.get(event);
|
|
2258
|
+
if (!listeners) {
|
|
2259
|
+
listeners = new Set();
|
|
2260
|
+
__eventListeners.set(event, listeners);
|
|
2261
|
+
}
|
|
2262
|
+
listeners.add(callback);
|
|
2263
|
+
return function() {
|
|
2264
|
+
listeners.delete(callback);
|
|
2265
|
+
if (listeners.size === 0) {
|
|
2266
|
+
__eventListeners.delete(event);
|
|
2267
|
+
}
|
|
2268
|
+
};
|
|
2269
|
+
};
|
|
2270
|
+
|
|
2271
|
+
globalThis.__dispatchExternalEvent = function(event, payloadJson) {
|
|
2272
|
+
const listeners = __eventListeners.get(event);
|
|
2273
|
+
if (!listeners) return;
|
|
2274
|
+
const payload = JSON.parse(payloadJson);
|
|
2275
|
+
for (const cb of listeners) {
|
|
2276
|
+
try { cb(payload); } catch (e) { console.error('Event listener error:', e); }
|
|
2277
|
+
}
|
|
2278
|
+
};
|
|
2279
|
+
})();
|
|
2280
|
+
`);
|
|
2281
|
+
return {
|
|
2282
|
+
dispose() {
|
|
2283
|
+
stateMap.clear();
|
|
2284
|
+
clearPassthruBodiesForContext(context);
|
|
2285
|
+
import_stream_state.clearStreamRegistryForContext(context);
|
|
2286
|
+
context.evalSync(`globalThis.__upgradeRegistry__.clear()`);
|
|
2287
|
+
serveState.activeConnections.clear();
|
|
2288
|
+
serveState.pendingUpgrade = null;
|
|
2289
|
+
releaseTrackedGlobalHandles(context);
|
|
2290
|
+
try {
|
|
2291
|
+
requestAbortSignalRef.release();
|
|
2292
|
+
} catch {}
|
|
2293
|
+
},
|
|
2294
|
+
async dispatchRequest(request, dispatchOptions) {
|
|
2295
|
+
if (serveState.pendingUpgrade) {
|
|
2296
|
+
const oldConnectionId = serveState.pendingUpgrade.connectionId;
|
|
2297
|
+
context.evalSync(`globalThis.__upgradeRegistry__.delete("${oldConnectionId}")`);
|
|
2298
|
+
serveState.pendingUpgrade = null;
|
|
2299
|
+
}
|
|
2300
|
+
const hasHandler = context.evalSync(`!!globalThis.__serveOptions__?.fetch`);
|
|
2301
|
+
if (!hasHandler) {
|
|
2302
|
+
throw new Error("No serve() handler registered");
|
|
2303
|
+
}
|
|
2304
|
+
const forwardedSignal = dispatchOptions?.signal ?? request.signal;
|
|
2305
|
+
const forwardedSignalInitiallyAborted = forwardedSignal?.aborted ?? false;
|
|
2306
|
+
let requestStreamId = null;
|
|
2307
|
+
let requestInstanceId = null;
|
|
2308
|
+
let streamCleanup = null;
|
|
2309
|
+
let onForwardedSignalAbort;
|
|
2310
|
+
const canHaveBody = !["GET", "HEAD"].includes(request.method.toUpperCase());
|
|
2311
|
+
if (canHaveBody && request.body) {
|
|
2312
|
+
requestStreamId = streamRegistry.create();
|
|
2313
|
+
streamCleanup = import_stream_state.startNativeStreamReader(request.body, requestStreamId, streamRegistry);
|
|
2314
|
+
}
|
|
2315
|
+
try {
|
|
2316
|
+
const headersArray = Array.from(request.headers.entries());
|
|
2317
|
+
requestInstanceId = nextInstanceId++;
|
|
2318
|
+
const requestState = {
|
|
2319
|
+
url: request.url,
|
|
2320
|
+
method: request.method,
|
|
2321
|
+
headers: headersArray,
|
|
2322
|
+
body: null,
|
|
2323
|
+
bodyUsed: false,
|
|
2324
|
+
streamId: requestStreamId,
|
|
2325
|
+
signalAborted: forwardedSignalInitiallyAborted,
|
|
2326
|
+
mode: request.mode,
|
|
2327
|
+
credentials: request.credentials,
|
|
2328
|
+
cache: request.cache,
|
|
2329
|
+
redirect: request.redirect,
|
|
2330
|
+
referrer: request.referrer,
|
|
2331
|
+
integrity: request.integrity
|
|
2332
|
+
};
|
|
2333
|
+
stateMap.set(requestInstanceId, requestState);
|
|
2334
|
+
if (forwardedSignal && !forwardedSignalInitiallyAborted) {
|
|
2335
|
+
onForwardedSignalAbort = () => {
|
|
2336
|
+
if (requestInstanceId == null)
|
|
2337
|
+
return;
|
|
2338
|
+
const currentState = stateMap.get(requestInstanceId);
|
|
2339
|
+
if (!currentState || currentState.signalAborted) {
|
|
2340
|
+
return;
|
|
2341
|
+
}
|
|
2342
|
+
currentState.signalAborted = true;
|
|
2343
|
+
try {
|
|
2344
|
+
requestAbortSignalRef.applyIgnored(undefined, [requestInstanceId], {
|
|
2345
|
+
arguments: { copy: true }
|
|
2346
|
+
});
|
|
2347
|
+
} catch {}
|
|
2348
|
+
};
|
|
2349
|
+
forwardedSignal.addEventListener("abort", onForwardedSignalAbort, { once: true });
|
|
2350
|
+
if (forwardedSignal.aborted) {
|
|
2351
|
+
onForwardedSignalAbort();
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
const responseInstanceId = await context.eval(`
|
|
2355
|
+
(async function() {
|
|
2356
|
+
const request = Request._fromInstanceId(${requestInstanceId});
|
|
2357
|
+
const server = new __Server__();
|
|
2358
|
+
const response = await Promise.resolve(__serveOptions__.fetch(request, server));
|
|
2359
|
+
if (response == null) {
|
|
2360
|
+
throw new TypeError("fetch handler did not return a Response object (got " + (response === null ? "null" : "undefined") + ")");
|
|
2361
|
+
}
|
|
2362
|
+
if (typeof response._getInstanceId !== 'function') {
|
|
2363
|
+
throw new TypeError("fetch handler must return a Response object (got " + (typeof response) + ")");
|
|
2364
|
+
}
|
|
2365
|
+
return response._getInstanceId();
|
|
2366
|
+
})()
|
|
2367
|
+
`, { promise: true });
|
|
2368
|
+
const responseState = stateMap.get(responseInstanceId);
|
|
2369
|
+
if (!responseState) {
|
|
2370
|
+
throw new Error("Response state not found");
|
|
2371
|
+
}
|
|
2372
|
+
if (responseState.streamId !== null) {
|
|
2373
|
+
const passthruMap = getPassthruBodiesForContext(context);
|
|
2374
|
+
const passthruBody = passthruMap.get(responseState.streamId);
|
|
2375
|
+
if (passthruBody) {
|
|
2376
|
+
passthruMap.delete(responseState.streamId);
|
|
2377
|
+
const responseHeaders2 = new Headers(responseState.headers);
|
|
2378
|
+
const status2 = responseState.status === 101 ? 200 : responseState.status;
|
|
2379
|
+
const hasNullBodyStatus2 = responseState.status === 101 || responseState.status === 103 || responseState.status === 204 || responseState.status === 205 || responseState.status === 304;
|
|
2380
|
+
const response2 = new Response(hasNullBodyStatus2 ? null : passthruBody, {
|
|
2381
|
+
status: status2,
|
|
2382
|
+
statusText: responseState.statusText,
|
|
2383
|
+
headers: responseHeaders2
|
|
2384
|
+
});
|
|
2385
|
+
response2._originalStatus = responseState.status;
|
|
2386
|
+
return response2;
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
if (responseState.streamId !== null) {
|
|
2390
|
+
const responseStreamId = responseState.streamId;
|
|
2391
|
+
let streamDone = false;
|
|
2392
|
+
const pumpedStream = new ReadableStream({
|
|
2393
|
+
async pull(controller) {
|
|
2394
|
+
if (streamDone)
|
|
2395
|
+
return;
|
|
2396
|
+
while (!streamDone) {
|
|
2397
|
+
const state = streamRegistry.get(responseStreamId);
|
|
2398
|
+
if (!state) {
|
|
2399
|
+
controller.close();
|
|
2400
|
+
streamDone = true;
|
|
2401
|
+
return;
|
|
2402
|
+
}
|
|
2403
|
+
if (state.queue.length > 0 || state.closed || state.errored) {
|
|
2404
|
+
break;
|
|
2405
|
+
}
|
|
2406
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
2407
|
+
}
|
|
2408
|
+
try {
|
|
2409
|
+
const result = await streamRegistry.pull(responseStreamId);
|
|
2410
|
+
if (result.done) {
|
|
2411
|
+
controller.close();
|
|
2412
|
+
streamDone = true;
|
|
2413
|
+
streamRegistry.delete(responseStreamId);
|
|
2414
|
+
return;
|
|
2415
|
+
}
|
|
2416
|
+
controller.enqueue(result.value);
|
|
2417
|
+
} catch (error) {
|
|
2418
|
+
controller.error(error);
|
|
2419
|
+
streamDone = true;
|
|
2420
|
+
streamRegistry.delete(responseStreamId);
|
|
2421
|
+
}
|
|
2422
|
+
},
|
|
2423
|
+
cancel() {
|
|
2424
|
+
streamDone = true;
|
|
2425
|
+
streamRegistry.cancel(responseStreamId);
|
|
2426
|
+
}
|
|
2427
|
+
});
|
|
2428
|
+
const responseHeaders2 = new Headers(responseState.headers);
|
|
2429
|
+
const status2 = responseState.status === 101 ? 200 : responseState.status;
|
|
2430
|
+
const hasNullBodyStatus2 = responseState.status === 101 || responseState.status === 103 || responseState.status === 204 || responseState.status === 205 || responseState.status === 304;
|
|
2431
|
+
if (hasNullBodyStatus2) {
|
|
2432
|
+
streamRegistry.cancel(responseStreamId);
|
|
2433
|
+
streamRegistry.delete(responseStreamId);
|
|
2434
|
+
}
|
|
2435
|
+
const response2 = new Response(hasNullBodyStatus2 ? null : pumpedStream, {
|
|
2436
|
+
status: status2,
|
|
2437
|
+
statusText: responseState.statusText,
|
|
2438
|
+
headers: responseHeaders2
|
|
2439
|
+
});
|
|
2440
|
+
response2._originalStatus = responseState.status;
|
|
2441
|
+
return response2;
|
|
2442
|
+
}
|
|
2443
|
+
const responseHeaders = new Headers(responseState.headers);
|
|
2444
|
+
const hasNullBodyStatus = responseState.status === 101 || responseState.status === 103 || responseState.status === 204 || responseState.status === 205 || responseState.status === 304;
|
|
2445
|
+
const responseBody = hasNullBodyStatus ? null : responseState.body;
|
|
2446
|
+
const status = responseState.status === 101 ? 200 : responseState.status;
|
|
2447
|
+
const response = new Response(responseBody, {
|
|
2448
|
+
status,
|
|
2449
|
+
statusText: responseState.statusText,
|
|
2450
|
+
headers: responseHeaders
|
|
2451
|
+
});
|
|
2452
|
+
response._originalStatus = responseState.status;
|
|
2453
|
+
return response;
|
|
2454
|
+
} finally {
|
|
2455
|
+
if (forwardedSignal && onForwardedSignalAbort) {
|
|
2456
|
+
forwardedSignal.removeEventListener("abort", onForwardedSignalAbort);
|
|
2457
|
+
}
|
|
2458
|
+
if (requestStreamId !== null) {
|
|
2459
|
+
const startTime = Date.now();
|
|
2460
|
+
let streamState = streamRegistry.get(requestStreamId);
|
|
2461
|
+
while (streamState && !streamState.closed && !streamState.errored && Date.now() - startTime < 100) {
|
|
2462
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2463
|
+
streamState = streamRegistry.get(requestStreamId);
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
2466
|
+
if (streamCleanup) {
|
|
2467
|
+
await streamCleanup();
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
},
|
|
2471
|
+
getUpgradeRequest() {
|
|
2472
|
+
const result = serveState.pendingUpgrade;
|
|
2473
|
+
return result;
|
|
2474
|
+
},
|
|
2475
|
+
dispatchWebSocketOpen(connectionId) {
|
|
2476
|
+
serveState.activeConnections.set(connectionId, { connectionId });
|
|
2477
|
+
const hasOpenHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.open`);
|
|
2478
|
+
context.evalSync(`
|
|
2479
|
+
(function() {
|
|
2480
|
+
const ws = new __ServerWebSocket__("${connectionId}");
|
|
2481
|
+
globalThis.__activeWs_${connectionId}__ = ws;
|
|
2482
|
+
})()
|
|
2483
|
+
`);
|
|
2484
|
+
if (hasOpenHandler) {
|
|
2485
|
+
context.evalSync(`
|
|
2486
|
+
(function() {
|
|
2487
|
+
const ws = globalThis.__activeWs_${connectionId}__;
|
|
2488
|
+
__serveOptions__.websocket.open(ws);
|
|
2489
|
+
})()
|
|
2490
|
+
`);
|
|
2491
|
+
}
|
|
2492
|
+
if (serveState.pendingUpgrade?.connectionId === connectionId) {
|
|
2493
|
+
serveState.pendingUpgrade = null;
|
|
2494
|
+
}
|
|
2495
|
+
},
|
|
2496
|
+
dispatchWebSocketMessage(connectionId, message) {
|
|
2497
|
+
if (!serveState.activeConnections.has(connectionId)) {
|
|
2498
|
+
return;
|
|
2499
|
+
}
|
|
2500
|
+
const hasMessageHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.message`);
|
|
2501
|
+
if (!hasMessageHandler) {
|
|
2502
|
+
return;
|
|
2503
|
+
}
|
|
2504
|
+
if (typeof message === "string") {
|
|
2505
|
+
context.evalSync(`
|
|
2506
|
+
(function() {
|
|
2507
|
+
const ws = globalThis.__activeWs_${connectionId}__;
|
|
2508
|
+
if (ws) __serveOptions__.websocket.message(ws, "${message.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n")}");
|
|
2509
|
+
})()
|
|
2510
|
+
`);
|
|
2511
|
+
} else {
|
|
2512
|
+
const bytes = Array.from(new Uint8Array(message));
|
|
2513
|
+
context.evalSync(`
|
|
2514
|
+
(function() {
|
|
2515
|
+
const ws = globalThis.__activeWs_${connectionId}__;
|
|
2516
|
+
if (ws) {
|
|
2517
|
+
const bytes = new Uint8Array([${bytes.join(",")}]);
|
|
2518
|
+
__serveOptions__.websocket.message(ws, bytes.buffer);
|
|
2519
|
+
}
|
|
2520
|
+
})()
|
|
2521
|
+
`);
|
|
2522
|
+
}
|
|
2523
|
+
},
|
|
2524
|
+
dispatchWebSocketClose(connectionId, code, reason) {
|
|
2525
|
+
if (!serveState.activeConnections.has(connectionId)) {
|
|
2526
|
+
return;
|
|
2527
|
+
}
|
|
2528
|
+
context.evalSync(`
|
|
2529
|
+
(function() {
|
|
2530
|
+
const ws = globalThis.__activeWs_${connectionId}__;
|
|
2531
|
+
if (ws) ws._setReadyState(3);
|
|
2532
|
+
})()
|
|
2533
|
+
`);
|
|
2534
|
+
const hasCloseHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.close`);
|
|
2535
|
+
if (hasCloseHandler) {
|
|
2536
|
+
const safeReason = reason.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
|
|
2537
|
+
context.evalSync(`
|
|
2538
|
+
(function() {
|
|
2539
|
+
const ws = globalThis.__activeWs_${connectionId}__;
|
|
2540
|
+
if (ws) __serveOptions__.websocket.close(ws, ${code}, "${safeReason}");
|
|
2541
|
+
})()
|
|
2542
|
+
`);
|
|
2543
|
+
}
|
|
2544
|
+
context.evalSync(`
|
|
2545
|
+
delete globalThis.__activeWs_${connectionId}__;
|
|
2546
|
+
globalThis.__upgradeRegistry__.delete("${connectionId}");
|
|
2547
|
+
`);
|
|
2548
|
+
serveState.activeConnections.delete(connectionId);
|
|
2549
|
+
},
|
|
2550
|
+
dispatchWebSocketError(connectionId, error) {
|
|
2551
|
+
if (!serveState.activeConnections.has(connectionId)) {
|
|
2552
|
+
return;
|
|
2553
|
+
}
|
|
2554
|
+
const hasErrorHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.error`);
|
|
2555
|
+
if (!hasErrorHandler) {
|
|
2556
|
+
return;
|
|
2557
|
+
}
|
|
2558
|
+
const safeName = error.name.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
|
|
2559
|
+
const safeMessage = error.message.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
|
|
2560
|
+
context.evalSync(`
|
|
2561
|
+
(function() {
|
|
2562
|
+
const ws = globalThis.__activeWs_${connectionId}__;
|
|
2563
|
+
if (ws) {
|
|
2564
|
+
const error = { name: "${safeName}", message: "${safeMessage}" };
|
|
2565
|
+
__serveOptions__.websocket.error(ws, error);
|
|
2566
|
+
}
|
|
2567
|
+
})()
|
|
2568
|
+
`);
|
|
2569
|
+
},
|
|
2570
|
+
onWebSocketCommand(callback) {
|
|
2571
|
+
wsCommandCallbacks.add(callback);
|
|
2572
|
+
return () => wsCommandCallbacks.delete(callback);
|
|
2573
|
+
},
|
|
2574
|
+
hasServeHandler() {
|
|
2575
|
+
return context.evalSync(`!!globalThis.__serveOptions__?.fetch`);
|
|
2576
|
+
},
|
|
2577
|
+
hasActiveConnections() {
|
|
2578
|
+
return serveState.activeConnections.size > 0;
|
|
2579
|
+
},
|
|
2580
|
+
dispatchClientWebSocketOpen(socketId, protocol, extensions) {
|
|
2581
|
+
const safeProtocol = protocol.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
|
|
2582
|
+
const safeExtensions = extensions.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
|
|
2583
|
+
context.evalSync(`
|
|
2584
|
+
__dispatchClientWebSocketEvent("${socketId}", "open", {
|
|
2585
|
+
protocol: "${safeProtocol}",
|
|
2586
|
+
extensions: "${safeExtensions}"
|
|
2587
|
+
});
|
|
2588
|
+
`);
|
|
2589
|
+
},
|
|
2590
|
+
dispatchClientWebSocketMessage(socketId, data) {
|
|
2591
|
+
if (typeof data === "string") {
|
|
2592
|
+
const safeData = data.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
|
|
2593
|
+
context.evalSync(`
|
|
2594
|
+
__dispatchClientWebSocketEvent("${socketId}", "message", { data: "${safeData}" });
|
|
2595
|
+
`);
|
|
2596
|
+
} else {
|
|
2597
|
+
const bytes = new Uint8Array(data);
|
|
2598
|
+
let binary = "";
|
|
2599
|
+
for (let i = 0;i < bytes.byteLength; i++) {
|
|
2600
|
+
binary += String.fromCharCode(bytes[i]);
|
|
2601
|
+
}
|
|
2602
|
+
const base64 = Buffer.from(binary, "binary").toString("base64");
|
|
2603
|
+
context.evalSync(`
|
|
2604
|
+
__dispatchClientWebSocketEvent("${socketId}", "message", { data: "__BINARY__${base64}" });
|
|
2605
|
+
`);
|
|
2606
|
+
}
|
|
2607
|
+
},
|
|
2608
|
+
dispatchClientWebSocketClose(socketId, code, reason, wasClean) {
|
|
2609
|
+
const safeReason = reason.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
|
|
2610
|
+
context.evalIgnored(`
|
|
2611
|
+
__dispatchClientWebSocketEvent("${socketId}", "close", {
|
|
2612
|
+
code: ${code},
|
|
2613
|
+
reason: "${safeReason}",
|
|
2614
|
+
wasClean: ${wasClean}
|
|
2615
|
+
});
|
|
2616
|
+
`);
|
|
2617
|
+
},
|
|
2618
|
+
dispatchClientWebSocketError(socketId) {
|
|
2619
|
+
context.evalIgnored(`
|
|
2620
|
+
__dispatchClientWebSocketEvent("${socketId}", "error", {});
|
|
2621
|
+
`);
|
|
2622
|
+
},
|
|
2623
|
+
onClientWebSocketCommand(callback) {
|
|
2624
|
+
clientWsCommandCallbacks.add(callback);
|
|
2625
|
+
return () => clientWsCommandCallbacks.delete(callback);
|
|
2626
|
+
},
|
|
2627
|
+
onEvent(callback) {
|
|
2628
|
+
eventCallbacks.add(callback);
|
|
2629
|
+
return () => eventCallbacks.delete(callback);
|
|
2630
|
+
},
|
|
2631
|
+
dispatchEvent(event, payload) {
|
|
2632
|
+
const json = JSON.stringify(payload);
|
|
2633
|
+
const safeEvent = JSON.stringify(event);
|
|
2634
|
+
const safeJson = JSON.stringify(json);
|
|
2635
|
+
context.evalSync(`__dispatchExternalEvent(${safeEvent}, ${safeJson});`);
|
|
2636
|
+
}
|
|
2637
|
+
};
|
|
2638
|
+
}
|
|
2639
|
+
|
|
2640
|
+
//# debugId=C7AE0924BFE61B3564756E2164756E21
|