@polyengine/runtime 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.
Files changed (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +23 -0
  3. package/esm/cabi/async_values.js +162 -0
  4. package/esm/cabi/bulk_lists.js +198 -0
  5. package/esm/cabi/context.js +42 -0
  6. package/esm/cabi/flatten.js +145 -0
  7. package/esm/cabi/float.js +67 -0
  8. package/esm/cabi/handles.js +253 -0
  9. package/esm/cabi/layout.js +149 -0
  10. package/esm/cabi/lift.js +196 -0
  11. package/esm/cabi/load.js +146 -0
  12. package/esm/cabi/lower.js +141 -0
  13. package/esm/cabi/memory.js +182 -0
  14. package/esm/cabi/mod.js +22 -0
  15. package/esm/cabi/store.js +186 -0
  16. package/esm/cabi/strings.js +336 -0
  17. package/esm/cabi/trap.js +38 -0
  18. package/esm/cabi/types.js +264 -0
  19. package/esm/cabi/values.js +64 -0
  20. package/esm/cache/core.js +156 -0
  21. package/esm/cache/dir.js +170 -0
  22. package/esm/cache/mod.js +4 -0
  23. package/esm/cache/web.js +136 -0
  24. package/esm/digest/digest.js +332 -0
  25. package/esm/digest/mod.js +3 -0
  26. package/esm/digest/verify.js +129 -0
  27. package/esm/embedder/casing.js +56 -0
  28. package/esm/embedder/copy.js +42 -0
  29. package/esm/embedder/errors.js +26 -0
  30. package/esm/embedder/imports.js +63 -0
  31. package/esm/embedder/instantiate.js +978 -0
  32. package/esm/embedder/mod.js +40 -0
  33. package/esm/embedder/resources.js +406 -0
  34. package/esm/embedder/streams.js +770 -0
  35. package/esm/embedder/values.js +450 -0
  36. package/esm/embedder/version.js +273 -0
  37. package/esm/exec/boundary.js +1902 -0
  38. package/esm/exec/executor.js +1004 -0
  39. package/esm/exec/host_streams.js +818 -0
  40. package/esm/exec/mod.js +4 -0
  41. package/esm/intrinsics/async_builtins.js +510 -0
  42. package/esm/intrinsics/context.js +90 -0
  43. package/esm/intrinsics/errors.js +13 -0
  44. package/esm/intrinsics/fact_calls.js +865 -0
  45. package/esm/intrinsics/mod.js +564 -0
  46. package/esm/intrinsics/stream_builtins.js +578 -0
  47. package/esm/intrinsics/transcode.js +443 -0
  48. package/esm/jspi/bridge.js +579 -0
  49. package/esm/jspi/mechanics.js +89 -0
  50. package/esm/jspi/mod.js +5 -0
  51. package/esm/jspi/suspending.js +15 -0
  52. package/esm/jspi/types.js +29 -0
  53. package/esm/package.json +3 -0
  54. package/esm/plan/format.js +5 -0
  55. package/esm/plan/loader.js +657 -0
  56. package/esm/plan/mod.js +3 -0
  57. package/esm/shim/mod.js +2 -0
  58. package/esm/shim/translator.js +94 -0
  59. package/esm/task/mod.js +483 -0
  60. package/esm/task/scheduler.js +1028 -0
  61. package/esm/task/streams.js +786 -0
  62. package/esm/task/subtask.js +135 -0
  63. package/esm/task/thread.js +255 -0
  64. package/esm/task/waitable.js +144 -0
  65. package/package.json +91 -0
  66. package/types/cabi/async_values.d.ts +35 -0
  67. package/types/cabi/bulk_lists.d.ts +18 -0
  68. package/types/cabi/context.d.ts +59 -0
  69. package/types/cabi/flatten.d.ts +14 -0
  70. package/types/cabi/float.d.ts +14 -0
  71. package/types/cabi/handles.d.ts +70 -0
  72. package/types/cabi/layout.d.ts +13 -0
  73. package/types/cabi/lift.d.ts +25 -0
  74. package/types/cabi/load.d.ts +14 -0
  75. package/types/cabi/lower.d.ts +10 -0
  76. package/types/cabi/memory.d.ts +58 -0
  77. package/types/cabi/mod.d.ts +15 -0
  78. package/types/cabi/store.d.ts +12 -0
  79. package/types/cabi/strings.d.ts +23 -0
  80. package/types/cabi/trap.d.ts +11 -0
  81. package/types/cabi/types.d.ts +206 -0
  82. package/types/cabi/values.d.ts +5 -0
  83. package/types/cache/core.d.ts +97 -0
  84. package/types/cache/dir.d.ts +6 -0
  85. package/types/cache/mod.d.ts +3 -0
  86. package/types/cache/web.d.ts +10 -0
  87. package/types/digest/digest.d.ts +17 -0
  88. package/types/digest/mod.d.ts +2 -0
  89. package/types/digest/verify.d.ts +48 -0
  90. package/types/embedder/casing.d.ts +40 -0
  91. package/types/embedder/copy.d.ts +24 -0
  92. package/types/embedder/errors.d.ts +11 -0
  93. package/types/embedder/imports.d.ts +47 -0
  94. package/types/embedder/instantiate.d.ts +88 -0
  95. package/types/embedder/mod.d.ts +11 -0
  96. package/types/embedder/resources.d.ts +158 -0
  97. package/types/embedder/streams.d.ts +202 -0
  98. package/types/embedder/values.d.ts +70 -0
  99. package/types/embedder/version.d.ts +85 -0
  100. package/types/exec/boundary.d.ts +360 -0
  101. package/types/exec/executor.d.ts +125 -0
  102. package/types/exec/host_streams.d.ts +165 -0
  103. package/types/exec/mod.d.ts +3 -0
  104. package/types/intrinsics/async_builtins.d.ts +69 -0
  105. package/types/intrinsics/context.d.ts +28 -0
  106. package/types/intrinsics/errors.d.ts +5 -0
  107. package/types/intrinsics/fact_calls.d.ts +120 -0
  108. package/types/intrinsics/mod.d.ts +187 -0
  109. package/types/intrinsics/stream_builtins.d.ts +113 -0
  110. package/types/intrinsics/transcode.d.ts +21 -0
  111. package/types/jspi/bridge.d.ts +227 -0
  112. package/types/jspi/mechanics.d.ts +50 -0
  113. package/types/jspi/mod.d.ts +3 -0
  114. package/types/jspi/suspending.d.ts +1 -0
  115. package/types/jspi/types.d.ts +26 -0
  116. package/types/plan/format.d.ts +369 -0
  117. package/types/plan/loader.d.ts +113 -0
  118. package/types/plan/mod.d.ts +2 -0
  119. package/types/shim/mod.d.ts +1 -0
  120. package/types/shim/translator.d.ts +55 -0
  121. package/types/task/mod.d.ts +257 -0
  122. package/types/task/scheduler.d.ts +421 -0
  123. package/types/task/streams.d.ts +370 -0
  124. package/types/task/subtask.d.ts +96 -0
  125. package/types/task/thread.d.ts +73 -0
  126. package/types/task/waitable.d.ts +67 -0
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/runtime
2
+
3
+ A WebAssembly Component Model host for JavaScript engines: plan executor, canonical ABI, 0.3 task scheduler, JSPI bridge, and embedder API.
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/runtime`, and the
8
+ two are built from the same sources at the same version.
9
+
10
+ ```sh
11
+ npm install @polyengine/runtime
12
+ ```
13
+
14
+ ```js
15
+ import * as api from "@polyengine/runtime/cabi";
16
+ ```
17
+
18
+ Entry points: `./cabi`, `./cache`, `./digest`, `./embedder`, `./exec`, `./intrinsics`, `./jspi`, `./plan`, `./shim`, `./task`.
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.
@@ -0,0 +1,162 @@
1
+ // Lift and lower for the async value types: `stream`, `future` and
2
+ // `error-context` (definitions.py `lift_async_value` line 1530,
3
+ // `lower_stream`/`lower_future` line 1828, `lift_error_context` line 1451,
4
+ // `lower_error_context` line 1757).
5
+ //
6
+ // ===========================================================================
7
+ // HOST SHAPE (interpreter decision — flagged, per contracts/descriptor-ir.md)
8
+ // ===========================================================================
9
+ //
10
+ // Every other `ComponentValue` in this interpreter is plain data: numbers,
11
+ // strings, arrays, records. The async value types cannot be, and the reference
12
+ // is explicit about why: `lift_async_value` returns `e.shared` — the *shared*
13
+ // stream/future object, not a copy and not an index — and `lower_stream` wraps
14
+ // that same object in a fresh `ReadableStreamEnd` in the destination
15
+ // instance's handle table. The identity of the shared object is the value; two
16
+ // components holding ends of one stream must observe each other's copies.
17
+ //
18
+ // So a lifted `stream`/`future` is a `SharedStreamImpl`/`SharedFutureImpl`
19
+ // instance, and a lifted `error-context` is an `ErrorContext` instance. Host
20
+ // code that receives one should treat it as an opaque token. This is the same
21
+ // concession the reference makes; it is recorded here because it widens what
22
+ // `ComponentValue` can hold beyond plain data, which the descriptor-IR
23
+ // contract's "host-shaped component values" wording did not anticipate.
24
+ import { copyCensus, ERROR_CONTEXT, hasBrand } from "@polyengine/protocol";
25
+ import { assert_, trapIf } from "./trap.js";
26
+ import { contains, fmtValType } from "./types.js";
27
+ import { CopyState, ErrorContext, ReadableFutureEnd, ReadableStreamEnd, SharedFutureImpl, sameElemType, SharedStreamImpl, } from "../task/streams.js";
28
+ /**
29
+ * Diagnostic for a handle-table entry that carries the A9 error-context brand
30
+ * without being one of THIS copy's `ErrorContext`s (amendment A9, issue #83).
31
+ *
32
+ * A backstop, deliberately: the embedder's lowering site (embedder/values.ts)
33
+ * refuses a foreign error-context before it can ever reach a handle table, so
34
+ * this branch should be unreachable. It exists because "handle is not an
35
+ * error-context" is precisely the misleading generic that made #83 expensive
36
+ * to diagnose — if a path ever does get here, it says what happened.
37
+ *
38
+ * This layer is below `embedder/`, so it composes the census from
39
+ * `@polyengine/protocol` directly rather than importing `embedder/copy.ts`.
40
+ */
41
+ export function errorContextTrapMessage(where, e) {
42
+ if (!hasBrand(e, ERROR_CONTEXT)) {
43
+ return `${where}: handle is not an error-context`;
44
+ }
45
+ const census = copyCensus();
46
+ return `${where}: this error-context was minted by a DIFFERENT polyengine ` +
47
+ `runtime copy and cannot be used through this one` +
48
+ `${census === "" ? "" : ` (${census})`} ` +
49
+ `(contracts/embedder-api.md amendment A9, issue #83)`;
50
+ }
51
+ /** definitions.py `contains_borrow` — async values may never carry borrows. */
52
+ function containsBorrow(t) {
53
+ return contains(t, (x) => x.kind === "borrow");
54
+ }
55
+ /**
56
+ * definitions.py `lift_async_value` (line 1530).
57
+ *
58
+ * Lifting **removes** the handle: the readable end is transferred out of this
59
+ * instance's table, which is why a stream can only be passed on once.
60
+ */
61
+ function liftAsyncValue(cx, i, t,
62
+ // deno-lint-ignore no-explicit-any
63
+ EndT, elem, what) {
64
+ assert_(!containsBorrow(t), `${what} may not contain a borrow`);
65
+ const inst = cx.inst;
66
+ assert_(inst !== null, `${what} lift requires a component instance`);
67
+ const e = inst.handles.remove(i);
68
+ trapIf(!(e instanceof EndT), `${what} lift: handle is not a ${what} end`);
69
+ const end = e;
70
+ trapIf(!sameElemType(end.shared.t, elem), `${what} lift: element type mismatch`);
71
+ trapIf(end.state === CopyState.DONE, what === "future"
72
+ ? "cannot lift future after previous read succeeded"
73
+ : "cannot lift stream after being notified that the writable end dropped");
74
+ trapIf(end.state !== CopyState.IDLE, `cannot remove busy ${what}`);
75
+ trapIf(end.inWaitableSet(), `cannot lift ${what} while it's in a waitable set`);
76
+ // Remember the driving store so a host wrapper can pump the guest later.
77
+ // Single-store only: a shared object crossing into a SECOND store is
78
+ // unsupported misuse — fail loudly rather than silently pumping the first
79
+ // (review advisory, host-streams round). Class field initializes to null;
80
+ // != null covers both sentinels.
81
+ const holder = end.shared;
82
+ const store = inst.store;
83
+ if (holder.boundStore != null && store != null) {
84
+ // A9: when several runtime copies are loaded, "a second store" is very
85
+ // often "a second COPY" — the shared object was minted by one runtime and
86
+ // is being driven by another. The two stores are indistinguishable from
87
+ // here (stores carry no copy identity), so the census is appended as the
88
+ // hypothesis it is, rather than asserted (issue #83).
89
+ const census = copyCensus();
90
+ assert_(holder.boundStore === store, `${what} crossed into a second store; multi-store is unsupported` +
91
+ (census === ""
92
+ ? ""
93
+ : ` (${census} — a value from one copy cannot be lowered through ` +
94
+ `another)`));
95
+ }
96
+ holder.boundStore ??= store;
97
+ // Host-wrapper re-arm hook (#162, embedder-api amendment A15): the readable
98
+ // end just left a guest table, so whoever receives it can act on it again.
99
+ // See `bindOnLower` in exec/host_streams.ts for the retention rule.
100
+ end.shared.onLifted?.(inst);
101
+ return end.shared;
102
+ }
103
+ export function liftStream(cx, i, t) {
104
+ return liftAsyncValue(cx, i, t, ReadableStreamEnd, t.element, "stream");
105
+ }
106
+ export function liftFuture(cx, i, t) {
107
+ return liftAsyncValue(cx, i, t, ReadableFutureEnd, t.element, "future");
108
+ }
109
+ /** definitions.py `lower_stream` (line 1828). */
110
+ export function lowerStream(cx, v, t) {
111
+ assert_(v instanceof SharedStreamImpl, "lower_stream expects a shared stream value");
112
+ assert_(!containsBorrow(t), "stream may not contain a borrow");
113
+ // Loud element-type check. A host-created stream carries a hand-passed
114
+ // `ValType` (typed derivation is bindgen's job), so this is the first point
115
+ // at which a mismatch against the guest's declared `stream<T>` can be
116
+ // caught — and a silent mismatch would corrupt every copy, since the
117
+ // element type is what sizes and lifts the buffer. `fmtValType`, not
118
+ // `JSON.stringify`: the latter throws on resource-bearing element types
119
+ // (cabi/types.ts `valTypeEqual` contract note) — and as a template-literal
120
+ // argument it was evaluated even when the assertion PASSED.
121
+ const declared = t.element ?? null;
122
+ if (!sameElemType(v.t, declared)) {
123
+ assert_(false, `stream element type mismatch: host end carries ` +
124
+ `${fmtValType(v.t)}, callee expects ${fmtValType(declared)}`);
125
+ }
126
+ const inst = cx.inst;
127
+ assert_(inst !== null, "stream lower requires a component instance");
128
+ v.boundStore ??=
129
+ inst.store;
130
+ v.onLowered?.(inst);
131
+ return inst.handles.add(new ReadableStreamEnd(v));
132
+ }
133
+ /** definitions.py `lower_future` (line 1833). */
134
+ export function lowerFuture(cx, v, t) {
135
+ assert_(v instanceof SharedFutureImpl, "lower_future expects a shared future value");
136
+ assert_(!containsBorrow(t), "future may not contain a borrow");
137
+ const declared = t.element ?? null;
138
+ if (!sameElemType(v.t, declared)) {
139
+ assert_(false, `future element type mismatch: host end carries ` +
140
+ `${fmtValType(v.t)}, callee expects ${fmtValType(declared)}`);
141
+ }
142
+ const inst = cx.inst;
143
+ assert_(inst !== null, "future lower requires a component instance");
144
+ v.boundStore ??=
145
+ inst.store;
146
+ v.onLowered?.(inst);
147
+ return inst.handles.add(new ReadableFutureEnd(v));
148
+ }
149
+ /** definitions.py `lift_error_context` (line 1451). Does NOT remove the handle. */
150
+ export function liftErrorContext(cx, i) {
151
+ const inst = cx.inst;
152
+ assert_(inst !== null, "error-context lift requires a component instance");
153
+ const e = inst.handles.get(i);
154
+ trapIf(!(e instanceof ErrorContext), errorContextTrapMessage("error-context lift", e));
155
+ return e;
156
+ }
157
+ /** definitions.py `lower_error_context` (line 1757). */
158
+ export function lowerErrorContext(cx, v) {
159
+ const inst = cx.inst;
160
+ assert_(inst !== null, "error-context lower requires a component instance");
161
+ return inst.handles.add(v);
162
+ }
@@ -0,0 +1,198 @@
1
+ // Bulk (TypedArray-backed) list copies for flat element types (issue #67).
2
+ //
3
+ // The per-element interpreted `load()`/`store()` costs ~13-45 ns/element
4
+ // (despecialize + asserts + DataView per element); these helpers replace the
5
+ // loop body with one typed-array view per list and a tight per-element pass
6
+ // that preserves the interpreted path's EXACT observable semantics:
7
+ //
8
+ // * integers: the same `assert_` type-shape texts as `storeInt` (`"int
9
+ // store"`, `"64-bit store requires bigint"`) but, unlike the scalar path
10
+ // in memory.ts (`storeInt`'s range `assert_`s, issue #96), NOT the same
11
+ // range check: this bulk path wraps out-of-range values instead of
12
+ // raising the host-precondition error (`OverflowError` per
13
+ // definitions.py:1568-1569 `int.to_bytes`) that `storeInt` raises. That
14
+ // is a deliberate scalar/bulk posture split, not an oversight:
15
+ // - the whole point of this file (see the perf numbers above) is an
16
+ // allocation-free, branch-minimal per-element loop; an added range
17
+ // check is itself a per-element cost, defeating the purpose;
18
+ // - values reaching this path from a descriptor-driven lower already
19
+ // went through the descriptor layer's own type conversions for the
20
+ // cases that matter in practice (see contracts/descriptor-ir.md);
21
+ // the wrap here is a defense-in-depth gap only for a raw/buggy
22
+ // embedder value, which the scalar path (used for non-bulk-eligible
23
+ // kinds, and reachable directly from embedder code) still catches.
24
+ // A TypedArray element write coerces exactly like the matching DataView
25
+ // setter (wraps mod 2^width), so this is pinned as intentional behavior
26
+ // (see bulk_list_test.ts), not merely undocumented;
27
+ // * floats: the deterministic profile's NaN canonicalization on BOTH
28
+ // directions (float.ts `decodeI32AsFloat` / `encodeFloatAsI32`): every
29
+ // lifted NaN becomes the JS canonical NaN, every stored `number` NaN
30
+ // writes the canonical bit pattern. Non-NaN values round-trip bit-exactly
31
+ // (Float32Array narrowing is the same IEEE round-to-nearest-even as
32
+ // `DataView.setFloat32`);
33
+ // * bool: store normalizes any value by truthiness to 0/1 (`store()`'s
34
+ // `Number(Boolean(v))`), lift maps any nonzero byte to `true`
35
+ // (`convertIntToBool` semantics — it never traps for unsigned bytes).
36
+ //
37
+ // u8 is NOT here: it has its own, shape-changing fast path (`list<u8>` is
38
+ // `Uint8Array` on the host — load.ts/store.ts). char is NOT here: its lift
39
+ // validates USVs per element (`convertI32ToChar` traps), which is the cost.
40
+ //
41
+ // NAMED ASSUMPTION (issue #67): wasm linear memory is little-endian by spec;
42
+ // JS TypedArrays follow the PLATFORM's endianness. Every engine polyengine
43
+ // targets runs little-endian, but rather than bake that in silently, the
44
+ // check below gates the fast paths — on a big-endian platform they decline
45
+ // and the callers keep the (endianness-correct) DataView per-element loops.
46
+ //
47
+ // Alignment: the canonical ABI guarantees list pointers are element-aligned,
48
+ // and real guest memories sit at byteOffset 0, so the view construction
49
+ // below virtually never declines; a misaligned combination (possible for a
50
+ // test MemInst wrapping a subarray) falls back the same way.
51
+ import { assert_ } from "./trap.js";
52
+ import { bytesOf } from "./memory.js";
53
+ import { CANONICAL_FLOAT32_NAN, CANONICAL_FLOAT64_NAN } from "./float.js";
54
+ export const PLATFORM_LITTLE_ENDIAN = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
55
+ const INT_CTORS = {
56
+ s8: Int8Array,
57
+ u16: Uint16Array,
58
+ s16: Int16Array,
59
+ u32: Uint32Array,
60
+ s32: Int32Array,
61
+ };
62
+ const BIG_CTORS = {
63
+ u64: BigUint64Array,
64
+ s64: BigInt64Array,
65
+ };
66
+ const FLOAT_CTORS = {
67
+ f32: Float32Array,
68
+ f64: Float64Array,
69
+ };
70
+ /** Kinds these helpers handle (besides them, u8 has its own path). */
71
+ export function isBulkListKind(kind) {
72
+ return kind === "bool" || kind in INT_CTORS || kind in BIG_CTORS ||
73
+ kind in FLOAT_CTORS;
74
+ }
75
+ function viewOf(ctor, mem, ptr, length) {
76
+ if (!PLATFORM_LITTLE_ENDIAN)
77
+ return null;
78
+ const byteOffset = mem.bytes.byteOffset + ptr;
79
+ if (byteOffset % ctor.BYTES_PER_ELEMENT !== 0)
80
+ return null;
81
+ return new ctor(mem.bytes.buffer, byteOffset, length);
82
+ }
83
+ /**
84
+ * Bulk lift of `length` elements of `kind` at `ptr`. Returns `null` when the
85
+ * kind is not handled here (caller falls back to the per-element loop) —
86
+ * never for a handled kind on a little-endian platform with an aligned view.
87
+ * The caller has already trap-checked alignment and bounds.
88
+ */
89
+ export function tryLoadNumericList(mem, ptr, length, kind) {
90
+ if (kind === "bool") {
91
+ const out = new Array(length);
92
+ const bytes = bytesOf(mem, ptr, length); // range assert: defense-in-depth
93
+ for (let i = 0; i < length; i++)
94
+ out[i] = bytes[i] !== 0;
95
+ return out;
96
+ }
97
+ const intCtor = INT_CTORS[kind];
98
+ if (intCtor !== undefined) {
99
+ const view = viewOf(intCtor, mem, ptr, length);
100
+ if (view === null)
101
+ return null;
102
+ // Manual preallocated loop: measurably faster than Array.from(view).
103
+ const out = new Array(length);
104
+ for (let i = 0; i < length; i++)
105
+ out[i] = view[i];
106
+ return out;
107
+ }
108
+ const bigCtor = BIG_CTORS[kind];
109
+ if (bigCtor !== undefined) {
110
+ const view = viewOf(bigCtor, mem, ptr, length);
111
+ if (view === null)
112
+ return null;
113
+ const out = new Array(length);
114
+ for (let i = 0; i < length; i++)
115
+ out[i] = view[i];
116
+ return out;
117
+ }
118
+ const floatCtor = FLOAT_CTORS[kind];
119
+ if (floatCtor !== undefined) {
120
+ const view = viewOf(floatCtor, mem, ptr, length);
121
+ if (view === null)
122
+ return null;
123
+ const out = new Array(length);
124
+ for (let i = 0; i < length; i++) {
125
+ const v = view[i];
126
+ // decodeI32AsFloat/decodeI64AsFloat: every NaN lifts as the canonical
127
+ // one (the JS NaN literal IS the canonical f64 NaN, and the canonical
128
+ // f32 NaN widens to it exactly).
129
+ out[i] = v === v ? v : NaN;
130
+ }
131
+ return out;
132
+ }
133
+ return null;
134
+ }
135
+ /**
136
+ * Bulk store of `v` as elements of `kind` at `ptr`. Returns false when not
137
+ * handled (caller falls back). The caller has already trap-checked alignment
138
+ * and bounds.
139
+ */
140
+ export function tryStoreNumericList(mem, v, ptr, kind) {
141
+ const n = v.length;
142
+ if (kind === "bool") {
143
+ const bytes = bytesOf(mem, ptr, n); // range assert: defense-in-depth
144
+ for (let i = 0; i < n; i++)
145
+ bytes[i] = v[i] ? 1 : 0;
146
+ return true;
147
+ }
148
+ const intCtor = INT_CTORS[kind];
149
+ if (intCtor !== undefined) {
150
+ const view = viewOf(intCtor, mem, ptr, n);
151
+ if (view === null)
152
+ return false;
153
+ for (let i = 0; i < n; i++) {
154
+ const x = v[i];
155
+ assert_(typeof x === "number" && Number.isInteger(x), "int store");
156
+ view[i] = x; // wraps exactly like the DataView setter
157
+ }
158
+ return true;
159
+ }
160
+ const bigCtor = BIG_CTORS[kind];
161
+ if (bigCtor !== undefined) {
162
+ const view = viewOf(bigCtor, mem, ptr, n);
163
+ if (view === null)
164
+ return false;
165
+ for (let i = 0; i < n; i++) {
166
+ const x = v[i];
167
+ assert_(typeof x === "bigint", "64-bit store requires bigint");
168
+ view[i] = x; // wraps mod 2^64 like setBigUint64/setBigInt64
169
+ }
170
+ return true;
171
+ }
172
+ const floatCtor = FLOAT_CTORS[kind];
173
+ if (floatCtor !== undefined) {
174
+ const view = viewOf(floatCtor, mem, ptr, n);
175
+ if (view === null)
176
+ return false;
177
+ const size = floatCtor.BYTES_PER_ELEMENT;
178
+ for (let i = 0; i < n; i++) {
179
+ const x = v[i];
180
+ if (typeof x === "number" && Number.isNaN(x)) {
181
+ // encodeFloatAsI32/encodeFloatAsI64: a number NaN stores the
182
+ // canonical bit pattern, never the engine's.
183
+ if (size === 4) {
184
+ mem.view.setUint32(ptr + i * 4, CANONICAL_FLOAT32_NAN, true);
185
+ }
186
+ else {
187
+ mem.view.setBigUint64(ptr + i * 8, CANONICAL_FLOAT64_NAN, true);
188
+ }
189
+ }
190
+ else {
191
+ // Same ToNumber coercion + IEEE narrowing as DataView.setFloat*.
192
+ view[i] = x;
193
+ }
194
+ }
195
+ return true;
196
+ }
197
+ return false;
198
+ }
@@ -0,0 +1,42 @@
1
+ // Canonical options and lift/lower context (definitions.py `## Canonical ABI
2
+ // Options`, `## Lifting and Lowering Context`).
3
+ import { assert_, trapIf } from "./trap.js";
4
+ export function mkCanonicalOptions(partial = {}) {
5
+ return {
6
+ stringEncoding: partial.stringEncoding ?? "utf8",
7
+ memory: partial.memory ?? null,
8
+ realloc: partial.realloc ?? null,
9
+ postReturn: partial.postReturn ?? null,
10
+ async_: partial.async_ ?? false,
11
+ callback: partial.callback ?? null,
12
+ };
13
+ }
14
+ /** Memory accessor that traps-or-asserts like `cx.opts.memory` derefs. */
15
+ export function requireMemory(opts) {
16
+ assert_(opts.memory !== null, "canonical option `memory` required");
17
+ return opts.memory;
18
+ }
19
+ export class LiftLowerContext {
20
+ opts;
21
+ inst;
22
+ borrowScope;
23
+ constructor(opts, inst = null, borrowScope = null) {
24
+ this.opts = opts;
25
+ this.inst = inst;
26
+ this.borrowScope = borrowScope;
27
+ }
28
+ /**
29
+ * definitions.py `LiftLowerContext.reallocate` routes the call through
30
+ * canon_lift (reentrance bookkeeping and may_leave toggling around a
31
+ * guest-side realloc export). v1 simplification: call the provided realloc
32
+ * directly. The full path returns with the task machinery.
33
+ */
34
+ reallocate(old, oldByteLength, alignment, newByteLength) {
35
+ const realloc = this.opts.realloc;
36
+ trapIf(realloc === null, "realloc required but not provided");
37
+ return realloc(old, oldByteLength, alignment, newByteLength);
38
+ }
39
+ allocate(alignment, byteLength) {
40
+ return this.reallocate(0, 0, alignment, byteLength);
41
+ }
42
+ }