@syntropika/tembra-sdk 0.2.1 → 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 -3298
  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 -3276
  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 -3287
  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 +9 -3
  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 +218 -56
  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 -293
@@ -0,0 +1,787 @@
1
+ import {
2
+ key,
3
+ isImplicit,
4
+ parseSocketAddress
5
+ } from "./index-v6heph77.js";
6
+ import {
7
+ RESOURCES,
8
+ METHODS,
9
+ STREAM_CHUNK,
10
+ Writer
11
+ } from "./index-h8t0n42q.js";
12
+
13
+ // src/interpreter/browser-network.ts
14
+ class SocketGrants {
15
+ #connect = new Set;
16
+ #listen = [];
17
+ #listenKeys = new Set;
18
+ #bind = new Set;
19
+ #datagrams = new Set;
20
+ resolve;
21
+ constructor(grants, provider) {
22
+ let resolve = false;
23
+ const parse = (text) => {
24
+ const address = parseSocketAddress(text);
25
+ if (!address)
26
+ throw new Error(`Invalid network grant address ${text}`);
27
+ return address;
28
+ };
29
+ for (const grant of grants.network ?? []) {
30
+ if (grant.provider !== provider)
31
+ continue;
32
+ for (const text of grant.connect ?? [])
33
+ this.#connect.add(key(parse(text)));
34
+ for (const text of grant.listen ?? []) {
35
+ const address = parse(text);
36
+ this.#listen.push(address);
37
+ this.#listenKeys.add(key(address));
38
+ }
39
+ for (const text of grant.bind ?? [])
40
+ this.#bind.add(key(parse(text)));
41
+ for (const text of grant.datagrams ?? [])
42
+ this.#datagrams.add(key(parse(text)));
43
+ resolve ||= grant.resolve === true;
44
+ }
45
+ this.resolve = resolve;
46
+ }
47
+ get tcp() {
48
+ return this.#connect.size > 0 || this.#listen.length > 0 || this.#bind.size > 0;
49
+ }
50
+ get udp() {
51
+ return this.#datagrams.size > 0 || this.#bind.size > 0;
52
+ }
53
+ allows(address, use) {
54
+ const exact = key(address);
55
+ switch (use) {
56
+ case "tcp-connect":
57
+ return this.#connect.has(exact);
58
+ case "tcp-bind":
59
+ return isImplicit(address) && this.tcp || this.#bind.has(exact) || this.#listenKeys.has(exact);
60
+ case "tcp-listen":
61
+ return this.#listen.some((granted) => granted.family === address.family && granted.ip.every((part, index) => part === address.ip[index]) && (granted.port === 0 || granted.port === address.port));
62
+ case "tcp-accept":
63
+ return this.#listen.length > 0;
64
+ case "udp-bind":
65
+ return isImplicit(address) && this.#datagrams.size > 0 || this.#bind.has(exact);
66
+ case "udp-send":
67
+ case "udp-receive":
68
+ return this.#datagrams.has(exact);
69
+ }
70
+ }
71
+ }
72
+
73
+ class BrowserNetwork {
74
+ grants;
75
+ providers;
76
+ #disposed = false;
77
+ constructor(grants, providers) {
78
+ this.grants = grants;
79
+ this.providers = providers;
80
+ for (const grant of grants.http ?? []) {
81
+ if (!grant.provider.trim() || !grant.origins.length)
82
+ throw new Error("HTTP grants require a provider and at least one origin");
83
+ for (const origin of grant.origins) {
84
+ const url = new URL(origin);
85
+ if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.href.includes("#") || url.pathname !== "/" || url.href.includes("?") || url.hostname.includes("*") || url.port === "0")
86
+ throw new Error("HTTP grants require exact http(s) origins without credentials, paths, queries, wildcards or port 0");
87
+ }
88
+ }
89
+ for (const grant of grants.network ?? [])
90
+ new SocketGrants(grants, grant.provider);
91
+ }
92
+ provider(url) {
93
+ if (this.#disposed || url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password)
94
+ return;
95
+ const grant = this.grants.http?.find((grant) => grant.origins.some((origin) => new URL(origin).origin === url.origin));
96
+ return grant && this.providers.http?.[grant.provider];
97
+ }
98
+ sockets(provider) {
99
+ if (provider === undefined)
100
+ return;
101
+ return {
102
+ provider: this.providers.network?.[provider],
103
+ grants: new SocketGrants(this.grants, provider)
104
+ };
105
+ }
106
+ dispose() {
107
+ this.#disposed = true;
108
+ }
109
+ }
110
+
111
+ // src/interpreter/io.ts
112
+ class BrowserCapabilities {
113
+ network;
114
+ #mounts = [];
115
+ #preopens = [];
116
+ constructor(network) {
117
+ this.network = network;
118
+ }
119
+ static async open(grants, providers) {
120
+ const capabilities = new BrowserCapabilities(new BrowserNetwork(grants, providers));
121
+ try {
122
+ for (const grant of grants.filesystem ?? []) {
123
+ const provider = providers.filesystem?.[grant.provider];
124
+ if (!provider)
125
+ throw new Error(`Unknown filesystem provider ${grant.provider}`);
126
+ capabilities.#mounts.push({
127
+ path: grant.mount,
128
+ writable: grant.writable,
129
+ filesystem: provider.open(grant.mount, grant.writable)
130
+ });
131
+ }
132
+ capabilities.#preopens = Object.freeze([...capabilities.#mounts]);
133
+ } catch (error) {
134
+ try {
135
+ await capabilities.dispose();
136
+ } catch (disposal) {
137
+ throw new AggregateError([error, disposal], "Filesystem initialization and disposal failed");
138
+ }
139
+ throw error;
140
+ }
141
+ return capabilities;
142
+ }
143
+ get mounts() {
144
+ return this.#preopens;
145
+ }
146
+ async dispose() {
147
+ const mounts = this.#mounts.splice(0);
148
+ this.#preopens = [];
149
+ const settled = await Promise.allSettled([
150
+ Promise.resolve().then(() => this.network.dispose()),
151
+ ...mounts.map(async (mount) => mount.filesystem.dispose())
152
+ ]);
153
+ const errors = settled.filter((result) => result.status === "rejected").map((result) => result.reason);
154
+ if (errors.length)
155
+ throw new AggregateError(errors, "Filesystem disposal failed");
156
+ }
157
+ }
158
+
159
+ // src/interpreter/standard-streams.ts
160
+ function methodKey(method) {
161
+ return method.resource === undefined ? `${method.interface}#${method.name}` : `${RESOURCES[method.resource]}.${method.name}`;
162
+ }
163
+ function bindResource(contract, resource, prototype, statics) {
164
+ const implementations = {};
165
+ const qualified = `${contract}#${resource}`;
166
+ for (const method of METHODS) {
167
+ if (method.resource === undefined || RESOURCES[method.resource] !== qualified)
168
+ continue;
169
+ const name = method.name;
170
+ if (method.kind !== undefined) {
171
+ if (!Object.hasOwn(statics, name))
172
+ throw new Error(`${qualified}.${name} is unbound`);
173
+ const implementation = statics[name];
174
+ implementations[methodKey(method)] = (call, args) => implementation(call, ...args);
175
+ } else {
176
+ if (typeof prototype[name] !== "function")
177
+ throw new Error(`${qualified}.${name} is unbound`);
178
+ implementations[methodKey(method)] = (call, [self, ...args]) => self[name](...args, call);
179
+ }
180
+ }
181
+ return implementations;
182
+ }
183
+ var cancelled = () => new Error("Operation cancelled");
184
+ function abortable(operation, signal) {
185
+ if (!signal)
186
+ return operation;
187
+ if (signal.aborted)
188
+ return Promise.reject(cancelled());
189
+ return new Promise((resolve, reject) => {
190
+ const abort = () => reject(cancelled());
191
+ signal.addEventListener("abort", abort, { once: true });
192
+ operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
193
+ });
194
+ }
195
+
196
+ class HostFuture {
197
+ value;
198
+ cancel;
199
+ constructor(value, cancel) {
200
+ this.value = value;
201
+ this.cancel = cancel;
202
+ }
203
+ static of(value) {
204
+ return new HostFuture(Promise.resolve(value));
205
+ }
206
+ }
207
+
208
+ class WritableFuture {
209
+ type;
210
+ abandoned;
211
+ release;
212
+ transferred = false;
213
+ #written = false;
214
+ #taken = false;
215
+ #closed = false;
216
+ #value;
217
+ #deliver;
218
+ constructor(type, abandoned, release) {
219
+ this.type = type;
220
+ this.abandoned = abandoned;
221
+ this.release = release;
222
+ }
223
+ get written() {
224
+ return this.#written;
225
+ }
226
+ write(value) {
227
+ if (this.#written)
228
+ throw new Error("future was already written");
229
+ this.#written = true;
230
+ this.#settle(value);
231
+ }
232
+ abandon() {
233
+ if (this.#written)
234
+ return;
235
+ this.#written = true;
236
+ this.#settle(this.abandoned);
237
+ }
238
+ #settle(value) {
239
+ if (this.#closed)
240
+ return this.release(value);
241
+ if (this.#deliver) {
242
+ const deliver = this.#deliver;
243
+ this.#deliver = undefined;
244
+ return deliver(value);
245
+ }
246
+ this.#value = { value };
247
+ }
248
+ take() {
249
+ if (this.#taken || this.#closed)
250
+ return Promise.reject(new Error("future was already read"));
251
+ this.#taken = true;
252
+ const stored = this.#value;
253
+ this.#value = undefined;
254
+ if (stored)
255
+ return Promise.resolve(stored.value);
256
+ return new Promise((resolve) => {
257
+ this.#deliver = resolve;
258
+ });
259
+ }
260
+ close() {
261
+ if (this.#closed)
262
+ return;
263
+ this.#closed = true;
264
+ this.#deliver = undefined;
265
+ const stored = this.#value;
266
+ this.#value = undefined;
267
+ if (stored)
268
+ this.release(stored.value);
269
+ }
270
+ }
271
+
272
+ class OutputStream {
273
+ producer;
274
+ settle;
275
+ release;
276
+ #queue = Promise.resolve();
277
+ #dropped = new AbortController;
278
+ #ended = false;
279
+ #closed = false;
280
+ #abandoned = false;
281
+ #stash = [];
282
+ #inflight;
283
+ #pending;
284
+ constructor(producer, settle, release) {
285
+ this.producer = producer;
286
+ this.settle = settle;
287
+ this.release = release;
288
+ }
289
+ #end(end, failure) {
290
+ if (this.#ended)
291
+ return;
292
+ this.#ended = true;
293
+ this.settle(failure, end);
294
+ this.producer.close(end);
295
+ }
296
+ close() {
297
+ if (this.#closed)
298
+ return;
299
+ this.#closed = true;
300
+ this.#dropped.abort();
301
+ this.#stash = [];
302
+ this.#inflight = undefined;
303
+ const pending = this.#pending;
304
+ this.#pending = undefined;
305
+ pending?.then((taken) => taken && this.release?.(taken.value), () => {});
306
+ this.#end("dropped");
307
+ }
308
+ get closed() {
309
+ return this.#closed;
310
+ }
311
+ abandon() {
312
+ this.#abandoned = true;
313
+ this.#end("failed", new Error("stream read was abandoned"));
314
+ this.close();
315
+ }
316
+ take(signal) {
317
+ const next = this.#queue.then(async () => {
318
+ if (this.#abandoned)
319
+ throw new Error("stream read was abandoned");
320
+ if (this.#closed)
321
+ throw new Error("stream was dropped");
322
+ if (signal?.aborted)
323
+ throw cancelled();
324
+ if (!this.#pending) {
325
+ if (this.#ended)
326
+ return;
327
+ this.#pending = (async () => {
328
+ try {
329
+ const value = await this.producer.next();
330
+ if (value !== undefined)
331
+ return { value };
332
+ this.#end("eof");
333
+ } catch (error) {
334
+ this.#end("failed", error);
335
+ }
336
+ return;
337
+ })();
338
+ }
339
+ const pending = this.#pending;
340
+ try {
341
+ const taken = await abortable(abortable(pending, this.#dropped.signal), signal);
342
+ if (this.#abandoned)
343
+ throw new Error("stream read was abandoned");
344
+ if (this.#closed)
345
+ throw new Error("stream was dropped");
346
+ this.#pending = undefined;
347
+ return taken;
348
+ } catch (error) {
349
+ if (this.#abandoned)
350
+ throw new Error("stream read was abandoned");
351
+ if (this.#closed)
352
+ throw new Error("stream was dropped");
353
+ throw error;
354
+ }
355
+ });
356
+ this.#queue = next.then(() => {}, () => {});
357
+ return next;
358
+ }
359
+ read(limit, bound, signal, encodeItem) {
360
+ const next = this.#queue.then(() => this.#serve(limit, bound, signal, encodeItem));
361
+ this.#queue = next.then(() => {}, () => {});
362
+ return next;
363
+ }
364
+ async#serve(limit, bound, signal, encodeItem) {
365
+ const writer = new Writer;
366
+ if (this.#abandoned)
367
+ throw new Error("stream read was abandoned");
368
+ if (this.#closed)
369
+ throw new Error("stream was dropped");
370
+ if (signal?.aborted)
371
+ throw cancelled();
372
+ if (!encodeItem) {
373
+ const chunk = this.#stash.shift() ?? await this.#produce(limit, signal);
374
+ if (!chunk) {
375
+ writer.u8(1);
376
+ return writer.finish();
377
+ }
378
+ if (chunk.byteLength > limit)
379
+ this.#stash.unshift(chunk.subarray(limit));
380
+ writer.u8(0);
381
+ writer.bytes(chunk.subarray(0, limit));
382
+ return writer.finish();
383
+ }
384
+ const items = [];
385
+ let size = 5;
386
+ try {
387
+ while (items.length < limit) {
388
+ const item = this.#stash.shift() ?? await this.#produce(1, signal, encodeItem);
389
+ if (!item)
390
+ break;
391
+ if (size + item.byteLength > bound) {
392
+ if (!items.length) {
393
+ this.#end("failed", new Error("stream item exceeds the packet bound"));
394
+ throw new Error("stream item exceeds the packet bound");
395
+ }
396
+ this.#stash.unshift(item);
397
+ break;
398
+ }
399
+ items.push(item);
400
+ size += item.byteLength;
401
+ }
402
+ } catch (error) {
403
+ if (!this.#closed)
404
+ this.#stash.unshift(...items);
405
+ throw error;
406
+ }
407
+ if (!items.length) {
408
+ writer.u8(1);
409
+ return writer.finish();
410
+ }
411
+ writer.u8(0);
412
+ writer.u32(items.length);
413
+ for (const item of items)
414
+ writer.raw(item);
415
+ return writer.finish();
416
+ }
417
+ async#produce(limit, signal, encodeItem) {
418
+ let inflight = this.#inflight;
419
+ if (!inflight) {
420
+ if (this.#ended)
421
+ return;
422
+ inflight = this.#inflight = (async () => {
423
+ try {
424
+ if (!encodeItem) {
425
+ const chunk = await this.producer.next(limit);
426
+ if (chunk?.byteLength)
427
+ return chunk;
428
+ this.#end("eof");
429
+ return;
430
+ }
431
+ const item = await this.producer.next();
432
+ if (item !== undefined)
433
+ return encodeItem(item);
434
+ this.#end("eof");
435
+ return;
436
+ } catch (error) {
437
+ this.#end("failed", error);
438
+ return;
439
+ }
440
+ })();
441
+ }
442
+ try {
443
+ const value = await abortable(abortable(inflight, this.#dropped.signal), signal);
444
+ this.#inflight = undefined;
445
+ return value;
446
+ } catch (error) {
447
+ if (this.#abandoned)
448
+ throw new Error("stream read was abandoned");
449
+ if (this.#closed)
450
+ throw new Error("stream was dropped");
451
+ throw error;
452
+ }
453
+ }
454
+ }
455
+ var INPUT_BUDGET = 1 << 20;
456
+
457
+ class InputBudget {
458
+ limit;
459
+ #used = 0;
460
+ #streams = new Set;
461
+ #waiters = [];
462
+ constructor(limit = INPUT_BUDGET) {
463
+ this.limit = limit;
464
+ }
465
+ get used() {
466
+ return this.#used;
467
+ }
468
+ reserve(bytes, signal, interrupt) {
469
+ if (signal?.aborted)
470
+ return Promise.reject(cancelled());
471
+ if (interrupt?.aborted)
472
+ return Promise.reject(interrupt.reason);
473
+ if (!this.#waiters.length && this.#used + bytes <= this.limit) {
474
+ this.#used += bytes;
475
+ return Promise.resolve();
476
+ }
477
+ return new Promise((resolve, reject) => {
478
+ const detach = () => {
479
+ signal?.removeEventListener("abort", onSignal);
480
+ interrupt?.removeEventListener("abort", onInterrupt);
481
+ };
482
+ const waiter = {
483
+ bytes,
484
+ grant: () => {
485
+ detach();
486
+ resolve();
487
+ }
488
+ };
489
+ const leave = (error) => {
490
+ const at = this.#waiters.indexOf(waiter);
491
+ if (at < 0)
492
+ return;
493
+ this.#waiters.splice(at, 1);
494
+ detach();
495
+ reject(error);
496
+ this.#drain();
497
+ };
498
+ const onSignal = () => leave(cancelled());
499
+ const onInterrupt = () => leave(interrupt.reason);
500
+ signal?.addEventListener("abort", onSignal, { once: true });
501
+ interrupt?.addEventListener("abort", onInterrupt, { once: true });
502
+ this.#waiters.push(waiter);
503
+ });
504
+ }
505
+ release(bytes) {
506
+ this.#used -= bytes;
507
+ this.#drain();
508
+ }
509
+ attach(stream) {
510
+ this.#streams.add(stream);
511
+ }
512
+ detach(stream) {
513
+ this.#streams.delete(stream);
514
+ }
515
+ discard() {
516
+ for (const stream of [...this.#streams])
517
+ stream.cancel();
518
+ }
519
+ #drain() {
520
+ while (this.#waiters.length && this.#used + this.#waiters[0].bytes <= this.limit) {
521
+ const waiter = this.#waiters.shift();
522
+ this.#used += waiter.bytes;
523
+ waiter.grant();
524
+ }
525
+ }
526
+ }
527
+
528
+ class InputStream {
529
+ type;
530
+ budget;
531
+ transferred = false;
532
+ #chunks = [];
533
+ #buffered = 0;
534
+ #eof = false;
535
+ #cancelled = false;
536
+ #writing;
537
+ #pending;
538
+ #wake;
539
+ #stopped = new AbortController;
540
+ constructor(type, budget) {
541
+ this.type = type;
542
+ this.budget = budget;
543
+ budget.attach(this);
544
+ }
545
+ get stopped() {
546
+ return this.#stopped.signal;
547
+ }
548
+ get buffered() {
549
+ return this.#buffered;
550
+ }
551
+ get cancelled() {
552
+ return this.#cancelled;
553
+ }
554
+ #notify() {
555
+ const wake = this.#wake;
556
+ this.#wake = undefined;
557
+ wake?.();
558
+ }
559
+ #accept(chunk) {
560
+ if (!chunk.byteLength)
561
+ return;
562
+ this.#chunks.push(chunk);
563
+ this.#buffered += chunk.byteLength;
564
+ this.#notify();
565
+ }
566
+ async write(length, copy, signal) {
567
+ if (length > STREAM_CHUNK)
568
+ throw new Error("stream write exceeds the 64 KiB chunk bound");
569
+ if (this.#eof)
570
+ throw new Error("stream was dropped");
571
+ if (this.#cancelled)
572
+ throw new Error("stream reader was dropped");
573
+ if (this.#writing)
574
+ throw new Error("a stream write is already pending");
575
+ if (signal?.aborted)
576
+ throw cancelled();
577
+ const writing = this.#writing = new AbortController;
578
+ try {
579
+ await this.budget.reserve(length, signal, writing.signal);
580
+ if (writing.signal.aborted || signal?.aborted) {
581
+ this.budget.release(length);
582
+ throw writing.signal.aborted ? writing.signal.reason : cancelled();
583
+ }
584
+ const chunk = copy();
585
+ if (this.#buffered + length <= STREAM_CHUNK)
586
+ return this.#accept(chunk);
587
+ await new Promise((resolve, reject) => {
588
+ const stop = (error) => {
589
+ if (this.#pending?.chunk !== chunk)
590
+ return;
591
+ this.#pending = undefined;
592
+ this.budget.release(length);
593
+ signal?.removeEventListener("abort", onSignal);
594
+ reject(error);
595
+ };
596
+ const onSignal = () => stop(cancelled());
597
+ signal?.addEventListener("abort", onSignal, { once: true });
598
+ writing.signal.addEventListener("abort", () => stop(writing.signal.reason), {
599
+ once: true
600
+ });
601
+ this.#pending = {
602
+ chunk,
603
+ resolve: () => {
604
+ signal?.removeEventListener("abort", onSignal);
605
+ resolve();
606
+ }
607
+ };
608
+ });
609
+ } finally {
610
+ if (this.#writing === writing)
611
+ this.#writing = undefined;
612
+ }
613
+ }
614
+ close() {
615
+ if (this.#eof)
616
+ return;
617
+ this.#eof = true;
618
+ this.#writing?.abort(new Error("stream was dropped"));
619
+ if (!this.transferred) {
620
+ this.#discard();
621
+ this.budget.detach(this);
622
+ }
623
+ this.#notify();
624
+ }
625
+ cancel() {
626
+ if (this.#cancelled)
627
+ return;
628
+ this.#cancelled = true;
629
+ this.#writing?.abort(new Error("stream reader was dropped"));
630
+ this.#discard();
631
+ this.budget.detach(this);
632
+ this.#stopped.abort();
633
+ this.#notify();
634
+ }
635
+ #discard() {
636
+ this.budget.release(this.#buffered);
637
+ this.#chunks = [];
638
+ this.#buffered = 0;
639
+ }
640
+ async read() {
641
+ while (!this.#buffered) {
642
+ if (this.#eof || this.#cancelled) {
643
+ this.budget.detach(this);
644
+ return;
645
+ }
646
+ await new Promise((resolve) => {
647
+ this.#wake = resolve;
648
+ });
649
+ }
650
+ const chunks = this.#chunks;
651
+ const total = this.#buffered;
652
+ this.#chunks = [];
653
+ this.#buffered = 0;
654
+ this.budget.release(total);
655
+ let bytes = chunks[0];
656
+ if (chunks.length > 1) {
657
+ bytes = new Uint8Array(total);
658
+ let offset = 0;
659
+ for (const chunk of chunks) {
660
+ bytes.set(chunk, offset);
661
+ offset += chunk.byteLength;
662
+ }
663
+ }
664
+ const pending = this.#pending;
665
+ if (pending) {
666
+ this.#pending = undefined;
667
+ this.#accept(pending.chunk);
668
+ pending.resolve();
669
+ }
670
+ return bytes;
671
+ }
672
+ }
673
+
674
+ // src/interpreter/standard-system.ts
675
+ var U64 = (1n << 64n) - 1n;
676
+ function duration(value) {
677
+ if (typeof value !== "bigint" || value < 0n || value > U64)
678
+ throw new RangeError("clock provider requires a u64 nanosecond value");
679
+ return value;
680
+ }
681
+ function checkedClocks(source) {
682
+ return {
683
+ systemNow() {
684
+ const value = source.systemNow();
685
+ if (typeof value.seconds !== "bigint" || value.seconds < -(1n << 63n) || value.seconds >= 1n << 63n || !Number.isInteger(value.nanoseconds) || value.nanoseconds < 0 || value.nanoseconds >= 1e9)
686
+ throw new RangeError("clock provider requires s64 seconds and fractional nanoseconds in [0, 1000000000)");
687
+ return value;
688
+ },
689
+ systemResolution: () => duration(source.systemResolution()),
690
+ monotonicNow: () => duration(source.monotonicNow()),
691
+ monotonicResolution: () => duration(source.monotonicResolution()),
692
+ waitUntil: (when, signal) => source.waitUntil(when, signal)
693
+ };
694
+ }
695
+ function revisionRandom(source) {
696
+ let seed;
697
+ return {
698
+ secure: (length) => source.secure(length),
699
+ insecure: (length) => source.insecure(length),
700
+ insecureSeed() {
701
+ if (seed)
702
+ return seed;
703
+ const value = source.insecureSeed();
704
+ if (value.length !== 2 || value.some((word) => typeof word !== "bigint" || word < 0n || word >= 1n << 64n))
705
+ throw new Error("random provider seed requires two u64 values");
706
+ return seed = [value[0], value[1]];
707
+ }
708
+ };
709
+ }
710
+ var TIMER_LIMIT = 2 ** 31 - 1;
711
+ function browserClocks() {
712
+ const now = () => BigInt(Math.floor(performance.now() * 1000)) * 1000n;
713
+ return {
714
+ systemNow() {
715
+ const milliseconds = Date.now();
716
+ const seconds = Math.floor(milliseconds / 1000);
717
+ return { seconds: BigInt(seconds), nanoseconds: (milliseconds - seconds * 1000) * 1e6 };
718
+ },
719
+ systemResolution: () => 1000000n,
720
+ monotonicNow: now,
721
+ monotonicResolution: () => 1000000n,
722
+ async waitUntil(deadline, signal) {
723
+ if (signal?.aborted)
724
+ throw cancelled();
725
+ for (let left = deadline - now();left > 0n; left = deadline - now()) {
726
+ const milliseconds = Math.min(TIMER_LIMIT, Math.ceil(Number(left) / 1e6));
727
+ await new Promise((resolve, reject) => {
728
+ if (signal?.aborted)
729
+ return reject(cancelled());
730
+ const abort = () => {
731
+ clearTimeout(timer);
732
+ reject(cancelled());
733
+ };
734
+ const timer = setTimeout(() => {
735
+ signal?.removeEventListener("abort", abort);
736
+ resolve();
737
+ }, milliseconds);
738
+ signal?.addEventListener("abort", abort, { once: true });
739
+ });
740
+ }
741
+ }
742
+ };
743
+ }
744
+ function browserRandom() {
745
+ const secure = (length) => {
746
+ const bytes = new Uint8Array(length);
747
+ for (let offset = 0;offset < length; offset += 65536)
748
+ globalThis.crypto.getRandomValues(bytes.subarray(offset, offset + 65536));
749
+ return bytes;
750
+ };
751
+ const insecureSeed = () => {
752
+ const view = new DataView(secure(16).buffer);
753
+ return [view.getBigUint64(0, true), view.getBigUint64(8, true)];
754
+ };
755
+ return { secure, insecure: secure, insecureSeed };
756
+ }
757
+ function bytes(provider, length) {
758
+ const result = provider(length);
759
+ if (!(result instanceof Uint8Array) || result.length !== length)
760
+ throw new Error("random provider returned the wrong byte length");
761
+ return result;
762
+ }
763
+ function systemMethods(clocks, random) {
764
+ const randomBytes = (secure) => (call, [length]) => {
765
+ const bound = BigInt(Math.max(0, call.host.packetBytes - 4));
766
+ return bytes((size) => secure ? random.secure(size) : random.insecure(size), Number(length > bound ? bound : length));
767
+ };
768
+ const randomU64 = (secure) => () => {
769
+ const result = bytes((size) => secure ? random.secure(size) : random.insecure(size), 8);
770
+ return new DataView(result.buffer, result.byteOffset, result.byteLength).getBigUint64(0, true);
771
+ };
772
+ return {
773
+ "wasi:random/random@0.3.0#getRandomBytes": randomBytes(true),
774
+ "wasi:random/random@0.3.0#getRandomU64": randomU64(true),
775
+ "wasi:random/insecure@0.3.0#getInsecureRandomBytes": randomBytes(false),
776
+ "wasi:random/insecure@0.3.0#getInsecureRandomU64": randomU64(false),
777
+ "wasi:random/insecure-seed@0.3.0#getInsecureSeed": () => random.insecureSeed(),
778
+ "wasi:clocks/system-clock@0.3.0#now": () => clocks.systemNow(),
779
+ "wasi:clocks/system-clock@0.3.0#getResolution": () => clocks.systemResolution(),
780
+ "wasi:clocks/monotonic-clock@0.3.0#now": () => clocks.monotonicNow(),
781
+ "wasi:clocks/monotonic-clock@0.3.0#getResolution": () => clocks.monotonicResolution(),
782
+ "wasi:clocks/monotonic-clock@0.3.0#waitUntil": ({ signal, host }, [when]) => abortable(host.physical(signal, () => clocks.waitUntil(when, signal)), signal),
783
+ "wasi:clocks/monotonic-clock@0.3.0#waitFor": ({ signal, host }, [duration]) => abortable(host.physical(signal, () => clocks.waitUntil(clocks.monotonicNow() + duration, signal)), signal)
784
+ };
785
+ }
786
+
787
+ export { BrowserCapabilities, methodKey, bindResource, cancelled, abortable, HostFuture, WritableFuture, OutputStream, InputBudget, InputStream, checkedClocks, revisionRandom, browserClocks, browserRandom, systemMethods };