@polyengine/wasi 0.1.0-pre.g633468a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # @polyengine/wasi
2
+
3
+ WASI providers for polyengine hosts: the p2 baseline and p3 clocks, one module per semver track.
4
+
5
+ Part of [polyengine](https://github.com/polymorph-components/polyengine), a
6
+ WebAssembly Component Model host for JavaScript engines. This is the npm
7
+ distribution; the same package is published to JSR as `jsr:@polyengine/wasi`, and the
8
+ two are built from the same sources at the same version.
9
+
10
+ ```sh
11
+ npm install @polyengine/wasi
12
+ ```
13
+
14
+ ```js
15
+ import * as api from "@polyengine/wasi";
16
+ ```
17
+
18
+ Entry points: `.`, `./cli`, `./cli-stdio`, `./clocks`, `./filesystem`, `./filesystem-node`, `./filesystem-web`, `./http`, `./io`, `./random`, `./sockets`.
19
+
20
+ ESM only, Node >= 22.14. Documentation, examples and the embedder API contract
21
+ live in the [repository](https://github.com/polymorph-components/polyengine).
22
+
23
+ Apache-2.0.
package/esm/cli.js ADDED
@@ -0,0 +1,160 @@
1
+ // `wasi:cli@0.2` + `wasi:cli@0.3` — environment, exit, stdin, stdout,
2
+ // stderr, terminal-* (contracts/embedder-api.md §"WASI examination"; 0.2
3
+ // leaf inventory mined from `iroh_exec_model_guest.wasm` /
4
+ // `engine-go/main.wasm`; 0.3 shapes from the WASI 0.3.1 release —
5
+ // WebAssembly/WASI v0.3.1, proposals/cli/wit). This is the CAPTURE impl
6
+ // (the batteries fragment `wasi()` merges): stdin from a caller-supplied
7
+ // buffer, stdout/stderr into capture buffers, exit recorded. The
8
+ // host-stdio impl is à la carte at `@polyengine/wasi/cli-stdio` (cli_stdio.ts
9
+ // — it grants terminal/process access, so it never rides the default).
10
+ //
11
+ // 0.3 reshapes stdio around streams: `stdin.read-via-stream: func() ->
12
+ // tuple<stream<u8>, future<result<_, error-code>>>` (the tcp-receive
13
+ // tuple shape) and `stdout/stderr.write-via-stream: func(data:
14
+ // stream<u8>) -> future<result<_, error-code>>` (the tcp-send shape:
15
+ // the async method's promise IS the future source, amendment A12); exit
16
+ // gains `exit-with-code: func(status-code: u8)`, and environment's cwd
17
+ // getter is renamed `get-initial-cwd` (0.2 spells it `initial-cwd`).
18
+ import { InputStream, OutputStream } from "./io.js";
19
+ import { ExitError, TerminalInput, TerminalOutput, } from "./internal/cli_shared.js";
20
+ // The shared `wasi:cli` vocabulary lives in internal/cli_shared.ts (both
21
+ // impls consume it); THIS module is its public home.
22
+ export { ExitError, TerminalInput, TerminalOutput, } from "./internal/cli_shared.js";
23
+ function concat(chunks) {
24
+ const total = chunks.reduce((n, c) => n + c.length, 0);
25
+ const out = new Uint8Array(total);
26
+ let at = 0;
27
+ for (const c of chunks) {
28
+ out.set(c, at);
29
+ at += c.length;
30
+ }
31
+ return out;
32
+ }
33
+ /**
34
+ * `wasi:cli@0.2` provider fragment (track key).
35
+ *
36
+ * `exit`'s WIT signature is `exit: func(status: result)` — `result` with no
37
+ * type parameters, i.e. `result<_, _>`. Per contracts/embedder-api.md's value
38
+ * table, a `result` in **parameter** (non-return) position is plain nested
39
+ * data: `{ kind: "ok" } | { kind: "err" }` (the A10 family — this comment
40
+ * and the impl carried the pre-A10 `tag` spelling until 2026-08-14, a
41
+ * latent bug the direct-call unit tests masked), never a throw. Only a
42
+ * function's own *return*-position result throws/rejects.
43
+ */
44
+ export function cli(options = {}) {
45
+ const stdoutChunks = [];
46
+ const stderrChunks = [];
47
+ const passthrough = options.passthrough ?? false;
48
+ let exited = false;
49
+ let exitOk;
50
+ let exitCode;
51
+ const stdout = new OutputStream((chunk) => {
52
+ stdoutChunks.push(chunk);
53
+ if (passthrough)
54
+ console.log(new TextDecoder().decode(chunk));
55
+ });
56
+ const stderr = new OutputStream((chunk) => {
57
+ stderrChunks.push(chunk);
58
+ if (passthrough)
59
+ console.error(new TextDecoder().decode(chunk));
60
+ });
61
+ const captured = {
62
+ stdout: () => concat(stdoutChunks),
63
+ stderr: () => concat(stderrChunks),
64
+ stdoutText: () => new TextDecoder().decode(concat(stdoutChunks)),
65
+ stderrText: () => new TextDecoder().decode(concat(stderrChunks)),
66
+ exited: () => exited,
67
+ exitOk: () => exitOk,
68
+ exitCode: () => exitCode,
69
+ };
70
+ /** 0.3 write-via-stream into a capture buffer (A12: the promise IS the future). */
71
+ const captureViaStream = (chunks, mirror) => async (data) => {
72
+ for await (const chunk of data) {
73
+ const bytes = chunk instanceof Uint8Array ? chunk : Uint8Array.from(chunk);
74
+ chunks.push(bytes);
75
+ mirror?.(new TextDecoder().decode(bytes));
76
+ }
77
+ return { kind: "ok" };
78
+ };
79
+ const imports = {
80
+ "wasi:cli/environment@0.2": {
81
+ getEnvironment: () => Object.entries(options.env ?? {}),
82
+ getArguments: () => options.args ?? [],
83
+ initialCwd: () => options.cwd,
84
+ },
85
+ "wasi:cli/exit@0.2": {
86
+ exit: (status) => {
87
+ exited = true;
88
+ exitOk = status.kind === "ok";
89
+ if (options.throwOnExit)
90
+ throw new ExitError(exitOk);
91
+ },
92
+ },
93
+ "wasi:cli/stdin@0.2": {
94
+ getStdin: () => new InputStream(options.stdinBuffer),
95
+ },
96
+ "wasi:cli/stdout@0.2": { getStdout: () => stdout },
97
+ "wasi:cli/stderr@0.2": { getStderr: () => stderr },
98
+ "wasi:cli/terminal-input@0.2": { TerminalInput },
99
+ "wasi:cli/terminal-output@0.2": { TerminalOutput },
100
+ // No terminal is ever attached; `option<terminal-*>` collapses to the
101
+ // outermost-option rule (contract §"Value mapping"): `undefined` = none.
102
+ "wasi:cli/terminal-stdin@0.2": {
103
+ getTerminalStdin: () => undefined,
104
+ },
105
+ "wasi:cli/terminal-stdout@0.2": {
106
+ getTerminalStdout: () => undefined,
107
+ },
108
+ "wasi:cli/terminal-stderr@0.2": {
109
+ getTerminalStderr: () => undefined,
110
+ },
111
+ // ---- the @0.3 track (WASI 0.3.1 shapes; module header) -------------------
112
+ "wasi:cli/types@0.3": {},
113
+ "wasi:cli/environment@0.3": {
114
+ getEnvironment: () => Object.entries(options.env ?? {}),
115
+ getArguments: () => options.args ?? [],
116
+ getInitialCwd: () => options.cwd,
117
+ },
118
+ "wasi:cli/exit@0.3": {
119
+ exit: (status) => {
120
+ exited = true;
121
+ exitOk = status.kind === "ok";
122
+ if (options.throwOnExit)
123
+ throw new ExitError(exitOk);
124
+ },
125
+ exitWithCode: (statusCode) => {
126
+ exited = true;
127
+ exitOk = statusCode === 0;
128
+ exitCode = statusCode;
129
+ if (options.throwOnExit)
130
+ throw new ExitError(exitOk);
131
+ },
132
+ },
133
+ "wasi:cli/stdin@0.3": {
134
+ // The tcp-receive tuple shape: [stream, completion future]. A
135
+ // buffered stdin always delivers cleanly.
136
+ readViaStream: () => [
137
+ options.stdinBuffer === undefined ? [] : [options.stdinBuffer],
138
+ Promise.resolve({ kind: "ok" }),
139
+ ],
140
+ },
141
+ "wasi:cli/stdout@0.3": {
142
+ writeViaStream: captureViaStream(stdoutChunks, passthrough ? (t) => console.log(t) : undefined),
143
+ },
144
+ "wasi:cli/stderr@0.3": {
145
+ writeViaStream: captureViaStream(stderrChunks, passthrough ? (t) => console.error(t) : undefined),
146
+ },
147
+ "wasi:cli/terminal-input@0.3": { TerminalInput },
148
+ "wasi:cli/terminal-output@0.3": { TerminalOutput },
149
+ "wasi:cli/terminal-stdin@0.3": {
150
+ getTerminalStdin: () => undefined,
151
+ },
152
+ "wasi:cli/terminal-stdout@0.3": {
153
+ getTerminalStdout: () => undefined,
154
+ },
155
+ "wasi:cli/terminal-stderr@0.3": {
156
+ getTerminalStderr: () => undefined,
157
+ },
158
+ };
159
+ return { imports, captured };
160
+ }
@@ -0,0 +1,203 @@
1
+ // `@polyengine/wasi/cli-stdio` — the HOST-STDIO impl of `wasi:cli` (both the
2
+ // `@0.2` and `@0.3` tracks), à la carte: it grants access to the host
3
+ // process's stdin/stdout/stderr, environment, and arguments, so it never
4
+ // rides the default `wasi()` merge (which carries the capture impl,
5
+ // cli.ts). Compose it over the batteries:
6
+ //
7
+ // instantiate(a, { ...wasi(), ...cliStdio().imports })
8
+ //
9
+ // Defaults come from `globalThis.process` (real Node, and Deno through
10
+ // its stable node compat — the same node-builtins-everywhere stance as
11
+ // sockets_platform.ts); every source and sink is injectable for
12
+ // virtualization and tests. On a host with no `process` and no
13
+ // injection, construction fails loudly — the capture impl is the honest
14
+ // browser answer.
15
+ //
16
+ // THE JSPI DEPENDENCE (the reason this impl exists as its own fragment):
17
+ // p2's `blocking-read` / `blocking-write-and-flush` / `blocking-flush`
18
+ // are SYNC WIT functions. Against capture buffers they degenerate to
19
+ // their non-blocking forms (io.ts base classes, sync fast path); against
20
+ // a REAL stdin/stdout they must genuinely wait, which parks the calling
21
+ // wasm frame through the suspending kernel (embedder-api A1/A2/A14 —
22
+ // io.ts marks the blocking declarations on the REGISTERED stream
23
+ // prototypes; these duck-typed stream impls override the behavior, and
24
+ // per A2 the mark relays). Consequences: guests linking the blocking
25
+ // leaves auto-select jspi mode on V8 engines, and on engines without
26
+ // JSPI a genuine wait raises a clean `NeedsJspi` at the park site. The
27
+ // `@0.3` track has no such dependence — its stdio is stream-shaped and
28
+ // async by construction (`read-via-stream` returns the tcp-receive
29
+ // tuple; `write-via-stream`'s promise is the future source, A12).
30
+ //
31
+ // Semantics:
32
+ //
33
+ // * p2 stdin: reads serve synchronously from an internal buffer fed by
34
+ // the source; `read` on an empty open stream returns an empty list
35
+ // (p2's non-blocking contract), `blocking-read` parks until bytes or
36
+ // EOF, and EOF-with-drained-buffer is the `closed` stream-error. The
37
+ // feed pauses past a high-water mark (no unbounded buffering).
38
+ // * p2 stdout/stderr: writes enqueue against a byte BUDGET
39
+ // (`check-write` reports the remaining permit; exceeding it is the
40
+ // guest's contract violation and traps via unbranded throw);
41
+ // `blocking-flush`/`blocking-write-and-flush` park until the sink
42
+ // drained everything; `subscribe` wakes when budget frees.
43
+ // * exit: throws the branded `ExitError` (the embedder decides what
44
+ // process-level exit means; `exitProcess: true` opts into a REAL
45
+ // `process.exit`). `exit-with-code` (0.3) records the code on the
46
+ // error.
47
+ // * terminals: reported from the real streams' `isTTY` (injectable).
48
+ // * environment/arguments/cwd: the host process's, overridable.
49
+ import { Stream } from "@polyengine/runtime/embedder";
50
+ import { ExitError, TerminalInput, TerminalOutput, } from "./internal/cli_shared.js";
51
+ import { FedInputStream, SinkOutputStream } from "./io.js";
52
+ const OK = { kind: "ok" };
53
+ function ioErrorCode(e) {
54
+ const m = (e instanceof Error ? e.message : String(e)).toLowerCase();
55
+ return m.includes("epipe") || m.includes("broken pipe") ? "pipe" : "io";
56
+ }
57
+ function hostProcess() {
58
+ const proc = globalThis.process;
59
+ return typeof proc === "object" && proc !== null ? proc : undefined;
60
+ }
61
+ function processSink(stream) {
62
+ return (chunk) => new Promise((resolve, reject) => {
63
+ const flushed = stream.write(chunk, (err) => {
64
+ if (err !== null && err !== undefined)
65
+ reject(err);
66
+ });
67
+ if (flushed)
68
+ resolve();
69
+ else
70
+ stream.once("drain", resolve);
71
+ });
72
+ }
73
+ /**
74
+ * `wasi:cli` over the host process's stdio (both tracks — module header).
75
+ */
76
+ export function cliStdio(options = {}) {
77
+ const proc = hostProcess();
78
+ const stdinSource = options.stdin ?? proc?.stdin;
79
+ const stdoutSink = options.stdout ??
80
+ (proc?.stdout === undefined ? undefined : processSink(proc.stdout));
81
+ const stderrSink = options.stderr ??
82
+ (proc?.stderr === undefined ? undefined : processSink(proc.stderr));
83
+ if (stdinSource === undefined || stdoutSink === undefined || stderrSink === undefined) {
84
+ throw new TypeError("cliStdio: no host process stdio and no injected replacement — " +
85
+ "on hosts without `process` (browsers), inject sources/sinks or " +
86
+ "use the capture impl (cli.ts)");
87
+ }
88
+ const tty = {
89
+ stdin: options.isTty?.stdin ?? proc?.stdin?.isTTY ?? false,
90
+ stdout: options.isTty?.stdout ?? proc?.stdout?.isTTY ?? false,
91
+ stderr: options.isTty?.stderr ?? proc?.stderr?.isTTY ?? false,
92
+ };
93
+ const env = () => {
94
+ if (options.env !== undefined)
95
+ return Object.entries(options.env);
96
+ const e = proc?.env ?? {};
97
+ return Object.entries(e).filter((kv) => kv[1] !== undefined);
98
+ };
99
+ const args = () => options.args ?? proc?.argv?.slice(2) ?? [];
100
+ const cwd = () => options.cwd ?? proc?.cwd?.();
101
+ const doExit = (ok, code) => {
102
+ if (options.exitProcess && proc?.exit !== undefined) {
103
+ proc.exit(code ?? (ok ? 0 : 1));
104
+ }
105
+ throw new ExitError(ok, code);
106
+ };
107
+ // One p2 stream per stdio channel, shared across get-* calls (the
108
+ // process's stdio is one resource, not one per call).
109
+ let p2Stdin;
110
+ const p2Stdout = new SinkOutputStream(stdoutSink);
111
+ const p2Stderr = new SinkOutputStream(stderrSink);
112
+ // 0.3 write-via-stream: drain the guest's stream to the sink; the
113
+ // promise is the future source (A12).
114
+ const writeViaStream = (sink) => async (data) => {
115
+ try {
116
+ for await (const chunk of data) {
117
+ await sink(chunk instanceof Uint8Array ? chunk : Uint8Array.from(chunk));
118
+ }
119
+ return OK;
120
+ }
121
+ catch (e) {
122
+ if (data instanceof Stream)
123
+ data.drop(); // the guest's writer must not hang
124
+ return { kind: "err", value: ioErrorCode(e) };
125
+ }
126
+ };
127
+ // 0.3 read-via-stream: the tcp-receive tuple over the shared source.
128
+ const readViaStream = () => {
129
+ let settle;
130
+ const done = new Promise((r) => (settle = r));
131
+ const source = (async function* () {
132
+ try {
133
+ for await (const chunk of stdinSource) {
134
+ if (chunk.length > 0)
135
+ yield chunk;
136
+ }
137
+ settle(OK);
138
+ }
139
+ catch (e) {
140
+ settle({ kind: "err", value: ioErrorCode(e) });
141
+ }
142
+ finally {
143
+ settle(OK); // reader dropped: the canceller observes (no-op if settled)
144
+ }
145
+ })();
146
+ return [source, done];
147
+ };
148
+ const environment = {
149
+ getEnvironment: env,
150
+ getArguments: args,
151
+ };
152
+ const imports = {
153
+ // ---- @0.2 -----------------------------------------------------------------
154
+ "wasi:cli/environment@0.2": { ...environment, initialCwd: cwd },
155
+ "wasi:cli/exit@0.2": {
156
+ exit: (status) => {
157
+ doExit(status.kind === "ok");
158
+ },
159
+ },
160
+ "wasi:cli/stdin@0.2": {
161
+ getStdin: () => (p2Stdin ??= new FedInputStream(stdinSource)),
162
+ },
163
+ "wasi:cli/stdout@0.2": { getStdout: () => p2Stdout },
164
+ "wasi:cli/stderr@0.2": { getStderr: () => p2Stderr },
165
+ "wasi:cli/terminal-input@0.2": { TerminalInput },
166
+ "wasi:cli/terminal-output@0.2": { TerminalOutput },
167
+ "wasi:cli/terminal-stdin@0.2": {
168
+ getTerminalStdin: () => tty.stdin ? new TerminalInput() : undefined,
169
+ },
170
+ "wasi:cli/terminal-stdout@0.2": {
171
+ getTerminalStdout: () => tty.stdout ? new TerminalOutput() : undefined,
172
+ },
173
+ "wasi:cli/terminal-stderr@0.2": {
174
+ getTerminalStderr: () => tty.stderr ? new TerminalOutput() : undefined,
175
+ },
176
+ // ---- @0.3 -----------------------------------------------------------------
177
+ "wasi:cli/types@0.3": {},
178
+ "wasi:cli/environment@0.3": { ...environment, getInitialCwd: cwd },
179
+ "wasi:cli/exit@0.3": {
180
+ exit: (status) => {
181
+ doExit(status.kind === "ok");
182
+ },
183
+ exitWithCode: (statusCode) => {
184
+ doExit(statusCode === 0, statusCode);
185
+ },
186
+ },
187
+ "wasi:cli/stdin@0.3": { readViaStream },
188
+ "wasi:cli/stdout@0.3": { writeViaStream: writeViaStream(stdoutSink) },
189
+ "wasi:cli/stderr@0.3": { writeViaStream: writeViaStream(stderrSink) },
190
+ "wasi:cli/terminal-input@0.3": { TerminalInput },
191
+ "wasi:cli/terminal-output@0.3": { TerminalOutput },
192
+ "wasi:cli/terminal-stdin@0.3": {
193
+ getTerminalStdin: () => tty.stdin ? new TerminalInput() : undefined,
194
+ },
195
+ "wasi:cli/terminal-stdout@0.3": {
196
+ getTerminalStdout: () => tty.stdout ? new TerminalOutput() : undefined,
197
+ },
198
+ "wasi:cli/terminal-stderr@0.3": {
199
+ getTerminalStderr: () => tty.stderr ? new TerminalOutput() : undefined,
200
+ },
201
+ };
202
+ return { imports };
203
+ }
package/esm/clocks.js ADDED
@@ -0,0 +1,84 @@
1
+ // `wasi:clocks@0.2` + `wasi:clocks@0.3` (contracts/embedder-api.md
2
+ // §"WASI examination"; the D-1 union clock — tools/smoke-c0/REPORT.md
3
+ // finding D-1: `monotonic-clock@0.3.0` exposes different function sets
4
+ // across the consumer corpus (`wait-for` vs `now`+`wait-until`) at the SAME
5
+ // version string — same track, divergent drafts, served by one union
6
+ // provider per contracts/embedder-api.md §"Version canonicalization").
7
+ // The @0.3 track also carries system-clock (0.3's wall-clock reshape) and
8
+ // the type-only types interface, per the WASI 0.3.1 release WIT.
9
+ import { Pollable } from "./io.js";
10
+ function sleep(ms) {
11
+ return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
12
+ }
13
+ /** `wasi:clocks@0.2` + `wasi:clocks@0.3` provider fragment (two track keys). */
14
+ export function clocks(options = {}) {
15
+ const nowFn = options.now ?? (() => BigInt(Math.round(performance.now() * 1e6)));
16
+ // A coarse but honest resolution: this clock is JS-timer-backed, not a
17
+ // real hardware tick; 1 microsecond avoids claiming false precision.
18
+ const RESOLUTION_NS = 1000n;
19
+ const monotonic02 = {
20
+ now: nowFn,
21
+ resolution: () => RESOLUTION_NS,
22
+ // Real timers (the parking kernel, io.ts): an always-ready timer stub
23
+ // livelocks any guest that sleeps by parking — tokio's reactor being
24
+ // the known consumer. `block()`/`poll()` on these park the frame until
25
+ // the deadline; `ready()` consults the clock, so the wake is exact.
26
+ subscribeInstant: (when) => Pollable.timer(when, nowFn),
27
+ subscribeDuration: (howLong) => Pollable.timer(nowFn() + howLong, nowFn),
28
+ };
29
+ const wallClock02 = {
30
+ now: () => {
31
+ const ms = Date.now();
32
+ return {
33
+ seconds: BigInt(Math.floor(ms / 1000)),
34
+ nanoseconds: (ms % 1000) * 1_000_000,
35
+ };
36
+ },
37
+ resolution: () => ({
38
+ seconds: 0n,
39
+ nanoseconds: 1_000_000,
40
+ }),
41
+ };
42
+ // The D-1 union provider (C0-proven shape, tools/smoke-c0/leg2_exec_model.ts):
43
+ // both drafts' functions live on the one `@0.3` track provider; per-leaf
44
+ // structural resolution (contracts/embedder-api.md §"Version
45
+ // canonicalization") lets each consumer link only the subset it imports.
46
+ const monotonic03 = {
47
+ now: nowFn,
48
+ getResolution: () => RESOLUTION_NS,
49
+ waitUntil: async (when) => {
50
+ const deltaNs = when - nowFn();
51
+ await sleep(Number(deltaNs) / 1e6);
52
+ },
53
+ waitFor: async (howLong) => {
54
+ await sleep(Number(howLong) / 1e6);
55
+ },
56
+ };
57
+ // 0.3 reshapes wall-clock into system-clock (WASI 0.3.1 release:
58
+ // clocks/system-clock.wit): `now() -> instant` — a RECORD with SIGNED
59
+ // seconds (record instant { seconds: s64, nanoseconds: u32 }; the same
60
+ // value shape as 0.2's datetime) — and `get-resolution() -> duration`
61
+ // (plain u64 nanoseconds, unlike 0.2's datetime-shaped resolution).
62
+ const systemClock03 = {
63
+ now: () => {
64
+ const ms = Date.now();
65
+ return {
66
+ seconds: BigInt(Math.floor(ms / 1000)),
67
+ nanoseconds: (ms % 1000) * 1_000_000,
68
+ };
69
+ },
70
+ getResolution: () => 1000000n, // Date.now() is millisecond-backed
71
+ };
72
+ return {
73
+ imports: {
74
+ "wasi:clocks/monotonic-clock@0.2": monotonic02,
75
+ "wasi:clocks/wall-clock@0.2": wallClock02,
76
+ "wasi:clocks/monotonic-clock@0.3": monotonic03,
77
+ "wasi:clocks/system-clock@0.3": systemClock03,
78
+ // Type-only interface (`type duration = u64`): nothing to
79
+ // implement, registered so the import target resolves (the
80
+ // cli/types@0.3 precedent).
81
+ "wasi:clocks/types@0.3": {},
82
+ },
83
+ };
84
+ }