wasm-platform-kit 0.0.0-stage → 0.2.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 (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +224 -2
  3. package/assets/wasi/LICENSE +220 -0
  4. package/assets/wasi/cli.d.ts +43 -0
  5. package/assets/wasi/cli.js +147 -0
  6. package/assets/wasi/clocks.d.ts +3 -0
  7. package/assets/wasi/clocks.js +55 -0
  8. package/assets/wasi/common.d.ts +5 -0
  9. package/assets/wasi/common.js +16 -0
  10. package/assets/wasi/config.d.ts +2 -0
  11. package/assets/wasi/config.js +7 -0
  12. package/assets/wasi/environment.d.ts +5 -0
  13. package/assets/wasi/environment.js +24 -0
  14. package/assets/wasi/filesystem.d.ts +117 -0
  15. package/assets/wasi/filesystem.js +341 -0
  16. package/assets/wasi/helpers/cli.d.ts +7 -0
  17. package/assets/wasi/helpers/cli.js +25 -0
  18. package/assets/wasi/helpers/filesystem.d.ts +6 -0
  19. package/assets/wasi/helpers/filesystem.js +10 -0
  20. package/assets/wasi/http.d.ts +13 -0
  21. package/assets/wasi/http.js +953 -0
  22. package/assets/wasi/in-memory-filesystem.d.ts +38 -0
  23. package/assets/wasi/in-memory-filesystem.js +620 -0
  24. package/assets/wasi/in-memory-http.d.ts +8 -0
  25. package/assets/wasi/in-memory-http.js +11 -0
  26. package/assets/wasi/in-memory-sockets.d.ts +34 -0
  27. package/assets/wasi/in-memory-sockets.js +294 -0
  28. package/assets/wasi/index.d.ts +7 -0
  29. package/assets/wasi/index.js +7 -0
  30. package/assets/wasi/io.d.ts +67 -0
  31. package/assets/wasi/io.js +366 -0
  32. package/assets/wasi/opfs-filesystem.d.ts +52 -0
  33. package/assets/wasi/opfs-filesystem.js +262 -0
  34. package/assets/wasi/random.d.ts +4 -0
  35. package/assets/wasi/random.js +51 -0
  36. package/assets/wasi/sockets.d.ts +9 -0
  37. package/assets/wasi/sockets.js +85 -0
  38. package/browser.mjs +209 -0
  39. package/client.mjs +138 -0
  40. package/index.d.ts +199 -0
  41. package/install.d.ts +22 -0
  42. package/install.mjs +176 -0
  43. package/native-registration.mjs +70 -0
  44. package/node.mjs +332 -0
  45. package/package.json +66 -4
  46. package/policy.mjs +433 -0
  47. package/worker.mjs +389 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 brain-fuel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,225 @@
1
- # Temporary Holding Version
1
+ # Wasm Platform Kit — development preview
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A capability-scoped platform SDK for WebAssembly applications in Node and browsers.
4
+ Haskell bindings are generated directly from WIT using upstream `wit-parser`;
5
+ there is no authored C bridge. GHC scalar foreign declarations, its RTS and libc
6
+ remain below the typed application interface. A Rust guest tests the same host
7
+ contract. Application-specific adapters live in their consuming repositories.
8
+
9
+ ## Release status
10
+
11
+ Version 0.2.0 is released to npm under the owner's 9 November 2026 decision
12
+ (`DEC-wpk-release-acceptance`). macOS and Linux ARM64 have recorded native
13
+ execution. Linux x64 is accepted on the installation lifecycle executed under
14
+ x64 emulation; native x64 hardware has not been recorded. **macOS x64 is
15
+ cross-built and unverified: no execution has been recorded on that platform.**
16
+ Existing acceptance JSON files record the runs they name; they do not certify
17
+ other platforms or later changes. Mandatory definition validation passes, while
18
+ optional law verification is not selected. Human Canon review remains pending.
19
+ See `DEC-wpk-installation-preparation` for the installation contract.
20
+
21
+ The npm lifecycle tests verify prebuilt installation, forced source preparation,
22
+ missing-prebuilt preparation, failure cleanup and execution with the compiler
23
+ removed. They do not establish full consumer application acceptance.
24
+
25
+ ## Packages
26
+
27
+ - `wasm-platform-kit`: Node/browser runtime, broker and public declarations.
28
+ - `wasm-platform-kit-<platform>`: execution-only Wasmtime helper, explicit source compiler and WIT metadata tool.
29
+ - `wasm-platform-kit-build`: generation, packaging, WIT and Haskell support sources.
30
+
31
+ The runtime tarball contains no compiler application, malicious fixtures or build
32
+ tools.
33
+ Platform packages target macOS and glibc Linux on x64 and ARM64. A cross-build
34
+ alone is not execution evidence; the release status above names what has run. Native
35
+ Windows and musl are unsupported; Windows users can use WSL. Consumers need no
36
+ Haskell or Rust compiler.
37
+
38
+ ## Development
39
+
40
+ Use Node 22+, Rust with wasm32-wasip2, GHC wasm32 9.14.1.20260731,
41
+ wasm-tools 1.257.1, Binaryen and Ormolu 0.9.0.0. `HOST_SDK_TOOLCHAIN` selects a
42
+ GHC Wasm toolchain directory (default ~/.ghc-wasm); `HOST_SDK_GHC_ENV` overrides
43
+ its environment file. These are build-time settings, never guest environment.
44
+
45
+ ```sh
46
+ npm ci
47
+ npm run build
48
+ npm test
49
+ npm run pack:local
50
+ ```
51
+
52
+ `dist/packages.json` records the local runtime, build-tool and platform tarballs.
53
+ Install the runtime, build tools and matching platform into an authoring project
54
+ with `npm install <tarballs...>`.
55
+ Builds and tests use this repository's own dependencies and generic fixtures.
56
+ No LawSpec checkout, compiler or application is required.
57
+
58
+ `npm run build:platform` rebuilds just the native helpers and WIT tool from Rust,
59
+ without a Haskell installation. Linux builds additionally use Cargo Zigbuild
60
+ 0.24.0 and Zig 0.16.0 with an explicit glibc 2.28 target; these are build-only
61
+ dependencies. `node tools/platform.mjs --build linux-x64` (or `linux-arm64`)
62
+ supports cross-compilation when the Rust target is installed. Linux staging
63
+ requires `llvm-readobj` or `readelf`; `HOST_SDK_READOBJ` can select the executable.
64
+ The actual linked glibc requirement must be at most 2.28, independent of the
65
+ builder's libc. ref:DEC-host-sdk-linux-abi-baseline
66
+
67
+ To collect cross-built binaries, place
68
+ `host-sdk-runtime`, `host-sdk-source-runtime` and `wit-haskell` in
69
+ `platforms/<platform>/bin/`, then run `node tools/platform.mjs --stage <platform>`.
70
+ Staging checks executable architecture and records file hashes. `pack:local`
71
+ includes every staged platform in the `platforms` map in `dist/packages.json`.
72
+ The `platform` field remains an alias for the build host's package.
73
+
74
+ ## Authoring and embedding
75
+
76
+ The build package exports `generateBindings`, `packageComponent`, `runHaskell`,
77
+ `supportDirectory` and `witDirectory`. Generate Haskell into a project-owned
78
+ output directory, implement `Application`, compile against the supplied Cabal
79
+ support library, and package the core Wasm with its WIT world. Packaging emits
80
+ Node and plain-browser entrypoints, declarations, worker and runtime assets,
81
+ an integrity manifest and deployment-header templates into the application's
82
+ output directory. It never modifies an installed SDK package.
83
+
84
+ The generated `node.mjs` and `browser.mjs` export `createApplication(options)`;
85
+ the returned instance has `invoke`, `identity`, `close` and `revoke`. Deploy the
86
+ whole generated browser directory. Each generated worker pins its approved
87
+ manifest digest before importing glue. The page entrypoint also pins registration.
88
+ The embedding build alone chooses registered components; plugin manifests cannot
89
+ register JavaScript. Application permissions remain a separate immutable `grants`
90
+ argument. Informational component `requirements` confer no permissions.
91
+
92
+ Files, approved network destinations, namespaced storage, explicit environment,
93
+ validated native callbacks and isolated text UI are mediated capabilities. Node
94
+ uses Wasmtime and cap-std; browser handles remain in the page broker. Redirects
95
+ cannot expand grants. Revocation terminates the instance and aborts cooperative
96
+ provider work. Trusted escape providers require the explicitly trusted profile.
97
+
98
+ Browsers require JSPI, secure context, workers and WebCrypto. Optional isolated
99
+ deployment requires effective COOP/COEP. WebKit file tests use a persistent
100
+ profile because its ephemeral OPFS implementation rejects handles. Missing
101
+ features fail explicitly. File-picker consent and server authorization remain
102
+ embedding-application responsibilities.
103
+
104
+ ## Precompiled Node execution and source builds
105
+
106
+ `packageComponent` emits a native artifact for the build platform and a separate
107
+ `node-registration.mjs`. The generated Node entrypoint supplies this trusted
108
+ registration automatically. Consumers do not locate native files or workers.
109
+
110
+ Wire the generated `install.mjs` into the embedding package's `postinstall`
111
+ script. Installation verifies its approved prebuilt artifact or compiles the
112
+ pinned portable Wasm with the shipped compiler helper. Neither path requires
113
+ Rust or Haskell on the consumer machine.
114
+
115
+ ```sh
116
+ npm install
117
+ # Explicitly compile during installation instead of selecting prebuilt code:
118
+ WASM_PLATFORM_KIT_BUILD_FROM_SOURCE=1 npm rebuild
119
+ ```
120
+
121
+ ```js
122
+ const app = await createApplication(); // loads prepared native code; never builds
123
+ ```
124
+
125
+ Runtime `compilation: 'source'` is rejected. If lifecycle scripts were disabled
126
+ and no prebuilt artifact is available, run `npm rebuild` with scripts enabled.
127
+ Compilation has a separate 15-minute installation deadline; it does not relax
128
+ runtime guest limits. Failed preparation never publishes a partial receipt or
129
+ replaces a previously valid receipt. Local compilation products are excluded
130
+ from subsequent npm archives. ref:DEC-wpk-installation-preparation
131
+
132
+ To rebuild the SDK and its Haskell fixtures, use the development commands above.
133
+ Application development builds still use GHC followed by `packageComponent`.
134
+
135
+ Direct `createHost` callers must supply embedding-approved `nativeArtifacts`
136
+ registration for a prepared artifact. A guest manifest
137
+ cannot authorize native code even if it carries matching hashes. The registration
138
+ binds component and native digests, target and pinned engine configuration. The
139
+ helper hashes a bounded copy into a private, already-unlinked file and maps that
140
+ immutable snapshot. Input mutation after verification cannot change executable
141
+ pages. Missing, corrupt or incompatible artifacts fail without an implicit
142
+ compilation fallback. Native artifacts are trusted compiler output, not safe
143
+ inputs merely because they have a checksum. ref:DEC-host-sdk-precompiled-node
144
+
145
+ The default helper is built without Cranelift. The installation-only compiler
146
+ helper retains it. Both preserve fuel and capability enforcement. Execution
147
+ identity includes compilation mode, configuration, target and native digest;
148
+ applications must retain those distinctions in cache/evidence keys. Portable
149
+ Wasm is still included for installation compilation and browser generation. Browser
150
+ engines continue to compile portable Wasm independently.
151
+
152
+ For multi-platform distribution, the build package exports
153
+ `precompileNative({component, output, target})` and `nativeTargets`. Precompilation
154
+ returns the trusted registration receipt; write it alongside the resulting file
155
+ in the build pipeline. `packageNativeArtifacts` takes a component `directory`
156
+ and an `artifacts` array of `{platform, file, registration}`. Supplying
157
+ `packagePrefix`, `version` and `packageDirectory` emits optional platform packages;
158
+ `license` and `licenseFile` carry the application's licensing. It returns the
159
+ optional dependency map for the application package manifest. Without a prefix,
160
+ it stages inline artifacts. Both forms generate trusted Node registration and
161
+ verify every input receipt against the component and native file before writing
162
+ authority. ref:DEC-host-sdk-native-platform-packaging
163
+
164
+ An optional native package is needed for default execution, but its absence does
165
+ not prevent explicit source compilation. The generated registration resolves
166
+ native files lazily so consumers never have to provide platform paths.
167
+
168
+ ## Limits and trust
169
+
170
+ The 0.2.0 generator accepts memory32 bool/string and signed and unsigned
171
+ 8/16/32/64-bit integers, records, enums, variants, lists, options, results and
172
+ imported or exported resources. Byte lists use Haskell ByteString. Both scalar
173
+ and aggregate results are supported; large parameter tuples use upstream
174
+ canonical indirect layouts. Resource constructors, methods and static functions
175
+ are generated. Floats, chars, flags, tuples, WIT async/future/stream types and
176
+ variants over 256 cases remain explicitly unsupported by the Haskell emitter.
177
+ Asynchronous host operations use the existing JSPI/Wasmtime integration.
178
+
179
+ Exported resources retain typed application state in `ResourceTypes` through
180
+ StablePtr. Generated helpers allocate, read and drop them; application modules
181
+ do not manipulate pointers. Consumed-owner flags and dynamic call epochs reject
182
+ repeated transfers and retained borrows. Destructors free retained state and run
183
+ consumer cleanup, using a safe GHC FFI drop import for synchronous re-entry.
184
+ Emergency termination releases the whole process or worker; it cannot promise
185
+ that application destructors finish. Resource lifetimes use bracket and runtime
186
+ validation, not linear proof. The generator, canonical codecs, initializer, build
187
+ instrumentation, runtime and providers are trusted code.
188
+
189
+ Fuel on Node, worker deadlines, guest memory/table bounds, host resource limits,
190
+ request/output limits and storage quotas bound execution. These are not universal
191
+ limits on browser or native host heaps or trusted callback allocations. The
192
+ containment suite establishes scoped execution evidence, not certification.
193
+
194
+ Canonical decisions and reference sources are in this repository. Human review
195
+ is pending. The original implementation was extracted from the LawSpec formatting
196
+ pilot; that application's adapter and parity tests remain in LawSpec.
197
+
198
+ Canon grammar snapshots and their provenance are checked in under `.ricestax/`;
199
+ review configuration has no dependency on a neighboring checkout. Use Canon
200
+ 0.2.3 with this repository. The LawSpec model can be checked by an independently
201
+ installed LawSpec CLI; it is not needed to build or test the runtime.
202
+
203
+ ## Generated application façades
204
+
205
+ Generated `node.mjs` and `browser.mjs` now return a client with named asynchronous
206
+ WIT methods as well as the low-level `invoke` operation. Adjacent `.d.mts` files
207
+ contain generated input, result and opaque resource types. Every method accepts
208
+ an optional final `{signal}`. Constructors appear as `new<Resource>`, resource
209
+ methods are asynchronous, and `dispose()` releases the resource. Per-call
210
+ cancellation still revokes that instance; separate long-lived UI/job lifecycles
211
+ are not yet implemented.
212
+
213
+ Use JavaScript `bigint` for WIT `u64`/`s64`, including small values. Node's helper
214
+ protocol preserves all bits and rejects Numbers and out-of-range values. Typed
215
+ byte-list façades use `Uint8Array`. Resource objects are bound to their creating
216
+ client. Copies of serialized IDs and resources from another instance convey no
217
+ access. The Wasmtime helper and browser worker cap retained public resources at
218
+ 1024 per instance.
219
+
220
+ The implementation follows WIT's resource new/rep/drop intrinsics and upstream
221
+ canonical parameter/result layouts. See the [WIT resource specification](https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md#item-resource)
222
+ and [canonical ABI](https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md).
223
+ The generated Haskell/backend support remains bespoke trusted implementation;
224
+ `wit-parser`, component validation, Wasmtime and jco supply the upstream machinery.
225
+ ref:DEC-host-sdk-typed-application-boundary
@@ -0,0 +1,220 @@
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.
203
+
204
+
205
+ --- LLVM Exceptions to the Apache 2.0 License ----
206
+
207
+ As an exception, if, as a result of your compiling your source code, portions
208
+ of this Software are embedded into an Object form of such source code, you
209
+ may redistribute such embedded portions in such Object form without complying
210
+ with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
211
+
212
+ In addition, if you combine or link compiled forms of this Software with
213
+ software that is licensed under the GPLv2 ("Combined Software") and if a
214
+ court of competent jurisdiction determines that the patent provision (Section
215
+ 3), the indemnity provision (Section 9) or other Section of the License
216
+ conflicts with the conditions of the GPLv2, you may retroactively and
217
+ prospectively choose to deem waived or otherwise exclude such Section(s) of
218
+ the License, but only in their entirety and only with respect to the Combined
219
+ Software.
220
+
@@ -0,0 +1,43 @@
1
+ import type { environment as EnvironmentNamespace, exit as ExitNamespace, stderr as StderrNamespace, stdin as StdinNamespace, stdout as StdoutNamespace, terminalInput as TerminalInputNamespace, terminalOutput as TerminalOutputNamespace, terminalStderr as TerminalStderrNamespace, terminalStdin as TerminalStdinNamespace, terminalStdout as TerminalStdoutNamespace } from "../../types/cli.js";
2
+ import { type InputStreamHandler, type OutputStreamHandler } from "./io.js";
3
+ export { _setEnv, _setArgs, environment } from "./environment.js";
4
+ export { _setCwd } from "./config.js";
5
+ export declare class ComponentExit extends Error {
6
+ exitError: boolean;
7
+ code: number;
8
+ constructor(code: number);
9
+ }
10
+ export declare const exit: typeof ExitNamespace;
11
+ export declare function _setStdin(handler: InputStreamHandler): void;
12
+ export declare function _setStderr(handler: OutputStreamHandler): void;
13
+ export declare function _setStdout(handler: OutputStreamHandler): void;
14
+ export interface BrowserCliConfig {
15
+ environment?: Record<string, string>;
16
+ arguments?: string[];
17
+ initialCwd?: string;
18
+ stdin?: InputStreamHandler;
19
+ stdout?: OutputStreamHandler;
20
+ stderr?: OutputStreamHandler;
21
+ onExit?: (code: number) => void;
22
+ }
23
+ export declare const stdin: typeof StdinNamespace;
24
+ export declare const stdout: typeof StdoutNamespace;
25
+ export declare const stderr: typeof StderrNamespace;
26
+ export declare const terminalInput: typeof TerminalInputNamespace;
27
+ export declare const terminalOutput: typeof TerminalOutputNamespace;
28
+ export declare const terminalStderr: typeof TerminalStderrNamespace;
29
+ export declare const terminalStdin: typeof TerminalStdinNamespace;
30
+ export declare const terminalStdout: typeof TerminalStdoutNamespace;
31
+ /** Create isolated browser CLI interfaces without changing compatibility globals. */
32
+ export declare function createCli(config?: BrowserCliConfig): {
33
+ environment: typeof EnvironmentNamespace;
34
+ exit: typeof ExitNamespace;
35
+ stdin: typeof StdinNamespace;
36
+ stdout: typeof StdoutNamespace;
37
+ stderr: typeof StderrNamespace;
38
+ terminalInput: typeof TerminalInputNamespace;
39
+ terminalOutput: typeof TerminalOutputNamespace;
40
+ terminalStdin: typeof TerminalStdinNamespace;
41
+ terminalStdout: typeof TerminalStdoutNamespace;
42
+ terminalStderr: typeof TerminalStderrNamespace;
43
+ };
@@ -0,0 +1,147 @@
1
+ import { inputStreamCreate, outputStreamCreate, pollableCreate, } from "./io.js";
2
+ export { _setEnv, _setArgs, environment } from "./environment.js";
3
+ export { _setCwd } from "./config.js";
4
+ const symbolDispose = Symbol.dispose ?? Symbol.for("dispose");
5
+ export class ComponentExit extends Error {
6
+ exitError = true;
7
+ code;
8
+ constructor(code) {
9
+ super(`Component exited ${code === 0 ? "successfully" : "with error"}`);
10
+ this.code = code;
11
+ }
12
+ }
13
+ function createExit(onExit) {
14
+ return {
15
+ exit(status) {
16
+ const code = status.tag === "err" ? 1 : 0;
17
+ onExit?.(code);
18
+ throw new ComponentExit(code);
19
+ },
20
+ // @ts-expect-error - Available only wasi-cli v0.2.12
21
+ exitWithCode(code) {
22
+ onExit?.(code);
23
+ throw new ComponentExit(code);
24
+ },
25
+ };
26
+ }
27
+ export const exit = createExit();
28
+ export function _setStdin(handler) {
29
+ stdinStream.handler = handler;
30
+ }
31
+ export function _setStderr(handler) {
32
+ stderrStream.handler = handler;
33
+ }
34
+ export function _setStdout(handler) {
35
+ stdoutStream.handler = handler;
36
+ }
37
+ const stdinStream = inputStreamCreate({
38
+ blockingRead() {
39
+ throw { tag: "closed" };
40
+ },
41
+ subscribe() {
42
+ return pollableCreate();
43
+ },
44
+ [symbolDispose]() { },
45
+ });
46
+ function consoleStream(writeLine) {
47
+ const decoder = new TextDecoder();
48
+ let pending = "";
49
+ const emitCompleteLines = () => {
50
+ const lines = pending.split("\n");
51
+ pending = lines.pop();
52
+ for (const line of lines) {
53
+ writeLine(line.endsWith("\r") ? line.slice(0, -1) : line);
54
+ }
55
+ };
56
+ const flush = () => {
57
+ pending += decoder.decode();
58
+ if (pending) {
59
+ writeLine(pending);
60
+ }
61
+ pending = "";
62
+ };
63
+ return {
64
+ write(contents) {
65
+ pending += decoder.decode(contents, { stream: true });
66
+ emitCompleteLines();
67
+ },
68
+ flush,
69
+ blockingFlush() {
70
+ this.flush?.();
71
+ },
72
+ // OutputStream marks itself closed before calling the handler's drop.
73
+ drop: flush,
74
+ };
75
+ }
76
+ const stdoutStream = outputStreamCreate(consoleStream((line) => console.log(line)));
77
+ const stderrStream = outputStreamCreate(consoleStream((line) => console.error(line)));
78
+ export const stdin = {
79
+ getStdin() {
80
+ return stdinStream;
81
+ },
82
+ };
83
+ export const stdout = {
84
+ getStdout() {
85
+ return stdoutStream;
86
+ },
87
+ };
88
+ export const stderr = {
89
+ getStderr() {
90
+ return stderrStream;
91
+ },
92
+ };
93
+ class TerminalInput {
94
+ }
95
+ class TerminalOutput {
96
+ }
97
+ export const terminalInput = {
98
+ TerminalInput,
99
+ };
100
+ export const terminalOutput = {
101
+ TerminalOutput,
102
+ };
103
+ export const terminalStderr = {
104
+ getTerminalStderr() {
105
+ return undefined;
106
+ },
107
+ };
108
+ export const terminalStdin = {
109
+ getTerminalStdin() {
110
+ return undefined;
111
+ },
112
+ };
113
+ export const terminalStdout = {
114
+ getTerminalStdout() {
115
+ return undefined;
116
+ },
117
+ };
118
+ /** Create isolated browser CLI interfaces without changing compatibility globals. */
119
+ export function createCli(config = {}) {
120
+ const stdinInstance = inputStreamCreate(config.stdin ?? {
121
+ blockingRead() {
122
+ throw { tag: "closed" };
123
+ },
124
+ subscribe: () => pollableCreate(),
125
+ });
126
+ const stdoutInstance = outputStreamCreate(config.stdout ?? consoleStream((line) => console.log(line)));
127
+ const stderrInstance = outputStreamCreate(config.stderr ?? consoleStream((line) => console.error(line)));
128
+ const env = Object.entries(config.environment ?? {});
129
+ const args = [...(config.arguments ?? [])];
130
+ const cwd = config.initialCwd ?? "/";
131
+ return {
132
+ environment: {
133
+ getEnvironment: () => env.map(([key, value]) => [key, value]),
134
+ getArguments: () => [...args],
135
+ initialCwd: () => cwd,
136
+ },
137
+ exit: createExit(config.onExit),
138
+ stdin: { getStdin: () => stdinInstance },
139
+ stdout: { getStdout: () => stdoutInstance },
140
+ stderr: { getStderr: () => stderrInstance },
141
+ terminalInput,
142
+ terminalOutput,
143
+ terminalStdin,
144
+ terminalStdout,
145
+ terminalStderr,
146
+ };
147
+ }
@@ -0,0 +1,3 @@
1
+ import type { monotonicClock as MonotonicClockNamespace, wallClock as WallClockNamespace } from "../../types/clocks.js";
2
+ export declare const monotonicClock: typeof MonotonicClockNamespace;
3
+ export declare const wallClock: typeof WallClockNamespace;