@onda-lang/processor-abi 0.8.3 → 0.8.4
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/README.md +44 -1
- package/api.md +31 -1
- package/package.json +1 -1
- package/src/index.d.ts +45 -4
- package/src/index.js +45 -58
- package/src/payload.js +427 -0
package/README.md
CHANGED
|
@@ -27,6 +27,48 @@ validate artifacts without installing the compiler or duplicating the ABI schema
|
|
|
27
27
|
The detailed TypeScript records mirror `onda_processor_abi::ProcessorDescriptor`; both packages
|
|
28
28
|
validate the same checked-in conformance fixture.
|
|
29
29
|
|
|
30
|
+
## Structured event payloads
|
|
31
|
+
|
|
32
|
+
Every event and delegate descriptor carries a recursive `schema`. `PayloadPlan` validates that
|
|
33
|
+
schema once and encodes or decodes logical values without exposing the flattened executable
|
|
34
|
+
parameters. Top-level parameters may be supplied by position or name; nominal structs are objects
|
|
35
|
+
with exactly their declared fields, and tuples, fixed arrays, and slices are sequences. An omitted
|
|
36
|
+
top-level parameter is legal only when its schema declares a default.
|
|
37
|
+
|
|
38
|
+
```js
|
|
39
|
+
import {
|
|
40
|
+
PayloadPlan,
|
|
41
|
+
writeEventInput,
|
|
42
|
+
} from "@onda-lang/processor-abi";
|
|
43
|
+
|
|
44
|
+
const event = artifact.metadata.metadata.events.find(({ name }) => name === "note_on");
|
|
45
|
+
const plan = new PayloadPlan(event.schema);
|
|
46
|
+
const payload = plan.encode({
|
|
47
|
+
note: { frequency: 440, velocity: 0.8 },
|
|
48
|
+
});
|
|
49
|
+
const workspaceBytes = plan.requiredWorkspace(payload);
|
|
50
|
+
|
|
51
|
+
// Addresses come from the host's wasm32 linear-memory allocator. Workspace must be 8-byte aligned.
|
|
52
|
+
new Uint8Array(memory.buffer, payloadAddress, payload.byteLength).set(payload);
|
|
53
|
+
writeEventInput(
|
|
54
|
+
memory,
|
|
55
|
+
inputAddress,
|
|
56
|
+
payloadAddress,
|
|
57
|
+
payload.byteLength,
|
|
58
|
+
workspaceAddress,
|
|
59
|
+
workspaceBytes,
|
|
60
|
+
);
|
|
61
|
+
// Pass inputAddress as the first argument to instance.exports[event.export](...).
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Wire payloads are packed little-endian in canonical structure-of-arrays leaf order. Use
|
|
65
|
+
`sizes(lengths)` when only dynamic slice lengths are known, or `requiredWorkspace(payload)` to
|
|
66
|
+
preflight encoded bytes. Allocate payload, workspace, and the 16-byte `EventInput` descriptor before
|
|
67
|
+
realtime dispatch, and keep their memory regions disjoint from one another and processor storage.
|
|
68
|
+
`PayloadPlan.encode()` itself allocates and therefore belongs on a host/control thread, as does
|
|
69
|
+
decoding published delegate records. An event result of `PROCESSOR_EXECUTION_INPUT_REJECTED` (`2`)
|
|
70
|
+
means preflight failed without handler or output mutation.
|
|
71
|
+
|
|
30
72
|
## Delegate batches
|
|
31
73
|
|
|
32
74
|
The package exports `DELEGATE_RECORD_HEADER_SIZE_BYTES`, `DELEGATE_BATCH_SIZE_BYTES`,
|
|
@@ -55,8 +97,9 @@ const fixedRecordBytes = delegates.map((delegate) =>
|
|
|
55
97
|
|
|
56
98
|
writeDelegateBatch(memory, batchAddress, storageAddress, capacityBytes);
|
|
57
99
|
writeExecutionOutput(memory, outputAddress, batchAddress, 0);
|
|
100
|
+
// Before onda_process (or initialization):
|
|
58
101
|
resetExecutionOutput(memory, outputAddress);
|
|
59
|
-
// Pass outputAddress as the final
|
|
102
|
+
// Pass outputAddress as the final entry argument. onda_event_N resets it itself after preflight.
|
|
60
103
|
const batch = readDelegateBatch(memory, batchAddress);
|
|
61
104
|
const storage = new Uint8Array(memory.buffer, storageAddress, batch.usedBytes);
|
|
62
105
|
const occurrences = decodeDelegateRecords(
|
package/api.md
CHANGED
|
@@ -139,7 +139,8 @@ real-time execution.
|
|
|
139
139
|
|
|
140
140
|
`writeDelegateBatch` and `writePrintBatch` initialize reusable batch descriptors.
|
|
141
141
|
`writeExecutionOutput` connects their addresses. Call `resetExecutionOutput` immediately before
|
|
142
|
-
every generated init
|
|
142
|
+
every generated init or process entry. Generated event entries reset after successful input
|
|
143
|
+
preflight instead, so rejected input preserves existing records. After a successful generated call,
|
|
143
144
|
`readDelegateBatch` or `readPrintBatch` validates the result counters.
|
|
144
145
|
`decodeDelegateRecords` converts delegate payloads using `metadata.delegates`.
|
|
145
146
|
`decodePrintRecords` preserves primitive types and source sites; `formatPrintRecords` and
|
|
@@ -296,6 +297,17 @@ validateProcessorModule
|
|
|
296
297
|
writeDelegateBatch
|
|
297
298
|
writeExecutionOutput
|
|
298
299
|
writePrintBatch
|
|
300
|
+
OndaPayloadType
|
|
301
|
+
OndaPayloadField
|
|
302
|
+
OndaPayloadSchema
|
|
303
|
+
OndaPayloadDefault
|
|
304
|
+
OndaPayloadValue
|
|
305
|
+
OndaPayloadSizes
|
|
306
|
+
PayloadPlan
|
|
307
|
+
canonicalF32Number
|
|
308
|
+
EVENT_INPUT_SIZE_BYTES
|
|
309
|
+
PROCESSOR_EXECUTION_INPUT_REJECTED
|
|
310
|
+
writeEventInput
|
|
299
311
|
<!-- END WEB API onda_processor_abi -->
|
|
300
312
|
|
|
301
313
|
### `@onda-lang/binaryen-web`
|
|
@@ -410,3 +422,21 @@ paramNormalizedToPlain
|
|
|
410
422
|
paramPlainToNormalized
|
|
411
423
|
registerOndaAudioWorklet
|
|
412
424
|
<!-- END WEB API onda_webaudio -->
|
|
425
|
+
|
|
426
|
+
### Structured event and delegate values
|
|
427
|
+
|
|
428
|
+
`PayloadPlan` prepares a recursive message schema once. `encode(values)` accepts ordered parameter
|
|
429
|
+
arrays or objects keyed by parameter name; structs are objects containing exactly their declared
|
|
430
|
+
own fields, and arrays/tuples are sequences. Unknown named parameters and excess positional values
|
|
431
|
+
are rejected. Missing event arguments use declared constant defaults.
|
|
432
|
+
Supply `i64` as `bigint`, an exact safe integer, or a decimal string. `decode(bytes)` returns named
|
|
433
|
+
nested values with `bigint` for `i64`. Plans own immutable schema snapshots.
|
|
434
|
+
|
|
435
|
+
`requiredWorkspace(bytes)` preflights packed little-endian input. `sizes(lengths)` reports wire
|
|
436
|
+
and aligned workspace sizes without allocating payload storage. Low-level wasm hosts provision
|
|
437
|
+
both regions and a 16-byte descriptor, then call `writeEventInput` before invoking the event.
|
|
438
|
+
Rejected input returns `PROCESSOR_EXECUTION_INPUT_REJECTED` (2) and leaves processor state usable.
|
|
439
|
+
`OndaAudioProcessor.trigger` performs logical encoding before transferring bytes to the worklet.
|
|
440
|
+
Decoded `f32` leaves use `canonicalF32Number(value)`: the returned JavaScript number has the
|
|
441
|
+
shortest decimal representation that round-trips to the same `f32`, so JSON and controls do not
|
|
442
|
+
expose an irrelevant widened binary tail.
|
package/package.json
CHANGED
package/src/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export const PROCESSOR_ARTIFACT_FORMAT: "onda-processor";
|
|
2
2
|
// Synchronized from format-versions.json; do not edit these copies directly.
|
|
3
|
-
export const PROCESSOR_ARTIFACT_FORMAT_VERSION:
|
|
4
|
-
export const PROCESSOR_ABI_VERSION:
|
|
3
|
+
export const PROCESSOR_ARTIFACT_FORMAT_VERSION: 6;
|
|
4
|
+
export const PROCESSOR_ABI_VERSION: 6;
|
|
5
5
|
export const PROCESSOR_EXECUTION_OK: 0;
|
|
6
6
|
export const PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE: 1;
|
|
7
7
|
export const PROCESSOR_INIT_PRESERVE_PINNED: 0;
|
|
@@ -19,6 +19,9 @@ export const PRINT_BATCH_SIZE_BYTES: 20;
|
|
|
19
19
|
/** wasm32 byte size of the call-scoped execution-output descriptor. */
|
|
20
20
|
export const EXECUTION_OUTPUT_SIZE_BYTES: 12;
|
|
21
21
|
|
|
22
|
+
/** Returns the shortest host number that round-trips to the same f32. */
|
|
23
|
+
export function canonicalF32Number(value: number): number;
|
|
24
|
+
|
|
22
25
|
export type OndaScalarType = "f32" | "f64" | "i32" | "i64" | "bool";
|
|
23
26
|
export type OndaArtifactKind = "webassembly_module" | "relocatable_object";
|
|
24
27
|
|
|
@@ -150,6 +153,42 @@ export interface OndaBufferArrayMetadata {
|
|
|
150
153
|
len: number;
|
|
151
154
|
}
|
|
152
155
|
|
|
156
|
+
export type OndaPayloadDefault = string | OndaPayloadDefault[];
|
|
157
|
+
export type OndaPayloadType =
|
|
158
|
+
| { kind: "scalar"; encoding: OndaScalarType; integer_range?: OndaStateMetadata["integer_range"] }
|
|
159
|
+
| { kind: "tuple"; elements: OndaPayloadType[] }
|
|
160
|
+
| { kind: "struct"; name: string; fields: [OndaPayloadField, ...OndaPayloadField[]] }
|
|
161
|
+
| { kind: "array"; element: OndaPayloadType; len: number }
|
|
162
|
+
| { kind: "slice"; element: OndaPayloadType };
|
|
163
|
+
export interface OndaPayloadField {
|
|
164
|
+
name: string;
|
|
165
|
+
ty: OndaPayloadType;
|
|
166
|
+
default?: OndaPayloadDefault;
|
|
167
|
+
}
|
|
168
|
+
export interface OndaPayloadSchema { params: OndaPayloadField[] }
|
|
169
|
+
|
|
170
|
+
export type OndaPayloadValue = number | bigint | boolean | string | OndaPayloadValue[] | { [name: string]: OndaPayloadValue };
|
|
171
|
+
export interface OndaPayloadSizes { wire: number; workspace: number }
|
|
172
|
+
export class PayloadPlan {
|
|
173
|
+
constructor(schema: OndaPayloadSchema);
|
|
174
|
+
readonly schema: OndaPayloadSchema;
|
|
175
|
+
readonly fixedWireSize: number | null;
|
|
176
|
+
readonly minimumWorkspace: number;
|
|
177
|
+
readonly dynamicParameters: number;
|
|
178
|
+
readonly abiParameterCount: number;
|
|
179
|
+
/** Whether scalar representations match this flattened ABI parameter's schema default. */
|
|
180
|
+
matchesAbiDefault(parameter: number, defaultReprs: readonly string[] | null): boolean;
|
|
181
|
+
sizes(lengths: readonly number[]): OndaPayloadSizes;
|
|
182
|
+
requiredWorkspace(input: Uint8Array | ArrayBuffer): number;
|
|
183
|
+
encode(values: readonly unknown[] | Record<string, unknown>): Uint8Array;
|
|
184
|
+
decode(input: Uint8Array | ArrayBuffer): Record<string, OndaPayloadValue>;
|
|
185
|
+
}
|
|
186
|
+
export const EVENT_INPUT_SIZE_BYTES: 16;
|
|
187
|
+
export const PROCESSOR_EXECUTION_INPUT_REJECTED: 2;
|
|
188
|
+
export function writeEventInput(memory: WebAssembly.Memory | ArrayBuffer, address: number,
|
|
189
|
+
payloadAddress: number, payloadBytes: number, workspaceAddress: number, workspaceCapacityBytes: number): void;
|
|
190
|
+
|
|
191
|
+
|
|
153
192
|
export interface OndaEventParamMetadata {
|
|
154
193
|
name: string;
|
|
155
194
|
type_repr: string;
|
|
@@ -165,6 +204,7 @@ export interface OndaEventParamMetadata {
|
|
|
165
204
|
}
|
|
166
205
|
|
|
167
206
|
export interface OndaEventMetadata {
|
|
207
|
+
schema: OndaPayloadSchema;
|
|
168
208
|
name: string;
|
|
169
209
|
export: string;
|
|
170
210
|
payload_size_bytes: number | null;
|
|
@@ -186,6 +226,7 @@ export interface OndaDelegateParamMetadata {
|
|
|
186
226
|
}
|
|
187
227
|
|
|
188
228
|
export interface OndaDelegateMetadata {
|
|
229
|
+
schema: OndaPayloadSchema;
|
|
189
230
|
index: number;
|
|
190
231
|
name: string;
|
|
191
232
|
payload_size_bytes: number | null;
|
|
@@ -214,9 +255,9 @@ export interface OndaStateMetadata {
|
|
|
214
255
|
|
|
215
256
|
export interface OndaProcessorMetadata {
|
|
216
257
|
format: "onda-processor";
|
|
217
|
-
format_version:
|
|
258
|
+
format_version: 6;
|
|
218
259
|
artifact_kind: OndaArtifactKind;
|
|
219
|
-
abi_version:
|
|
260
|
+
abi_version: 6;
|
|
220
261
|
backend: string;
|
|
221
262
|
mir_schema_version: number;
|
|
222
263
|
target: OndaTargetInfo;
|
package/src/index.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
+
import { canonicalF32Number, PayloadPlan } from "./payload.js";
|
|
2
|
+
export { canonicalF32Number, PayloadPlan, EVENT_INPUT_SIZE_BYTES, PROCESSOR_EXECUTION_INPUT_REJECTED, writeEventInput } from "./payload.js";
|
|
1
3
|
import "./param-control.js";
|
|
2
4
|
|
|
3
5
|
const PARAM_CONTROL = globalThis.__ONDA_PARAM_CONTROL_V2__;
|
|
4
6
|
|
|
5
7
|
export const PROCESSOR_ARTIFACT_FORMAT = "onda-processor";
|
|
6
8
|
// Synchronized from format-versions.json; do not edit these copies directly.
|
|
7
|
-
export const PROCESSOR_ARTIFACT_FORMAT_VERSION =
|
|
8
|
-
export const PROCESSOR_ABI_VERSION =
|
|
9
|
+
export const PROCESSOR_ARTIFACT_FORMAT_VERSION = 6;
|
|
10
|
+
export const PROCESSOR_ABI_VERSION = 6;
|
|
9
11
|
export const PROCESSOR_EXECUTION_OK = 0;
|
|
10
12
|
export const PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE = 1;
|
|
11
13
|
export const PROCESSOR_INIT_PRESERVE_PINNED = 0;
|
|
@@ -479,12 +481,27 @@ function validateEventMetadata(value, path) {
|
|
|
479
481
|
}
|
|
480
482
|
|
|
481
483
|
function validatePayloadMetadata(value, path, supportsDefaults) {
|
|
484
|
+
let plan;
|
|
485
|
+
try { plan = new PayloadPlan(value?.schema); }
|
|
486
|
+
catch (error) { throw new OndaArtifactError(`${path}.schema: ${error.message}`); }
|
|
487
|
+
const prefixes = new Set(plan.tensors.filter((tensor) => tensor.lengthPrefix).map((tensor) => tensor.parameter));
|
|
488
|
+
const lengths = new Set(plan.parameters.map((group) => group.lengthParameter).filter((index) => index !== null));
|
|
482
489
|
requireNullableInteger(value?.payload_size_bytes, `${path}.payload_size_bytes`, 0);
|
|
483
490
|
requireInteger(value?.payload_min_size_bytes, `${path}.payload_min_size_bytes`, 0);
|
|
484
491
|
requireBoolean(value?.has_dynamic_payload, `${path}.has_dynamic_payload`);
|
|
485
492
|
if (!Array.isArray(value?.params)) {
|
|
486
493
|
throw new OndaArtifactError(`${path}.params must be an array`);
|
|
487
494
|
}
|
|
495
|
+
if (value.params.length !== plan.abiParameterCount) throw new OndaArtifactError(`${path}.params do not match schema`);
|
|
496
|
+
const expected = Array(plan.abiParameterCount);
|
|
497
|
+
for (const group of plan.parameters) {
|
|
498
|
+
if (group.lengthParameter !== null) expected[group.lengthParameter] = { name: group.name, scalar: "i32", length: 1, array: false, slice: false };
|
|
499
|
+
for (let index = group.start; index < group.end; index += 1) {
|
|
500
|
+
const tensor = plan.tensors[index];
|
|
501
|
+
expected[tensor.parameter] = { name: tensor.path, scalar: tensor.encoding,
|
|
502
|
+
length: group.dynamic ? 0 : tensor.elements, array: !group.dynamic && tensor.shape.length > 0, slice: group.dynamic };
|
|
503
|
+
}
|
|
504
|
+
}
|
|
488
505
|
let minimumSize = 0;
|
|
489
506
|
let hasDynamicParam = false;
|
|
490
507
|
value.params.forEach((param, index) => {
|
|
@@ -503,6 +520,11 @@ function validatePayloadMetadata(value, path, supportsDefaults) {
|
|
|
503
520
|
requireNullableStringArray(param?.default_reprs, `${paramPath}.default_reprs`);
|
|
504
521
|
}
|
|
505
522
|
requireScalarElementSize(param, paramPath);
|
|
523
|
+
const shape = expected[index];
|
|
524
|
+
if (param.name !== shape.name || param.scalar !== shape.scalar || param.array_len !== shape.length
|
|
525
|
+
|| param.is_array !== shape.array || param.is_slice !== shape.slice) {
|
|
526
|
+
throw new OndaArtifactError(`${paramPath} does not match its schema tensor`);
|
|
527
|
+
}
|
|
506
528
|
if (hasDynamicParam ? param.byte_offset !== null : param.byte_offset !== minimumSize) {
|
|
507
529
|
throw new OndaArtifactError(`${paramPath}.byte_offset is inconsistent with event layout`);
|
|
508
530
|
}
|
|
@@ -516,7 +538,7 @@ function validatePayloadMetadata(value, path, supportsDefaults) {
|
|
|
516
538
|
) {
|
|
517
539
|
throw new OndaArtifactError(`${paramPath} has an invalid slice descriptor`);
|
|
518
540
|
}
|
|
519
|
-
minimumSize += 4;
|
|
541
|
+
if (prefixes.has(index)) minimumSize += 4;
|
|
520
542
|
hasDynamicParam = true;
|
|
521
543
|
} else {
|
|
522
544
|
const expectedType = param.is_array
|
|
@@ -531,13 +553,12 @@ function validatePayloadMetadata(value, path, supportsDefaults) {
|
|
|
531
553
|
throw new OndaArtifactError(`${paramPath} has an invalid fixed-size descriptor`);
|
|
532
554
|
}
|
|
533
555
|
minimumSize += param.byte_size;
|
|
556
|
+
if (lengths.has(index)) hasDynamicParam = true;
|
|
534
557
|
}
|
|
535
558
|
if (supportsDefaults) {
|
|
536
|
-
if (param.has_default !== (param.default_reprs !== null)
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
if (param.default_reprs !== null && param.default_reprs.length !== param.array_len) {
|
|
540
|
-
throw new OndaArtifactError(`${paramPath}.default_reprs must contain one value per element`);
|
|
559
|
+
if (param.has_default !== (param.default_reprs !== null)
|
|
560
|
+
|| !plan.matchesAbiDefault(index, param.default_reprs)) {
|
|
561
|
+
throw new OndaArtifactError(`${paramPath} defaults do not match schema`);
|
|
541
562
|
}
|
|
542
563
|
}
|
|
543
564
|
});
|
|
@@ -1077,14 +1098,6 @@ export function decodePrintRecords(
|
|
|
1077
1098
|
return records;
|
|
1078
1099
|
}
|
|
1079
1100
|
|
|
1080
|
-
function shortestF32(value) {
|
|
1081
|
-
for (let precision = 1; precision <= 9; precision += 1) {
|
|
1082
|
-
const candidate = value.toPrecision(precision);
|
|
1083
|
-
if (Object.is(Math.fround(Number(candidate)), value)) return candidate;
|
|
1084
|
-
}
|
|
1085
|
-
return value.toPrecision(9);
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
1101
|
function canonicalFloat(value, width) {
|
|
1089
1102
|
if (Number.isNaN(value)) return "NaN";
|
|
1090
1103
|
if (value === Infinity) return "inf";
|
|
@@ -1092,7 +1105,9 @@ function canonicalFloat(value, width) {
|
|
|
1092
1105
|
if (Object.is(value, -0)) return "-0.0";
|
|
1093
1106
|
if (value === 0) return "0.0";
|
|
1094
1107
|
const negative = value < 0;
|
|
1095
|
-
const shortest = width === 32
|
|
1108
|
+
const shortest = width === 32
|
|
1109
|
+
? canonicalF32Number(Math.abs(value)).toString()
|
|
1110
|
+
: Math.abs(value).toString();
|
|
1096
1111
|
const [mantissa, exponentText] = shortest.toLowerCase().split("e");
|
|
1097
1112
|
let digits = mantissa.replace(".", "");
|
|
1098
1113
|
const leading = digits.match(/^0*/u)[0].length;
|
|
@@ -1193,6 +1208,8 @@ export function formatPrintRecords(storage, usedBytes, metadata, overflowCount =
|
|
|
1193
1208
|
return { text, entries: records, overflowCount };
|
|
1194
1209
|
}
|
|
1195
1210
|
|
|
1211
|
+
const delegatePayloadPlans = new WeakMap();
|
|
1212
|
+
|
|
1196
1213
|
export function decodeDelegateRecords(
|
|
1197
1214
|
storage,
|
|
1198
1215
|
usedBytes,
|
|
@@ -1213,6 +1230,7 @@ export function decodeDelegateRecords(
|
|
|
1213
1230
|
}
|
|
1214
1231
|
const view = new DataView(bytes.buffer, bytes.byteOffset, usedBytes);
|
|
1215
1232
|
const records = [];
|
|
1233
|
+
const plans = new Array(delegates.length);
|
|
1216
1234
|
let cursor = 0;
|
|
1217
1235
|
while (cursor < usedBytes) {
|
|
1218
1236
|
if (usedBytes - cursor < DELEGATE_RECORD_HEADER_SIZE_BYTES) {
|
|
@@ -1240,8 +1258,7 @@ export function decodeDelegateRecords(
|
|
|
1240
1258
|
view,
|
|
1241
1259
|
payloadOffset,
|
|
1242
1260
|
payloadByteLength,
|
|
1243
|
-
delegate,
|
|
1244
|
-
littleEndian,
|
|
1261
|
+
plans[delegateIndex] ??= delegatePayloadPlan(delegate.schema),
|
|
1245
1262
|
),
|
|
1246
1263
|
});
|
|
1247
1264
|
cursor = end;
|
|
@@ -1249,50 +1266,20 @@ export function decodeDelegateRecords(
|
|
|
1249
1266
|
return records;
|
|
1250
1267
|
}
|
|
1251
1268
|
|
|
1252
|
-
function
|
|
1253
|
-
let
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
let count = param.array_len;
|
|
1258
|
-
if (param.is_slice) {
|
|
1259
|
-
if (cursor + 4 > end) {
|
|
1260
|
-
throw new OndaArtifactError(`delegate '${delegate.name}' has a truncated slice length`);
|
|
1261
|
-
}
|
|
1262
|
-
count = view.getInt32(cursor, littleEndian);
|
|
1263
|
-
cursor += 4;
|
|
1264
|
-
if (count < 0) {
|
|
1265
|
-
throw new OndaArtifactError(`delegate '${delegate.name}' has a negative slice length`);
|
|
1266
|
-
}
|
|
1267
|
-
}
|
|
1268
|
-
const byteLength = count * param.element_size_bytes;
|
|
1269
|
-
if (!Number.isSafeInteger(byteLength) || cursor + byteLength > end) {
|
|
1270
|
-
throw new OndaArtifactError(`delegate '${delegate.name}' has a truncated '${param.name}' payload`);
|
|
1271
|
-
}
|
|
1272
|
-
const entries = [];
|
|
1273
|
-
for (let index = 0; index < count; index += 1) {
|
|
1274
|
-
entries.push(readPayloadScalar(view, cursor, param.scalar, littleEndian));
|
|
1275
|
-
cursor += param.element_size_bytes;
|
|
1276
|
-
}
|
|
1277
|
-
values[param.name] = param.is_array || param.is_slice ? entries : entries[0];
|
|
1278
|
-
}
|
|
1279
|
-
if (cursor !== end) {
|
|
1280
|
-
throw new OndaArtifactError(`delegate '${delegate.name}' payload has trailing bytes`);
|
|
1269
|
+
function delegatePayloadPlan(schema) {
|
|
1270
|
+
let plan = delegatePayloadPlans.get(schema);
|
|
1271
|
+
if (plan === undefined) {
|
|
1272
|
+
plan = new PayloadPlan(schema);
|
|
1273
|
+
delegatePayloadPlans.set(schema, plan);
|
|
1281
1274
|
}
|
|
1282
|
-
return
|
|
1275
|
+
return plan;
|
|
1283
1276
|
}
|
|
1284
1277
|
|
|
1285
|
-
function
|
|
1286
|
-
|
|
1287
|
-
case "bool": return view.getUint8(address) !== 0;
|
|
1288
|
-
case "i32": return view.getInt32(address, littleEndian);
|
|
1289
|
-
case "i64": return view.getBigInt64(address, littleEndian);
|
|
1290
|
-
case "f32": return view.getFloat32(address, littleEndian);
|
|
1291
|
-
case "f64": return view.getFloat64(address, littleEndian);
|
|
1292
|
-
default: throw new OndaArtifactError(`unsupported delegate scalar '${String(scalar)}'`);
|
|
1293
|
-
}
|
|
1278
|
+
function decodeDelegatePayload(view, start, size, plan) {
|
|
1279
|
+
return plan.decode(new Uint8Array(view.buffer, view.byteOffset + start, size));
|
|
1294
1280
|
}
|
|
1295
1281
|
|
|
1282
|
+
|
|
1296
1283
|
function writableDataView(memory) {
|
|
1297
1284
|
if (memory instanceof DataView) return memory;
|
|
1298
1285
|
if (memory instanceof WebAssembly.Memory) return new DataView(memory.buffer);
|
package/src/payload.js
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
// Logical SoA shape planning. Array extents remain axes; plans never expand
|
|
2
|
+
// array elements into metadata. This mirrors the compiler-free Rust planner.
|
|
3
|
+
const LIMIT = 0x7fffffff;
|
|
4
|
+
const SIZES = Object.freeze({ bool: 1, i32: 4, i64: 8, f32: 4, f64: 8 });
|
|
5
|
+
const SIGNED_DECIMAL_INTEGER = /^[+-]?[0-9]+$/;
|
|
6
|
+
export const EVENT_INPUT_SIZE_BYTES = 16;
|
|
7
|
+
export const PROCESSOR_EXECUTION_INPUT_REJECTED = 2;
|
|
8
|
+
|
|
9
|
+
/** Return the shortest host number that round-trips to the same f32. */
|
|
10
|
+
export function canonicalF32Number(value) {
|
|
11
|
+
const rounded = Math.fround(value);
|
|
12
|
+
if (!Number.isFinite(rounded) || rounded === 0) return rounded;
|
|
13
|
+
for (let precision = 1; precision <= 9; precision += 1) {
|
|
14
|
+
const candidate = Number(rounded.toPrecision(precision));
|
|
15
|
+
if (Math.fround(candidate) === rounded) return candidate;
|
|
16
|
+
}
|
|
17
|
+
return rounded;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function freeze(value, seen = new Set()) {
|
|
21
|
+
if (!value || typeof value !== "object" || seen.has(value)) return;
|
|
22
|
+
seen.add(value);
|
|
23
|
+
for (const child of Object.values(value)) freeze(child, seen);
|
|
24
|
+
Object.freeze(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function extent(value) {
|
|
28
|
+
if (!Number.isSafeInteger(value) || value < 0 || value > LIMIT) {
|
|
29
|
+
throw new RangeError("payload byte extent exceeds i32");
|
|
30
|
+
}
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
function align(value, alignment) {
|
|
34
|
+
return Math.floor(extent(value + alignment - 1) / alignment) * alignment;
|
|
35
|
+
}
|
|
36
|
+
function fields(entries) {
|
|
37
|
+
if (!Array.isArray(entries)) throw new TypeError("invalid payload fields");
|
|
38
|
+
const names = new Set();
|
|
39
|
+
for (const entry of entries) {
|
|
40
|
+
if (typeof entry?.name !== "string" || !entry.name || /[.\[\]]/.test(entry.name) || names.has(entry.name)) {
|
|
41
|
+
throw new TypeError("invalid or duplicate payload field name");
|
|
42
|
+
}
|
|
43
|
+
names.add(entry.name);
|
|
44
|
+
}
|
|
45
|
+
return names;
|
|
46
|
+
}
|
|
47
|
+
function arrayElement(ty) {
|
|
48
|
+
return ty?.kind === "scalar" || ty?.kind === "struct";
|
|
49
|
+
}
|
|
50
|
+
function parseSignedDecimalInteger(value, message) {
|
|
51
|
+
if (typeof value !== "string" || !SIGNED_DECIMAL_INTEGER.test(value)) {
|
|
52
|
+
throw new TypeError(message);
|
|
53
|
+
}
|
|
54
|
+
return BigInt(value);
|
|
55
|
+
}
|
|
56
|
+
function domain(encoding, range) {
|
|
57
|
+
if (range == null) return null;
|
|
58
|
+
if (!["i32", "i64"].includes(encoding) || !["clamp", "wrap"].includes(range.mode)
|
|
59
|
+
|| range.min?.type !== encoding || range.max?.type !== encoding) {
|
|
60
|
+
throw new TypeError("invalid payload integer range");
|
|
61
|
+
}
|
|
62
|
+
const bits = encoding === "i32" ? 32 : 64;
|
|
63
|
+
const min = parseSignedDecimalInteger(range.min.value, "invalid payload integer range");
|
|
64
|
+
const max = parseSignedDecimalInteger(range.max.value, "invalid payload integer range");
|
|
65
|
+
if (min > max || BigInt.asIntN(bits, min) !== min || BigInt.asIntN(bits, max) !== max) {
|
|
66
|
+
throw new RangeError("invalid payload integer range");
|
|
67
|
+
}
|
|
68
|
+
return { min, max, wrap: range.mode === "wrap" };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export class PayloadPlan {
|
|
72
|
+
#parameterNames;
|
|
73
|
+
#abiDefaults;
|
|
74
|
+
|
|
75
|
+
constructor(schema) {
|
|
76
|
+
schema = structuredClone(schema);
|
|
77
|
+
this.#parameterNames = fields(schema?.params);
|
|
78
|
+
this.parameters = [];
|
|
79
|
+
this.tensors = [];
|
|
80
|
+
this.schema = schema;
|
|
81
|
+
const active = new Set();
|
|
82
|
+
const visit = (ty, path, shape, steps) => {
|
|
83
|
+
if (!ty || active.has(ty)) throw new TypeError("invalid recursive payload schema");
|
|
84
|
+
active.add(ty);
|
|
85
|
+
shape.reduce((count, axis) => extent(count * axis), 1);
|
|
86
|
+
switch (ty.kind) {
|
|
87
|
+
case "scalar": {
|
|
88
|
+
const size = SIZES[ty.encoding];
|
|
89
|
+
if (size === undefined) throw new TypeError("invalid payload scalar encoding");
|
|
90
|
+
const elements = shape.reduce((count, axis) => extent(count * axis), 1);
|
|
91
|
+
this.tensors.push({ path, encoding: ty.encoding, size, shape, steps: steps.map((step) => ({ ...step })), elements,
|
|
92
|
+
domain: domain(ty.encoding, ty.integer_range) });
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
case "tuple":
|
|
96
|
+
if (!Array.isArray(ty.elements) || !ty.elements.length
|
|
97
|
+
|| ty.elements.some((element) => element?.kind !== "scalar")) {
|
|
98
|
+
throw new TypeError("invalid payload tuple");
|
|
99
|
+
}
|
|
100
|
+
ty.elements.forEach((element, index) =>
|
|
101
|
+
visit(element, `${path}.__${index}`, shape, [...steps, { field: index }]));
|
|
102
|
+
break;
|
|
103
|
+
case "struct":
|
|
104
|
+
if (typeof ty.name !== "string" || !ty.name) throw new TypeError("invalid payload struct name");
|
|
105
|
+
fields(ty.fields);
|
|
106
|
+
if (!ty.fields.length) throw new TypeError("payload structs must contain at least one field");
|
|
107
|
+
for (const field of ty.fields) {
|
|
108
|
+
if (field.default !== undefined) parsePayloadDefault(field.ty, field.default);
|
|
109
|
+
visit(field.ty, `${path}.${field.name}`, shape, [...steps, { field: field.name }]);
|
|
110
|
+
}
|
|
111
|
+
break;
|
|
112
|
+
case "array":
|
|
113
|
+
if (!arrayElement(ty.element) || extent(ty.len) === 0) {
|
|
114
|
+
throw new TypeError("invalid payload array");
|
|
115
|
+
}
|
|
116
|
+
visit(ty.element, path, [...shape, ty.len], [...steps, { axis: ty.len }]);
|
|
117
|
+
break;
|
|
118
|
+
default: throw new TypeError("invalid payload type");
|
|
119
|
+
}
|
|
120
|
+
active.delete(ty);
|
|
121
|
+
};
|
|
122
|
+
let abiParameter = 0;
|
|
123
|
+
for (const field of schema.params) {
|
|
124
|
+
const dynamic = field.ty?.kind === "slice";
|
|
125
|
+
const start = this.tensors.length;
|
|
126
|
+
const ty = dynamic ? field.ty.element : field.ty;
|
|
127
|
+
if (dynamic && !arrayElement(ty)) throw new TypeError("invalid payload slice element");
|
|
128
|
+
const lengthParameter = dynamic && ty.kind === "struct" ? abiParameter++ : null;
|
|
129
|
+
visit(ty, field.name, [], dynamic ? [{ axis: null }] : []);
|
|
130
|
+
if (this.tensors.length === start) throw new TypeError("payload types must contain at least one scalar");
|
|
131
|
+
for (let index = start; index < this.tensors.length; index += 1) {
|
|
132
|
+
this.tensors[index].parameter = abiParameter++;
|
|
133
|
+
this.tensors[index].lengthPrefix = dynamic && lengthParameter === null;
|
|
134
|
+
}
|
|
135
|
+
this.parameters.push({ name: field.name, dynamic, lengthParameter, start, end: this.tensors.length });
|
|
136
|
+
}
|
|
137
|
+
this.abiParameterCount = abiParameter;
|
|
138
|
+
this.dynamicParameters = this.parameters.filter((param) => param.dynamic).length;
|
|
139
|
+
const minimum = this.sizes(Array(this.dynamicParameters).fill(0));
|
|
140
|
+
this.fixedWireSize = this.dynamicParameters === 0 ? minimum.wire : null;
|
|
141
|
+
this.minimumWorkspace = minimum.workspace;
|
|
142
|
+
this.defaults = schema.params.map((field) =>
|
|
143
|
+
field.default === undefined ? undefined : parsePayloadDefault(field.ty, field.default));
|
|
144
|
+
for (const tensor of this.tensors) {
|
|
145
|
+
let stride = 1;
|
|
146
|
+
for (let index = tensor.steps.length - 1; index >= 0; index -= 1) {
|
|
147
|
+
const step = tensor.steps[index];
|
|
148
|
+
if (step.field === undefined) { step.stride = stride; if (step.axis !== null) stride *= step.axis; }
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
this.#abiDefaults = Array(this.abiParameterCount).fill(null);
|
|
152
|
+
for (let parameter = 0; parameter < this.parameters.length; parameter += 1) {
|
|
153
|
+
const source = this.defaults[parameter];
|
|
154
|
+
if (source === undefined) continue;
|
|
155
|
+
const group = this.parameters[parameter];
|
|
156
|
+
for (let index = group.start; index < group.end; index += 1) {
|
|
157
|
+
const tensor = this.tensors[index];
|
|
158
|
+
this.#abiDefaults[tensor.parameter] = {
|
|
159
|
+
encoding: tensor.encoding,
|
|
160
|
+
values: Array.from(
|
|
161
|
+
{ length: tensor.elements },
|
|
162
|
+
(_, element) => leafValue(source, tensor.steps, element),
|
|
163
|
+
),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
freeze(this);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
matchesAbiDefault(parameter, defaultReprs) {
|
|
171
|
+
if (!Number.isInteger(parameter) || parameter < 0 || parameter >= this.abiParameterCount) return false;
|
|
172
|
+
const defaults = this.#abiDefaults[parameter];
|
|
173
|
+
if (defaults === null || defaultReprs === null) return defaults === defaultReprs;
|
|
174
|
+
if (!Array.isArray(defaultReprs) || defaultReprs.length !== defaults.values.length) return false;
|
|
175
|
+
try {
|
|
176
|
+
return defaultReprs.every((repr, index) => {
|
|
177
|
+
const actual = parseScalarDefault(defaults.encoding, repr);
|
|
178
|
+
const expected = defaults.values[index];
|
|
179
|
+
return defaults.encoding === "f32"
|
|
180
|
+
? Object.is(Math.fround(actual), Math.fround(expected))
|
|
181
|
+
: Object.is(actual, expected);
|
|
182
|
+
});
|
|
183
|
+
} catch {
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Read-only preflight: no per-element metadata or temporary payload copies.
|
|
189
|
+
walk(length, tensor, prefix = null) {
|
|
190
|
+
let wire = 0;
|
|
191
|
+
let workspace = 0;
|
|
192
|
+
for (let parameter = 0; parameter < this.parameters.length; parameter += 1) {
|
|
193
|
+
const param = this.parameters[parameter];
|
|
194
|
+
let logicalLength = 1;
|
|
195
|
+
if (param.dynamic) {
|
|
196
|
+
logicalLength = extent(length(wire, parameter));
|
|
197
|
+
workspace = align(workspace, 4);
|
|
198
|
+
if (prefix) prefix(wire, workspace, logicalLength);
|
|
199
|
+
wire = extent(wire + 4);
|
|
200
|
+
workspace = extent(workspace + 4);
|
|
201
|
+
}
|
|
202
|
+
for (let index = param.start; index < param.end; index += 1) {
|
|
203
|
+
const leaf = this.tensors[index];
|
|
204
|
+
const elements = extent(logicalLength * leaf.elements);
|
|
205
|
+
const bytes = extent(elements * leaf.size);
|
|
206
|
+
workspace = align(workspace, leaf.size);
|
|
207
|
+
if (tensor) tensor(index, wire, workspace, elements, parameter);
|
|
208
|
+
wire = extent(wire + bytes);
|
|
209
|
+
workspace = extent(workspace + bytes);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return { wire, workspace };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
sizes(lengths) {
|
|
216
|
+
if (lengths.length !== this.dynamicParameters) throw new RangeError("payload lengths do not match schema");
|
|
217
|
+
let index = 0;
|
|
218
|
+
return this.walk(() => lengths[index++], null);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
requiredWorkspace(input) {
|
|
222
|
+
const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
|
|
223
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
224
|
+
const sizes = this.walk((offset) => {
|
|
225
|
+
if (offset + 4 > bytes.byteLength) throw new RangeError("truncated payload slice length");
|
|
226
|
+
const length = view.getInt32(offset, true);
|
|
227
|
+
if (length < 0) throw new RangeError("negative payload slice length");
|
|
228
|
+
return length;
|
|
229
|
+
}, null);
|
|
230
|
+
if (sizes.wire > bytes.byteLength) throw new RangeError("truncated payload");
|
|
231
|
+
if (sizes.wire < bytes.byteLength) throw new RangeError("unexpected trailing payload bytes");
|
|
232
|
+
return sizes.workspace;
|
|
233
|
+
}
|
|
234
|
+
/** Encode logical values outside realtime dispatch, preserving exact i64 values.
|
|
235
|
+
* Accept ordered parameter arrays or objects keyed by the declared names. */
|
|
236
|
+
encode(values) {
|
|
237
|
+
const positional = Array.isArray(values);
|
|
238
|
+
const named = !positional && values !== null && typeof values === "object";
|
|
239
|
+
if (!positional && !named) throw new TypeError("payload values must be an ordered array or named object");
|
|
240
|
+
if (positional && values.length > this.parameters.length) {
|
|
241
|
+
throw new RangeError("payload parameter count exceeds schema");
|
|
242
|
+
}
|
|
243
|
+
if (named) {
|
|
244
|
+
const unexpected = Object.keys(values).find((name) => !this.#parameterNames.has(name));
|
|
245
|
+
if (unexpected !== undefined) throw new TypeError(`unexpected payload parameter '${unexpected}'`);
|
|
246
|
+
}
|
|
247
|
+
const roots = this.schema.params.map((field, index) => {
|
|
248
|
+
let value;
|
|
249
|
+
if (positional) value = values[index];
|
|
250
|
+
else if (named && Object.hasOwn(values, field.name)) value = values[field.name];
|
|
251
|
+
const result = value === undefined ? this.defaults[index] : value;
|
|
252
|
+
if (result === undefined) throw new TypeError(`missing payload parameter '${field.name}'`);
|
|
253
|
+
validateValue(field.ty, result);
|
|
254
|
+
return result;
|
|
255
|
+
});
|
|
256
|
+
const sizes = this.walk((_, parameter) => roots[parameter].length, null);
|
|
257
|
+
const bytes = new Uint8Array(sizes.wire);
|
|
258
|
+
const view = new DataView(bytes.buffer);
|
|
259
|
+
this.walk((_, parameter) => roots[parameter].length, (index, offset, _workspace, count, parameter) => {
|
|
260
|
+
const tensor = this.tensors[index];
|
|
261
|
+
for (let element = 0; element < count; element += 1) {
|
|
262
|
+
writeScalar(view, offset + element * tensor.size, tensor.encoding, leafValue(roots[parameter], tensor.steps, element));
|
|
263
|
+
}
|
|
264
|
+
}, (offset, _workspace, length) => view.setInt32(offset, length, true));
|
|
265
|
+
return bytes;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Decode one complete wire payload into nested host values. */
|
|
269
|
+
decode(input) {
|
|
270
|
+
const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
|
|
271
|
+
this.requiredWorkspace(bytes);
|
|
272
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
273
|
+
const roots = this.schema.params.map((field) => field.ty.kind === "slice" ? null : emptyValue(field.ty));
|
|
274
|
+
this.walk((offset, parameter) => {
|
|
275
|
+
const length = view.getInt32(offset, true);
|
|
276
|
+
roots[parameter] = emptyValue(this.schema.params[parameter].ty, length);
|
|
277
|
+
return length;
|
|
278
|
+
}, (index, offset, _workspace, count, parameter) => {
|
|
279
|
+
const tensor = this.tensors[index];
|
|
280
|
+
for (let element = 0; element < count; element += 1) {
|
|
281
|
+
roots[parameter] = leafValue(roots[parameter], tensor.steps, element,
|
|
282
|
+
readScalar(view, offset + element * tensor.size, tensor.encoding), true);
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
return Object.fromEntries(this.schema.params.map((field, index) => [field.name, roots[index]]));
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function writeEventInput(memory, address, payloadAddress, payloadBytes, workspaceAddress, workspaceCapacityBytes) {
|
|
290
|
+
const view = new DataView(memory.buffer ?? memory);
|
|
291
|
+
for (const value of [address, payloadAddress, payloadBytes, workspaceAddress, workspaceCapacityBytes]) extent(value);
|
|
292
|
+
if (address % 4 || workspaceAddress % 8) throw new RangeError("misaligned event input storage");
|
|
293
|
+
if (address + EVENT_INPUT_SIZE_BYTES > view.byteLength
|
|
294
|
+
|| payloadAddress + payloadBytes > view.byteLength
|
|
295
|
+
|| workspaceAddress + workspaceCapacityBytes > view.byteLength) throw new RangeError("event input exceeds memory");
|
|
296
|
+
view.setUint32(address, payloadAddress, true);
|
|
297
|
+
view.setUint32(address + 4, payloadBytes, true);
|
|
298
|
+
view.setUint32(address + 8, workspaceAddress, true);
|
|
299
|
+
view.setUint32(address + 12, workspaceCapacityBytes, true);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function scalarValue(encoding, value) {
|
|
303
|
+
if (encoding === "bool") {
|
|
304
|
+
if (typeof value !== "boolean") throw new TypeError("bool payload value must be a boolean");
|
|
305
|
+
return value;
|
|
306
|
+
}
|
|
307
|
+
if (encoding === "i64") {
|
|
308
|
+
if (typeof value === "number" && !Number.isSafeInteger(value)) throw new TypeError("i64 payload value must be an exact integer");
|
|
309
|
+
let integer;
|
|
310
|
+
if (typeof value === "string") {
|
|
311
|
+
integer = parseSignedDecimalInteger(value, "invalid i64 payload value");
|
|
312
|
+
} else {
|
|
313
|
+
if (typeof value !== "bigint" && typeof value !== "number") {
|
|
314
|
+
throw new TypeError("invalid i64 payload value");
|
|
315
|
+
}
|
|
316
|
+
integer = BigInt(value);
|
|
317
|
+
}
|
|
318
|
+
if (BigInt.asIntN(64, integer) !== integer) throw new RangeError("i64 payload value is outside the signed 64-bit range");
|
|
319
|
+
return integer;
|
|
320
|
+
}
|
|
321
|
+
if (typeof value !== "number") throw new TypeError(`${encoding} payload value must be a number`);
|
|
322
|
+
if (encoding === "i32" && (!Number.isInteger(value) || value < -2147483648 || value > 2147483647)) {
|
|
323
|
+
throw new RangeError("i32 payload value is outside the signed 32-bit range");
|
|
324
|
+
}
|
|
325
|
+
return value;
|
|
326
|
+
}
|
|
327
|
+
function parseScalarDefault(encoding, value) {
|
|
328
|
+
if (typeof value !== "string") throw new TypeError("invalid scalar payload default");
|
|
329
|
+
switch (encoding) {
|
|
330
|
+
case "bool":
|
|
331
|
+
if (value !== "true" && value !== "false") throw new TypeError("invalid bool payload default");
|
|
332
|
+
return value === "true";
|
|
333
|
+
case "i32":
|
|
334
|
+
return scalarValue(encoding, Number(parseSignedDecimalInteger(value, "invalid i32 payload default")));
|
|
335
|
+
case "i64":
|
|
336
|
+
return scalarValue(encoding, parseSignedDecimalInteger(value, "invalid i64 payload default"));
|
|
337
|
+
case "f32": case "f64":
|
|
338
|
+
if (!/^[+-]?(?:(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?|inf(?:inity)?|nan)$/i.test(value)) {
|
|
339
|
+
throw new TypeError("invalid floating-point payload default");
|
|
340
|
+
}
|
|
341
|
+
return /^[+-]?inf(?:inity)?$/i.test(value)
|
|
342
|
+
? (value.startsWith("-") ? -Infinity : Infinity)
|
|
343
|
+
: Number(value);
|
|
344
|
+
default: throw new TypeError("invalid payload scalar encoding");
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
function parsePayloadDefault(ty, value) {
|
|
348
|
+
if (ty.kind === "scalar") return parseScalarDefault(ty.encoding, value);
|
|
349
|
+
if (!Array.isArray(value)) throw new TypeError("invalid aggregate payload default");
|
|
350
|
+
if (ty.kind === "struct") {
|
|
351
|
+
if (value.length !== ty.fields.length) throw new TypeError("payload default field count mismatch");
|
|
352
|
+
return Object.fromEntries(ty.fields.map((field, index) =>
|
|
353
|
+
[field.name, parsePayloadDefault(field.ty, value[index])]));
|
|
354
|
+
}
|
|
355
|
+
if (ty.kind === "tuple") {
|
|
356
|
+
if (value.length !== ty.elements.length) throw new TypeError("payload default tuple length mismatch");
|
|
357
|
+
return value.map((entry, index) => parsePayloadDefault(ty.elements[index], entry));
|
|
358
|
+
}
|
|
359
|
+
if (ty.kind === "array" && value.length === ty.len) {
|
|
360
|
+
return value.map((entry) => parsePayloadDefault(ty.element, entry));
|
|
361
|
+
}
|
|
362
|
+
throw new TypeError("invalid payload default shape");
|
|
363
|
+
}
|
|
364
|
+
function validateValue(ty, value) {
|
|
365
|
+
switch (ty.kind) {
|
|
366
|
+
case "scalar": scalarValue(ty.encoding, value); return;
|
|
367
|
+
case "struct": {
|
|
368
|
+
const keys = value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : [];
|
|
369
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || keys.length !== ty.fields.length
|
|
370
|
+
|| ty.fields.some((field) => !Object.hasOwn(value, field.name))) {
|
|
371
|
+
throw new TypeError(`payload '${ty.name}' must be an object with exactly its declared fields`);
|
|
372
|
+
}
|
|
373
|
+
for (const field of ty.fields) validateValue(field.ty, value[field.name]);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
case "tuple":
|
|
377
|
+
if (!Array.isArray(value) || value.length !== ty.elements.length) throw new TypeError("payload tuple length mismatch");
|
|
378
|
+
for (let index = 0; index < value.length; index += 1) validateValue(ty.elements[index], value[index]);
|
|
379
|
+
return;
|
|
380
|
+
case "slice": case "array":
|
|
381
|
+
if (!Array.isArray(value) && !(ArrayBuffer.isView(value) && !(value instanceof DataView))) throw new TypeError("payload array must be a sequence");
|
|
382
|
+
extent(value.length);
|
|
383
|
+
if (ty.kind === "array" && value.length !== ty.len) throw new RangeError("payload fixed array length mismatch");
|
|
384
|
+
for (let index = 0; index < value.length; index += 1) validateValue(ty.element, value[index]);
|
|
385
|
+
return;
|
|
386
|
+
default: throw new TypeError("invalid payload value type");
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
function emptyValue(ty, length = 0) {
|
|
390
|
+
switch (ty.kind) {
|
|
391
|
+
case "scalar": return null;
|
|
392
|
+
case "struct": return Object.fromEntries(ty.fields.map((field) => [field.name, emptyValue(field.ty)]));
|
|
393
|
+
case "tuple": return ty.elements.map((element) => emptyValue(element));
|
|
394
|
+
case "array": return Array.from({ length: ty.len }, () => emptyValue(ty.element));
|
|
395
|
+
case "slice": return Array.from({ length }, () => emptyValue(ty.element));
|
|
396
|
+
default: throw new TypeError("invalid payload type");
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
function leafValue(root, steps, index, replacement, write) {
|
|
400
|
+
if (steps.length === 0) return write ? replacement : root;
|
|
401
|
+
let current = root;
|
|
402
|
+
for (let part = 0; part < steps.length; part += 1) {
|
|
403
|
+
const step = steps[part];
|
|
404
|
+
const key = step.field !== undefined ? step.field : (step.axis === null ? Math.floor(index / step.stride) : Math.floor(index / step.stride) % step.axis);
|
|
405
|
+
if (write && part === steps.length - 1) current[key] = replacement;
|
|
406
|
+
else current = current[key];
|
|
407
|
+
}
|
|
408
|
+
return write ? root : current;
|
|
409
|
+
}
|
|
410
|
+
function readScalar(view, offset, encoding) {
|
|
411
|
+
switch (encoding) {
|
|
412
|
+
case "bool": return view.getUint8(offset) !== 0;
|
|
413
|
+
case "i32": return view.getInt32(offset, true);
|
|
414
|
+
case "i64": return view.getBigInt64(offset, true);
|
|
415
|
+
case "f32": return canonicalF32Number(view.getFloat32(offset, true));
|
|
416
|
+
case "f64": return view.getFloat64(offset, true);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
function writeScalar(view, offset, encoding, value) {
|
|
420
|
+
switch (encoding) {
|
|
421
|
+
case "bool": view.setUint8(offset, value ? 1 : 0); break;
|
|
422
|
+
case "i32": view.setInt32(offset, value, true); break;
|
|
423
|
+
case "i64": view.setBigInt64(offset, scalarValue(encoding, value), true); break;
|
|
424
|
+
case "f32": view.setFloat32(offset, value, true); break;
|
|
425
|
+
case "f64": view.setFloat64(offset, value, true); break;
|
|
426
|
+
}
|
|
427
|
+
}
|