@syntropika/tembra-sdk 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/README.md +43 -17
  2. package/dist/authoring/types.d.ts +64 -3
  3. package/dist/authoring/wit.d.ts +6 -0
  4. package/dist/bridge/commands.d.ts +1190 -0
  5. package/dist/bridge/identifiers.d.ts +2 -0
  6. package/dist/bridge/kernel.d.ts +18 -107
  7. package/dist/bridge/protocol.d.ts +3 -138
  8. package/dist/browser.d.ts +14 -1
  9. package/dist/browser.js +141 -3332
  10. package/dist/chunks/browser-b8jamxw2.js +3399 -0
  11. package/dist/chunks/execution-nsqc6nrt.js +1419 -0
  12. package/dist/chunks/index-01zk0xqx.js +160 -0
  13. package/dist/chunks/index-3fjdfdfd.js +152 -0
  14. package/dist/chunks/index-aaymjn7v.js +787 -0
  15. package/dist/chunks/index-c1w7z9hx.js +356 -0
  16. package/dist/chunks/index-h8t0n42q.js +738 -0
  17. package/dist/chunks/index-hfds9mzp.js +308 -0
  18. package/dist/chunks/index-kr4x67wt.js +177 -0
  19. package/dist/chunks/index-kr6bnh34.js +117 -0
  20. package/dist/chunks/index-kyt9dj0a.js +1421 -0
  21. package/dist/chunks/index-n1wxzc9w.js +830 -0
  22. package/dist/chunks/index-pvac426d.js +74 -0
  23. package/dist/chunks/index-smyds5ce.js +3234 -0
  24. package/dist/chunks/index-sse8aapb.js +121 -0
  25. package/dist/chunks/index-v6heph77.js +643 -0
  26. package/dist/chunks/index-xrdvnv37.js +3448 -0
  27. package/dist/chunks/index-za4mg94e.js +26 -0
  28. package/dist/chunks/index-zkqmnjj8.js +167 -0
  29. package/dist/coordinator.js +9 -500
  30. package/dist/error.d.ts +2 -0
  31. package/dist/errors.d.ts +3 -0
  32. package/dist/guest.d.ts +173 -0
  33. package/dist/guest.js +26 -0
  34. package/dist/host.d.ts +36 -30
  35. package/dist/host.js +37 -3310
  36. package/dist/http/bytes.d.ts +8 -0
  37. package/dist/http/events.d.ts +7 -0
  38. package/dist/http.d.ts +45 -0
  39. package/dist/http.js +291 -0
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.js +49 -862
  42. package/dist/infrastructure/rpc/client.d.ts +2 -1
  43. package/dist/infrastructure/rpc/resources.d.ts +28 -0
  44. package/dist/interpreter/abi.d.ts +54 -0
  45. package/dist/interpreter/acquire.d.ts +18 -0
  46. package/dist/interpreter/browser-network.d.ts +52 -0
  47. package/dist/interpreter/browser-port.d.ts +55 -0
  48. package/dist/interpreter/browser.d.ts +79 -0
  49. package/dist/interpreter/cli.d.ts +5 -0
  50. package/dist/interpreter/codec.d.ts +42 -0
  51. package/dist/interpreter/component/execution.d.ts +42 -0
  52. package/dist/interpreter/component/host.d.ts +69 -0
  53. package/dist/interpreter/component/instance.d.ts +40 -0
  54. package/dist/interpreter/component/kernel.d.ts +120 -0
  55. package/dist/interpreter/component/names.d.ts +5 -0
  56. package/dist/interpreter/component/port.d.ts +85 -0
  57. package/dist/interpreter/component/prepared.d.ts +97 -0
  58. package/dist/interpreter/component/resources.d.ts +45 -0
  59. package/dist/interpreter/component/revision.d.ts +87 -0
  60. package/dist/interpreter/component/scope.d.ts +116 -0
  61. package/dist/interpreter/component/streams.d.ts +28 -0
  62. package/dist/interpreter/component/values.d.ts +79 -0
  63. package/dist/interpreter/component/wasi-filesystem.d.ts +21 -0
  64. package/dist/interpreter/component/wasi-host.d.ts +64 -0
  65. package/dist/interpreter/component/wasi-http.d.ts +33 -0
  66. package/dist/interpreter/component/wasi-sockets.d.ts +183 -0
  67. package/dist/interpreter/component/wasi.d.ts +41 -0
  68. package/dist/interpreter/core.d.ts +64 -0
  69. package/dist/interpreter/fetch-http-provider.d.ts +17 -0
  70. package/dist/interpreter/filesystem/contract.d.ts +85 -0
  71. package/dist/interpreter/filesystem/memory.d.ts +3 -0
  72. package/dist/interpreter/filesystem/opfs.d.ts +3 -0
  73. package/dist/interpreter/filesystem/scope.d.ts +35 -0
  74. package/dist/interpreter/filesystem.d.ts +8 -0
  75. package/dist/interpreter/gate.d.ts +6 -0
  76. package/dist/interpreter/host-protocol.d.ts +100 -0
  77. package/dist/interpreter/http-ingress-fetch.d.ts +7 -0
  78. package/dist/interpreter/http-ingress.d.ts +96 -0
  79. package/dist/interpreter/http-provider.d.ts +85 -0
  80. package/dist/interpreter/io.d.ts +20 -0
  81. package/dist/interpreter/mobile.d.ts +149 -0
  82. package/dist/interpreter/native-ingress.d.ts +95 -0
  83. package/dist/interpreter/node-port.d.ts +25 -0
  84. package/dist/interpreter/node.d.ts +36 -0
  85. package/dist/interpreter/revision.d.ts +64 -0
  86. package/dist/interpreter/scope.d.ts +89 -0
  87. package/dist/interpreter/socket-addresses.d.ts +50 -0
  88. package/dist/interpreter/socket-provider.d.ts +110 -0
  89. package/dist/interpreter/standard-cli.d.ts +34 -0
  90. package/dist/interpreter/standard-codec.d.ts +96 -0
  91. package/dist/interpreter/standard-filesystem.d.ts +47 -0
  92. package/dist/interpreter/standard-host.d.ts +71 -0
  93. package/dist/interpreter/standard-http-values.d.ts +159 -0
  94. package/dist/interpreter/standard-http.d.ts +9 -0
  95. package/dist/interpreter/standard-ingress.d.ts +63 -0
  96. package/dist/interpreter/standard-sockets.d.ts +177 -0
  97. package/dist/interpreter/standard-streams.d.ts +218 -0
  98. package/dist/interpreter/standard-system.d.ts +35 -0
  99. package/dist/interpreter/standard-utf8.d.ts +4 -0
  100. package/dist/interpreter/standard.d.ts +18 -0
  101. package/dist/interpreter/types.d.ts +152 -0
  102. package/dist/interpreter/wit-shape.d.ts +92 -0
  103. package/dist/manager.js +5 -332
  104. package/dist/msgpack.js +9 -615
  105. package/dist/node.d.ts +8 -1
  106. package/dist/node.js +248 -3321
  107. package/dist/rpc.js +196 -699
  108. package/dist/runtime/adapters.d.ts +120 -0
  109. package/dist/runtime/adapters.js +38 -0
  110. package/dist/runtime/calls.d.ts +7 -6
  111. package/dist/runtime/lifecycle.d.ts +3 -1
  112. package/dist/runtime/orbs.d.ts +5 -4
  113. package/dist/runtime/references.d.ts +27 -1
  114. package/dist/runtime/reload.d.ts +5 -3
  115. package/dist/runtime/scopes.d.ts +1 -1
  116. package/dist/runtime/signals.d.ts +4 -0
  117. package/dist/runtime/wit-client.d.ts +38 -0
  118. package/dist/telemetry.js +4 -25
  119. package/dist/tooling/build.d.ts +2 -2
  120. package/dist/tooling/client-resources.d.ts +23 -0
  121. package/dist/tooling/client.d.ts +10 -0
  122. package/dist/tooling/component-glue.d.ts +17 -0
  123. package/dist/tooling/component.d.ts +11 -0
  124. package/dist/tooling/index.d.ts +3 -1
  125. package/dist/tooling/index.js +1155 -102
  126. package/dist/tooling/resolver.d.ts +4 -4
  127. package/dist/tooling/typecheck.d.ts +2 -1
  128. package/dist/tooling/types.d.ts +27 -12
  129. package/dist/tooling/wit.d.ts +9 -0
  130. package/dist/wasi/wasi-clocks-types.d.ts +2 -0
  131. package/dist/wasi/wasi-http-client.d.ts +5 -0
  132. package/dist/wasi/wasi-http-types.d.ts +285 -0
  133. package/dist/wasi/wasi-sockets-ip-name-lookup.d.ts +23 -0
  134. package/dist/wasi/wasi-sockets-types.d.ts +146 -0
  135. package/package.json +62 -35
  136. package/src/authoring/declaration.ts +1 -1
  137. package/src/authoring/types.ts +53 -3
  138. package/src/authoring/wit.ts +15 -0
  139. package/src/bridge/commands.ts +1105 -0
  140. package/src/bridge/identifiers.ts +2 -0
  141. package/src/bridge/kernel.ts +56 -98
  142. package/src/bridge/protocol.ts +3 -142
  143. package/src/browser.ts +90 -6
  144. package/src/context-key.ts +4 -7
  145. package/src/error.ts +1 -1
  146. package/src/errors.ts +7 -0
  147. package/src/guest.ts +327 -0
  148. package/src/host.ts +128 -23
  149. package/src/http/bytes.ts +87 -0
  150. package/src/http/events.ts +34 -0
  151. package/src/http.ts +272 -0
  152. package/src/index.ts +3 -0
  153. package/src/infrastructure/rpc/client.ts +136 -17
  154. package/src/infrastructure/rpc/resources.ts +123 -0
  155. package/src/interpreter/abi.ts +69 -0
  156. package/src/interpreter/acquire.ts +58 -0
  157. package/src/interpreter/browser-network.ts +170 -0
  158. package/src/interpreter/browser-port.ts +425 -0
  159. package/src/interpreter/browser.ts +340 -0
  160. package/src/interpreter/cli.ts +30 -0
  161. package/src/interpreter/codec.ts +298 -0
  162. package/src/interpreter/component/execution.ts +264 -0
  163. package/src/interpreter/component/host.ts +409 -0
  164. package/src/interpreter/component/instance.ts +138 -0
  165. package/src/interpreter/component/kernel.ts +611 -0
  166. package/src/interpreter/component/names.ts +13 -0
  167. package/src/interpreter/component/port.ts +598 -0
  168. package/src/interpreter/component/prepared.ts +194 -0
  169. package/src/interpreter/component/resources.ts +345 -0
  170. package/src/interpreter/component/revision.ts +702 -0
  171. package/src/interpreter/component/scope.ts +447 -0
  172. package/src/interpreter/component/streams.ts +180 -0
  173. package/src/interpreter/component/values.ts +254 -0
  174. package/src/interpreter/component/wasi-filesystem.ts +472 -0
  175. package/src/interpreter/component/wasi-host.ts +197 -0
  176. package/src/interpreter/component/wasi-http.ts +939 -0
  177. package/src/interpreter/component/wasi-sockets.ts +958 -0
  178. package/src/interpreter/component/wasi.ts +238 -0
  179. package/src/interpreter/core.ts +386 -0
  180. package/src/interpreter/fetch-http-provider.ts +98 -0
  181. package/src/interpreter/filesystem/contract.ts +138 -0
  182. package/src/interpreter/filesystem/memory.ts +180 -0
  183. package/src/interpreter/filesystem/opfs.ts +294 -0
  184. package/src/interpreter/filesystem/scope.ts +390 -0
  185. package/src/interpreter/filesystem.ts +20 -0
  186. package/src/interpreter/gate.ts +55 -0
  187. package/src/interpreter/host-protocol.ts +242 -0
  188. package/src/interpreter/http-ingress-fetch.ts +133 -0
  189. package/src/interpreter/http-ingress.ts +203 -0
  190. package/src/interpreter/http-provider.ts +105 -0
  191. package/src/interpreter/io.ts +66 -0
  192. package/src/interpreter/mobile.ts +385 -0
  193. package/src/interpreter/native-ingress.ts +550 -0
  194. package/src/interpreter/node-port.ts +218 -0
  195. package/src/interpreter/node.ts +114 -0
  196. package/src/interpreter/revision.ts +450 -0
  197. package/src/interpreter/scope.ts +453 -0
  198. package/src/interpreter/socket-addresses.ts +246 -0
  199. package/src/interpreter/socket-provider.ts +126 -0
  200. package/src/interpreter/standard-cli.ts +184 -0
  201. package/src/interpreter/standard-codec.ts +403 -0
  202. package/src/interpreter/standard-filesystem.ts +545 -0
  203. package/src/interpreter/standard-host.ts +840 -0
  204. package/src/interpreter/standard-http-values.ts +624 -0
  205. package/src/interpreter/standard-http.ts +622 -0
  206. package/src/interpreter/standard-ingress.ts +344 -0
  207. package/src/interpreter/standard-sockets.ts +847 -0
  208. package/src/interpreter/standard-streams.ts +710 -0
  209. package/src/interpreter/standard-system.ts +182 -0
  210. package/src/interpreter/standard-utf8.ts +72 -0
  211. package/src/interpreter/standard.ts +283 -0
  212. package/src/interpreter/types.ts +163 -0
  213. package/src/interpreter/wit-shape.ts +175 -0
  214. package/src/node.ts +43 -14
  215. package/src/runtime/activities.ts +6 -6
  216. package/src/runtime/adapters.ts +314 -0
  217. package/src/runtime/calls.ts +213 -90
  218. package/src/runtime/context.ts +7 -7
  219. package/src/runtime/lifecycle.ts +36 -17
  220. package/src/runtime/orbs.ts +81 -39
  221. package/src/runtime/programs.ts +16 -8
  222. package/src/runtime/references.ts +128 -11
  223. package/src/runtime/reload.ts +71 -30
  224. package/src/runtime/resources.ts +2 -2
  225. package/src/runtime/scopes.ts +17 -17
  226. package/src/runtime/session.ts +3 -1
  227. package/src/runtime/signals.ts +31 -0
  228. package/src/runtime/wit-client.ts +228 -0
  229. package/src/tooling/build.ts +152 -54
  230. package/src/tooling/client-resources.ts +74 -0
  231. package/src/tooling/client.ts +531 -0
  232. package/src/tooling/component-glue.ts +288 -0
  233. package/src/tooling/component.ts +225 -0
  234. package/src/tooling/index.ts +3 -7
  235. package/src/tooling/resolver.ts +42 -25
  236. package/src/tooling/typecheck.ts +59 -4
  237. package/src/tooling/types.ts +27 -12
  238. package/src/tooling/wit.ts +188 -0
  239. package/dist/embedded.d.ts +0 -1
  240. package/dist/embedded.js +0 -1
  241. package/src/embedded.ts +0 -301
@@ -0,0 +1,3399 @@
1
+ import"./index-c1w7z9hx.js";
2
+ import {
3
+ reply,
4
+ combinedSignal
5
+ } from "./index-kyt9dj0a.js";
6
+ import {
7
+ decodeHostRequest,
8
+ decodeAsyncHostRequest,
9
+ exportedFunctions,
10
+ Revision
11
+ } from "./index-xrdvnv37.js";
12
+ import {
13
+ HttpHandlerError2,
14
+ CONNECTION_TERMINATED,
15
+ HttpProviderError2,
16
+ query,
17
+ TYPES,
18
+ RESOURCES,
19
+ METHODS,
20
+ WRITABLE_FUTURES,
21
+ STANDARD_PACKET,
22
+ CALL,
23
+ STREAM_READ,
24
+ FUTURE_READ,
25
+ DROP,
26
+ STREAM_NEW,
27
+ STREAM_WRITE,
28
+ WRITE_ACCEPTED,
29
+ WRITE_CLOSED,
30
+ FUTURE_NEW,
31
+ FUTURE_WRITE,
32
+ INGRESS_HEAD,
33
+ STREAM_IMPORT,
34
+ STREAM_CHUNK,
35
+ Writer,
36
+ Reader,
37
+ encode2,
38
+ decode
39
+ } from "./index-h8t0n42q.js";
40
+ import {
41
+ fromWit,
42
+ toWit,
43
+ key,
44
+ unspecified,
45
+ isUnicast,
46
+ isRemote,
47
+ hasFamily,
48
+ checkedIpAddress,
49
+ parseHostName,
50
+ ok,
51
+ err,
52
+ internal,
53
+ done,
54
+ digits,
55
+ HttpFields,
56
+ HttpRequestOptions,
57
+ HttpRequest,
58
+ HttpResponse
59
+ } from "./index-v6heph77.js";
60
+ import"./index-kr4x67wt.js";
61
+ import"./index-zkqmnjj8.js";
62
+ import {
63
+ preparedRegistry,
64
+ FilesystemError2,
65
+ SocketProviderError2,
66
+ NameLookupError2
67
+ } from "./index-n1wxzc9w.js";
68
+ import {
69
+ BrowserCapabilities,
70
+ methodKey,
71
+ bindResource,
72
+ cancelled,
73
+ abortable,
74
+ HostFuture,
75
+ WritableFuture,
76
+ OutputStream,
77
+ InputBudget,
78
+ InputStream,
79
+ checkedClocks,
80
+ revisionRandom,
81
+ browserClocks,
82
+ browserRandom,
83
+ systemMethods
84
+ } from "./index-aaymjn7v.js";
85
+
86
+ // src/interpreter/abi.ts
87
+ var IMPORT_MODULE = "tembra-interpreter-v13-d82248b7b421e5294c2536726adcbbe2c178bc87142fc7ee04faf691081c101b";
88
+ var SYNC_IMPORT = "sync";
89
+ var SYNC_READ_IMPORT = "sync_read";
90
+ var MEMORY_MODULE = "env";
91
+ var MEMORY_IMPORT = "memory";
92
+ var INITIALIZE_EXPORT = "_initialize";
93
+ var ALLOC_EXPORT = "tembra_alloc";
94
+ var CALL_EXPORT = "tembra_call";
95
+ var WASI_MODULE = "wasi_snapshot_preview1";
96
+ var SYNC_ERROR = 2147483648;
97
+ var STANDARD_PACKET2 = 0;
98
+ var MEMORY_INITIAL_PAGES = 32;
99
+ var PAGE_BYTES = 65536;
100
+ var LENGTH_LIMIT = 2147483647;
101
+ var EFFECT_LIMIT = 128;
102
+ var REPLY_HEADER_BYTES = 20;
103
+ var EFFECT_RECORD_BYTES = 12;
104
+ var COMPLETION_HEADER_BYTES = 4;
105
+ var COMPLETION_RECORD_BYTES = 16;
106
+ var ERRNO_SUCCESS = 0;
107
+ var ERRNO_BADF = 8;
108
+ var ERRNO_FAULT = 21;
109
+ var ERRNO_INVAL = 28;
110
+ var ERRNO_NOTDIR = 54;
111
+ var ERRNO_SPIPE = 70;
112
+ var CLOCK_REALTIME = 0;
113
+ var CLOCK_MONOTONIC = 1;
114
+ var FILETYPE_CHARACTER_DEVICE = 2;
115
+ var RIGHT_FD_WRITE = 64;
116
+ var FDSTAT_BYTES = 24;
117
+ var STDIO_LIMIT = 4096;
118
+ var WASI_IMPORTS = Object.freeze([
119
+ "clock_time_get",
120
+ "environ_get",
121
+ "environ_sizes_get",
122
+ "fd_close",
123
+ "fd_fdstat_get",
124
+ "fd_prestat_dir_name",
125
+ "fd_prestat_get",
126
+ "fd_seek",
127
+ "fd_write",
128
+ "path_open",
129
+ "proc_exit"
130
+ ]);
131
+ var Operation = Object.freeze({
132
+ Load: 0,
133
+ Declare: 1,
134
+ Start: 2,
135
+ Resume: 3,
136
+ Cancel: 4,
137
+ Capture: 5
138
+ });
139
+ var ReplyKind = Object.freeze({
140
+ Pending: 0,
141
+ Ok: 1,
142
+ Error: 2
143
+ });
144
+ var Status = Object.freeze({
145
+ Ok: 0,
146
+ Error: 1
147
+ });
148
+
149
+ // src/interpreter/core.ts
150
+ class GuestTrap extends Error {
151
+ }
152
+ var encoder = new TextEncoder;
153
+ var decoder = new TextDecoder("utf-8", { fatal: true });
154
+ function checkInterpreter(module) {
155
+ for (const { module: namespace, name, kind } of WebAssembly.Module.imports(module)) {
156
+ const allowed = kind === "memory" ? namespace === MEMORY_MODULE && name === MEMORY_IMPORT : kind === "function" && (namespace === IMPORT_MODULE && (name === SYNC_IMPORT || name === SYNC_READ_IMPORT) || namespace === WASI_MODULE && WASI_IMPORTS.includes(name));
157
+ if (!allowed)
158
+ throw new Error(`Interpreter import ${namespace}::${name} is not allowed`);
159
+ }
160
+ const exports = new Map(WebAssembly.Module.exports(module).map((entry) => [entry.name, entry.kind]));
161
+ for (const name of [INITIALIZE_EXPORT, ALLOC_EXPORT, CALL_EXPORT])
162
+ if (exports.get(name) !== "function")
163
+ throw new Error(`Interpreter export ${name} is missing`);
164
+ }
165
+ var field = (view, offset) => view.getUint32(offset, true);
166
+
167
+ class CoreGuest {
168
+ memory;
169
+ host;
170
+ #trapped = false;
171
+ #reply;
172
+ #alloc;
173
+ #call;
174
+ constructor(memory, host) {
175
+ this.memory = memory;
176
+ this.host = host;
177
+ }
178
+ static async create(module, memoryBytes, host) {
179
+ const maximum = Math.floor(memoryBytes / PAGE_BYTES);
180
+ if (!Number.isSafeInteger(memoryBytes) || maximum < MEMORY_INITIAL_PAGES || maximum > 65536)
181
+ throw new Error("Invalid interpreter memory bound");
182
+ const memory = new WebAssembly.Memory({ initial: MEMORY_INITIAL_PAGES, maximum });
183
+ const guest = new CoreGuest(memory, host);
184
+ const instance = await WebAssembly.instantiate(module, {
185
+ [MEMORY_MODULE]: { [MEMORY_IMPORT]: memory },
186
+ [IMPORT_MODULE]: {
187
+ [SYNC_IMPORT]: (pointer, length) => guest.#sync(pointer, length),
188
+ [SYNC_READ_IMPORT]: (pointer, length) => guest.#read(pointer, length)
189
+ },
190
+ [WASI_MODULE]: wasi(memory, host)
191
+ });
192
+ const exports = instance.exports;
193
+ guest.#alloc = exports[ALLOC_EXPORT];
194
+ guest.#call = exports[CALL_EXPORT];
195
+ guest.#enter(() => exports[INITIALIZE_EXPORT]());
196
+ return guest;
197
+ }
198
+ get trapped() {
199
+ return this.#trapped;
200
+ }
201
+ #range(pointer, length) {
202
+ const start = pointer >>> 0;
203
+ const buffer = this.memory.buffer;
204
+ if (start + length > buffer.byteLength)
205
+ throw new Error("Interpreter range is outside memory");
206
+ return new Uint8Array(buffer, start, length);
207
+ }
208
+ #sync(pointer, length) {
209
+ if (this.#reply)
210
+ throw new Error("Synchronous reply was not read");
211
+ const range = this.#range(pointer, length >>> 0);
212
+ const binary = range.byteLength > 0 && range[0] === STANDARD_PACKET2;
213
+ let ok = true, value;
214
+ try {
215
+ value = binary ? this.host.sync(range.slice()) : this.host.sync(decoder.decode(range));
216
+ if (binary !== value instanceof Uint8Array)
217
+ throw new Error("Host reply has the wrong kind");
218
+ } catch (error) {
219
+ if (error instanceof GuestTrap)
220
+ throw error;
221
+ ok = false;
222
+ value = error instanceof Error ? error.message : String(error);
223
+ }
224
+ const bytes = typeof value === "string" ? encoder.encode(value) : value;
225
+ if (bytes.byteLength > LENGTH_LIMIT)
226
+ throw new Error("Host reply exceeds the ABI limit");
227
+ this.#reply = bytes;
228
+ return (ok ? 0 : SYNC_ERROR) + bytes.byteLength;
229
+ }
230
+ #read(pointer, length) {
231
+ const reply = this.#reply;
232
+ this.#reply = undefined;
233
+ if (!reply || reply.byteLength !== length >>> 0)
234
+ throw new Error("Synchronous reply read does not match");
235
+ this.#range(pointer, reply.byteLength).set(reply);
236
+ }
237
+ #enter(operation) {
238
+ if (this.#trapped)
239
+ throw new Error("Interpreter instance is trapped");
240
+ try {
241
+ return operation();
242
+ } catch (error) {
243
+ this.#trapped = true;
244
+ throw error;
245
+ }
246
+ }
247
+ #invoke(operation, input) {
248
+ return this.#enter(() => {
249
+ let pointer = 0, length = 0;
250
+ if (input) {
251
+ length = input.byteLength;
252
+ if (length > LENGTH_LIMIT)
253
+ throw new Error("Interpreter input exceeds the ABI limit");
254
+ pointer = this.#alloc(length) >>> 0;
255
+ if (pointer === 0)
256
+ throw new Error("Interpreter input reservation was refused");
257
+ this.#range(pointer, length).set(input);
258
+ }
259
+ const reply = this.#call(operation, pointer, length) >>> 0;
260
+ const buffer = this.memory.buffer;
261
+ if (reply + REPLY_HEADER_BYTES > buffer.byteLength)
262
+ throw new Error("Interpreter reply is outside memory");
263
+ const total = new DataView(buffer, reply, 4).getUint32(0, true);
264
+ if (total < REPLY_HEADER_BYTES || reply + total > buffer.byteLength)
265
+ throw new Error("Interpreter reply is outside memory");
266
+ return new DataView(buffer, reply, total);
267
+ });
268
+ }
269
+ #progress(view, text = true) {
270
+ return this.#enter(() => {
271
+ const kind = field(view, 4), interrupted = field(view, 8), count = field(view, 12);
272
+ if (kind > ReplyKind.Error || interrupted > 1)
273
+ throw new Error("Invalid interpreter reply");
274
+ if (count > EFFECT_LIMIT || kind !== ReplyKind.Pending && count !== 0)
275
+ throw new Error("Invalid interpreter effect count");
276
+ let offset = REPLY_HEADER_BYTES + count * EFFECT_RECORD_BYTES;
277
+ if (offset > view.byteLength)
278
+ throw new Error("Invalid interpreter reply");
279
+ const body = (length) => {
280
+ if (offset + length > view.byteLength)
281
+ throw new Error("Invalid interpreter reply");
282
+ const bytes = new Uint8Array(view.buffer, view.byteOffset + offset, length);
283
+ offset += length;
284
+ return bytes;
285
+ };
286
+ const value = body(field(view, 16));
287
+ const effects = [];
288
+ for (let index = 0;index < count; index++) {
289
+ const record = REPLY_HEADER_BYTES + index * EFFECT_RECORD_BYTES;
290
+ const low = field(view, record), high = field(view, record + 4);
291
+ const id = high * 2 ** 32 + low;
292
+ if (id === 0 || high >= 2 ** 21)
293
+ throw new Error("Invalid interpreter effect identity");
294
+ const packet = body(field(view, record + 8));
295
+ effects.push({
296
+ id,
297
+ packet: packet[0] === STANDARD_PACKET2 && packet.byteLength > 0 ? packet.slice() : decoder.decode(packet)
298
+ });
299
+ }
300
+ if (offset !== view.byteLength)
301
+ throw new Error("Interpreter reply has trailing bytes");
302
+ if (kind === ReplyKind.Pending)
303
+ return { effects };
304
+ const outcome = {
305
+ ok: kind === ReplyKind.Ok,
306
+ value: text || kind !== ReplyKind.Ok ? decoder.decode(value) : "",
307
+ interrupted: interrupted === 1
308
+ };
309
+ return { outcome, effects, bytes: text ? undefined : value.slice() };
310
+ });
311
+ }
312
+ #outcome(operation, input) {
313
+ const progress = this.#progress(this.#invoke(operation, input === undefined ? undefined : encoder.encode(input)));
314
+ if (!progress.outcome) {
315
+ this.#trapped = true;
316
+ throw new Error("Interpreter operation cannot return effects");
317
+ }
318
+ return progress.outcome;
319
+ }
320
+ load(packet) {
321
+ return this.#outcome(Operation.Load, packet);
322
+ }
323
+ declare(packet) {
324
+ return this.#outcome(Operation.Declare, packet);
325
+ }
326
+ start(packet) {
327
+ return this.#progress(this.#invoke(Operation.Start, encoder.encode(packet)));
328
+ }
329
+ resume(completed) {
330
+ if (!completed.length || completed.length > EFFECT_LIMIT)
331
+ throw new Error("Invalid completion batch");
332
+ const values = completed.map(({ value }) => typeof value === "string" ? encoder.encode(value) : value);
333
+ const records = COMPLETION_HEADER_BYTES + completed.length * COMPLETION_RECORD_BYTES;
334
+ const batch = new Uint8Array(values.reduce((total, value) => total + value.byteLength, records));
335
+ const view = new DataView(batch.buffer);
336
+ view.setUint32(0, completed.length, true);
337
+ let offset = records;
338
+ completed.forEach((completion, index) => {
339
+ const { id } = completion;
340
+ if (!Number.isSafeInteger(id) || id < 1)
341
+ throw new Error("Invalid effect identity");
342
+ const record = COMPLETION_HEADER_BYTES + index * COMPLETION_RECORD_BYTES;
343
+ view.setUint32(record, id % 2 ** 32, true);
344
+ view.setUint32(record + 4, Math.floor(id / 2 ** 32), true);
345
+ view.setUint32(record + 8, completion.ok ? Status.Ok : Status.Error, true);
346
+ view.setUint32(record + 12, values[index].byteLength, true);
347
+ batch.set(values[index], offset);
348
+ offset += values[index].byteLength;
349
+ });
350
+ return this.#progress(this.#invoke(Operation.Resume, batch));
351
+ }
352
+ cancel() {
353
+ return this.#outcome(Operation.Cancel);
354
+ }
355
+ capture() {
356
+ const progress = this.#progress(this.#invoke(Operation.Capture), false);
357
+ if (!progress.outcome?.ok)
358
+ throw new Error(progress.outcome?.value ?? "Capture failed");
359
+ return progress.bytes;
360
+ }
361
+ }
362
+ function wasi(memory, host) {
363
+ const open = [true, true, true];
364
+ const isOpen = (descriptor) => open[descriptor] === true;
365
+ const view = () => new DataView(memory.buffer);
366
+ const fits = (pointer, length) => (pointer >>> 0) + length <= memory.buffer.byteLength;
367
+ return {
368
+ clock_time_get(clock, _precision, out) {
369
+ if (clock !== CLOCK_REALTIME && clock !== CLOCK_MONOTONIC)
370
+ return ERRNO_INVAL;
371
+ if (!fits(out, 8))
372
+ return ERRNO_FAULT;
373
+ const nanoseconds = host.clock?.(clock) ?? 0n;
374
+ const maximum = (1n << 64n) - 1n;
375
+ view().setBigUint64(out >>> 0, nanoseconds < 0n ? 0n : nanoseconds > maximum ? maximum : nanoseconds, true);
376
+ return ERRNO_SUCCESS;
377
+ },
378
+ environ_get: () => ERRNO_SUCCESS,
379
+ environ_sizes_get(count, size) {
380
+ if (!fits(count, 4) || !fits(size, 4))
381
+ return ERRNO_FAULT;
382
+ view().setUint32(count >>> 0, 0, true);
383
+ view().setUint32(size >>> 0, 0, true);
384
+ return ERRNO_SUCCESS;
385
+ },
386
+ fd_close(descriptor) {
387
+ if (!isOpen(descriptor))
388
+ return ERRNO_BADF;
389
+ open[descriptor] = false;
390
+ return ERRNO_SUCCESS;
391
+ },
392
+ fd_fdstat_get(descriptor, out) {
393
+ if (!isOpen(descriptor))
394
+ return ERRNO_BADF;
395
+ if (!fits(out, FDSTAT_BYTES))
396
+ return ERRNO_FAULT;
397
+ new Uint8Array(memory.buffer, out >>> 0, FDSTAT_BYTES).fill(0);
398
+ const stat = view();
399
+ stat.setUint8(out >>> 0, FILETYPE_CHARACTER_DEVICE);
400
+ stat.setUint32((out >>> 0) + 8, descriptor === 0 ? 0 : RIGHT_FD_WRITE, true);
401
+ return ERRNO_SUCCESS;
402
+ },
403
+ fd_prestat_get: () => ERRNO_BADF,
404
+ fd_prestat_dir_name: () => ERRNO_BADF,
405
+ fd_seek: (descriptor) => isOpen(descriptor) ? ERRNO_SPIPE : ERRNO_BADF,
406
+ path_open: (descriptor) => isOpen(descriptor) ? ERRNO_NOTDIR : ERRNO_BADF,
407
+ fd_write(descriptor, vectors, count, written) {
408
+ const level = descriptor === 1 ? "log" : descriptor === 2 ? "error" : undefined;
409
+ if (!level || !isOpen(descriptor))
410
+ return ERRNO_BADF;
411
+ if (!fits(vectors, (count >>> 0) * 8))
412
+ return ERRNO_FAULT;
413
+ const table = view();
414
+ const kept = new Uint8Array(STDIO_LIMIT);
415
+ let total = 0, size = 0;
416
+ for (let index = 0;index < count >>> 0; index++) {
417
+ const pointer = table.getUint32((vectors >>> 0) + index * 8, true);
418
+ const length = table.getUint32((vectors >>> 0) + index * 8 + 4, true);
419
+ if (!fits(pointer, length))
420
+ return ERRNO_FAULT;
421
+ total += length;
422
+ if (total > 4294967295)
423
+ return ERRNO_INVAL;
424
+ const room = Math.min(length, STDIO_LIMIT - size);
425
+ kept.set(new Uint8Array(memory.buffer, pointer >>> 0, room), size);
426
+ size += room;
427
+ }
428
+ if (!fits(written, 4))
429
+ return ERRNO_FAULT;
430
+ view().setUint32(written >>> 0, total, true);
431
+ const text = new TextDecoder().decode(kept.subarray(0, size)).replace(/\n+$/, "");
432
+ if (text)
433
+ host.log(level, text);
434
+ return ERRNO_SUCCESS;
435
+ },
436
+ proc_exit(code) {
437
+ throw new Error(`Interpreter exited with status ${code}`);
438
+ }
439
+ };
440
+ }
441
+
442
+ // src/interpreter/browser-port.ts
443
+ var REFUSAL = '{"operation":"refusal"}';
444
+ var REFUSED = '{"operation":"refused",';
445
+
446
+ class Refusals {
447
+ static KEPT = 64;
448
+ #requests = new Map;
449
+ #effects = new Map;
450
+ #sequence = 0;
451
+ #last;
452
+ named;
453
+ static #keep(refusals, id, error) {
454
+ refusals.set(id, error);
455
+ if (refusals.size > Refusals.KEPT)
456
+ refusals.delete(refusals.keys().next().value);
457
+ }
458
+ sync(error) {
459
+ const id = ++this.#sequence;
460
+ Refusals.#keep(this.#requests, id, error);
461
+ this.#last = id;
462
+ }
463
+ forget() {
464
+ this.#last = undefined;
465
+ }
466
+ effect(id, error) {
467
+ Refusals.#keep(this.#effects, id, error);
468
+ }
469
+ question() {
470
+ const last = this.#last;
471
+ this.#last = undefined;
472
+ return last === undefined ? "null" : String(last);
473
+ }
474
+ name(packet) {
475
+ let named = {};
476
+ try {
477
+ named = JSON.parse(packet);
478
+ } catch {}
479
+ const [refusals, id] = typeof named.effect === "number" && named.request === undefined ? [this.#effects, named.effect] : typeof named.request === "number" && named.effect === undefined ? [this.#requests, named.request] : [undefined, undefined];
480
+ this.named = refusals && id !== undefined && refusals.has(id) ? { error: refusals.get(id) } : undefined;
481
+ }
482
+ }
483
+
484
+ class BrowserPort {
485
+ timeout;
486
+ dispose;
487
+ log;
488
+ packetBytes;
489
+ guest;
490
+ standard;
491
+ #description = "";
492
+ #scope;
493
+ #running = false;
494
+ #closed = false;
495
+ #poisoned = false;
496
+ #refusals = new Refusals;
497
+ constructor(timeout, dispose, log, packetBytes = 8 << 20) {
498
+ this.timeout = timeout;
499
+ this.dispose = dispose;
500
+ this.log = log;
501
+ this.packetBytes = packetBytes;
502
+ }
503
+ bounded(packet) {
504
+ if (packet.length > this.packetBytes || packet.length > Math.floor(this.packetBytes / 3) && new TextEncoder().encode(packet).byteLength > this.packetBytes)
505
+ throw new Error("Interpreter packet exceeds its configured bound");
506
+ return packet;
507
+ }
508
+ boundedBytes(packet) {
509
+ if (packet.byteLength > this.packetBytes)
510
+ throw new Error("Interpreter packet exceeds its configured bound");
511
+ return packet;
512
+ }
513
+ sync(packet) {
514
+ if (packet instanceof Uint8Array) {
515
+ this.#refusals.forget();
516
+ if (!this.#scope || !this.standard)
517
+ throw "No active host scope";
518
+ try {
519
+ if (packet[1] !== DROP)
520
+ this.#scope.check();
521
+ return this.boundedBytes(this.standard.sync(this.boundedBytes(packet)));
522
+ } catch (error) {
523
+ if (error instanceof GuestTrap)
524
+ throw error;
525
+ throw error instanceof Error ? error.message : String(error);
526
+ }
527
+ }
528
+ if (packet === REFUSAL)
529
+ return this.#refusals.question();
530
+ if (packet.startsWith(REFUSED)) {
531
+ this.#refusals.name(packet);
532
+ return "null";
533
+ }
534
+ this.#refusals.forget();
535
+ try {
536
+ const request = decodeHostRequest(this.bounded(packet));
537
+ if (request.operation === "console") {
538
+ this.log(request);
539
+ return "null";
540
+ }
541
+ if (!this.#scope)
542
+ throw new Error("No active host scope");
543
+ let value;
544
+ try {
545
+ value = this.#scope.sync(request);
546
+ } catch (error) {
547
+ this.#refusals.sync(error);
548
+ throw error;
549
+ }
550
+ return this.bounded(reply(value));
551
+ } catch (error) {
552
+ throw error instanceof Error ? error.message : String(error);
553
+ }
554
+ }
555
+ value(outcome) {
556
+ return JSON.parse(this.text(outcome));
557
+ }
558
+ text(outcome) {
559
+ this.#poisoned ||= outcome.interrupted;
560
+ this.bounded(outcome.value);
561
+ if (!outcome.ok)
562
+ throw this.#refusals.named ? this.#refusals.named.error : new Error(outcome.value);
563
+ return outcome.value;
564
+ }
565
+ guard(operation) {
566
+ try {
567
+ return operation();
568
+ } catch (error) {
569
+ this.#poisoned = true;
570
+ throw error;
571
+ }
572
+ }
573
+ enter(scope) {
574
+ if (this.#closed || this.#poisoned || this.#running)
575
+ throw new Error("Interpreter is closed or busy");
576
+ this.#running = true;
577
+ this.#scope = scope;
578
+ this.#refusals = new Refusals;
579
+ }
580
+ async load(packet) {
581
+ this.enter();
582
+ try {
583
+ const input = this.bounded(packet);
584
+ const outcome = this.guard(() => this.guest.load(input));
585
+ this.#description = this.bounded(outcome.value);
586
+ this.value(outcome);
587
+ } finally {
588
+ this.#running = false;
589
+ }
590
+ }
591
+ description() {
592
+ return this.#description;
593
+ }
594
+ async declare(packet, scope) {
595
+ this.enter(scope);
596
+ try {
597
+ const input = this.bounded(packet);
598
+ return this.value(this.guard(() => this.guest.declare(input)));
599
+ } finally {
600
+ this.#scope = undefined;
601
+ this.#running = false;
602
+ }
603
+ }
604
+ async ingress(dispatch, exchange, scope) {
605
+ if (this.#closed || this.#poisoned || this.#running)
606
+ throw new Error("Interpreter is closed or busy");
607
+ if (!this.standard)
608
+ throw new Error("No standard WASI host");
609
+ const request = this.standard.beginIngress(exchange);
610
+ let failure = new Error("the HTTP handler callback ended");
611
+ try {
612
+ await this.execute(JSON.stringify({ kind: "ingress", ...dispatch, request }), scope);
613
+ } catch (error) {
614
+ failure = error;
615
+ throw error;
616
+ } finally {
617
+ this.standard.endIngress(failure);
618
+ }
619
+ }
620
+ async execute(packet, scope) {
621
+ this.enter(scope);
622
+ const refusals = this.#refusals;
623
+ const pending = new Map;
624
+ const ready = [];
625
+ let wake;
626
+ let finished = false;
627
+ let rejectDeadline;
628
+ const deadline = new Promise((_, reject) => {
629
+ rejectDeadline = reject;
630
+ });
631
+ deadline.catch(() => {});
632
+ const ended = new AbortController;
633
+ const signal = scope.signal ? combinedSignal(scope.signal, ended.signal) : ended.signal;
634
+ let timeout;
635
+ const expired = () => {
636
+ if (!timeout) {
637
+ timeout = new Error("Interpreter callback exceeded its wall time limit");
638
+ this.#poisoned = true;
639
+ ended.abort();
640
+ scope.cancel();
641
+ }
642
+ return timeout;
643
+ };
644
+ const started = performance.now();
645
+ const timer = setTimeout(() => rejectDeadline(expired()), this.timeout);
646
+ const step = (operation) => {
647
+ let outcome;
648
+ try {
649
+ outcome = { value: this.guard(operation) };
650
+ } catch (error) {
651
+ outcome = { error };
652
+ }
653
+ if (performance.now() - started > this.timeout)
654
+ throw expired();
655
+ if ("error" in outcome)
656
+ throw outcome.error;
657
+ return outcome.value;
658
+ };
659
+ try {
660
+ const input = this.bounded(packet);
661
+ let progress = step(() => this.guest.start(input));
662
+ while (!progress.outcome) {
663
+ if (timeout)
664
+ throw timeout;
665
+ for (const effect of progress.effects) {
666
+ if (pending.size >= 128 || pending.has(effect.id))
667
+ throw new Error("Invalid interpreter effect queue");
668
+ const packet = effect.packet;
669
+ let issued;
670
+ let reads;
671
+ const completed = (typeof packet === "string" ? Promise.resolve().then(() => decodeAsyncHostRequest(this.bounded(packet))).then((request) => scope.async(request).catch((error) => {
672
+ refusals.effect(effect.id, error);
673
+ throw error;
674
+ })).then((value) => this.bounded(reply(value))) : Promise.resolve().then(async () => {
675
+ if (!this.standard)
676
+ throw new Error("No standard WASI host");
677
+ scope.check();
678
+ const delivery = await this.standard.async(this.boundedBytes(packet), signal);
679
+ issued = delivery.issued;
680
+ reads = delivery.reads;
681
+ return this.boundedBytes(delivery.bytes);
682
+ })).then((value) => ({ id: effect.id, ok: true, value, issued, reads })).catch((error) => ({
683
+ id: effect.id,
684
+ ok: false,
685
+ issued,
686
+ reads,
687
+ value: typeof packet !== "string" && error instanceof Error ? error.message : String(error)
688
+ })).then((response) => {
689
+ ready.push(response);
690
+ wake?.();
691
+ return response;
692
+ });
693
+ pending.set(effect.id, completed);
694
+ }
695
+ if (!ready.length)
696
+ await Promise.race([
697
+ new Promise((resolve) => {
698
+ wake = resolve;
699
+ }),
700
+ deadline
701
+ ]);
702
+ wake = undefined;
703
+ const completed = ready.splice(0);
704
+ for (const response of completed) {
705
+ pending.delete(response.id);
706
+ if (!response.ok)
707
+ this.standard?.discard({ issued: response.issued ?? [], reads: response.reads });
708
+ }
709
+ progress = step(() => this.guest.resume(completed));
710
+ }
711
+ finished = true;
712
+ if (timeout)
713
+ throw timeout;
714
+ return this.text(progress.outcome);
715
+ } finally {
716
+ clearTimeout(timer);
717
+ ended.abort();
718
+ scope.cancel();
719
+ if (!finished) {
720
+ this.#poisoned = true;
721
+ try {
722
+ this.guest.cancel();
723
+ } catch {}
724
+ }
725
+ this.#scope = undefined;
726
+ await Promise.allSettled(pending.values());
727
+ for (const delivery of ready)
728
+ this.standard?.discard({ issued: delivery.issued ?? [], reads: delivery.reads });
729
+ this.standard?.endCallback();
730
+ await this.standard?.settled();
731
+ this.#running = false;
732
+ }
733
+ }
734
+ async release(environment) {
735
+ if (this.#closed || this.#poisoned)
736
+ return;
737
+ await this.execute(JSON.stringify({ kind: "release", environment }), {
738
+ check() {},
739
+ cancel() {},
740
+ deliver(_request, value, publish) {
741
+ publish(value);
742
+ },
743
+ sync() {
744
+ throw new Error("Release has no host scope");
745
+ },
746
+ async() {
747
+ return Promise.reject(new Error("Release has no host scope"));
748
+ }
749
+ });
750
+ }
751
+ async close() {
752
+ if (this.#running)
753
+ throw new Error("Guest still owns physical work");
754
+ if (this.#closed)
755
+ return;
756
+ this.#closed = true;
757
+ this.guest = undefined;
758
+ const standard = this.standard;
759
+ this.standard = undefined;
760
+ try {
761
+ await standard?.dispose();
762
+ } finally {
763
+ await this.dispose();
764
+ }
765
+ }
766
+ }
767
+
768
+ // src/interpreter/standard-filesystem.ts
769
+ var TYPES2 = "wasi:filesystem/types@0.3.0";
770
+ var PREOPENS = "wasi:filesystem/preopens@0.3.0";
771
+ var U64 = (1n << 64n) - 1n;
772
+ var ok2 = (val) => ({ tag: "ok", val });
773
+ var err2 = (code) => ({ tag: "err", val: { tag: code } });
774
+
775
+ class HostDescriptor {
776
+ host;
777
+ provider;
778
+ flags;
779
+ borrows = 0;
780
+ #users = 1;
781
+ constructor(host, provider, flags) {
782
+ this.host = host;
783
+ this.provider = provider;
784
+ this.flags = flags;
785
+ }
786
+ get file() {
787
+ return this.provider.type === "file" ? this.provider : undefined;
788
+ }
789
+ get directory() {
790
+ return this.provider.type === "directory" ? this.provider : undefined;
791
+ }
792
+ get mutable() {
793
+ return this.provider.type === "directory" && this.flags.mutateDirectory;
794
+ }
795
+ retain() {
796
+ this.#users++;
797
+ }
798
+ release() {
799
+ if (--this.#users === 0)
800
+ closeProvider(this.host, this.provider);
801
+ }
802
+ }
803
+ function closeProvider(host, descriptor) {
804
+ host.cleanup(() => descriptor.close());
805
+ }
806
+ function code(error) {
807
+ return error instanceof FilesystemError2 ? error.code : "io";
808
+ }
809
+ function failed(call, error) {
810
+ if (call.signal?.aborted)
811
+ throw cancelled();
812
+ return err2(code(error));
813
+ }
814
+ function provider(call, operation, orphan) {
815
+ const work = call.host.physical(call.signal, operation);
816
+ if (orphan)
817
+ work.then((value) => {
818
+ if (call.signal?.aborted)
819
+ orphan(value);
820
+ }, () => {});
821
+ return abortable(work, call.signal);
822
+ }
823
+ function refusal(path) {
824
+ if (path.includes("\x00"))
825
+ return "invalid";
826
+ if (path.startsWith("/"))
827
+ return "not-permitted";
828
+ let depth = 0;
829
+ for (const part of path.split("/")) {
830
+ if (part === "" || part === ".")
831
+ continue;
832
+ if (part !== "..")
833
+ depth++;
834
+ else if (--depth < 0)
835
+ return "not-permitted";
836
+ }
837
+ return;
838
+ }
839
+ function instant(milliseconds) {
840
+ if (milliseconds === undefined || !Number.isFinite(milliseconds))
841
+ return;
842
+ const whole = Math.floor(milliseconds);
843
+ const seconds = Math.floor(whole / 1000);
844
+ return { seconds: BigInt(seconds), nanoseconds: (whole - seconds * 1000) * 1e6 };
845
+ }
846
+ function descriptorType(type) {
847
+ return { tag: type === "file" ? "regular-file" : "directory" };
848
+ }
849
+ function descriptorStat(stat) {
850
+ return {
851
+ type: descriptorType(stat.type),
852
+ linkCount: 1n,
853
+ size: stat.size,
854
+ dataAccessTimestamp: undefined,
855
+ dataModificationTimestamp: instant(stat.modified),
856
+ statusChangeTimestamp: undefined
857
+ };
858
+ }
859
+ function metadataHash(stat) {
860
+ const hash = (seed) => {
861
+ let value = seed;
862
+ const mix = (word) => {
863
+ for (let shift = 0n;shift < 64n; shift += 8n) {
864
+ value ^= word >> shift & 0xffn;
865
+ value = value * 0x100000001b3n & U64;
866
+ }
867
+ };
868
+ mix(stat.type === "file" ? 1n : 2n);
869
+ mix(BigInt.asUintN(64, stat.size));
870
+ mix(stat.modified === undefined ? U64 : BigInt.asUintN(64, BigInt(Math.floor(stat.modified))));
871
+ return value;
872
+ };
873
+ return { lower: hash(0xcbf29ce484222325n), upper: hash(0x84222325cbf29ce4n) };
874
+ }
875
+ function directoryAt(self, ...paths) {
876
+ const directory = self.directory;
877
+ if (!directory)
878
+ return err2("not-directory");
879
+ for (const path of paths) {
880
+ const refused = refusal(path);
881
+ if (refused)
882
+ return err2(refused);
883
+ }
884
+ return directory;
885
+ }
886
+ function mutableAt(self, paths, other) {
887
+ if (!self.directory || other && !other.directory)
888
+ return err2("not-directory");
889
+ if (!self.mutable || other && !other.mutable)
890
+ return err2("not-permitted");
891
+ return directoryAt(self, ...paths);
892
+ }
893
+ var isResult = (value) => typeof value === "object" && value !== null && ("tag" in value);
894
+ async function attempt(call, checked, operation) {
895
+ if (isResult(checked))
896
+ return checked;
897
+ try {
898
+ return ok2(await provider(call, () => operation(checked)));
899
+ } catch (error) {
900
+ return failed(call, error);
901
+ }
902
+ }
903
+ function failedOutput(failure) {
904
+ const stream = new OutputStream({ next: async () => {
905
+ return;
906
+ }, close() {} }, () => {});
907
+ return [stream, HostFuture.of(err2(failure))];
908
+ }
909
+ function output(self, producer) {
910
+ let settle;
911
+ const value = new Promise((resolve) => {
912
+ settle = resolve;
913
+ });
914
+ self.retain();
915
+ const stream = new OutputStream({
916
+ next: producer.next,
917
+ close() {
918
+ producer.close?.();
919
+ self.release();
920
+ }
921
+ }, (failure) => settle(failure === undefined ? ok2() : err2(code(failure))));
922
+ return [stream, new HostFuture(value)];
923
+ }
924
+ function chunks(input) {
925
+ return {
926
+ [Symbol.asyncIterator]: () => ({
927
+ async next() {
928
+ const chunk = await input.read();
929
+ if (chunk)
930
+ return { done: false, value: chunk };
931
+ if (input.cancelled)
932
+ throw new Error("stream reader was dropped");
933
+ return { done: true, value: undefined };
934
+ },
935
+ async return() {
936
+ input.cancel();
937
+ return { done: true, value: undefined };
938
+ }
939
+ })
940
+ };
941
+ }
942
+ function consume(host, self, input, offset) {
943
+ const file = self.file;
944
+ if (!file || !self.flags.write) {
945
+ input.cancel();
946
+ return HostFuture.of(err2("bad-descriptor"));
947
+ }
948
+ self.retain();
949
+ const value = (async () => {
950
+ try {
951
+ if (file.writeStream) {
952
+ const stream = input;
953
+ await host.physical(undefined, () => file.writeStream(chunks(stream), offset));
954
+ return ok2();
955
+ }
956
+ let position = offset;
957
+ for (let chunk = await input.read();chunk; chunk = await input.read()) {
958
+ const bytes = chunk;
959
+ if (position === undefined)
960
+ await host.physical(undefined, () => file.append(bytes));
961
+ else {
962
+ const at = position;
963
+ await host.physical(undefined, () => file.write(at, bytes));
964
+ position += BigInt(bytes.byteLength);
965
+ }
966
+ }
967
+ return ok2();
968
+ } catch (error) {
969
+ return err2(code(error));
970
+ } finally {
971
+ input.cancel();
972
+ self.release();
973
+ }
974
+ })();
975
+ host.cleanup(() => value);
976
+ return new HostFuture(value, () => input.cancel());
977
+ }
978
+ function filesystemMethods(mounts) {
979
+ const methods = {
980
+ [`${PREOPENS}#getDirectories`]: (call) => mounts().map((mount) => [
981
+ new HostDescriptor(call.host, mount.filesystem.openRoot(), {
982
+ read: true,
983
+ write: false,
984
+ fileIntegritySync: false,
985
+ dataIntegritySync: false,
986
+ requestedWriteSync: false,
987
+ mutateDirectory: mount.writable
988
+ }),
989
+ mount.path
990
+ ]),
991
+ readViaStream(_call, [self, offset]) {
992
+ const file = self.file;
993
+ if (!file || !self.flags.read)
994
+ return failedOutput("bad-descriptor");
995
+ let position = offset;
996
+ return output(self, {
997
+ next: async (limit) => {
998
+ const chunk = await _call.host.physical(undefined, () => file.read(position, limit));
999
+ position += BigInt(chunk.byteLength);
1000
+ return chunk;
1001
+ }
1002
+ });
1003
+ },
1004
+ writeViaStream: ({ host }, [self, input, offset]) => consume(host, self, input, offset),
1005
+ appendViaStream: ({ host }, [self, input]) => consume(host, self, input, undefined),
1006
+ readDirectory({ host }, [self]) {
1007
+ const directory = self.directory;
1008
+ if (!directory)
1009
+ return failedOutput("not-directory");
1010
+ let entries;
1011
+ try {
1012
+ entries = directory.readDirectory();
1013
+ } catch (error) {
1014
+ return failedOutput(code(error));
1015
+ }
1016
+ let done = false;
1017
+ return output(self, {
1018
+ next: async () => {
1019
+ const next = await host.physical(undefined, () => entries.next());
1020
+ if (next.done) {
1021
+ done = true;
1022
+ return;
1023
+ }
1024
+ return { type: descriptorType(next.value.type), name: next.value.name };
1025
+ },
1026
+ close() {
1027
+ if (!done)
1028
+ host.cleanup(() => entries.return?.());
1029
+ }
1030
+ });
1031
+ },
1032
+ async advise(_call, [self]) {
1033
+ return self.file ? ok2() : err2("bad-descriptor");
1034
+ },
1035
+ sync: (call, [self]) => attempt(call, self.provider, (p) => p.sync()),
1036
+ syncData: (call, [self]) => attempt(call, self.provider, (p) => p.sync()),
1037
+ async getFlags(_call, [self]) {
1038
+ return ok2({ ...self.flags });
1039
+ },
1040
+ async getType(_call, [self]) {
1041
+ return ok2(descriptorType(self.provider.type));
1042
+ },
1043
+ setSize(call, [self, size]) {
1044
+ const file = self.file && self.flags.write ? self.file : err2("bad-descriptor");
1045
+ return attempt(call, file, (target) => target.setSize(size));
1046
+ },
1047
+ async setTimes(_call, [self, accessed, modified]) {
1048
+ if (self.file ? !self.flags.write : !self.mutable)
1049
+ return err2(self.file ? "bad-descriptor" : "not-permitted");
1050
+ return accessed.tag === "no-change" && modified.tag === "no-change" ? ok2() : err2("unsupported");
1051
+ },
1052
+ setTimesAt(call, [self, , path, accessed, modified]) {
1053
+ const checked = mutableAt(self, [path]);
1054
+ if (isResult(checked) || accessed.tag !== "no-change" || modified.tag !== "no-change")
1055
+ return Promise.resolve(isResult(checked) ? checked : err2("unsupported"));
1056
+ return attempt(call, checked, (directory) => directory.statAt(path).then(() => {
1057
+ return;
1058
+ }));
1059
+ },
1060
+ stat: (call, [self]) => attempt(call, self.provider, (p) => p.stat().then(descriptorStat)),
1061
+ statAt: (call, [self, , path]) => attempt(call, directoryAt(self, path), (directory) => directory.statAt(path).then(descriptorStat)),
1062
+ async openAt(call, [self, , path, open, flags]) {
1063
+ const write = Boolean(flags.write || flags.mutateDirectory);
1064
+ const directory = self.directory;
1065
+ if (!directory)
1066
+ return err2("not-directory");
1067
+ if ((open.create || open.truncate || write) && !self.mutable)
1068
+ return err2("not-permitted");
1069
+ const refused = refusal(path);
1070
+ if (refused)
1071
+ return err2(refused);
1072
+ try {
1073
+ const opened = await provider(call, () => directory.openAt(path, {
1074
+ create: Boolean(open.create),
1075
+ exclusive: Boolean(open.exclusive),
1076
+ truncate: Boolean(open.truncate),
1077
+ directory: Boolean(open.directory),
1078
+ write
1079
+ }), (descriptor) => closeProvider(call.host, descriptor));
1080
+ const granted = opened.writable && write;
1081
+ return ok2(new HostDescriptor(call.host, opened, {
1082
+ read: opened.type === "directory" || Boolean(flags.read),
1083
+ write: opened.type === "file" && granted,
1084
+ fileIntegritySync: Boolean(flags.fileIntegritySync),
1085
+ dataIntegritySync: Boolean(flags.dataIntegritySync),
1086
+ requestedWriteSync: Boolean(flags.requestedWriteSync),
1087
+ mutateDirectory: opened.type === "directory" && granted
1088
+ }));
1089
+ } catch (error) {
1090
+ return failed(call, error);
1091
+ }
1092
+ },
1093
+ async readlinkAt(call, [self, path]) {
1094
+ const result = await attempt(call, directoryAt(self, path), (directory) => directory.statAt(path));
1095
+ return result.tag === "ok" ? err2("invalid") : result;
1096
+ },
1097
+ createDirectoryAt: (call, [self, path]) => attempt(call, mutableAt(self, [path]), (directory) => directory.createDirectoryAt(path)),
1098
+ removeDirectoryAt: (call, [self, path]) => attempt(call, mutableAt(self, [path]), (directory) => directory.removeDirectoryAt(path)),
1099
+ unlinkFileAt: (call, [self, path]) => attempt(call, mutableAt(self, [path]), (directory) => directory.unlinkFileAt(path)),
1100
+ renameAt: (call, [self, from, target, to]) => attempt(call, mutableAt(self, [from, to], target), (directory) => directory.renameAt(from, target.directory, to)),
1101
+ async linkAt(_call, [self, , from, target, to]) {
1102
+ const checked = mutableAt(self, [from, to], target);
1103
+ return isResult(checked) ? checked : err2("unsupported");
1104
+ },
1105
+ async symlinkAt(_call, [self, , to]) {
1106
+ const checked = mutableAt(self, [to]);
1107
+ return isResult(checked) ? checked : err2("unsupported");
1108
+ },
1109
+ async isSameObject(call, [self, other]) {
1110
+ try {
1111
+ return await provider(call, () => self.provider.isSameObject(other.provider));
1112
+ } catch (error) {
1113
+ if (call.signal?.aborted || !(error instanceof FilesystemError2))
1114
+ throw error;
1115
+ return false;
1116
+ }
1117
+ },
1118
+ metadataHash: (call, [self]) => attempt(call, self.provider, (p) => p.stat().then(metadataHash)),
1119
+ metadataHashAt: (call, [self, , path]) => attempt(call, directoryAt(self, path), (directory) => directory.statAt(path).then(metadataHash))
1120
+ };
1121
+ return Object.fromEntries(Object.entries(methods).map(([name, method]) => [
1122
+ name.includes("#") ? name : `${TYPES2}#${name}`,
1123
+ method
1124
+ ]));
1125
+ }
1126
+
1127
+ // src/interpreter/standard-cli.ts
1128
+ var ok3 = () => ({ tag: "ok" });
1129
+ var io = () => ({ tag: "err", val: "io" });
1130
+
1131
+ class StandardCli {
1132
+ #input;
1133
+ #providers;
1134
+ #writes = new Map;
1135
+ #stopped = new AbortController;
1136
+ #reading = Promise.resolve();
1137
+ #closed = false;
1138
+ methods;
1139
+ constructor(configuration = {}, streams = {}) {
1140
+ this.#providers = new Set;
1141
+ for (const provider of [streams.stdin, streams.stdout, streams.stderr])
1142
+ if (provider)
1143
+ this.#providers.add(provider);
1144
+ const input = configuration.stdin;
1145
+ if (typeof input === "object" && "file" in input && !streams.stdin)
1146
+ throw new Error("Browser stdin files require an injected stdio provider");
1147
+ if (input === "empty")
1148
+ this.#input = undefined;
1149
+ else if (typeof input === "object" && "bytes" in input) {
1150
+ const bytes = input.bytes.slice();
1151
+ let offset = 0;
1152
+ this.#input = {
1153
+ async read(limit) {
1154
+ if (offset === bytes.length)
1155
+ return;
1156
+ const next = bytes.subarray(offset, offset + limit);
1157
+ offset += next.length;
1158
+ return next;
1159
+ }
1160
+ };
1161
+ } else
1162
+ this.#input = streams.stdin;
1163
+ const output = (name) => {
1164
+ const selected = configuration[name];
1165
+ if (selected === "discard")
1166
+ return;
1167
+ const stream = streams[name];
1168
+ if (typeof selected === "object" && !stream)
1169
+ throw new Error(`Browser ${name} files require an injected stdio provider`);
1170
+ return stream;
1171
+ };
1172
+ const stdout = output("stdout"), stderr = output("stderr");
1173
+ const environment = configuration.environment?.map(([name, value]) => [name, value]);
1174
+ const arguments_ = [...configuration.arguments ?? []];
1175
+ const cwd = configuration.initialCwd;
1176
+ this.methods = {
1177
+ "wasi:cli/environment@0.3.0#getEnvironment": () => environment?.map((pair) => [...pair]) ?? [],
1178
+ "wasi:cli/environment@0.3.0#getArguments": () => [...arguments_],
1179
+ "wasi:cli/environment@0.3.0#getInitialCwd": () => cwd,
1180
+ "wasi:cli/stdin@0.3.0#readViaStream": ({ host }) => this.read(host),
1181
+ "wasi:cli/stdout@0.3.0#writeViaStream": ({ host }, [input]) => this.write(host, stdout, input),
1182
+ "wasi:cli/stderr@0.3.0#writeViaStream": ({ host }, [input]) => this.write(host, stderr, input),
1183
+ "wasi:cli/terminal-stdin@0.3.0#getTerminalStdin": () => {
1184
+ return;
1185
+ },
1186
+ "wasi:cli/terminal-stdout@0.3.0#getTerminalStdout": () => {
1187
+ return;
1188
+ },
1189
+ "wasi:cli/terminal-stderr@0.3.0#getTerminalStderr": () => {
1190
+ return;
1191
+ },
1192
+ "wasi:cli/exit@0.3.0#exit": (_call, [status]) => this.exit(status.tag === "ok" ? 0 : 1),
1193
+ "wasi:cli/exit@0.3.0#exitWithCode": (_call, [status]) => this.exit(status)
1194
+ };
1195
+ }
1196
+ exit(status) {
1197
+ throw new GuestTrap(`orb exited with status ${status}; revision retired`);
1198
+ }
1199
+ read(host) {
1200
+ let settle;
1201
+ const completed = new Promise((resolve) => {
1202
+ settle = resolve;
1203
+ });
1204
+ const dropped = new AbortController;
1205
+ const signal = combinedSignal(this.#stopped.signal, dropped.signal);
1206
+ const stream = new OutputStream({
1207
+ next: async (limit) => {
1208
+ const operation = this.#reading.then(() => host.physical(signal, async () => {
1209
+ const bytes = await this.#input?.read(limit, signal);
1210
+ if (bytes !== undefined && (!(bytes instanceof Uint8Array) || bytes.length > limit))
1211
+ throw new Error("stdin provider returned an invalid or oversized byte chunk");
1212
+ return bytes;
1213
+ }));
1214
+ this.#reading = operation.then(() => {}, () => {});
1215
+ return operation;
1216
+ },
1217
+ close: () => dropped.abort()
1218
+ }, (failure) => settle(failure === undefined ? ok3() : io()));
1219
+ return [stream, new HostFuture(completed)];
1220
+ }
1221
+ write(host, sink, input) {
1222
+ const value = (async () => {
1223
+ try {
1224
+ for (let bytes = await input.read();bytes; bytes = await input.read()) {
1225
+ if (sink) {
1226
+ const chunk = bytes;
1227
+ const operation = (this.#writes.get(sink) ?? Promise.resolve()).then(() => host.physical(this.#stopped.signal, () => sink.write(chunk, this.#stopped.signal)));
1228
+ const turn = operation.then(() => {}, () => {});
1229
+ this.#writes.set(sink, turn);
1230
+ try {
1231
+ await operation;
1232
+ } finally {
1233
+ if (this.#writes.get(sink) === turn)
1234
+ this.#writes.delete(sink);
1235
+ }
1236
+ }
1237
+ }
1238
+ return input.cancelled ? io() : ok3();
1239
+ } catch {
1240
+ return io();
1241
+ } finally {
1242
+ input.cancel();
1243
+ }
1244
+ })();
1245
+ host.cleanup(() => value);
1246
+ return new HostFuture(value, () => input.cancel());
1247
+ }
1248
+ retire() {
1249
+ this.#stopped.abort();
1250
+ }
1251
+ close(host) {
1252
+ if (this.#closed)
1253
+ return;
1254
+ this.#closed = true;
1255
+ for (const provider of this.#providers)
1256
+ if (provider.close)
1257
+ host.cleanup(() => provider.close());
1258
+ }
1259
+ }
1260
+
1261
+ // src/interpreter/standard-http.ts
1262
+ var TYPES_INTERFACE = "wasi:http/types@0.3.0";
1263
+ var CLIENT_INTERFACE = "wasi:http/client@0.3.0";
1264
+ var ERROR_CODE = (() => {
1265
+ const send = METHODS.find((m) => m.interface === CLIENT_INTERFACE && m.name === "send");
1266
+ const result = send?.result === undefined ? undefined : TYPES[send.result];
1267
+ return result?.[0] === "result" ? result[2] : undefined;
1268
+ })();
1269
+ var NO_HANDLES = {
1270
+ handle() {
1271
+ throw new Error("an error code carries no handles");
1272
+ },
1273
+ value() {
1274
+ throw new Error("an error code carries no handles");
1275
+ }
1276
+ };
1277
+ function checkedCode(code) {
1278
+ if (ERROR_CODE === undefined)
1279
+ return;
1280
+ try {
1281
+ encode2(new Writer, ERROR_CODE, code, NO_HANDLES);
1282
+ return code;
1283
+ } catch {
1284
+ return;
1285
+ }
1286
+ }
1287
+ function errorCode(error, fallback = internal) {
1288
+ if (error instanceof HttpProviderError2) {
1289
+ const code = checkedCode(error.code);
1290
+ if (code)
1291
+ return code;
1292
+ }
1293
+ return fallback(error instanceof Error ? error.message : String(error));
1294
+ }
1295
+ function millis(duration) {
1296
+ if (duration === undefined)
1297
+ return;
1298
+ const ms = (duration + 999999n) / 1000000n;
1299
+ return ms > 0x7fffffffn ? undefined : Number(ms);
1300
+ }
1301
+ var EMPTY = { next: async () => {
1302
+ return;
1303
+ }, close() {} };
1304
+
1305
+ class GuestBody {
1306
+ contents;
1307
+ trailers;
1308
+ #settle;
1309
+ result;
1310
+ constructor(contents, trailers) {
1311
+ this.contents = contents;
1312
+ this.trailers = trailers;
1313
+ this.result = new HostFuture(new Promise((resolve) => {
1314
+ this.#settle = resolve;
1315
+ }));
1316
+ }
1317
+ settle(outcome) {
1318
+ const settle = this.#settle;
1319
+ this.#settle = undefined;
1320
+ settle?.(outcome);
1321
+ }
1322
+ consume(_host, res) {
1323
+ const contents = this.contents;
1324
+ const stream = new OutputStream(contents ? { next: () => contents.read(), close: () => contents.cancel() } : EMPTY, () => {});
1325
+ res.take().then((outcome) => this.settle(outcome));
1326
+ const trailers = this.trailers.take();
1327
+ return [stream, new HostFuture(trailers, () => this.trailers.close())];
1328
+ }
1329
+ fail(code) {
1330
+ this.contents?.cancel();
1331
+ this.trailers.close();
1332
+ this.settle(err(code));
1333
+ }
1334
+ close() {
1335
+ this.contents?.cancel();
1336
+ this.trailers.close();
1337
+ this.settle(done);
1338
+ }
1339
+ }
1340
+
1341
+ class Upload {
1342
+ source;
1343
+ length;
1344
+ body;
1345
+ trailers;
1346
+ completed;
1347
+ #terminal;
1348
+ #sent = 0;
1349
+ #controller;
1350
+ #complete;
1351
+ #reject;
1352
+ constructor(source, length) {
1353
+ this.source = source;
1354
+ this.length = length;
1355
+ let resolveTrailers;
1356
+ let rejectTrailers;
1357
+ this.trailers = new Promise((resolve, reject) => {
1358
+ resolveTrailers = resolve;
1359
+ rejectTrailers = reject;
1360
+ });
1361
+ this.completed = new Promise((resolve, reject) => {
1362
+ this.#complete = (trailers) => {
1363
+ resolveTrailers(trailers);
1364
+ resolve();
1365
+ };
1366
+ this.#reject = (error) => {
1367
+ rejectTrailers(error);
1368
+ reject(error);
1369
+ };
1370
+ });
1371
+ this.trailers.catch(() => {});
1372
+ this.completed.catch(() => {});
1373
+ const contents = source.contents;
1374
+ if (!contents) {
1375
+ this.body = null;
1376
+ this.#finish();
1377
+ return;
1378
+ }
1379
+ contents.stopped.addEventListener("abort", () => this.abort(internal("the request body was discarded")), { once: true });
1380
+ this.body = new ReadableStream({
1381
+ start: (controller) => {
1382
+ this.#controller = controller;
1383
+ },
1384
+ pull: (controller) => this.#pull(contents, controller),
1385
+ cancel: (reason) => this.#fail(reason instanceof HttpProviderError2 ? reason : new HttpProviderError2(internal("the HTTP provider cancelled the request body")))
1386
+ }, { highWaterMark: 0 });
1387
+ }
1388
+ get ended() {
1389
+ return this.#terminal !== undefined;
1390
+ }
1391
+ abort(code) {
1392
+ this.#fail(new HttpProviderError2(code));
1393
+ }
1394
+ #fail(error) {
1395
+ if (this.#terminal)
1396
+ return;
1397
+ this.#terminal = error;
1398
+ this.source.fail(error.code);
1399
+ this.#reject(error);
1400
+ this.#controller?.error(error);
1401
+ }
1402
+ #oversized() {
1403
+ return new HttpProviderError2({ tag: "HTTP-request-body-size", val: BigInt(this.#sent) });
1404
+ }
1405
+ async#pull(contents, controller) {
1406
+ const chunk = await contents.read();
1407
+ if (this.#terminal)
1408
+ return;
1409
+ if (!chunk) {
1410
+ if (await this.#finish())
1411
+ controller.close();
1412
+ return;
1413
+ }
1414
+ this.#sent += chunk.byteLength;
1415
+ if (this.length !== undefined && BigInt(this.#sent) > this.length)
1416
+ return this.#fail(this.#oversized());
1417
+ controller.enqueue(chunk);
1418
+ }
1419
+ async#finish() {
1420
+ if (this.length !== undefined && BigInt(this.#sent) !== this.length) {
1421
+ this.#fail(this.#oversized());
1422
+ return false;
1423
+ }
1424
+ let result;
1425
+ try {
1426
+ result = await this.source.trailers.take();
1427
+ } catch (error) {
1428
+ this.#fail(new HttpProviderError2(errorCode(error)));
1429
+ return false;
1430
+ }
1431
+ if (this.#terminal)
1432
+ return false;
1433
+ if (result.tag === "err") {
1434
+ this.#fail(new HttpProviderError2(result.val));
1435
+ return false;
1436
+ }
1437
+ const fields = result.val?.pairs();
1438
+ result.val?.release();
1439
+ this.#terminal = "completed";
1440
+ this.#complete(fields);
1441
+ return true;
1442
+ }
1443
+ }
1444
+
1445
+ class ReceivedBody {
1446
+ host;
1447
+ signal;
1448
+ upload;
1449
+ reader;
1450
+ trailers;
1451
+ length;
1452
+ betweenBytes;
1453
+ #released = false;
1454
+ #received = 0;
1455
+ #reading;
1456
+ constructor(host, signal, upload, reader, trailers, length, betweenBytes) {
1457
+ this.host = host;
1458
+ this.signal = signal;
1459
+ this.upload = upload;
1460
+ this.reader = reader;
1461
+ this.trailers = trailers;
1462
+ this.length = length;
1463
+ this.betweenBytes = betweenBytes;
1464
+ trailers?.catch(() => {});
1465
+ }
1466
+ consume(_host, res) {
1467
+ res.close();
1468
+ let settle;
1469
+ const trailers = new Promise((resolve) => {
1470
+ settle = resolve;
1471
+ });
1472
+ const stream = new OutputStream({ next: () => this.#read(), close: (end) => this.#end(end) }, (failure, end) => {
1473
+ if (end === "failed")
1474
+ return settle(err(errorCode(failure, () => ({ tag: "HTTP-response-incomplete" }))));
1475
+ if (end === "dropped" || !this.trailers)
1476
+ return settle(ok(undefined));
1477
+ this.trailers.then((fields) => {
1478
+ try {
1479
+ settle(ok(fields ? HttpFields.received(fields) : undefined));
1480
+ } catch (error) {
1481
+ settle(err(errorCode(error)));
1482
+ }
1483
+ }, (error) => settle(err(errorCode(error))));
1484
+ });
1485
+ return [stream, new HostFuture(trailers)];
1486
+ }
1487
+ async#read() {
1488
+ for (;; ) {
1489
+ const next = this.reader ? await this.#next(this.reader) : undefined;
1490
+ if (!next || next.done) {
1491
+ if (this.length !== undefined && BigInt(this.#received) !== this.length)
1492
+ throw new HttpProviderError2({ tag: "HTTP-response-incomplete" });
1493
+ return;
1494
+ }
1495
+ const chunk = next.value;
1496
+ if (!(chunk instanceof Uint8Array))
1497
+ throw new HttpProviderError2(internal("the HTTP provider produced a non-byte chunk"));
1498
+ if (!chunk.byteLength)
1499
+ continue;
1500
+ this.#received += chunk.byteLength;
1501
+ if (this.length !== undefined && BigInt(this.#received) > this.length)
1502
+ throw new HttpProviderError2({
1503
+ tag: "HTTP-response-body-size",
1504
+ val: BigInt(this.#received)
1505
+ });
1506
+ return chunk;
1507
+ }
1508
+ }
1509
+ async#next(reader) {
1510
+ const read = reader.read();
1511
+ this.#reading = read.catch(() => {});
1512
+ if (this.betweenBytes === undefined)
1513
+ return read;
1514
+ let timer;
1515
+ try {
1516
+ return await Promise.race([
1517
+ read,
1518
+ new Promise((_, reject) => {
1519
+ timer = setTimeout(() => reject(new HttpProviderError2({ tag: "connection-read-timeout" })), this.betweenBytes);
1520
+ })
1521
+ ]);
1522
+ } finally {
1523
+ clearTimeout(timer);
1524
+ }
1525
+ }
1526
+ #end(end = "dropped") {
1527
+ if (end !== "eof")
1528
+ this.close();
1529
+ }
1530
+ close() {
1531
+ if (this.#released)
1532
+ return;
1533
+ this.#released = true;
1534
+ this.signal.abort();
1535
+ this.upload.abort(internal("the response was released before its request body completed"));
1536
+ const reader = this.reader;
1537
+ const reading = this.#reading;
1538
+ if (reader)
1539
+ this.host.cleanup(async () => {
1540
+ await reader.cancel();
1541
+ await reading;
1542
+ });
1543
+ }
1544
+ }
1545
+ function discard(host, response) {
1546
+ const body = response?.body;
1547
+ if (body instanceof ReadableStream)
1548
+ host.cleanup(() => body.cancel());
1549
+ }
1550
+ function deadline(pending, signal, ms) {
1551
+ return new Promise((resolve, reject) => {
1552
+ let timer;
1553
+ const stop = () => {
1554
+ clearTimeout(timer);
1555
+ signal?.removeEventListener("abort", abort);
1556
+ };
1557
+ const abort = () => {
1558
+ stop();
1559
+ reject(cancelled());
1560
+ };
1561
+ if (signal?.aborted)
1562
+ return abort();
1563
+ signal?.addEventListener("abort", abort, { once: true });
1564
+ if (ms !== undefined)
1565
+ timer = setTimeout(() => {
1566
+ stop();
1567
+ reject(new HttpProviderError2({ tag: "connection-read-timeout" }));
1568
+ }, ms);
1569
+ pending.then((value) => {
1570
+ stop();
1571
+ resolve(value);
1572
+ }, (error) => {
1573
+ stop();
1574
+ reject(error);
1575
+ });
1576
+ });
1577
+ }
1578
+ function framedLength(method, status, fields) {
1579
+ if (method === "HEAD" || status < 200 || status === 204 || status === 304)
1580
+ return;
1581
+ const declared = new Set(fields.get("content-length").map(digits));
1582
+ if (declared.size > 1)
1583
+ throw new HttpProviderError2(internal("the HTTP provider returned conflicting lengths"));
1584
+ const [length] = declared;
1585
+ return length === undefined ? undefined : BigInt(length);
1586
+ }
1587
+ async function send(call, client, request) {
1588
+ const body = request.take();
1589
+ const method = request.methodName;
1590
+ const timeouts = Object.freeze({ ...request.options });
1591
+ const target = request.target();
1592
+ if (target.tag === "err") {
1593
+ body.fail(target.val);
1594
+ return target;
1595
+ }
1596
+ const provider = client?.provider(target.val.url);
1597
+ if (!provider) {
1598
+ body.fail({ tag: "HTTP-request-denied" });
1599
+ return err({ tag: "HTTP-request-denied" });
1600
+ }
1601
+ const declared = request.headers.get("content-length")[0];
1602
+ const upload = new Upload(body, declared && BigInt(digits(declared)));
1603
+ const signal = new AbortController;
1604
+ const outgoing = Object.freeze({
1605
+ url: target.val.url,
1606
+ pathWithQuery: target.val.pathWithQuery,
1607
+ method,
1608
+ fields: request.headers.pairs(),
1609
+ body: upload.body,
1610
+ trailers: upload.trailers,
1611
+ timeouts,
1612
+ signal: signal.signal
1613
+ });
1614
+ const fail = (code) => {
1615
+ signal.abort();
1616
+ upload.abort(code);
1617
+ body.settle(err(code));
1618
+ return err(code);
1619
+ };
1620
+ const pending = call.host.physical(call.signal, () => provider.send(outgoing));
1621
+ let response;
1622
+ try {
1623
+ response = await deadline(pending, call.signal, millis(timeouts.firstByte));
1624
+ } catch (error) {
1625
+ pending.then((late) => discard(call.host, late), () => {});
1626
+ if (!call.signal?.aborted)
1627
+ return fail(errorCode(error));
1628
+ fail(internal("request was cancelled"));
1629
+ throw cancelled();
1630
+ }
1631
+ let fields;
1632
+ let length;
1633
+ let reader;
1634
+ try {
1635
+ const status = response?.status;
1636
+ if (!Number.isInteger(status) || status < 100 || status > 999)
1637
+ throw new HttpProviderError2(internal("the HTTP provider returned an invalid status"));
1638
+ fields = HttpFields.received(response.fields);
1639
+ length = framedLength(method, status, fields);
1640
+ if (response.body !== null && !(response.body instanceof ReadableStream))
1641
+ throw new HttpProviderError2(internal("the HTTP provider returned an invalid body"));
1642
+ reader = response.body?.getReader();
1643
+ } catch (error) {
1644
+ discard(call.host, response);
1645
+ return fail(errorCode(error));
1646
+ }
1647
+ upload.completed.then(() => body.settle(done), () => {});
1648
+ const received = new ReceivedBody(call.host, signal, upload, reader, response.trailers, length, millis(timeouts.betweenBytes));
1649
+ return ok(new HttpResponse(fields, received, response.status));
1650
+ }
1651
+ function httpMethods(client) {
1652
+ const consume = (call, message, res) => message.take().consume(call.host, res);
1653
+ return {
1654
+ ...bindResource(TYPES_INTERFACE, "fields", HttpFields.prototype, {
1655
+ constructor: () => HttpFields.create(),
1656
+ fromList: (_call, entries) => HttpFields.fromList(entries)
1657
+ }),
1658
+ ...bindResource(TYPES_INTERFACE, "request-options", HttpRequestOptions.prototype, {
1659
+ constructor: () => new HttpRequestOptions
1660
+ }),
1661
+ ...bindResource(TYPES_INTERFACE, "request", HttpRequest.prototype, {
1662
+ new: (_call, headers, contents, trailers, options) => {
1663
+ const body = new GuestBody(contents, trailers);
1664
+ return [new HttpRequest(headers.frozen(), options?.timeouts, body), body.result];
1665
+ },
1666
+ consumeBody: consume
1667
+ }),
1668
+ ...bindResource(TYPES_INTERFACE, "response", HttpResponse.prototype, {
1669
+ new: (_call, headers, contents, trailers) => {
1670
+ const body = new GuestBody(contents, trailers);
1671
+ return [new HttpResponse(headers.frozen(), body), body.result];
1672
+ },
1673
+ consumeBody: consume
1674
+ }),
1675
+ [`${CLIENT_INTERFACE}#send`]: (call, [request]) => send(call, client, request)
1676
+ };
1677
+ }
1678
+
1679
+ // src/interpreter/standard-ingress.ts
1680
+ function codeOf(error) {
1681
+ if (error instanceof HttpProviderError2 || error instanceof HttpHandlerError2)
1682
+ return error.code;
1683
+ return internal(error instanceof Error ? error.message : String(error));
1684
+ }
1685
+ function fields(pairs, what) {
1686
+ try {
1687
+ return HttpFields.received(pairs);
1688
+ } catch {
1689
+ throw new TypeError(`invalid incoming ${what} field`);
1690
+ }
1691
+ }
1692
+
1693
+ class IncomingBody {
1694
+ cleanup;
1695
+ source;
1696
+ trailers;
1697
+ #iterator;
1698
+ #stopped = false;
1699
+ #terminated;
1700
+ #stop = new AbortController;
1701
+ constructor(cleanup, source, trailers) {
1702
+ this.cleanup = cleanup;
1703
+ this.source = source;
1704
+ this.trailers = trailers;
1705
+ }
1706
+ consume(_host, res) {
1707
+ res.close();
1708
+ let settle;
1709
+ const trailers = new Promise((resolve) => {
1710
+ settle = resolve;
1711
+ });
1712
+ const stream = new OutputStream({ next: () => this.#read(), close: (end) => end !== "eof" && this.#release() }, (failure, end) => {
1713
+ if (end === "failed")
1714
+ return settle(err(codeOf(failure)));
1715
+ if (end === "dropped" || !this.trailers)
1716
+ return settle(ok(undefined));
1717
+ Promise.resolve(this.trailers).then((pairs) => {
1718
+ try {
1719
+ settle(ok(pairs?.length ? fields(pairs, "trailer") : undefined));
1720
+ } catch (error) {
1721
+ settle(err(codeOf(error)));
1722
+ }
1723
+ }, (error) => settle(err(codeOf(error))));
1724
+ });
1725
+ return [stream, new HostFuture(trailers)];
1726
+ }
1727
+ async#read() {
1728
+ if (this.#terminated)
1729
+ throw new HttpProviderError2(this.#terminated);
1730
+ if (!this.source || this.#stopped)
1731
+ return;
1732
+ this.#iterator ??= this.source[Symbol.asyncIterator]();
1733
+ for (;; ) {
1734
+ let next;
1735
+ try {
1736
+ next = await abortable(this.#iterator.next(), this.#stop.signal);
1737
+ } catch (error) {
1738
+ if (this.#terminated)
1739
+ throw new HttpProviderError2(this.#terminated);
1740
+ throw error;
1741
+ }
1742
+ if (next.done) {
1743
+ this.#iterator = undefined;
1744
+ return;
1745
+ }
1746
+ if (!(next.value instanceof Uint8Array))
1747
+ throw new HttpProviderError2(internal("incoming request chunks must be Uint8Array"));
1748
+ if (next.value.byteLength)
1749
+ return next.value;
1750
+ }
1751
+ }
1752
+ #release() {
1753
+ if (this.#stopped)
1754
+ return;
1755
+ this.#stopped = true;
1756
+ const iterator = this.#iterator;
1757
+ const source = this.source;
1758
+ this.#iterator = undefined;
1759
+ if (iterator || source)
1760
+ this.cleanup(() => (iterator ?? source[Symbol.asyncIterator]()).return?.());
1761
+ }
1762
+ terminate(code) {
1763
+ if (this.#terminated)
1764
+ return;
1765
+ this.#terminated = code;
1766
+ this.#stop.abort();
1767
+ this.#release();
1768
+ }
1769
+ close() {
1770
+ this.#release();
1771
+ }
1772
+ }
1773
+
1774
+ class Delivery {
1775
+ host;
1776
+ request;
1777
+ ended;
1778
+ response;
1779
+ #end;
1780
+ #transmitted;
1781
+ #stopTrailers;
1782
+ #stream;
1783
+ #finished = false;
1784
+ #started = false;
1785
+ #failure;
1786
+ constructor(host, published, request) {
1787
+ this.host = host;
1788
+ this.request = request;
1789
+ this.ended = new Promise((resolve) => {
1790
+ this.#end = resolve;
1791
+ });
1792
+ const transmitted = new Promise((resolve) => {
1793
+ this.#transmitted = resolve;
1794
+ });
1795
+ const status = published.getStatusCode();
1796
+ const pairs = published.headers.pairs();
1797
+ const body = published.take();
1798
+ published.release();
1799
+ const [stream, future] = body.consume(host, {
1800
+ take: () => transmitted,
1801
+ close() {}
1802
+ });
1803
+ this.#stream = stream;
1804
+ const written = future.value.then((result) => {
1805
+ if (result.tag === "err")
1806
+ throw new HttpHandlerError2(result.val);
1807
+ const fields = result.val?.pairs();
1808
+ result.val?.release();
1809
+ return fields?.length ? fields : undefined;
1810
+ });
1811
+ const stopped = new Promise((_, reject) => {
1812
+ this.#stopTrailers = reject;
1813
+ });
1814
+ const trailers = Promise.race([written, stopped]);
1815
+ for (const promise of [written, stopped, trailers])
1816
+ promise.catch(() => {});
1817
+ const delivery = this;
1818
+ this.response = Object.freeze({
1819
+ status,
1820
+ fields: Object.freeze(pairs.map((pair) => Object.freeze(pair))),
1821
+ body: Object.freeze({
1822
+ [Symbol.asyncIterator]: () => delivery.#iterator()
1823
+ }),
1824
+ trailers
1825
+ });
1826
+ }
1827
+ #iterator() {
1828
+ if (this.#started)
1829
+ throw new TypeError("the response body is read once");
1830
+ this.#started = true;
1831
+ return {
1832
+ next: () => this.#next(),
1833
+ return: async () => {
1834
+ this.disconnect();
1835
+ return { done: true, value: undefined };
1836
+ }
1837
+ };
1838
+ }
1839
+ async#next() {
1840
+ if (this.#finished) {
1841
+ if (this.#failure !== undefined)
1842
+ throw this.#failure;
1843
+ return { done: true, value: undefined };
1844
+ }
1845
+ let bytes;
1846
+ try {
1847
+ bytes = await this.#stream.read(STREAM_CHUNK, this.host.packetBytes);
1848
+ } catch (error) {
1849
+ if (this.#finished)
1850
+ throw this.#failure ?? error;
1851
+ this.#finish(err(codeOf(error)));
1852
+ throw error;
1853
+ }
1854
+ const reader = new Reader(bytes);
1855
+ if (reader.u8() === 0) {
1856
+ const chunk = reader.bytes();
1857
+ reader.end();
1858
+ return { done: false, value: chunk };
1859
+ }
1860
+ reader.end();
1861
+ try {
1862
+ await this.response.trailers;
1863
+ } catch (error) {
1864
+ this.#finish(err(codeOf(error)));
1865
+ throw error;
1866
+ }
1867
+ this.#finish(ok(undefined));
1868
+ return { done: true, value: undefined };
1869
+ }
1870
+ disconnect() {
1871
+ if (this.#finished)
1872
+ return;
1873
+ this.#stream.close();
1874
+ this.request.terminate(CONNECTION_TERMINATED);
1875
+ this.#stopTrailers(this.#failure ?? new HttpHandlerError2(CONNECTION_TERMINATED));
1876
+ this.#finish(err(CONNECTION_TERMINATED));
1877
+ }
1878
+ abort(reason) {
1879
+ if (this.#finished)
1880
+ return;
1881
+ this.#failure = reason;
1882
+ this.disconnect();
1883
+ }
1884
+ #finish(outcome) {
1885
+ if (this.#finished)
1886
+ return;
1887
+ this.#finished = true;
1888
+ this.#transmitted(outcome);
1889
+ this.#end();
1890
+ }
1891
+ }
1892
+
1893
+ class IngressCall {
1894
+ exchange;
1895
+ body;
1896
+ #delivery;
1897
+ constructor(exchange, cleanup) {
1898
+ this.exchange = exchange;
1899
+ const request = exchange.own();
1900
+ this.body = new IncomingBody(cleanup, request.body, request.trailers);
1901
+ }
1902
+ resource() {
1903
+ const parts = this.exchange.request;
1904
+ let headers;
1905
+ try {
1906
+ headers = fields(parts.fields, "request");
1907
+ } catch (error) {
1908
+ this.body.close();
1909
+ throw error;
1910
+ }
1911
+ const request = new HttpRequest(headers, undefined, this.body);
1912
+ const refuse = (what) => {
1913
+ request.release();
1914
+ return new TypeError(`invalid incoming request ${what}`);
1915
+ };
1916
+ if (request.setMethod({ tag: "other", val: parts.method }).tag === "err")
1917
+ throw refuse("method");
1918
+ if (parts.scheme !== undefined) {
1919
+ if (request.setScheme({ tag: "other", val: parts.scheme }).tag === "err")
1920
+ throw refuse("scheme");
1921
+ }
1922
+ if (request.setAuthority(parts.authority).tag === "err")
1923
+ throw refuse("authority");
1924
+ if (request.setPathWithQuery(parts.pathWithQuery).tag === "err")
1925
+ throw refuse("path with query");
1926
+ return request;
1927
+ }
1928
+ respond(host, result) {
1929
+ if (result.tag === "err") {
1930
+ this.exchange.refuse(result.val);
1931
+ return Promise.resolve();
1932
+ }
1933
+ const delivery = new Delivery(host, result.val, this.body);
1934
+ this.#delivery = delivery;
1935
+ this.exchange.respond(delivery.response);
1936
+ return delivery.ended;
1937
+ }
1938
+ end(reason) {
1939
+ this.#delivery?.abort(reason);
1940
+ this.body.terminate(CONNECTION_TERMINATED);
1941
+ }
1942
+ }
1943
+
1944
+ // src/interpreter/standard-sockets.ts
1945
+ var TYPES_INTERFACE2 = "wasi:sockets/types@0.3.0";
1946
+ var LOOKUP_INTERFACE = "wasi:sockets/ip-name-lookup@0.3.0";
1947
+ var MAX_DATAGRAM = 65535;
1948
+ var DEFAULT_BACKLOG = 128;
1949
+ var MAX_BACKLOG = 2147483647;
1950
+ var ok4 = (val) => ({ tag: "ok", val });
1951
+ var fail = (tag) => ({
1952
+ tag: "err",
1953
+ val: { tag }
1954
+ });
1955
+ function errorType(contract, name) {
1956
+ const method = METHODS.find((m) => m.interface === contract && m.name === name);
1957
+ const result = method?.result === undefined ? undefined : TYPES[method.result];
1958
+ return result?.[0] === "result" ? result[2] : undefined;
1959
+ }
1960
+ var NO_HANDLES2 = {
1961
+ handle() {
1962
+ throw new Error("an error code carries no handles");
1963
+ },
1964
+ value() {
1965
+ throw new Error("an error code carries no handles");
1966
+ }
1967
+ };
1968
+ function code2(error, type, typed) {
1969
+ if (typed !== undefined && type !== undefined) {
1970
+ try {
1971
+ encode2(new Writer, type, typed, NO_HANDLES2);
1972
+ return typed;
1973
+ } catch {}
1974
+ }
1975
+ return {
1976
+ tag: "other",
1977
+ val: error instanceof Error ? error.message : String(error)
1978
+ };
1979
+ }
1980
+ var socketCode = (error) => code2(error, errorType(TYPES_INTERFACE2, "connect"), error instanceof SocketProviderError2 ? error.code : undefined);
1981
+ var lookupCode = (error) => code2(error, errorType(LOOKUP_INTERFACE, "resolveAddresses"), error instanceof NameLookupError2 ? error.code : undefined);
1982
+ function attempt2(operation) {
1983
+ try {
1984
+ return ok4(operation());
1985
+ } catch (error) {
1986
+ return { tag: "err", val: socketCode(error) };
1987
+ }
1988
+ }
1989
+ function localAddress(value) {
1990
+ if (value === undefined)
1991
+ return fail("invalid-state");
1992
+ const address = fromWit(value);
1993
+ return address ? ok4(toWit(address)) : { tag: "err", val: { tag: "other", val: "invalid provider address" } };
1994
+ }
1995
+ function provided(value) {
1996
+ const address = fromWit(value);
1997
+ if (!address)
1998
+ throw new Error("invalid provider address");
1999
+ return address;
2000
+ }
2001
+
2002
+ class Shared {
2003
+ host;
2004
+ backend;
2005
+ #users = 1;
2006
+ constructor(host, backend) {
2007
+ this.host = host;
2008
+ this.backend = backend;
2009
+ }
2010
+ retain() {
2011
+ this.#users++;
2012
+ }
2013
+ release() {
2014
+ if (--this.#users === 0)
2015
+ this.host.cleanup(() => this.backend.close());
2016
+ }
2017
+ }
2018
+
2019
+ class SocketResource {
2020
+ borrows = 0;
2021
+ #users = 1;
2022
+ retain() {
2023
+ this.#users++;
2024
+ }
2025
+ release() {
2026
+ if (--this.#users === 0)
2027
+ this.close();
2028
+ }
2029
+ }
2030
+ function getOption(backend, name, valid) {
2031
+ if (!backend.getOption)
2032
+ return fail("not-supported");
2033
+ const value = attempt2(() => backend.getOption(name));
2034
+ if (value.tag === "ok" && !valid(value.val))
2035
+ return { tag: "err", val: { tag: "other", val: `invalid provider ${String(name)}` } };
2036
+ return value;
2037
+ }
2038
+ function setOption(backend, name, value) {
2039
+ if (!backend.setOption)
2040
+ return fail("not-supported");
2041
+ return attempt2(() => backend.setOption(name, value));
2042
+ }
2043
+ var isU8 = (v) => typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 255;
2044
+ var isU32 = (v) => typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 4294967295;
2045
+ var isU64 = (v) => typeof v === "bigint" && v > 0n && v < 1n << 64n;
2046
+ var isBool = (v) => typeof v === "boolean";
2047
+ function discardConnection(host, connection) {
2048
+ host.cleanup(() => connection.readable.cancel());
2049
+ host.cleanup(() => connection.writable.abort());
2050
+ }
2051
+ function checkedConnection(value) {
2052
+ const connection = value;
2053
+ if (!(connection?.readable instanceof ReadableStream) || !(connection.writable instanceof WritableStream))
2054
+ throw new Error("invalid provider connection");
2055
+ provided(connection.remote);
2056
+ return connection;
2057
+ }
2058
+
2059
+ class TcpSocket extends SocketResource {
2060
+ access;
2061
+ family;
2062
+ shared;
2063
+ #state;
2064
+ #bound;
2065
+ #backlog = DEFAULT_BACKLOG;
2066
+ #sent = false;
2067
+ #received = false;
2068
+ constructor(access, family, shared, connection) {
2069
+ super();
2070
+ this.access = access;
2071
+ this.family = family;
2072
+ this.shared = shared;
2073
+ this.#state = connection ? { kind: "connected", connection } : { kind: "default" };
2074
+ this.#bound = connection !== undefined;
2075
+ }
2076
+ close() {
2077
+ this.shared.release();
2078
+ }
2079
+ get #backend() {
2080
+ return this.shared.backend;
2081
+ }
2082
+ get #grants() {
2083
+ return this.access.grants;
2084
+ }
2085
+ bind(local) {
2086
+ if (this.#bound || this.#state.kind !== "default")
2087
+ return fail("invalid-state");
2088
+ const address = fromWit(local);
2089
+ if (!isUnicast(address) || !hasFamily(address, this.family))
2090
+ return fail("invalid-argument");
2091
+ if (!this.#grants.allows(address, "tcp-bind"))
2092
+ return fail("access-denied");
2093
+ const backend = this.#backend;
2094
+ if (!backend.bind)
2095
+ return fail("not-supported");
2096
+ const bound = attempt2(() => backend.bind(toWit(address)));
2097
+ if (bound.tag === "ok")
2098
+ this.#bound = true;
2099
+ return bound;
2100
+ }
2101
+ async connect(remote, call) {
2102
+ if (this.#state.kind !== "default")
2103
+ return fail("invalid-state");
2104
+ const address = fromWit(remote);
2105
+ if (!isUnicast(address) || !isRemote(address) || !hasFamily(address, this.family))
2106
+ return fail("invalid-argument");
2107
+ if (!this.#bound && !this.#grants.allows(unspecified(this.family), "tcp-bind"))
2108
+ return fail("access-denied");
2109
+ if (!this.#grants.allows(address, "tcp-connect"))
2110
+ return fail("access-denied");
2111
+ this.#state = { kind: "connecting" };
2112
+ const abort = new AbortController;
2113
+ const stop = () => abort.abort();
2114
+ call.signal?.addEventListener("abort", stop, { once: true });
2115
+ const pending = call.host.physical(call.signal, () => this.#backend.connect(toWit(address), abort.signal));
2116
+ try {
2117
+ const connection = checkedConnection(await abortable(pending, call.signal));
2118
+ this.#state = { kind: "connected", connection };
2119
+ this.#bound = true;
2120
+ return ok4(undefined);
2121
+ } catch (error) {
2122
+ this.#state = { kind: "closed", code: { tag: "invalid-state" } };
2123
+ if (!call.signal?.aborted) {
2124
+ const failure = socketCode(error);
2125
+ this.#state = { kind: "closed", code: failure };
2126
+ return { tag: "err", val: failure };
2127
+ }
2128
+ pending.then((late) => discardConnection(call.host, late), () => {});
2129
+ throw cancelled();
2130
+ } finally {
2131
+ call.signal?.removeEventListener("abort", stop);
2132
+ }
2133
+ }
2134
+ listen(call) {
2135
+ if (this.#state.kind !== "default")
2136
+ return fail("invalid-state");
2137
+ const implicit = unspecified(this.family);
2138
+ if (this.#bound) {
2139
+ const local = localAddress(this.#backend.local);
2140
+ if (local.tag === "err")
2141
+ return local;
2142
+ if (!this.#grants.allows(fromWit(local.val), "tcp-listen"))
2143
+ return fail("access-denied");
2144
+ } else if (!this.#grants.allows(implicit, "tcp-bind") || !this.#grants.allows(implicit, "tcp-listen"))
2145
+ return fail("access-denied");
2146
+ const backend = this.#backend;
2147
+ if (!backend.listen)
2148
+ return fail("not-supported");
2149
+ const listened = attempt2(() => backend.listen(this.#backlog));
2150
+ if (listened.tag === "err")
2151
+ return listened;
2152
+ const listener = listened.val;
2153
+ if (typeof listener?.accept !== "function")
2154
+ return { tag: "err", val: { tag: "other", val: "invalid provider listener" } };
2155
+ this.#state = { kind: "listening", listener };
2156
+ this.#bound = true;
2157
+ return ok4(this.#acceptStream(call.host, listener));
2158
+ }
2159
+ #acceptStream(host, listener) {
2160
+ this.shared.retain();
2161
+ const stop = new AbortController;
2162
+ let accepting;
2163
+ const next = async () => {
2164
+ for (;; ) {
2165
+ const pull = listener.accept(stop.signal);
2166
+ accepting = pull;
2167
+ const { socket, connection } = await pull;
2168
+ let checked;
2169
+ try {
2170
+ checked = checkedConnection(connection);
2171
+ if (typeof socket?.close !== "function")
2172
+ throw new Error("invalid provider socket");
2173
+ } catch (error) {
2174
+ host.cleanup(() => socket?.close?.());
2175
+ throw error;
2176
+ }
2177
+ const child = new TcpSocket(this.access, this.family, new Shared(host, socket), checked);
2178
+ if (this.#grants.allows(provided(checked.remote), "tcp-accept"))
2179
+ return child;
2180
+ child.release();
2181
+ }
2182
+ };
2183
+ return new OutputStream({
2184
+ next,
2185
+ close: () => {
2186
+ stop.abort();
2187
+ const pending = accepting;
2188
+ host.cleanup(async () => {
2189
+ await pending?.then(() => {}, () => {});
2190
+ this.shared.release();
2191
+ });
2192
+ }
2193
+ }, () => {}, (value) => value.release());
2194
+ }
2195
+ send(data, call) {
2196
+ if (this.#state.kind !== "connected" || this.#sent) {
2197
+ data.cancel();
2198
+ return HostFuture.of(fail("invalid-state"));
2199
+ }
2200
+ const connection = this.#state.connection;
2201
+ const locked = attempt2(() => connection.writable.getWriter());
2202
+ if (locked.tag === "err") {
2203
+ data.cancel();
2204
+ return HostFuture.of(locked);
2205
+ }
2206
+ this.#sent = true;
2207
+ const host = call.host;
2208
+ const writer = locked.val;
2209
+ this.shared.retain();
2210
+ const value = (async () => {
2211
+ try {
2212
+ for (let chunk = await data.read();chunk; chunk = await data.read())
2213
+ await writer.write(chunk);
2214
+ if (data.cancelled)
2215
+ throw new Error("send stopped");
2216
+ const closing = writer.close();
2217
+ host.cleanup(() => closing);
2218
+ await closing;
2219
+ return ok4(undefined);
2220
+ } catch (error) {
2221
+ data.cancel();
2222
+ const aborting = writer.abort(error);
2223
+ host.cleanup(() => aborting);
2224
+ return { tag: "err", val: socketCode(error) };
2225
+ } finally {
2226
+ this.shared.release();
2227
+ }
2228
+ })();
2229
+ return new HostFuture(value);
2230
+ }
2231
+ receive(call) {
2232
+ const empty = { next: async () => {
2233
+ return;
2234
+ }, close() {} };
2235
+ if (this.#state.kind !== "connected" || this.#received)
2236
+ return [new OutputStream(empty, () => {}), HostFuture.of(fail("invalid-state"))];
2237
+ const connection = this.#state.connection;
2238
+ const locked = attempt2(() => connection.readable.getReader());
2239
+ if (locked.tag === "err")
2240
+ return [new OutputStream(empty, () => {}), HostFuture.of(locked)];
2241
+ this.#received = true;
2242
+ const host = call.host;
2243
+ const reader = locked.val;
2244
+ this.shared.retain();
2245
+ let settle;
2246
+ const done = new Promise((resolve) => {
2247
+ settle = resolve;
2248
+ });
2249
+ const stream = new OutputStream({
2250
+ async next() {
2251
+ for (;; ) {
2252
+ const { done: end, value } = await reader.read();
2253
+ if (end)
2254
+ return;
2255
+ if (!(value instanceof Uint8Array))
2256
+ throw new Error("invalid provider chunk");
2257
+ if (value.byteLength)
2258
+ return value.slice();
2259
+ }
2260
+ },
2261
+ close: (end) => {
2262
+ host.cleanup(async () => {
2263
+ if (end !== "eof")
2264
+ await reader.cancel();
2265
+ this.shared.release();
2266
+ });
2267
+ }
2268
+ }, (failure, end) => settle(end === "failed" ? { tag: "err", val: socketCode(failure) } : ok4(undefined)));
2269
+ return [stream, new HostFuture(done)];
2270
+ }
2271
+ getLocalAddress() {
2272
+ if (this.#state.kind === "closed")
2273
+ return { tag: "err", val: this.#state.code };
2274
+ if (!this.#bound || this.#state.kind === "connecting")
2275
+ return fail("invalid-state");
2276
+ return localAddress(this.#backend.local);
2277
+ }
2278
+ getRemoteAddress() {
2279
+ if (this.#state.kind === "closed")
2280
+ return { tag: "err", val: this.#state.code };
2281
+ if (this.#state.kind !== "connected")
2282
+ return fail("invalid-state");
2283
+ return ok4(toWit(provided(this.#state.connection.remote)));
2284
+ }
2285
+ getIsListening() {
2286
+ return this.#state.kind === "listening";
2287
+ }
2288
+ getAddressFamily() {
2289
+ return this.family;
2290
+ }
2291
+ setListenBacklogSize(value) {
2292
+ if (value === 0n)
2293
+ return fail("invalid-argument");
2294
+ const backlog = value > BigInt(MAX_BACKLOG) ? MAX_BACKLOG : Number(value);
2295
+ switch (this.#state.kind) {
2296
+ case "default":
2297
+ this.#backlog = backlog;
2298
+ return ok4(undefined);
2299
+ case "listening":
2300
+ return setOption(this.#backend, "listenBacklogSize", BigInt(backlog));
2301
+ case "closed":
2302
+ return { tag: "err", val: this.#state.code };
2303
+ default:
2304
+ return fail("invalid-state");
2305
+ }
2306
+ }
2307
+ #get(name, valid) {
2308
+ if (this.#state.kind === "closed")
2309
+ return { tag: "err", val: this.#state.code };
2310
+ return getOption(this.#backend, name, valid);
2311
+ }
2312
+ #set(name, value, positive) {
2313
+ if (positive && (value === 0 || value === 0n))
2314
+ return fail("invalid-argument");
2315
+ if (this.#state.kind === "closed")
2316
+ return { tag: "err", val: this.#state.code };
2317
+ return setOption(this.#backend, name, value);
2318
+ }
2319
+ getKeepAliveEnabled() {
2320
+ return this.#get("keepAliveEnabled", isBool);
2321
+ }
2322
+ setKeepAliveEnabled(value) {
2323
+ return this.#set("keepAliveEnabled", value, false);
2324
+ }
2325
+ getKeepAliveIdleTime() {
2326
+ return this.#get("keepAliveIdleTime", isU64);
2327
+ }
2328
+ setKeepAliveIdleTime(value) {
2329
+ return this.#set("keepAliveIdleTime", value, true);
2330
+ }
2331
+ getKeepAliveInterval() {
2332
+ return this.#get("keepAliveInterval", isU64);
2333
+ }
2334
+ setKeepAliveInterval(value) {
2335
+ return this.#set("keepAliveInterval", value, true);
2336
+ }
2337
+ getKeepAliveCount() {
2338
+ return this.#get("keepAliveCount", isU32);
2339
+ }
2340
+ setKeepAliveCount(value) {
2341
+ return this.#set("keepAliveCount", value, true);
2342
+ }
2343
+ getHopLimit() {
2344
+ return this.#get("hopLimit", isU8);
2345
+ }
2346
+ setHopLimit(value) {
2347
+ return this.#set("hopLimit", value, true);
2348
+ }
2349
+ getReceiveBufferSize() {
2350
+ return this.#get("receiveBufferSize", isU64);
2351
+ }
2352
+ setReceiveBufferSize(value) {
2353
+ return this.#set("receiveBufferSize", value, true);
2354
+ }
2355
+ getSendBufferSize() {
2356
+ return this.#get("sendBufferSize", isU64);
2357
+ }
2358
+ setSendBufferSize(value) {
2359
+ return this.#set("sendBufferSize", value, true);
2360
+ }
2361
+ }
2362
+
2363
+ class UdpSocket extends SocketResource {
2364
+ access;
2365
+ family;
2366
+ shared;
2367
+ #bound = false;
2368
+ #remote;
2369
+ constructor(access, family, shared) {
2370
+ super();
2371
+ this.access = access;
2372
+ this.family = family;
2373
+ this.shared = shared;
2374
+ }
2375
+ close() {
2376
+ this.shared.release();
2377
+ }
2378
+ get #backend() {
2379
+ return this.shared.backend;
2380
+ }
2381
+ get #grants() {
2382
+ return this.access.grants;
2383
+ }
2384
+ bind(local) {
2385
+ if (this.#bound)
2386
+ return fail("invalid-state");
2387
+ const address = fromWit(local);
2388
+ if (!hasFamily(address, this.family))
2389
+ return fail("invalid-argument");
2390
+ if (!this.#grants.allows(address, "udp-bind"))
2391
+ return fail("access-denied");
2392
+ return this.#bind(address);
2393
+ }
2394
+ #bind(address) {
2395
+ const backend = this.#backend;
2396
+ if (!backend.bind)
2397
+ return fail("not-supported");
2398
+ const bound = attempt2(() => backend.bind(toWit(address)));
2399
+ if (bound.tag === "ok")
2400
+ this.#bound = true;
2401
+ return bound;
2402
+ }
2403
+ connect(remote) {
2404
+ const address = fromWit(remote);
2405
+ if (!hasFamily(address, this.family) || !isRemote(address))
2406
+ return fail("invalid-argument");
2407
+ const implicit = unspecified(this.family);
2408
+ if (!this.#bound && !this.#grants.allows(implicit, "udp-bind"))
2409
+ return fail("access-denied");
2410
+ if (!this.#grants.allows(address, "udp-send") || !this.#grants.allows(address, "udp-receive"))
2411
+ return fail("access-denied");
2412
+ if (!this.#bound) {
2413
+ const bound = this.#bind(implicit);
2414
+ if (bound.tag === "err")
2415
+ return bound;
2416
+ }
2417
+ this.#remote = address;
2418
+ return ok4(undefined);
2419
+ }
2420
+ disconnect() {
2421
+ if (!this.#remote)
2422
+ return fail("invalid-state");
2423
+ this.#remote = undefined;
2424
+ return ok4(undefined);
2425
+ }
2426
+ async send(data, remote, call) {
2427
+ if (data.byteLength > MAX_DATAGRAM)
2428
+ return fail("datagram-too-large");
2429
+ let target;
2430
+ if (remote !== undefined) {
2431
+ target = fromWit(remote);
2432
+ if (!isRemote(target) || !hasFamily(target, this.family))
2433
+ return fail("invalid-argument");
2434
+ if (this.#remote && key(this.#remote) !== key(target))
2435
+ return fail("invalid-argument");
2436
+ } else if (this.#remote)
2437
+ target = this.#remote;
2438
+ else
2439
+ return fail("invalid-argument");
2440
+ if (!this.#bound && !this.#grants.allows(unspecified(this.family), "udp-bind"))
2441
+ return fail("access-denied");
2442
+ if (!this.#grants.allows(target, "udp-send"))
2443
+ return fail("access-denied");
2444
+ const abort = new AbortController;
2445
+ const stop = () => abort.abort();
2446
+ call.signal?.addEventListener("abort", stop, { once: true });
2447
+ try {
2448
+ await abortable(call.host.physical(call.signal, () => this.#backend.send(data.slice(), toWit(target), abort.signal)), call.signal);
2449
+ this.#bound = true;
2450
+ return ok4(undefined);
2451
+ } catch (error) {
2452
+ if (call.signal?.aborted)
2453
+ throw cancelled();
2454
+ return { tag: "err", val: socketCode(error) };
2455
+ } finally {
2456
+ call.signal?.removeEventListener("abort", stop);
2457
+ }
2458
+ }
2459
+ async receive(call) {
2460
+ if (!this.#bound)
2461
+ return fail("invalid-state");
2462
+ const abort = new AbortController;
2463
+ const stop = () => abort.abort();
2464
+ call.signal?.addEventListener("abort", stop, { once: true });
2465
+ try {
2466
+ for (;; ) {
2467
+ const datagram = await abortable(call.host.physical(call.signal, () => this.#backend.receive(abort.signal)), call.signal);
2468
+ const sender = provided(datagram?.remote);
2469
+ if (!(datagram.data instanceof Uint8Array) || datagram.data.byteLength > MAX_DATAGRAM)
2470
+ throw new Error("invalid provider datagram");
2471
+ if (this.#remote && key(this.#remote) !== key(sender))
2472
+ continue;
2473
+ if (!this.#grants.allows(sender, "udp-receive"))
2474
+ continue;
2475
+ return ok4([datagram.data.slice(), toWit(sender)]);
2476
+ }
2477
+ } catch (error) {
2478
+ if (call.signal?.aborted)
2479
+ throw cancelled();
2480
+ return { tag: "err", val: socketCode(error) };
2481
+ } finally {
2482
+ call.signal?.removeEventListener("abort", stop);
2483
+ }
2484
+ }
2485
+ getLocalAddress() {
2486
+ return this.#bound ? localAddress(this.#backend.local) : fail("invalid-state");
2487
+ }
2488
+ getRemoteAddress() {
2489
+ return this.#remote ? ok4(toWit(this.#remote)) : fail("invalid-state");
2490
+ }
2491
+ getAddressFamily() {
2492
+ return this.family;
2493
+ }
2494
+ #set(name, value) {
2495
+ if (value === 0 || value === 0n)
2496
+ return fail("invalid-argument");
2497
+ return setOption(this.#backend, name, value);
2498
+ }
2499
+ getUnicastHopLimit() {
2500
+ return getOption(this.#backend, "unicastHopLimit", isU8);
2501
+ }
2502
+ setUnicastHopLimit(value) {
2503
+ return this.#set("unicastHopLimit", value);
2504
+ }
2505
+ getReceiveBufferSize() {
2506
+ return getOption(this.#backend, "receiveBufferSize", isU64);
2507
+ }
2508
+ setReceiveBufferSize(value) {
2509
+ return this.#set("receiveBufferSize", value);
2510
+ }
2511
+ getSendBufferSize() {
2512
+ return getOption(this.#backend, "sendBufferSize", isU64);
2513
+ }
2514
+ setSendBufferSize(value) {
2515
+ return this.#set("sendBufferSize", value);
2516
+ }
2517
+ }
2518
+ async function resolveAddresses(access, name, call) {
2519
+ const failure = (tag) => ({
2520
+ tag: "err",
2521
+ val: { tag }
2522
+ });
2523
+ if (!access?.grants.resolve)
2524
+ return failure("access-denied");
2525
+ const parsed = parseHostName(name);
2526
+ if (!parsed)
2527
+ return failure("invalid-argument");
2528
+ if ("ip" in parsed)
2529
+ return ok4([parsed.ip]);
2530
+ const resolve = access.provider?.resolve;
2531
+ if (!resolve)
2532
+ return failure("permanent-resolver-failure");
2533
+ const abort = new AbortController;
2534
+ const stop = () => abort.abort();
2535
+ call.signal?.addEventListener("abort", stop, { once: true });
2536
+ try {
2537
+ const found = await abortable(call.host.physical(call.signal, () => resolve.call(access.provider, parsed.domain, abort.signal)), call.signal);
2538
+ if (!Array.isArray(found))
2539
+ throw new Error("invalid provider result");
2540
+ const addresses = found.map(checkedIpAddress);
2541
+ if (addresses.some((address) => address === undefined))
2542
+ throw new Error("invalid provider address");
2543
+ if (!addresses.length)
2544
+ return failure("name-unresolvable");
2545
+ return ok4(addresses);
2546
+ } catch (error) {
2547
+ if (call.signal?.aborted)
2548
+ throw cancelled();
2549
+ return { tag: "err", val: lookupCode(error) };
2550
+ } finally {
2551
+ call.signal?.removeEventListener("abort", stop);
2552
+ }
2553
+ }
2554
+ function create(access, allowed, factory, family, host, make) {
2555
+ if (!access || !allowed)
2556
+ return fail("access-denied");
2557
+ if (!factory)
2558
+ return fail("not-supported");
2559
+ const created = attempt2(() => factory.create(family));
2560
+ if (created.tag === "err")
2561
+ return created;
2562
+ if (typeof created.val?.close !== "function")
2563
+ return { tag: "err", val: { tag: "other", val: "invalid provider socket" } };
2564
+ return ok4(make(access, new Shared(host, created.val)));
2565
+ }
2566
+ function socketStatics(bindings) {
2567
+ const types = bindings.types;
2568
+ return {
2569
+ tcpCreate: (call, family) => create(types, types?.grants.tcp ?? false, types?.provider?.tcp, family, call.host, (access, shared) => new TcpSocket(access, family, shared)),
2570
+ udpCreate: (call, family) => create(types, types?.grants.udp ?? false, types?.provider?.udp, family, call.host, (access, shared) => new UdpSocket(access, family, shared)),
2571
+ resolveAddresses: (call, name) => resolveAddresses(bindings.lookup, name, call)
2572
+ };
2573
+ }
2574
+ function socketMethods(bindings) {
2575
+ const statics = socketStatics(bindings);
2576
+ return {
2577
+ ...bindResource(TYPES_INTERFACE2, "tcp-socket", TcpSocket.prototype, {
2578
+ create: statics.tcpCreate
2579
+ }),
2580
+ ...bindResource(TYPES_INTERFACE2, "udp-socket", UdpSocket.prototype, {
2581
+ create: statics.udpCreate
2582
+ }),
2583
+ [`${LOOKUP_INTERFACE}#resolveAddresses`]: (call, [name]) => statics.resolveAddresses(call, name)
2584
+ };
2585
+ }
2586
+
2587
+ // src/interpreter/standard-host.ts
2588
+ var HANDLE_LIMIT = 4096;
2589
+ var NONE = -1;
2590
+ var BYTE_STREAM = TYPES.findIndex(([kind, item]) => kind === "stream" && item === "u8");
2591
+ var HANDLER_RESULT = METHODS.find((method) => method.interface === "wasi:http/client@0.3.0" && method.name === "send").result;
2592
+ var HTTP_REQUEST = RESOURCES.indexOf("wasi:http/types@0.3.0#request");
2593
+ var ABANDONED = { tag: "err", val: { tag: "internal-error", val: "callback ended" } };
2594
+ var issued = 0;
2595
+ function slots(type) {
2596
+ const [kind, a, b] = TYPES[type];
2597
+ switch (kind) {
2598
+ case "own":
2599
+ case "stream":
2600
+ case "future":
2601
+ return 1;
2602
+ case "tuple":
2603
+ return a.reduce((sum, item) => sum + slots(item), 0);
2604
+ case "record":
2605
+ return a.reduce((sum, [, item]) => sum + slots(item), 0);
2606
+ case "option":
2607
+ return slots(a);
2608
+ case "result":
2609
+ return Math.max(a === NONE ? 0 : slots(a), b === NONE ? 0 : slots(b));
2610
+ case "variant":
2611
+ return Math.max(0, ...a.map(([, item]) => item === NONE ? 0 : slots(item)));
2612
+ default:
2613
+ return 0;
2614
+ }
2615
+ }
2616
+ var HANDLE_FREE = {
2617
+ handle() {
2618
+ throw new Error("handle-bearing stream items are unsupported");
2619
+ },
2620
+ value() {
2621
+ throw new Error("handle-bearing stream items are unsupported");
2622
+ }
2623
+ };
2624
+
2625
+ class StandardHost {
2626
+ mounts;
2627
+ packetBytes;
2628
+ clocks;
2629
+ random;
2630
+ #cli;
2631
+ #entries = new Map;
2632
+ #reserved = 0;
2633
+ #work = new Set;
2634
+ #implementations;
2635
+ #allowed;
2636
+ #inputs = new Set;
2637
+ #budget = new InputBudget;
2638
+ #ingress;
2639
+ #closed = false;
2640
+ constructor(allowed, mounts, packetBytes, providers = {}) {
2641
+ this.mounts = mounts;
2642
+ this.packetBytes = packetBytes;
2643
+ this.clocks = checkedClocks(providers.clocks ?? browserClocks());
2644
+ this.random = revisionRandom(providers.random ?? browserRandom());
2645
+ this.#cli = new StandardCli(providers.cli, providers.stdio);
2646
+ const implementations = {
2647
+ ...systemMethods(this.clocks, this.random),
2648
+ ...filesystemMethods(() => this.mounts),
2649
+ ...this.#cli.methods,
2650
+ ...httpMethods(providers.http),
2651
+ ...socketMethods(providers.sockets ?? {})
2652
+ };
2653
+ this.#allowed = METHODS.map((method) => allowed.has(method.interface));
2654
+ this.#implementations = METHODS.map((method, index) => this.#allowed[index] ? implementations[methodKey(method)] ?? implementations[`${method.interface}#${method.name}`] : undefined);
2655
+ }
2656
+ get closed() {
2657
+ return this.#closed;
2658
+ }
2659
+ get size() {
2660
+ return this.#entries.size;
2661
+ }
2662
+ get inputBytes() {
2663
+ return this.#budget.used;
2664
+ }
2665
+ get pending() {
2666
+ return this.#work.size;
2667
+ }
2668
+ #track(work) {
2669
+ this.#work.add(work);
2670
+ const done = () => this.#work.delete(work);
2671
+ work.then(done, done);
2672
+ return work;
2673
+ }
2674
+ async settled() {
2675
+ while (this.#work.size)
2676
+ await Promise.allSettled([...this.#work]);
2677
+ }
2678
+ physical(signal, operation) {
2679
+ if (this.#closed)
2680
+ return Promise.reject(new Error("Standard host is closed"));
2681
+ if (signal?.aborted)
2682
+ return Promise.reject(cancelled());
2683
+ return this.#track((async () => operation())());
2684
+ }
2685
+ cleanup(operation) {
2686
+ this.#track((async () => operation())().catch(() => {}));
2687
+ }
2688
+ #issue(entry) {
2689
+ const full = this.#entries.size + this.#reserved >= HANDLE_LIMIT;
2690
+ if (full || issued >= Number.MAX_SAFE_INTEGER)
2691
+ throw new Error(full ? "standard handle table is full" : "standard handle space is exhausted");
2692
+ this.#entries.set(++issued, entry);
2693
+ return issued;
2694
+ }
2695
+ #orphan(future, payload) {
2696
+ future.value.then((value) => this.#releaseValue(payload, value), () => {});
2697
+ }
2698
+ #release(entry, undelivered = false) {
2699
+ switch (entry.kind) {
2700
+ case "own":
2701
+ return entry.value.release();
2702
+ case "output":
2703
+ case "input":
2704
+ return entry.value.close();
2705
+ case "future":
2706
+ if (undelivered)
2707
+ entry.value.cancel?.();
2708
+ return this.#orphan(entry.value, entry.payload);
2709
+ case "writable":
2710
+ entry.value.abandon();
2711
+ if (!entry.value.transferred)
2712
+ entry.value.close();
2713
+ return;
2714
+ }
2715
+ }
2716
+ #releaseValue(type, value, issued) {
2717
+ if (type === undefined || type === NONE || value === undefined || value === null)
2718
+ return;
2719
+ const [kind, a, b] = TYPES[type];
2720
+ switch (kind) {
2721
+ case "own":
2722
+ case "stream":
2723
+ case "future":
2724
+ if (issued?.has(value))
2725
+ return;
2726
+ if (value instanceof OutputStream || value instanceof InputStream)
2727
+ value.close();
2728
+ else if (value instanceof HostFuture) {
2729
+ value.cancel?.();
2730
+ this.#orphan(value, a);
2731
+ } else
2732
+ value.release();
2733
+ return;
2734
+ case "list":
2735
+ for (const item of value)
2736
+ this.#releaseValue(a, item, issued);
2737
+ return;
2738
+ case "tuple":
2739
+ a.forEach((item, position) => this.#releaseValue(item, value[position], issued));
2740
+ return;
2741
+ case "record":
2742
+ for (const [name, item] of a)
2743
+ this.#releaseValue(item, value[name], issued);
2744
+ return;
2745
+ case "option":
2746
+ return this.#releaseValue(a, value, issued);
2747
+ case "result":
2748
+ return this.#releaseValue(value.tag === "ok" ? a : b, value.val, issued);
2749
+ case "variant": {
2750
+ const found = a.find(([tag]) => tag === value.tag);
2751
+ return this.#releaseValue(found?.[1], value.val, issued);
2752
+ }
2753
+ }
2754
+ }
2755
+ #handles = {
2756
+ handle: (kind, detail, value) => {
2757
+ if (kind === "own" && typeof detail === "number" && RESOURCES[detail] !== undefined)
2758
+ return this.#issue({ kind: "own", resource: detail, value });
2759
+ if (kind === "stream" && value instanceof OutputStream)
2760
+ return this.#issue({
2761
+ kind: "output",
2762
+ item: detail === "u8" ? undefined : detail,
2763
+ value
2764
+ });
2765
+ if (kind === "future" && value instanceof HostFuture)
2766
+ return this.#issue({ kind: "future", payload: detail, value });
2767
+ throw new Error(`standard ${kind} results are unsupported in this browser host`);
2768
+ },
2769
+ value: () => {
2770
+ throw new Error("standard handles are decoded only as call parameters");
2771
+ }
2772
+ };
2773
+ #claims() {
2774
+ const commits = [];
2775
+ const owned = [];
2776
+ const borrowed = [];
2777
+ const moved = new Set;
2778
+ const lent = new Set;
2779
+ const codec = {
2780
+ handle: this.#handles.handle,
2781
+ value: (kind, detail, handle) => {
2782
+ const entry = this.#entries.get(handle);
2783
+ if (!entry)
2784
+ throw new Error("unknown or dropped handle");
2785
+ if (moved.has(handle))
2786
+ throw new Error("handle is passed more than once");
2787
+ switch (kind) {
2788
+ case "own":
2789
+ case "borrow":
2790
+ if (entry.kind !== "own" || entry.resource !== detail)
2791
+ throw new Error("handle has a different type");
2792
+ if (kind === "borrow") {
2793
+ lent.add(handle);
2794
+ borrowed.push(entry.value);
2795
+ return entry.value;
2796
+ }
2797
+ if (lent.has(handle))
2798
+ throw new Error("handle is passed more than once");
2799
+ if (entry.value.borrows)
2800
+ throw new Error("handle is borrowed by a pending call");
2801
+ moved.add(handle);
2802
+ owned.push(entry.value);
2803
+ commits.push(() => this.#entries.delete(handle));
2804
+ return entry.value;
2805
+ case "stream":
2806
+ if (entry.kind !== "input" || TYPES[entry.value.type][1] !== detail)
2807
+ throw new Error("handle has a different type");
2808
+ if (entry.value.transferred)
2809
+ throw new Error("stream was already transferred");
2810
+ moved.add(handle);
2811
+ commits.push(() => {
2812
+ entry.value.transferred = true;
2813
+ });
2814
+ return entry.value;
2815
+ case "future":
2816
+ if (entry.kind !== "writable" || TYPES[entry.value.type][1] !== detail)
2817
+ throw new Error("handle has a different type");
2818
+ if (entry.value.transferred)
2819
+ throw new Error("future was already transferred");
2820
+ moved.add(handle);
2821
+ commits.push(() => {
2822
+ entry.value.transferred = true;
2823
+ });
2824
+ return entry.value;
2825
+ default:
2826
+ throw new Error(`standard ${kind} parameters are unsupported`);
2827
+ }
2828
+ }
2829
+ };
2830
+ return {
2831
+ codec,
2832
+ owned,
2833
+ borrowed,
2834
+ commit: () => {
2835
+ for (const commit of commits)
2836
+ commit();
2837
+ }
2838
+ };
2839
+ }
2840
+ #method(reader, asynchronous) {
2841
+ const index = reader.u32();
2842
+ const method = METHODS[index];
2843
+ if (!method)
2844
+ throw new Error("unknown standard method");
2845
+ if (!this.#allowed[index])
2846
+ throw new Error("standard interface is not imported by this Orb");
2847
+ if (method.asynchronous !== asynchronous)
2848
+ throw new Error("standard call uses the wrong calling convention");
2849
+ if (!this.#implementations[index])
2850
+ throw new Error(`${method.interface}#${method.name} is unavailable in this browser host`);
2851
+ return index;
2852
+ }
2853
+ #arguments(index, reader, lent) {
2854
+ const claims = this.#claims();
2855
+ const method = METHODS[index];
2856
+ const args = method.params.map((type) => decode(reader, type, claims.codec));
2857
+ reader.end();
2858
+ const needed = method.result === undefined ? 0 : slots(method.result);
2859
+ if (this.#entries.size + this.#reserved + needed > HANDLE_LIMIT)
2860
+ throw new Error("standard handle table is full");
2861
+ claims.commit();
2862
+ for (const resource of lent ? claims.borrowed : []) {
2863
+ resource.borrows++;
2864
+ resource.retain();
2865
+ lent.push(resource);
2866
+ }
2867
+ return { args, owned: claims.owned };
2868
+ }
2869
+ #deliver(type, value, head) {
2870
+ const issued = [];
2871
+ const values = new Set;
2872
+ const codec = {
2873
+ ...this.#handles,
2874
+ handle: (kind, detail, item) => {
2875
+ const handle = this.#handles.handle(kind, detail, item);
2876
+ issued.push(handle);
2877
+ values.add(item);
2878
+ return handle;
2879
+ }
2880
+ };
2881
+ try {
2882
+ const writer = new Writer;
2883
+ head?.(writer);
2884
+ if (type !== undefined && type !== NONE)
2885
+ encode2(writer, type, value, codec);
2886
+ const bytes = writer.finish();
2887
+ if (bytes.length > this.packetBytes)
2888
+ throw new Error("standard reply exceeds the packet bound");
2889
+ return { bytes, issued };
2890
+ } catch (error) {
2891
+ this.discard({ issued });
2892
+ this.#releaseValue(type, value, values);
2893
+ throw error;
2894
+ }
2895
+ }
2896
+ sync(packet) {
2897
+ if (this.#closed)
2898
+ throw new Error("Standard host is closed");
2899
+ const reader = new Reader(packet);
2900
+ if (reader.u8() !== STANDARD_PACKET)
2901
+ throw new Error("not a standard packet");
2902
+ switch (reader.u8()) {
2903
+ case CALL: {
2904
+ const index = this.#method(reader, false);
2905
+ const { args, owned } = this.#arguments(index, reader);
2906
+ let value;
2907
+ try {
2908
+ value = this.#implementations[index]({ host: this }, args);
2909
+ } finally {
2910
+ for (const resource of owned)
2911
+ resource.release();
2912
+ }
2913
+ return this.#deliver(METHODS[index].result, value).bytes;
2914
+ }
2915
+ case DROP: {
2916
+ const handle = reader.handle();
2917
+ reader.end();
2918
+ const entry = this.#entries.get(handle);
2919
+ if (!entry)
2920
+ throw new Error("unknown or dropped handle");
2921
+ if (entry.kind === "own" && entry.value.borrows)
2922
+ throw new Error("handle is borrowed by a pending call");
2923
+ this.#entries.delete(handle);
2924
+ this.#inputs.delete(handle);
2925
+ this.#release(entry);
2926
+ return new Uint8Array;
2927
+ }
2928
+ case STREAM_NEW: {
2929
+ const type = reader.u32();
2930
+ reader.end();
2931
+ if (type !== BYTE_STREAM)
2932
+ throw new Error("unsupported input stream type");
2933
+ const handle = this.#issue({ kind: "input", value: new InputStream(type, this.#budget) });
2934
+ this.#inputs.add(handle);
2935
+ const writer = new Writer;
2936
+ writer.handle(handle);
2937
+ return writer.finish();
2938
+ }
2939
+ case FUTURE_NEW: {
2940
+ const type = reader.u32();
2941
+ reader.end();
2942
+ if (!WRITABLE_FUTURES.includes(type))
2943
+ throw new Error("unsupported writable future type");
2944
+ const payload = TYPES[type][1];
2945
+ const future = new WritableFuture(type, ABANDONED, (value) => this.#releaseValue(payload, value));
2946
+ const handle = this.#issue({ kind: "writable", value: future });
2947
+ this.#inputs.add(handle);
2948
+ const writer = new Writer;
2949
+ writer.handle(handle);
2950
+ return writer.finish();
2951
+ }
2952
+ case FUTURE_WRITE: {
2953
+ const handle = reader.handle();
2954
+ const entry = this.#entries.get(handle);
2955
+ if (entry?.kind !== "writable")
2956
+ throw new Error("handle is not a live writable future");
2957
+ if (entry.value.written)
2958
+ throw new Error("future was already written");
2959
+ const claims = this.#claims();
2960
+ const value = decode(reader, TYPES[entry.value.type][1], claims.codec);
2961
+ reader.end();
2962
+ if (claims.borrowed.length)
2963
+ throw new Error("future payloads cannot borrow");
2964
+ claims.commit();
2965
+ entry.value.write(value);
2966
+ return new Uint8Array;
2967
+ }
2968
+ default:
2969
+ throw new Error("unknown standard operation");
2970
+ }
2971
+ }
2972
+ async async(packet, signal) {
2973
+ if (this.#closed)
2974
+ throw new Error("Standard host is closed");
2975
+ const reader = new Reader(packet);
2976
+ if (reader.u8() !== STANDARD_PACKET)
2977
+ throw new Error("not a standard packet");
2978
+ switch (reader.u8()) {
2979
+ case CALL: {
2980
+ const index = this.#method(reader, true);
2981
+ if (signal?.aborted)
2982
+ throw cancelled();
2983
+ const lent = [];
2984
+ const { args, owned } = this.#arguments(index, reader, lent);
2985
+ let release = () => {};
2986
+ if (lent.length)
2987
+ this.#track(new Promise((resolve) => {
2988
+ release = resolve;
2989
+ }));
2990
+ const work = [];
2991
+ const host = this;
2992
+ const services = {
2993
+ packetBytes: this.packetBytes,
2994
+ get closed() {
2995
+ return host.closed;
2996
+ },
2997
+ physical: (signal, operation) => {
2998
+ const started = this.physical(signal, operation);
2999
+ work.push(started);
3000
+ return started;
3001
+ },
3002
+ cleanup: (operation) => this.cleanup(operation)
3003
+ };
3004
+ try {
3005
+ let started;
3006
+ try {
3007
+ started = this.#implementations[index]({ host: services, signal }, args);
3008
+ } finally {
3009
+ for (const resource of owned)
3010
+ resource.release();
3011
+ }
3012
+ const value = await started;
3013
+ if (signal?.aborted || this.#closed) {
3014
+ this.#releaseValue(METHODS[index].result, value);
3015
+ throw cancelled();
3016
+ }
3017
+ return this.#deliver(METHODS[index].result, value);
3018
+ } finally {
3019
+ Promise.allSettled(work).then(() => {
3020
+ for (const resource of lent) {
3021
+ resource.borrows--;
3022
+ resource.release();
3023
+ }
3024
+ release();
3025
+ });
3026
+ }
3027
+ }
3028
+ case STREAM_READ: {
3029
+ const handle = reader.handle();
3030
+ const requested = reader.u32();
3031
+ reader.end();
3032
+ const entry = this.#entries.get(handle);
3033
+ if (entry?.kind !== "output")
3034
+ throw new Error("handle is not a live output stream");
3035
+ const item = entry.item;
3036
+ if (item !== undefined && slots(item) > 0) {
3037
+ let reserved = slots(item);
3038
+ if (this.#entries.size + this.#reserved + reserved > HANDLE_LIMIT)
3039
+ throw new Error("standard handle table is full");
3040
+ this.#reserved += reserved;
3041
+ const unreserve = () => {
3042
+ this.#reserved -= reserved;
3043
+ reserved = 0;
3044
+ };
3045
+ try {
3046
+ const taken = await this.#track(entry.value.take(signal));
3047
+ unreserve();
3048
+ if (!taken)
3049
+ return { bytes: Uint8Array.of(1), issued: [], reads: [handle] };
3050
+ if (this.#closed || entry.value.closed) {
3051
+ this.#releaseValue(item, taken.value);
3052
+ throw new Error(this.#closed ? "Standard host is closed" : "stream was dropped");
3053
+ }
3054
+ const delivery = this.#deliver(item, taken.value, (writer) => {
3055
+ writer.u8(0);
3056
+ writer.u32(1);
3057
+ });
3058
+ return { ...delivery, reads: [handle] };
3059
+ } finally {
3060
+ unreserve();
3061
+ }
3062
+ }
3063
+ const limit = item === undefined ? Math.min(Math.max(requested, 1), STREAM_CHUNK, this.packetBytes - 5) : Math.max(requested, 1);
3064
+ if (limit < 1)
3065
+ throw new Error("standard reply exceeds the packet bound");
3066
+ const encodeItem = item === undefined ? undefined : (value) => {
3067
+ const writer = new Writer;
3068
+ encode2(writer, item, value, HANDLE_FREE);
3069
+ return writer.finish();
3070
+ };
3071
+ const bytes = await this.#track(entry.value.read(limit, this.packetBytes, signal, encodeItem));
3072
+ return { bytes, issued: [], reads: [handle] };
3073
+ }
3074
+ case STREAM_WRITE: {
3075
+ const handle = reader.handle();
3076
+ const length = reader.u32();
3077
+ if (length > STREAM_CHUNK)
3078
+ throw new Error("stream write exceeds the 64 KiB chunk bound");
3079
+ if (reader.remaining !== length)
3080
+ throw new RangeError(reader.remaining < length ? "standard packet is truncated" : "standard packet has trailing bytes");
3081
+ const entry = this.#entries.get(handle);
3082
+ if (entry?.kind !== "input")
3083
+ throw new Error("handle is not a live input stream");
3084
+ try {
3085
+ await entry.value.write(length, () => reader.raw(length), signal);
3086
+ } catch (error) {
3087
+ if (entry.value.cancelled)
3088
+ return { bytes: Uint8Array.of(WRITE_CLOSED), issued: [] };
3089
+ throw error;
3090
+ }
3091
+ return { bytes: Uint8Array.of(WRITE_ACCEPTED), issued: [] };
3092
+ }
3093
+ case INGRESS_HEAD: {
3094
+ const call = this.#ingress;
3095
+ if (!call)
3096
+ throw new Error("no incoming HTTP request is being served");
3097
+ if (call.exchange.published)
3098
+ throw new Error("the response head was already published");
3099
+ if (signal?.aborted)
3100
+ throw cancelled();
3101
+ const claims = this.#claims();
3102
+ const result = decode(reader, HANDLER_RESULT, claims.codec);
3103
+ reader.end();
3104
+ claims.commit();
3105
+ const ended = call.respond(this, result);
3106
+ try {
3107
+ await abortable(ended, signal);
3108
+ } catch (error) {
3109
+ call.end(error);
3110
+ throw error;
3111
+ }
3112
+ return { bytes: new Uint8Array, issued: [] };
3113
+ }
3114
+ case FUTURE_READ: {
3115
+ const handle = reader.handle();
3116
+ reader.end();
3117
+ const entry = this.#entries.get(handle);
3118
+ if (entry?.kind !== "future")
3119
+ throw new Error("handle is not a live future");
3120
+ this.#entries.delete(handle);
3121
+ let value;
3122
+ try {
3123
+ value = await abortable(entry.value.value, signal);
3124
+ } catch (error) {
3125
+ if (signal?.aborted)
3126
+ this.#orphan(entry.value, entry.payload);
3127
+ throw error;
3128
+ }
3129
+ if (signal?.aborted || this.#closed) {
3130
+ this.#releaseValue(entry.payload, value);
3131
+ throw cancelled();
3132
+ }
3133
+ return this.#deliver(entry.payload, value);
3134
+ }
3135
+ case STREAM_IMPORT:
3136
+ throw new Error("stream imports are served only through the native Rust facade");
3137
+ default:
3138
+ throw new Error("unknown standard operation");
3139
+ }
3140
+ }
3141
+ discard(delivery) {
3142
+ for (const handle of delivery.reads ?? []) {
3143
+ const entry = this.#entries.get(handle);
3144
+ if (entry?.kind === "output")
3145
+ entry.value.abandon();
3146
+ }
3147
+ for (const handle of delivery.issued) {
3148
+ const entry = this.#entries.get(handle);
3149
+ if (!entry)
3150
+ continue;
3151
+ this.#entries.delete(handle);
3152
+ this.#release(entry, true);
3153
+ }
3154
+ }
3155
+ beginIngress(exchange) {
3156
+ if (this.#closed)
3157
+ throw new Error("Standard host is closed");
3158
+ if (this.#ingress)
3159
+ throw new Error("an incoming HTTP request is already being served");
3160
+ const call = new IngressCall(exchange, (operation) => this.cleanup(operation));
3161
+ const request = call.resource();
3162
+ try {
3163
+ const handle = this.#issue({ kind: "own", resource: HTTP_REQUEST, value: request });
3164
+ this.#ingress = call;
3165
+ return handle;
3166
+ } catch (error) {
3167
+ request.release();
3168
+ throw error;
3169
+ }
3170
+ }
3171
+ endIngress(reason) {
3172
+ const call = this.#ingress;
3173
+ this.#ingress = undefined;
3174
+ call?.end(reason);
3175
+ }
3176
+ endCallback() {
3177
+ for (const handle of this.#inputs) {
3178
+ const entry = this.#entries.get(handle);
3179
+ if (entry?.kind !== "input" && entry?.kind !== "writable")
3180
+ continue;
3181
+ this.#entries.delete(handle);
3182
+ this.#release(entry);
3183
+ }
3184
+ this.#inputs.clear();
3185
+ }
3186
+ async dispose() {
3187
+ this.#closed = true;
3188
+ this.endIngress(new Error("Standard host is closed"));
3189
+ this.#cli.retire();
3190
+ for (const [handle, entry] of this.#entries)
3191
+ if (entry.kind === "input" || entry.kind === "writable") {
3192
+ this.#entries.delete(handle);
3193
+ this.#release(entry);
3194
+ }
3195
+ this.#inputs.clear();
3196
+ await this.settled();
3197
+ const entries = [...this.#entries.values()];
3198
+ this.#entries.clear();
3199
+ for (const entry of entries)
3200
+ this.#release(entry, true);
3201
+ await this.settled();
3202
+ this.#cli.close(this);
3203
+ await this.settled();
3204
+ this.#budget.discard();
3205
+ }
3206
+ }
3207
+
3208
+ // src/interpreter/browser.ts
3209
+ async function compileEngine(url) {
3210
+ const response = await fetch(url);
3211
+ if (!response.ok)
3212
+ throw new Error("Engine module request failed");
3213
+ const module = await WebAssembly.compile(await response.arrayBuffer());
3214
+ checkInterpreter(module);
3215
+ return module;
3216
+ }
3217
+
3218
+ class BrowserExecution {
3219
+ options;
3220
+ contracts;
3221
+ #engine;
3222
+ #components;
3223
+ constructor(options, contracts) {
3224
+ this.options = options;
3225
+ this.contracts = contracts;
3226
+ this.#components = preparedRegistry(options.components);
3227
+ }
3228
+ engine() {
3229
+ if (!this.#engine) {
3230
+ const compiled = compileEngine(new URL(this.options.engine));
3231
+ this.#engine = compiled;
3232
+ compiled.catch(() => {
3233
+ if (this.#engine === compiled)
3234
+ this.#engine = undefined;
3235
+ });
3236
+ }
3237
+ return this.#engine;
3238
+ }
3239
+ async materialize(definition) {
3240
+ if (this.contracts.compiledArtifact(definition.artifact))
3241
+ return this.compiled(definition);
3242
+ const artifact = new this.contracts.WasmArtifact(definition.artifact);
3243
+ let released = false;
3244
+ const release = () => {
3245
+ if (released)
3246
+ return;
3247
+ released = true;
3248
+ artifact.free();
3249
+ };
3250
+ try {
3251
+ return await this.open(artifact, definition, release);
3252
+ } catch (error) {
3253
+ release();
3254
+ throw error;
3255
+ }
3256
+ }
3257
+ async compiled(definition) {
3258
+ if (!this.#components.size)
3259
+ throw new Error("Compiled Orbs run in browsers only through a prepared adapter: build the Orb with " + "`browser: true` and pass the generated module to " + "createHost({ isolated: { components: [...] } })");
3260
+ let contract;
3261
+ try {
3262
+ contract = new this.contracts.WasmPreparedComponent(definition.artifact, [
3263
+ ...this.#components.keys()
3264
+ ]);
3265
+ } catch (error) {
3266
+ if (!String(error).includes("no prepared browser adapter"))
3267
+ throw error;
3268
+ throw new Error("This compiled Orb matches no registered prepared adapter; rebuild it with " + "`browser: true` and register the module generated for exactly this artifact", { cause: error });
3269
+ }
3270
+ let released = false;
3271
+ const release = () => {
3272
+ if (released)
3273
+ return;
3274
+ released = true;
3275
+ contract.free();
3276
+ };
3277
+ try {
3278
+ const record = this.#components.get(contract.digest());
3279
+ if (!record)
3280
+ throw new Error("The verifier selected an unregistered prepared adapter");
3281
+ const { openComponent } = await import("./execution-nsqc6nrt.js");
3282
+ return await openComponent(record, contract, definition, this.options, release);
3283
+ } catch (error) {
3284
+ release();
3285
+ throw error;
3286
+ }
3287
+ }
3288
+ async open(contract, installation, release) {
3289
+ const identity = JSON.parse(contract.description());
3290
+ if (identity.kind !== "source")
3291
+ throw new Error("Compiled Orb execution is unavailable in this browser backend");
3292
+ const prepared = query(contract, {
3293
+ kind: "install",
3294
+ name: identity.name,
3295
+ apiVersion: identity.apiVersion,
3296
+ requires: installation.requires ?? {},
3297
+ grants: installation.grants ?? {},
3298
+ filesystem: Object.keys(this.options.providers?.filesystem ?? {}),
3299
+ network: Object.keys(this.options.providers?.network ?? {}),
3300
+ http: Object.keys(this.options.providers?.http ?? {})
3301
+ });
3302
+ const kernel = Object.entries(prepared.bindings).find(([, binding]) => binding.kind === "kernel");
3303
+ if (kernel)
3304
+ throw new Error(`${kernel[0]}: the kernel serves tembra:guest to compiled components only; a source Orb reaches its state, resources and context through its bundle`);
3305
+ const options = { ...identity, grants: installation.grants };
3306
+ let capabilities;
3307
+ let stdio;
3308
+ const port = new BrowserPort(this.options.limits?.timeoutMs ?? 1e4, async () => {
3309
+ const cleanup = [Promise.resolve().then(() => capabilities?.dispose())];
3310
+ if (stdio)
3311
+ for (const provider of new Set([stdio.stdin, stdio.stdout, stdio.stderr]))
3312
+ cleanup.push(Promise.resolve().then(() => provider?.close?.()));
3313
+ const settled = await Promise.allSettled(cleanup);
3314
+ release();
3315
+ const failed = settled.filter((result) => result.status === "rejected");
3316
+ if (failed.length)
3317
+ throw new AggregateError(failed.map((result) => result.reason), "Provider cleanup failed");
3318
+ }, (record) => {
3319
+ if (!["log", "debug", "info", "warn", "error"].includes(record.level))
3320
+ throw new Error("Invalid console level");
3321
+ try {
3322
+ this.options.onLog?.({
3323
+ orb: options.name,
3324
+ level: record.level,
3325
+ message: String(record.message)
3326
+ });
3327
+ } catch {}
3328
+ }, this.options.limits?.packetBytes ?? 8388608);
3329
+ try {
3330
+ const memory = this.options.limits?.memoryBytes ?? 134217728;
3331
+ if (!Number.isSafeInteger(memory) || memory < 2097152 || memory > 4294967295)
3332
+ throw new Error("Invalid interpreter memory bound");
3333
+ capabilities = await BrowserCapabilities.open(options.grants ?? {}, this.options.providers ?? {});
3334
+ const description = query(contract, { kind: "describe" });
3335
+ const bound = (name) => {
3336
+ const entry = description.imports.find((item) => item.contract === name);
3337
+ const binding = entry && prepared.bindings[entry.binding];
3338
+ return binding?.kind === "host" ? binding.provider : undefined;
3339
+ };
3340
+ if (options.grants?.system?.includes("cli"))
3341
+ stdio = this.options.providers?.stdio?.(options.name, installation.cli ?? {});
3342
+ port.standard = new StandardHost(new Set(description.imports.filter((item) => item.type_only === false).map((item) => item.contract)), capabilities.mounts, this.options.limits?.packetBytes ?? 8388608, {
3343
+ clocks: this.options.providers?.clocks,
3344
+ random: this.options.providers?.random,
3345
+ http: capabilities.network,
3346
+ sockets: {
3347
+ types: capabilities.network.sockets(bound("wasi:sockets/types@0.3.0")),
3348
+ lookup: capabilities.network.sockets(bound("wasi:sockets/ip-name-lookup@0.3.0"))
3349
+ },
3350
+ ...options.grants?.system?.includes("cli") ? {
3351
+ cli: installation.cli,
3352
+ stdio
3353
+ } : { stdio: undefined }
3354
+ });
3355
+ stdio = undefined;
3356
+ const { clocks, random } = port.standard;
3357
+ port.guest = await CoreGuest.create(await this.engine(), memory, {
3358
+ sync: (packet) => typeof packet === "string" ? port.sync(packet) : port.sync(packet),
3359
+ log: (level, message) => port.log({ operation: "console", level, message }),
3360
+ clock: (clock) => {
3361
+ if (!options.grants?.system?.includes("clocks"))
3362
+ return 0n;
3363
+ if (clock === CLOCK_MONOTONIC)
3364
+ return clocks.monotonicNow();
3365
+ const instant = clocks.systemNow();
3366
+ return instant.seconds * 1000000000n + BigInt(instant.nanoseconds);
3367
+ }
3368
+ });
3369
+ await port.load(JSON.stringify({
3370
+ source: contract.source(),
3371
+ heap_bytes: Math.floor(memory / 2),
3372
+ instruction_ticks: this.options.limits?.instructionTicks ?? 1e4,
3373
+ contract: description,
3374
+ exports: exportedFunctions(description, contract),
3375
+ builtins: {
3376
+ clock: options.grants?.system?.includes("clocks") ?? false,
3377
+ seed: options.grants?.system?.includes("random") ? random.insecureSeed().map(String) : null
3378
+ }
3379
+ }));
3380
+ return new Revision(port, contract, this.options.limits?.timeoutMs ?? 1e4).definition(options, prepared);
3381
+ } catch (error) {
3382
+ try {
3383
+ await port.close();
3384
+ } catch (disposal) {
3385
+ throw new AggregateError([error, disposal], "Interpreter initialization and disposal failed");
3386
+ }
3387
+ throw error;
3388
+ }
3389
+ }
3390
+ }
3391
+ async function createExecution(options) {
3392
+ const engine = options.engine === undefined ? (await import("@syntropika/tembra-engine-wasm/assets")).interpreterURL() : new URL(options.engine, globalThis.location?.href);
3393
+ const contracts = await import("@syntropika/tembra-engine-wasm/contracts");
3394
+ await contracts.default(options.contractsInput);
3395
+ return new BrowserExecution({ ...options, engine }, contracts);
3396
+ }
3397
+ export {
3398
+ createExecution
3399
+ };