@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,545 @@
1
+ /**
2
+ * Browser implementations of the generated `wasi:filesystem` methods over provider descriptors
3
+ * (`filesystem.ts`). Tembra checks descriptor kind, rights and lexical confinement before any
4
+ * provider call, then providers enforce their own scope as well. Error codes follow upstream
5
+ * Wasmtime: a wrong descriptor kind or a missing file right is `bad-descriptor` (`not-directory`
6
+ * for directory methods), and a directory mutation without `mutate-directory` is
7
+ * `not-permitted`.
8
+ *
9
+ * Browser providers have no settable timestamps, hard links or symbolic links: those methods
10
+ * report `unsupported` after their authority checks. `advise` is an advisory no-op, and
11
+ * `set-times`/`set-times-at` with `no-change` for both timestamps succeed without effect.
12
+ */
13
+ import {
14
+ FilesystemError,
15
+ type Descriptor as ProviderDescriptor,
16
+ type DirectoryDescriptor,
17
+ type FileDescriptor,
18
+ type FileStat,
19
+ type MountedFilesystem,
20
+ } from "./filesystem.ts";
21
+ import {
22
+ abortable,
23
+ cancelled,
24
+ HostFuture,
25
+ type Implementation,
26
+ type InputStream,
27
+ OutputStream,
28
+ type StandardCall,
29
+ type StandardResource,
30
+ type StandardServices,
31
+ } from "./standard-streams.ts";
32
+
33
+ const TYPES = "wasi:filesystem/types@0.3.0";
34
+ const PREOPENS = "wasi:filesystem/preopens@0.3.0";
35
+ const U64 = (1n << 64n) - 1n;
36
+
37
+ /** A mount granted to this revision. */
38
+ export interface StandardMount {
39
+ readonly path: string;
40
+ readonly writable: boolean;
41
+ readonly filesystem: MountedFilesystem;
42
+ }
43
+
44
+ /** jco `descriptor-flags`. */
45
+ interface DescriptorFlags {
46
+ read: boolean;
47
+ write: boolean;
48
+ fileIntegritySync: boolean;
49
+ dataIntegritySync: boolean;
50
+ requestedWriteSync: boolean;
51
+ mutateDirectory: boolean;
52
+ }
53
+
54
+ type ErrorCode = { tag: string };
55
+ type Result = { tag: "ok"; val?: unknown } | { tag: "err"; val: ErrorCode };
56
+ type Timestamp = { tag: "no-change" | "now" | "timestamp"; val?: unknown };
57
+
58
+ const ok = (val?: unknown): Result => ({ tag: "ok", val });
59
+ const err = (code: string): Result => ({ tag: "err", val: { tag: code } });
60
+
61
+ /** A provider descriptor behind one host handle; streams and borrows retain it independently. */
62
+ export class HostDescriptor implements StandardResource {
63
+ borrows = 0;
64
+ #users = 1;
65
+
66
+ constructor(
67
+ readonly host: StandardServices,
68
+ readonly provider: ProviderDescriptor,
69
+ readonly flags: Readonly<DescriptorFlags>,
70
+ ) {}
71
+
72
+ get file(): FileDescriptor | undefined {
73
+ return this.provider.type === "file" ? this.provider : undefined;
74
+ }
75
+
76
+ get directory(): DirectoryDescriptor | undefined {
77
+ return this.provider.type === "directory" ? this.provider : undefined;
78
+ }
79
+
80
+ /** `mutate-directory` for a directory. */
81
+ get mutable(): boolean {
82
+ return this.provider.type === "directory" && this.flags.mutateDirectory;
83
+ }
84
+
85
+ retain(): void {
86
+ this.#users++;
87
+ }
88
+
89
+ release(): void {
90
+ if (--this.#users === 0) closeProvider(this.host, this.provider);
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Close a provider descriptor. The contract's `close()` is synchronous, but a custom provider
96
+ * may still return a promise; it stays physically owned by the revision until it settles.
97
+ */
98
+ function closeProvider(host: StandardServices, descriptor: ProviderDescriptor): void {
99
+ host.cleanup(() => descriptor.close() as unknown);
100
+ }
101
+
102
+ /** Map a provider failure to its WASI error code; anything else is `io`. */
103
+ function code(error: unknown): string {
104
+ return error instanceof FilesystemError ? error.code : "io";
105
+ }
106
+
107
+ /** A refused provider call is an error-code result unless the callback was cancelled. */
108
+ function failed(call: StandardCall, error: unknown): Result {
109
+ if (call.signal?.aborted) throw cancelled();
110
+ return err(code(error));
111
+ }
112
+
113
+ /**
114
+ * Run a provider operation under physical accounting. The call itself rejects promptly on
115
+ * cancellation; `orphan` releases a value that a cancelled call will never deliver.
116
+ */
117
+ function provider<T>(
118
+ call: StandardCall,
119
+ operation: () => Promise<T>,
120
+ orphan?: (value: T) => void,
121
+ ): Promise<T> {
122
+ const work = call.host.physical(call.signal, operation);
123
+ if (orphan)
124
+ work.then(
125
+ (value) => {
126
+ if (call.signal?.aborted) orphan(value);
127
+ },
128
+ () => {},
129
+ );
130
+ return abortable(work, call.signal);
131
+ }
132
+
133
+ /** Refuse a path lexically before any provider call; `undefined` admits it to the provider. */
134
+ function refusal(path: string): string | undefined {
135
+ if (path.includes("\0")) return "invalid";
136
+ if (path.startsWith("/")) return "not-permitted";
137
+ let depth = 0;
138
+ for (const part of path.split("/")) {
139
+ if (part === "" || part === ".") continue;
140
+ if (part !== "..") depth++;
141
+ else if (--depth < 0) return "not-permitted";
142
+ }
143
+ return undefined;
144
+ }
145
+
146
+ /** Milliseconds since the epoch as a WASI `instant` with signed seconds. */
147
+ function instant(milliseconds: number | undefined) {
148
+ if (milliseconds === undefined || !Number.isFinite(milliseconds)) return undefined;
149
+ const whole = Math.floor(milliseconds);
150
+ const seconds = Math.floor(whole / 1000);
151
+ return { seconds: BigInt(seconds), nanoseconds: (whole - seconds * 1000) * 1_000_000 };
152
+ }
153
+
154
+ function descriptorType(type: "file" | "directory"): ErrorCode {
155
+ return { tag: type === "file" ? "regular-file" : "directory" };
156
+ }
157
+
158
+ function descriptorStat(stat: FileStat) {
159
+ return {
160
+ type: descriptorType(stat.type),
161
+ linkCount: 1n,
162
+ size: stat.size,
163
+ dataAccessTimestamp: undefined,
164
+ dataModificationTimestamp: instant(stat.modified),
165
+ statusChangeTimestamp: undefined,
166
+ };
167
+ }
168
+
169
+ /** FNV-1a over the metadata browser providers report; equal metadata gives an equal hash. */
170
+ function metadataHash(stat: FileStat) {
171
+ const hash = (seed: bigint) => {
172
+ let value = seed;
173
+ const mix = (word: bigint) => {
174
+ for (let shift = 0n; shift < 64n; shift += 8n) {
175
+ value ^= (word >> shift) & 0xffn;
176
+ value = (value * 0x100000001b3n) & U64;
177
+ }
178
+ };
179
+ mix(stat.type === "file" ? 1n : 2n);
180
+ mix(BigInt.asUintN(64, stat.size));
181
+ mix(stat.modified === undefined ? U64 : BigInt.asUintN(64, BigInt(Math.floor(stat.modified))));
182
+ return value;
183
+ };
184
+ return { lower: hash(0xcbf29ce484222325n), upper: hash(0x84222325cbf29ce4n) };
185
+ }
186
+
187
+ /** Directory methods: the descriptor kind, then the lexical path, before the provider. */
188
+ function directoryAt(self: HostDescriptor, ...paths: string[]): DirectoryDescriptor | Result {
189
+ const directory = self.directory;
190
+ if (!directory) return err("not-directory");
191
+ for (const path of paths) {
192
+ const refused = refusal(path);
193
+ if (refused) return err(refused);
194
+ }
195
+ return directory;
196
+ }
197
+
198
+ /** Directory mutations additionally need `mutate-directory` on every directory involved. */
199
+ function mutableAt(
200
+ self: HostDescriptor,
201
+ paths: string[],
202
+ other?: HostDescriptor,
203
+ ): DirectoryDescriptor | Result {
204
+ if (!self.directory || (other && !other.directory)) return err("not-directory");
205
+ if (!self.mutable || (other && !other.mutable)) return err("not-permitted");
206
+ return directoryAt(self, ...paths);
207
+ }
208
+
209
+ const isResult = (value: unknown): value is Result =>
210
+ typeof value === "object" && value !== null && "tag" in value;
211
+
212
+ /** Run one checked provider call and map its failure. */
213
+ async function attempt<T>(
214
+ call: StandardCall,
215
+ checked: T | Result,
216
+ operation: (target: T) => Promise<unknown>,
217
+ ): Promise<Result> {
218
+ if (isResult(checked)) return checked;
219
+ try {
220
+ return ok(await provider(call, () => operation(checked)));
221
+ } catch (error) {
222
+ return failed(call, error);
223
+ }
224
+ }
225
+
226
+ /** A sync stream method's failure is reported through its future, as upstream does. */
227
+ function failedOutput(failure: string): [OutputStream, HostFuture] {
228
+ // The stream ends at its first read; the future carries the error.
229
+ const stream = new OutputStream({ next: async () => undefined, close() {} }, () => {});
230
+ return [stream, HostFuture.of(err(failure))];
231
+ }
232
+
233
+ /** Pair an output stream with the future that reports how it ended. */
234
+ function output(
235
+ self: HostDescriptor,
236
+ producer: { next(limit: number): Promise<unknown>; close?(): void },
237
+ ): [OutputStream, HostFuture] {
238
+ let settle!: (value: Result) => void;
239
+ const value = new Promise<Result>((resolve) => {
240
+ settle = resolve;
241
+ });
242
+ // The stream keeps its descriptor's provider object open after the handle is dropped.
243
+ self.retain();
244
+ const stream = new OutputStream(
245
+ {
246
+ next: producer.next as never,
247
+ close() {
248
+ producer.close?.();
249
+ self.release();
250
+ },
251
+ },
252
+ (failure) => settle(failure === undefined ? ok() : err(code(failure))),
253
+ );
254
+ return [stream, new HostFuture(value)];
255
+ }
256
+
257
+ /**
258
+ * Present a transferred input stream as the provider's chunk iterable: chunks of at most
259
+ * `STREAM_CHUNK` bytes, pulled only when the provider asks (backpressure), ending at the
260
+ * writer's EOF. The provider's `return()` (early exit) stops the input; a stopped input ends
261
+ * the provider's iteration with an error rather than a silent end of stream.
262
+ */
263
+ function chunks(input: InputStream): AsyncIterable<Uint8Array> {
264
+ return {
265
+ [Symbol.asyncIterator]: () => ({
266
+ async next(): Promise<IteratorResult<Uint8Array>> {
267
+ const chunk = await input.read();
268
+ if (chunk) return { done: false, value: chunk };
269
+ if (input.cancelled) throw new Error("stream reader was dropped");
270
+ return { done: true, value: undefined };
271
+ },
272
+ async return(): Promise<IteratorResult<Uint8Array>> {
273
+ input.cancel();
274
+ return { done: true, value: undefined };
275
+ },
276
+ }),
277
+ };
278
+ }
279
+
280
+ /**
281
+ * Consume a transferred input stream into a file; the future reports the outcome. A provider
282
+ * with `writeStream` receives the whole stream in one call (one OPFS writer and commit);
283
+ * otherwise each chunk is a sequential `write`/`append`. Either way the descriptor stays open
284
+ * and the work stays physically owned until the provider settles; the input ends when its
285
+ * writer is dropped, which the host forces at callback end and retirement.
286
+ */
287
+ function consume(
288
+ host: StandardServices,
289
+ self: HostDescriptor,
290
+ input: InputStream,
291
+ offset: bigint | undefined,
292
+ ): HostFuture {
293
+ const file = self.file;
294
+ if (!file || !self.flags.write) {
295
+ input.cancel();
296
+ return HostFuture.of(err("bad-descriptor"));
297
+ }
298
+ self.retain();
299
+ const value = (async (): Promise<Result> => {
300
+ try {
301
+ if (file.writeStream) {
302
+ const stream = input;
303
+ await host.physical(undefined, () => file.writeStream!(chunks(stream), offset));
304
+ return ok();
305
+ }
306
+ let position = offset;
307
+ for (let chunk = await input.read(); chunk; chunk = await input.read()) {
308
+ const bytes = chunk;
309
+ if (position === undefined) await host.physical(undefined, () => file.append(bytes));
310
+ else {
311
+ const at = position;
312
+ await host.physical(undefined, () => file.write(at, bytes));
313
+ position += BigInt(bytes.byteLength);
314
+ }
315
+ }
316
+ return ok();
317
+ } catch (error) {
318
+ return err(code(error));
319
+ } finally {
320
+ // Stop the writer side (later writes fail) and free any buffered budget.
321
+ input.cancel();
322
+ self.release();
323
+ }
324
+ })();
325
+ host.cleanup(() => value);
326
+ return new HostFuture(value, () => input.cancel());
327
+ }
328
+
329
+ /** Build the filesystem implementations over this revision's granted mounts. */
330
+ export function filesystemMethods(
331
+ mounts: () => readonly StandardMount[],
332
+ ): Readonly<Record<string, Implementation>> {
333
+ const methods: Record<string, Implementation> = {
334
+ [`${PREOPENS}#getDirectories`]: (call) =>
335
+ // Like upstream, every call issues fresh owned descriptors for the preopened mounts.
336
+ mounts().map((mount) => [
337
+ new HostDescriptor(call.host, mount.filesystem.openRoot(), {
338
+ read: true,
339
+ write: false,
340
+ fileIntegritySync: false,
341
+ dataIntegritySync: false,
342
+ requestedWriteSync: false,
343
+ mutateDirectory: mount.writable,
344
+ }),
345
+ mount.path,
346
+ ]),
347
+
348
+ readViaStream(_call, [self, offset]: [HostDescriptor, bigint]) {
349
+ const file = self.file;
350
+ if (!file || !self.flags.read) return failedOutput("bad-descriptor");
351
+ let position = offset;
352
+ return output(self, {
353
+ next: async (limit: number) => {
354
+ const chunk = await _call.host.physical(undefined, () => file.read(position, limit));
355
+ position += BigInt(chunk.byteLength);
356
+ return chunk;
357
+ },
358
+ });
359
+ },
360
+
361
+ writeViaStream: ({ host }, [self, input, offset]: [HostDescriptor, InputStream, bigint]) =>
362
+ consume(host, self, input, offset),
363
+
364
+ appendViaStream: ({ host }, [self, input]: [HostDescriptor, InputStream]) =>
365
+ consume(host, self, input, undefined),
366
+
367
+ readDirectory({ host }, [self]: [HostDescriptor]) {
368
+ const directory = self.directory;
369
+ if (!directory) return failedOutput("not-directory");
370
+ let entries: ReturnType<DirectoryDescriptor["readDirectory"]>;
371
+ try {
372
+ entries = directory.readDirectory();
373
+ } catch (error) {
374
+ return failedOutput(code(error));
375
+ }
376
+ let done = false;
377
+ return output(self, {
378
+ next: async () => {
379
+ const next = await host.physical(undefined, () => entries.next());
380
+ if (next.done) {
381
+ done = true;
382
+ return undefined;
383
+ }
384
+ return { type: descriptorType(next.value.type), name: next.value.name };
385
+ },
386
+ close() {
387
+ // Close an unfinished provider iterator, also during retirement.
388
+ if (!done) host.cleanup(() => entries.return?.());
389
+ },
390
+ });
391
+ },
392
+
393
+ async advise(_call, [self]: [HostDescriptor]) {
394
+ return self.file ? ok() : err("bad-descriptor");
395
+ },
396
+
397
+ sync: (call, [self]: [HostDescriptor]) => attempt(call, self.provider, (p) => p.sync()),
398
+ syncData: (call, [self]: [HostDescriptor]) => attempt(call, self.provider, (p) => p.sync()),
399
+
400
+ async getFlags(_call, [self]: [HostDescriptor]) {
401
+ return ok({ ...self.flags });
402
+ },
403
+
404
+ async getType(_call, [self]: [HostDescriptor]) {
405
+ return ok(descriptorType(self.provider.type));
406
+ },
407
+
408
+ setSize(call, [self, size]: [HostDescriptor, bigint]) {
409
+ const file = self.file && self.flags.write ? self.file : err("bad-descriptor");
410
+ return attempt(call, file, (target) => target.setSize(size));
411
+ },
412
+
413
+ async setTimes(_call, [self, accessed, modified]: [HostDescriptor, Timestamp, Timestamp]) {
414
+ if (self.file ? !self.flags.write : !self.mutable)
415
+ return err(self.file ? "bad-descriptor" : "not-permitted");
416
+ return accessed.tag === "no-change" && modified.tag === "no-change"
417
+ ? ok()
418
+ : err("unsupported");
419
+ },
420
+
421
+ setTimesAt(
422
+ call,
423
+ [self, , path, accessed, modified]: [HostDescriptor, unknown, string, Timestamp, Timestamp],
424
+ ) {
425
+ const checked = mutableAt(self, [path]);
426
+ if (isResult(checked) || accessed.tag !== "no-change" || modified.tag !== "no-change")
427
+ return Promise.resolve(isResult(checked) ? checked : err("unsupported"));
428
+ // Nothing changes, but the entry must exist.
429
+ return attempt(call, checked, (directory) => directory.statAt(path).then(() => undefined));
430
+ },
431
+
432
+ stat: (call, [self]: [HostDescriptor]) =>
433
+ attempt(call, self.provider, (p) => p.stat().then(descriptorStat)),
434
+
435
+ statAt: (call, [self, , path]: [HostDescriptor, unknown, string]) =>
436
+ attempt(call, directoryAt(self, path), (directory) =>
437
+ directory.statAt(path).then(descriptorStat),
438
+ ),
439
+
440
+ async openAt(
441
+ call,
442
+ [self, , path, open, flags]: [
443
+ HostDescriptor,
444
+ unknown,
445
+ string,
446
+ { create?: boolean; directory?: boolean; exclusive?: boolean; truncate?: boolean },
447
+ Partial<DescriptorFlags>,
448
+ ],
449
+ ) {
450
+ const write = Boolean(flags.write || flags.mutateDirectory);
451
+ const directory = self.directory;
452
+ if (!directory) return err("not-directory");
453
+ // Write authority comes only from a mutable directory, checked before the provider.
454
+ if ((open.create || open.truncate || write) && !self.mutable) return err("not-permitted");
455
+ const refused = refusal(path);
456
+ if (refused) return err(refused);
457
+ try {
458
+ const opened = await provider(
459
+ call,
460
+ () =>
461
+ directory.openAt(path, {
462
+ create: Boolean(open.create),
463
+ exclusive: Boolean(open.exclusive),
464
+ truncate: Boolean(open.truncate),
465
+ directory: Boolean(open.directory),
466
+ write,
467
+ }),
468
+ (descriptor) => closeProvider(call.host, descriptor),
469
+ );
470
+ const granted = opened.writable && write;
471
+ return ok(
472
+ new HostDescriptor(call.host, opened, {
473
+ read: opened.type === "directory" || Boolean(flags.read),
474
+ write: opened.type === "file" && granted,
475
+ fileIntegritySync: Boolean(flags.fileIntegritySync),
476
+ dataIntegritySync: Boolean(flags.dataIntegritySync),
477
+ requestedWriteSync: Boolean(flags.requestedWriteSync),
478
+ mutateDirectory: opened.type === "directory" && granted,
479
+ }),
480
+ );
481
+ } catch (error) {
482
+ return failed(call, error);
483
+ }
484
+ },
485
+
486
+ async readlinkAt(call, [self, path]: [HostDescriptor, string]) {
487
+ // There are no symbolic links: an existing entry is not one (`invalid`), as in POSIX.
488
+ const result = await attempt(call, directoryAt(self, path), (directory) =>
489
+ directory.statAt(path),
490
+ );
491
+ return result.tag === "ok" ? err("invalid") : result;
492
+ },
493
+
494
+ createDirectoryAt: (call, [self, path]: [HostDescriptor, string]) =>
495
+ attempt(call, mutableAt(self, [path]), (directory) => directory.createDirectoryAt(path)),
496
+
497
+ removeDirectoryAt: (call, [self, path]: [HostDescriptor, string]) =>
498
+ attempt(call, mutableAt(self, [path]), (directory) => directory.removeDirectoryAt(path)),
499
+
500
+ unlinkFileAt: (call, [self, path]: [HostDescriptor, string]) =>
501
+ attempt(call, mutableAt(self, [path]), (directory) => directory.unlinkFileAt(path)),
502
+
503
+ renameAt: (call, [self, from, target, to]: [HostDescriptor, string, HostDescriptor, string]) =>
504
+ attempt(call, mutableAt(self, [from, to], target), (directory) =>
505
+ directory.renameAt(from, target.directory!, to),
506
+ ),
507
+
508
+ async linkAt(
509
+ _call,
510
+ [self, , from, target, to]: [HostDescriptor, unknown, string, HostDescriptor, string],
511
+ ) {
512
+ const checked = mutableAt(self, [from, to], target);
513
+ return isResult(checked) ? checked : err("unsupported");
514
+ },
515
+
516
+ async symlinkAt(_call, [self, , to]: [HostDescriptor, string, string]) {
517
+ const checked = mutableAt(self, [to]);
518
+ return isResult(checked) ? checked : err("unsupported");
519
+ },
520
+
521
+ async isSameObject(call, [self, other]: [HostDescriptor, HostDescriptor]) {
522
+ try {
523
+ return await provider(call, () => self.provider.isSameObject(other.provider));
524
+ } catch (error) {
525
+ if (call.signal?.aborted || !(error instanceof FilesystemError)) throw error;
526
+ return false;
527
+ }
528
+ },
529
+
530
+ metadataHash: (call, [self]: [HostDescriptor]) =>
531
+ attempt(call, self.provider, (p) => p.stat().then(metadataHash)),
532
+
533
+ metadataHashAt: (call, [self, , path]: [HostDescriptor, unknown, string]) =>
534
+ attempt(call, directoryAt(self, path), (directory) =>
535
+ directory.statAt(path).then(metadataHash),
536
+ ),
537
+ };
538
+ // Resource methods are keyed by their WIT interface like free functions.
539
+ return Object.fromEntries(
540
+ Object.entries(methods).map(([name, method]) => [
541
+ name.includes("#") ? name : `${TYPES}#${name}`,
542
+ method,
543
+ ]),
544
+ );
545
+ }