@onda-lang/processor-abi 0.7.5 → 0.8.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.
package/README.md CHANGED
@@ -5,6 +5,8 @@ artifacts. It validates current-format descriptors and complete core-WebAssembly
5
5
  loads integrity-associated `.wasm`/`.onda.json` pairs, and provides the shared TypeScript surface
6
6
  used by `@onda-lang/wasm-compiler`, `@onda-lang/binaryen-web`, and `@onda-lang/webaudio`.
7
7
 
8
+ See [api.md](api.md) for the complete public Web API shared with the released package.
9
+
8
10
  ```js
9
11
  import {
10
12
  createParamControl,
@@ -25,6 +27,62 @@ validate artifacts without installing the compiler or duplicating the ABI schema
25
27
  The detailed TypeScript records mirror `onda_processor_abi::ProcessorDescriptor`; both packages
26
28
  validate the same checked-in conformance fixture.
27
29
 
30
+ ## Delegate batches
31
+
32
+ The package exports `DELEGATE_RECORD_HEADER_SIZE_BYTES`, `DELEGATE_BATCH_SIZE_BYTES`,
33
+ `writeDelegateBatch()`, `readDelegateBatch()`, and `decodeDelegateRecords()` for allocation-free
34
+ call-scoped delegate collection. Descriptor entries expose exact fixed payload sizes or dynamic
35
+ minimum sizes. A complete fixed record occupies the twelve-byte header (index, payload size, and
36
+ call-local output sequence) plus its payload; no exact
37
+ whole-call capacity exists because occurrence counts and slice lengths may be runtime-dependent.
38
+
39
+ ```js
40
+ import {
41
+ DELEGATE_RECORD_HEADER_SIZE_BYTES,
42
+ writeDelegateBatch,
43
+ writeExecutionOutput,
44
+ resetExecutionOutput,
45
+ readDelegateBatch,
46
+ decodeDelegateRecords,
47
+ } from "@onda-lang/processor-abi";
48
+
49
+ const delegates = artifact.metadata.metadata.delegates;
50
+ const fixedRecordBytes = delegates.map((delegate) =>
51
+ delegate.payload_size_bytes == null
52
+ ? null
53
+ : DELEGATE_RECORD_HEADER_SIZE_BYTES + delegate.payload_size_bytes
54
+ );
55
+
56
+ writeDelegateBatch(memory, batchAddress, storageAddress, capacityBytes);
57
+ writeExecutionOutput(memory, outputAddress, batchAddress, 0);
58
+ resetExecutionOutput(memory, outputAddress);
59
+ // Pass outputAddress as the final onda_process or onda_event_N argument.
60
+ const batch = readDelegateBatch(memory, batchAddress);
61
+ const storage = new Uint8Array(memory.buffer, storageAddress, batch.usedBytes);
62
+ const occurrences = decodeDelegateRecords(
63
+ storage,
64
+ batch.usedBytes,
65
+ delegates,
66
+ artifact.metadata.target.byte_order,
67
+ );
68
+ if (batch.overflowCount) reportOverflow(batch.overflowCount);
69
+ ```
70
+
71
+ Allocate the descriptor and storage before realtime execution and consume records before the next
72
+ call reuses them. Reset the execution output immediately before every generated entry call. See the
73
+ internal [delegate host integration](../../docs/delegates.md) reference
74
+ for the complete lifecycle, capacity guidance, and APIs for other hosts.
75
+
76
+ ## Print batches
77
+
78
+ Print delivery uses an independent caller-owned batch with the same physical descriptor shape.
79
+ `writePrintBatch()`, `readPrintBatch()`, and `decodePrintRecords()` preserve each site's concrete
80
+ scalar types; `formatPrintBatch()` and `formatPrintRecords()` produce canonical newline-terminated
81
+ text with exact `i64` and width-correct floating-point formatting. Use `writeExecutionOutput()` to
82
+ pass independently nullable delegate and print batch addresses to init, process, or event exports.
83
+ See the internal [print host integration](../../docs/printing.md) reference for the complete
84
+ lifecycle and metadata contract.
85
+
28
86
  The current descriptor represents every bindable buffer-array slot as a physical
29
87
  `metadata.buffers` entry and records logical contiguous groups in `metadata.buffer_arrays`. At
30
88
  runtime all four descriptor tables are present when any buffer exists, but an individual sample
package/api.md ADDED
@@ -0,0 +1,407 @@
1
+ <!-- Generated from docs/web-api.md; do not edit this packaged copy. -->
2
+
3
+ # Web API reference
4
+
5
+ Onda publishes four ECMAScript-module packages for browsers and Node.js:
6
+
7
+ | Package | Purpose |
8
+ | --- | --- |
9
+ | `@onda-lang/wasm-compiler` | Compile Onda source, workspaces, and project images to complete WebAssembly processor artifacts. |
10
+ | `@onda-lang/processor-abi` | Validate artifacts, inspect metadata, prepare parameter controls, and decode raw delegate and print output. |
11
+ | `@onda-lang/binaryen-web` | Lower trusted, version-matched Onda MIR directly to a processor artifact. |
12
+ | `@onda-lang/webaudio` | Host a complete processor artifact in an `AudioWorklet`. |
13
+
14
+ All packages are ESM-only. `@onda-lang/wasm-compiler` and `@onda-lang/binaryen-web` support modern
15
+ browsers and Node.js 20 or newer. Web Audio construction requires a browser environment with
16
+ `AudioWorklet`; the metadata and parameter helpers re-exported by `@onda-lang/webaudio` are ordinary
17
+ synchronous JavaScript.
18
+
19
+ Each published package contains this reference as `api.md`. TypeScript declarations are included
20
+ at every exported module path.
21
+
22
+ ## Compile source and start audio
23
+
24
+ ```js
25
+ import { createCompiler } from "@onda-lang/wasm-compiler";
26
+ import {
27
+ createOndaAudioProcessorInitialized,
28
+ } from "@onda-lang/webaudio";
29
+
30
+ const compiler = await createCompiler();
31
+ const { artifact } = await compiler.compileSource(source, {
32
+ sampleRate: audioContext.sampleRate,
33
+ blockSize: 128,
34
+ });
35
+
36
+ const print = ({ text }) => console.debug(text);
37
+ const processor = await createOndaAudioProcessorInitialized(
38
+ audioContext,
39
+ artifact,
40
+ {
41
+ params: { gain: 0.5 },
42
+ // A construction-time listener also receives prints emitted by init.
43
+ onPrint: print,
44
+ },
45
+ );
46
+ processor.node.connect(audioContext.destination);
47
+
48
+ const stopDelegates = processor.onDelegates(({ occurrences }) => {
49
+ for (const occurrence of occurrences) {
50
+ console.log(occurrence.name, occurrence.values);
51
+ }
52
+ });
53
+ ```
54
+
55
+ Compilation is an offline operation and may allocate. Constructing the adapter compiles or accepts
56
+ a reusable `WebAssembly.Module` before the audio node starts. Normal rendering uses preallocated
57
+ storage. Delegate and print callbacks run on the main side after bounded worklet transport; they do
58
+ not call JavaScript from generated DSP execution.
59
+
60
+ ## `@onda-lang/wasm-compiler`
61
+
62
+ ### `createCompiler(options?)`
63
+
64
+ Creates an `OndaCompilerInstance`. With no options, compilation runs directly on the calling
65
+ JavaScript thread. Pass `{ worker: true }` to run the frontend and backend in a module worker;
66
+ `workerUrl`, `frontendWasm`, and a custom `Worker` constructor are optional integration hooks.
67
+
68
+ The returned instance provides:
69
+
70
+ - `compileSource(source, options?)` and `inspectSourceConstants(source, options?)`.
71
+ - `compileWorkspace(workspace, options?)` and `inspectWorkspaceConstants(workspace, options?)`.
72
+ - `compileProjectImage(bytes, options?)` and `inspectProjectImageConstants(bytes, options?)`.
73
+ - `createProjectImage(sourceGraph, buffers?)`, `inspectProjectImage(bytes)`,
74
+ `loadProjectFiles(files, projectFilePath?)`, and `materializeProjectImage(bytes, names?)`.
75
+ - `encodeBufferAsset(binding)`, `decodeBufferAsset(bytes)`, and `decodeBufferFile(bytes, path?)`.
76
+ - `projectCapabilities()` for supported image, buffer, and standard-library versions.
77
+ - `sendLspMessage(message)` and `setLspAnalysisOptions(options?)` for the embedded language server.
78
+ - `dispose()`, an idempotent terminal release of compiler and worker resources.
79
+
80
+ Compile options accept `sampleRate`, `blockSize`, typed compile-constant overrides, and `codegen`.
81
+ Code generation can select optimization level `0..4`, shrink level `0..2`, strict or fast math,
82
+ SIMD, loop-containing inlining, and optional WAT emission. A successful compilation returns an
83
+ `OndaCompilationResult` containing the artifact, resolved source paths, and the exact source graph
84
+ when one is available.
85
+
86
+ Configuration and lifecycle failures throw `OndaCompilerError`. Authored-source, project, MIR, and
87
+ code-generation failures throw `OndaCompileError`, whose `diagnostics`, `sourceFiles`, and
88
+ `unresolvedSourceFiles` fields support editors and file watchers. `OndaBinaryenError` identifies a
89
+ failure in the MIR-to-Wasm backend.
90
+
91
+ `MIR_SCHEMA_VERSION` is the schema accepted by the bundled backend. `ONDA_VERSION` is the compiler
92
+ version. `createDefaultImports()` returns the imports required by current generated modules; it is
93
+ currently an empty object because artifacts are self-contained.
94
+
95
+ The `@onda-lang/wasm-compiler/artifact` subpath re-exports the complete
96
+ `@onda-lang/processor-abi` surface without loading the compiler. The
97
+ `@onda-lang/wasm-compiler/worker` subpath is a side-effect-only module-worker entry and has no
98
+ named exports.
99
+
100
+ ## `@onda-lang/processor-abi`
101
+
102
+ An `OndaProcessorArtifact` contains WebAssembly bytes, an `OndaProcessorMetadata` descriptor, and
103
+ optional WAT. Treat the bytes and descriptor as one integrity-associated pair.
104
+
105
+ ### Validation and files
106
+
107
+ - `validateProcessorMetadata(metadata, expectedKind?)` validates and returns the current descriptor.
108
+ - `validateProcessorArtifact(artifact, options?)` normalizes bytes and optionally inspects the module.
109
+ - `validateProcessorModule(module, metadata)` verifies a precompiled module against its descriptor.
110
+ - `parseProcessorMetadata(input, expectedKind?)` parses JSON or validates an object.
111
+ - `serializeProcessorMetadata(metadata, space?)` validates before producing newline-terminated JSON.
112
+ - `createProcessorArtifactFiles(artifact, options?)` creates associated `.wasm` and `.onda.json`
113
+ records, including integrity metadata.
114
+ - `loadProcessorArtifactFiles(wasm, metadata)` validates a loaded pair and its integrity association.
115
+
116
+ Failures throw `OndaArtifactError`. Hosts must reject unsupported artifact-format, ABI, and snapshot
117
+ versions rather than guessing layout compatibility.
118
+
119
+ ### Parameter controls
120
+
121
+ `createParamControl(metadata)` validates one scalar parameter descriptor and returns a reusable
122
+ `OndaPreparedParamControl`. `createParamDomain(domain)` does the same from already-decoded values.
123
+ Prepared controls expose `constrainPlain`, `normalizedToPlain`, and `plainToNormalized` methods.
124
+
125
+ The one-shot `constrainParamPlain`, `paramNormalizedToPlain`, and `paramPlainToNormalized`
126
+ functions provide the same behavior. Preparing once is preferable for frequently updated UI:
127
+ validation and decimal descriptor decoding stay off the interaction path. Mappings preserve exact
128
+ endpoints, apply linear, logarithmic, or curved scale, and clamp and snap to the declared grid.
129
+
130
+ ### Delegates and print output
131
+
132
+ Complete wasm32 processor exports receive an optional execution-output descriptor containing
133
+ independently nullable delegate and print batches. Allocate all descriptors and storage before
134
+ real-time execution.
135
+
136
+ `writeDelegateBatch` and `writePrintBatch` initialize reusable batch descriptors.
137
+ `writeExecutionOutput` connects their addresses. Call `resetExecutionOutput` immediately before
138
+ every generated init, process, or event entry. After a successful generated call,
139
+ `readDelegateBatch` or `readPrintBatch` validates the result counters.
140
+ `decodeDelegateRecords` converts delegate payloads using `metadata.delegates`.
141
+ `decodePrintRecords` preserves primitive types and source sites; `formatPrintRecords` and
142
+ `formatPrintBatch` add canonical text formatting. Both decoded record types expose a `sequence` from
143
+ the host-reset call-local counter; merge that call's two arrays by this field when presenting one
144
+ chronological output stream.
145
+
146
+ Batch capacity is host policy. `overflowCount` reports whole records that did not fit; it is not a
147
+ byte count. Consume the returned storage before reusing it for another init, process, or event call.
148
+ See the [language guide](https://onda-lang.org/docs/language/#delegates) for authored semantics and
149
+ the [processor API](https://onda-lang.org/docs/processor-api/#call-scoped-execution-output) for
150
+ physical record layout.
151
+
152
+ The metadata interfaces expose target facts, storage sizes, ports, parameters, states, events,
153
+ delegates, print sites, buffers, and integration profiles. Scalar `i64` values decoded from records
154
+ use `bigint`; booleans use `boolean`; fixed arrays and slices become JavaScript arrays.
155
+
156
+ ## `@onda-lang/binaryen-web`
157
+
158
+ ### `compileTrustedMir(mir, options?)`
159
+
160
+ Lowers MIR emitted by the matching Onda semantic frontend. Input may be compact MessagePack, JSON,
161
+ or an already-decoded object. The function is synchronous and returns an
162
+ `OndaProcessorArtifact`. It is intentionally not a validator for untrusted or hand-authored MIR;
163
+ the producer owns semantic, type, bounds, and resource proofs.
164
+
165
+ `OndaBinaryenOptions` controls the same backend policies exposed through compiler `codegen`.
166
+ `SUPPORTED_MIR_SCHEMA_VERSION` identifies the required producer schema. `createDefaultImports()`
167
+ returns an empty object for current self-contained artifacts. Backend failures throw
168
+ `OndaBinaryenError`.
169
+
170
+ The package root re-exports the common artifact validation and file helpers. The
171
+ `@onda-lang/binaryen-web/artifact` subpath re-exports the complete
172
+ `@onda-lang/processor-abi` module without loading Binaryen.
173
+
174
+ ## `@onda-lang/webaudio`
175
+
176
+ ### Construction
177
+
178
+ - `registerOndaAudioWorklet(context, workletUrl?)` registers the processor once per context.
179
+ - `compileOndaProcessorModule(artifact)` validates and compiles a reusable module off the render thread.
180
+ - `ondaAudioWorkletNodeOptions(artifact, options?)` builds low-level node options.
181
+ - `createOndaAudioProcessor(context, artifact, options?)` allocates an uninitialized adapter.
182
+ - `createOndaAudioProcessorInitialized(context, artifact, options?)` allocates and fully initializes it.
183
+ - `flattenedAudioChannelCount(ports?)` totals declared physical channels with validation.
184
+
185
+ `OndaAudioProcessorOptions` accepts initial plain parameter values, external buffers, event,
186
+ delegate, and print capacities, an optional construction-time `onPrint` listener, a precompiled
187
+ module, custom node options, and an `AudioWorkletNode` constructor. Pass `onPrint` when using the
188
+ initialized constructor if initialization output must be observed; registering a listener after
189
+ construction cannot replay output from an execution that has already completed. The artifact sample
190
+ rate must equal the context sample rate and it must expose at least one audio input or output.
191
+ Print and delegate delivery uses a bounded `SharedArrayBuffer` ring and requires cross-origin
192
+ isolation in browsers; ordinary audio processing remains available when shared memory is absent.
193
+ Low-level callers that manually pair the returned node options with `OndaAudioProcessor` must pass
194
+ `processorOptions.executionOutputRing` as the adapter constructor's fourth argument.
195
+
196
+ ### `OndaAudioProcessor`
197
+
198
+ The adapter exposes its `node` and validated `metadata`, plus these operations:
199
+
200
+ - `setParam(nameOrIndex, plain)` and `setParamNormalized(nameOrIndex, normalized)`.
201
+ - `trigger(nameOrIndex, values?)` for input events.
202
+ - `onDelegates(listener)` and `onPrint(listener)`, each returning an unsubscribe function.
203
+ - `init(mode)`, `snapshot()`, and `restoreSnapshot(bytes)`.
204
+ - `readControlOutputs()` and `readBuffer(nameOrIndex)`.
205
+ - `request(type, fields?, transfer?)` for adapter protocol extensions.
206
+ - `close(reason?)`, an idempotent terminal release of adapter-side resources.
207
+
208
+ Delegate and print batches report `overflowCount` for generated-storage loss and
209
+ `transportDropCount` for bounded worklet-to-main queue loss. Loss-only notifications can arrive
210
+ without occurrences. Collection is enabled only while the corresponding listener set is nonempty;
211
+ setting the capacity to zero disables host delivery even with listeners while preserving language
212
+ evaluation semantics.
213
+
214
+ With both listener types active, the adapter invokes them in call-local sequence order and may split
215
+ a same-stream batch around an intervening occurrence from the other stream. Ordering resets for
216
+ each init, event, or process segment.
217
+
218
+ `ONDA_INIT_FULL` clears and initializes all physical state. `ONDA_INIT_PRESERVE_PINNED` retains
219
+ pinned state according to the processor ABI. The package also re-exports the prepared and one-shot
220
+ parameter conversion helpers.
221
+
222
+ `@onda-lang/webaudio/worklet` is the side-effect-only AudioWorklet registration module and has no
223
+ named exports.
224
+
225
+ ## Complete exported surface
226
+
227
+ The following indexes include runtime values and TypeScript-only types from each package root.
228
+ They are checked against the shipped declarations so additions cannot silently escape this
229
+ reference. Artifact subpaths are complete processor-ABI re-exports; worker and worklet subpaths are
230
+ side-effect-only as described above.
231
+
232
+ ### `@onda-lang/processor-abi`
233
+
234
+ <!-- BEGIN WEB API onda_processor_abi -->
235
+ DELEGATE_BATCH_SIZE_BYTES
236
+ DELEGATE_RECORD_HEADER_SIZE_BYTES
237
+ EXECUTION_OUTPUT_SIZE_BYTES
238
+ OndaArtifactError
239
+ OndaArtifactKind
240
+ OndaBufferArrayMetadata
241
+ OndaBufferMetadata
242
+ OndaDelegateBatch
243
+ OndaDelegateMetadata
244
+ OndaDelegateOccurrence
245
+ OndaDelegateParamMetadata
246
+ OndaEventMetadata
247
+ OndaEventParamMetadata
248
+ OndaIntegrationProfile
249
+ OndaIoMetadata
250
+ OndaLogSiteMetadata
251
+ OndaParamControlMetadata
252
+ OndaParamDomain
253
+ OndaPreparedParamControl
254
+ OndaPrintBatch
255
+ OndaPrintEntry
256
+ OndaProcessorArtifact
257
+ OndaProcessorInitMode
258
+ OndaProcessorMetadata
259
+ OndaScalarType
260
+ OndaStateMetadata
261
+ OndaTargetInfo
262
+ PRINT_BATCH_SIZE_BYTES
263
+ PRINT_RECORD_HEADER_SIZE_BYTES
264
+ PROCESSOR_ABI_VERSION
265
+ PROCESSOR_ARTIFACT_FORMAT
266
+ PROCESSOR_ARTIFACT_FORMAT_VERSION
267
+ PROCESSOR_EXECUTION_OK
268
+ PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE
269
+ PROCESSOR_INIT_FULL
270
+ PROCESSOR_INIT_PRESERVE_PINNED
271
+ PROCESSOR_SNAPSHOT_FORMAT_VERSION
272
+ constrainParamPlain
273
+ createParamControl
274
+ createParamDomain
275
+ createProcessorArtifactFiles
276
+ decodeDelegateRecords
277
+ decodePrintRecords
278
+ formatPrintBatch
279
+ formatPrintRecords
280
+ loadProcessorArtifactFiles
281
+ paramNormalizedToPlain
282
+ paramPlainToNormalized
283
+ parseProcessorMetadata
284
+ readDelegateBatch
285
+ readPrintBatch
286
+ resetExecutionOutput
287
+ serializeProcessorMetadata
288
+ validateProcessorArtifact
289
+ validateProcessorMetadata
290
+ validateProcessorModule
291
+ writeDelegateBatch
292
+ writeExecutionOutput
293
+ writePrintBatch
294
+ <!-- END WEB API onda_processor_abi -->
295
+
296
+ ### `@onda-lang/binaryen-web`
297
+
298
+ <!-- BEGIN WEB API onda_binaryen_web -->
299
+ OndaArtifactError
300
+ OndaBinaryenError
301
+ OndaBinaryenOptions
302
+ OndaProcessorArtifact
303
+ OndaProcessorMetadata
304
+ PROCESSOR_ABI_VERSION
305
+ PROCESSOR_ARTIFACT_FORMAT
306
+ PROCESSOR_ARTIFACT_FORMAT_VERSION
307
+ PROCESSOR_EXECUTION_OK
308
+ PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE
309
+ PROCESSOR_SNAPSHOT_FORMAT_VERSION
310
+ SUPPORTED_MIR_SCHEMA_VERSION
311
+ compileTrustedMir
312
+ createDefaultImports
313
+ createProcessorArtifactFiles
314
+ loadProcessorArtifactFiles
315
+ parseProcessorMetadata
316
+ serializeProcessorMetadata
317
+ validateProcessorArtifact
318
+ validateProcessorMetadata
319
+ validateProcessorModule
320
+ <!-- END WEB API onda_binaryen_web -->
321
+
322
+ ### `@onda-lang/wasm-compiler`
323
+
324
+ <!-- BEGIN WEB API onda_wasm_compiler -->
325
+ DirectCompilerOptions
326
+ MIR_SCHEMA_VERSION
327
+ ONDA_VERSION
328
+ OndaArtifactError
329
+ OndaBinaryenError
330
+ OndaBufferAssetBinding
331
+ OndaBufferData
332
+ OndaBufferElement
333
+ OndaCodegenOptions
334
+ OndaCompilationResult
335
+ OndaCompileConstDescriptor
336
+ OndaCompileConstElement
337
+ OndaCompileConstInspectionOptions
338
+ OndaCompileConstKind
339
+ OndaCompileConstValue
340
+ OndaCompileError
341
+ OndaCompileOptions
342
+ OndaCompilerDiagnostic
343
+ OndaCompilerError
344
+ OndaCompilerInstance
345
+ OndaLspAnalysisOptions
346
+ OndaLspMessage
347
+ OndaMaterializedProjectFile
348
+ OndaProcessorArtifact
349
+ OndaProcessorMetadata
350
+ OndaProjectBufferInfo
351
+ OndaProjectCapabilities
352
+ OndaProjectImageInfo
353
+ OndaProjectMaterialization
354
+ OndaResolvedCompileConstValue
355
+ OndaSerializedProjectImage
356
+ OndaSourceDocument
357
+ OndaSourceGraph
358
+ OndaSourceReferenceKind
359
+ OndaSourceResolution
360
+ OndaSourceWorkspace
361
+ OndaWorkerConstructor
362
+ OndaWorkerLike
363
+ PROCESSOR_ABI_VERSION
364
+ PROCESSOR_ARTIFACT_FORMAT
365
+ PROCESSOR_ARTIFACT_FORMAT_VERSION
366
+ PROCESSOR_EXECUTION_OK
367
+ PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE
368
+ PROCESSOR_SNAPSHOT_FORMAT_VERSION
369
+ WorkerCompilerOptions
370
+ createCompiler
371
+ createDefaultImports
372
+ createProcessorArtifactFiles
373
+ loadProcessorArtifactFiles
374
+ parseProcessorMetadata
375
+ serializeProcessorMetadata
376
+ validateProcessorArtifact
377
+ validateProcessorMetadata
378
+ validateProcessorModule
379
+ <!-- END WEB API onda_wasm_compiler -->
380
+
381
+ ### `@onda-lang/webaudio`
382
+
383
+ <!-- BEGIN WEB API onda_webaudio -->
384
+ ONDA_AUDIO_WORKLET_PROCESSOR_NAME
385
+ ONDA_INIT_FULL
386
+ ONDA_INIT_PRESERVE_PINNED
387
+ OndaAudioProcessor
388
+ OndaAudioProcessorOptions
389
+ OndaAudioPrintBatch
390
+ OndaAudioPrintListener
391
+ OndaInitMode
392
+ OndaParamDomain
393
+ OndaPreparedParamControl
394
+ OndaProcessorArtifact
395
+ OndaProcessorMetadata
396
+ compileOndaProcessorModule
397
+ constrainParamPlain
398
+ createOndaAudioProcessor
399
+ createOndaAudioProcessorInitialized
400
+ createParamControl
401
+ createParamDomain
402
+ flattenedAudioChannelCount
403
+ ondaAudioWorkletNodeOptions
404
+ paramNormalizedToPlain
405
+ paramPlainToNormalized
406
+ registerOndaAudioWorklet
407
+ <!-- END WEB API onda_webaudio -->
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onda-lang/processor-abi",
3
- "version": "0.7.5",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "Shared Onda processor artifact schema, validation, and integrity helpers",
6
6
  "license": "MIT",
@@ -22,11 +22,13 @@
22
22
  },
23
23
  "files": [
24
24
  "src",
25
+ "api.md",
25
26
  "LICENSE",
26
27
  "README.md"
27
28
  ],
28
29
  "scripts": {
29
- "test": "node --test"
30
+ "test": "node --test",
31
+ "prepack": "node ../../scripts/stage-web-api-docs.mjs"
30
32
  },
31
33
  "publishConfig": {
32
34
  "access": "public"
package/src/index.d.ts CHANGED
@@ -1,10 +1,23 @@
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;
4
- export const PROCESSOR_ABI_VERSION: 4;
3
+ export const PROCESSOR_ARTIFACT_FORMAT_VERSION: 5;
4
+ export const PROCESSOR_ABI_VERSION: 5;
5
5
  export const PROCESSOR_EXECUTION_OK: 0;
6
6
  export const PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE: 1;
7
+ export const PROCESSOR_INIT_PRESERVE_PINNED: 0;
8
+ export const PROCESSOR_INIT_FULL: 1;
9
+ export type OndaProcessorInitMode = 0 | 1;
7
10
  export const PROCESSOR_SNAPSHOT_FORMAT_VERSION: 1;
11
+ /** Bytes preceding the payload of every packed delegate occurrence. */
12
+ export const DELEGATE_RECORD_HEADER_SIZE_BYTES: 12;
13
+ /** wasm32 byte size of the call-scoped delegate batch descriptor. */
14
+ export const DELEGATE_BATCH_SIZE_BYTES: 20;
15
+ /** Bytes preceding the payload of every packed print occurrence. */
16
+ export const PRINT_RECORD_HEADER_SIZE_BYTES: 12;
17
+ /** wasm32 byte size of the call-scoped print batch descriptor. */
18
+ export const PRINT_BATCH_SIZE_BYTES: 20;
19
+ /** wasm32 byte size of the call-scoped execution-output descriptor. */
20
+ export const EXECUTION_OUTPUT_SIZE_BYTES: 12;
8
21
 
9
22
  export type OndaScalarType = "f32" | "f64" | "i32" | "i64" | "bool";
10
23
  export type OndaArtifactKind = "webassembly_module" | "relocatable_object";
@@ -139,6 +152,7 @@ export interface OndaEventParamMetadata {
139
152
  type_repr: string;
140
153
  scalar: OndaScalarType;
141
154
  array_len: number;
155
+ is_array: boolean;
142
156
  is_slice: boolean;
143
157
  byte_offset: number | null;
144
158
  byte_size: number | null;
@@ -156,8 +170,31 @@ export interface OndaEventMetadata {
156
170
  params: OndaEventParamMetadata[];
157
171
  }
158
172
 
173
+ export interface OndaDelegateParamMetadata {
174
+ name: string;
175
+ type_repr: string;
176
+ scalar: OndaScalarType;
177
+ array_len: number;
178
+ is_array: boolean;
179
+ is_slice: boolean;
180
+ byte_offset: number | null;
181
+ byte_size: number | null;
182
+ element_size_bytes: number;
183
+ }
184
+
185
+ export interface OndaDelegateMetadata {
186
+ index: number;
187
+ name: string;
188
+ payload_size_bytes: number | null;
189
+ payload_min_size_bytes: number;
190
+ has_dynamic_payload: boolean;
191
+ params: OndaDelegateParamMetadata[];
192
+ }
193
+
159
194
  export interface OndaStateMetadata {
160
195
  name: string;
196
+ /** False for compiler-owned snapshot storage omitted from authored-state reflection. */
197
+ authored?: boolean;
161
198
  type_repr: string;
162
199
  scalar: OndaScalarType;
163
200
  array_len: number;
@@ -174,9 +211,9 @@ export interface OndaStateMetadata {
174
211
 
175
212
  export interface OndaProcessorMetadata {
176
213
  format: "onda-processor";
177
- format_version: 4;
214
+ format_version: 5;
178
215
  artifact_kind: OndaArtifactKind;
179
- abi_version: 4;
216
+ abi_version: 5;
180
217
  backend: string;
181
218
  mir_schema_version: number;
182
219
  target: OndaTargetInfo;
@@ -204,8 +241,12 @@ export interface OndaProcessorMetadata {
204
241
  snapshot_byte_order: "little_endian";
205
242
  snapshot_restore_base: "post_init_physical_state_image";
206
243
  requires_full_blocks: boolean;
244
+ delegate_record_header_size_bytes: 12;
245
+ print_record_header_size_bytes: 12;
207
246
  };
208
247
  metadata: {
248
+ source_files: Array<{ path: string }>;
249
+ log_sites: OndaLogSiteMetadata[];
209
250
  inputs: OndaIoMetadata[];
210
251
  outputs: OndaIoMetadata[];
211
252
  control_outputs: OndaIoMetadata[];
@@ -213,6 +254,7 @@ export interface OndaProcessorMetadata {
213
254
  buffers: OndaBufferMetadata[];
214
255
  buffer_arrays: OndaBufferArrayMetadata[];
215
256
  events: OndaEventMetadata[];
257
+ delegates: OndaDelegateMetadata[];
216
258
  states: OndaStateMetadata[];
217
259
  };
218
260
  required_features?: string[];
@@ -227,6 +269,16 @@ export interface OndaProcessorMetadata {
227
269
  integrity?: { algorithm: string; wasm: string };
228
270
  }
229
271
 
272
+ export interface OndaLogSiteMetadata {
273
+ index: number;
274
+ label: string | null;
275
+ source: { file: number | null; line: number; column: number; end_line: number; end_column: number };
276
+ lexical_owner: string;
277
+ declaration: string | null;
278
+ argument_types: Array<"f32" | "f64" | "i32" | "i64" | "bool">;
279
+ payload_size_bytes: number;
280
+ }
281
+
230
282
  export interface OndaProcessorArtifact {
231
283
  wasm: Uint8Array | ArrayBuffer | ArrayBufferView;
232
284
  metadata: OndaProcessorMetadata;
@@ -267,3 +319,89 @@ export function loadProcessorArtifactFiles(
267
319
  wasm: Uint8Array | ArrayBuffer | ArrayBufferView,
268
320
  metadata: string | object,
269
321
  ): Promise<{ wasm: Uint8Array; metadata: OndaProcessorMetadata }>;
322
+
323
+ export interface OndaDelegateBatch {
324
+ storageAddress: number;
325
+ capacityBytes: number;
326
+ usedBytes: number;
327
+ recordCount: number;
328
+ overflowCount: number;
329
+ }
330
+
331
+ export type OndaPrintBatch = OndaDelegateBatch;
332
+ export interface OndaPrintEntry {
333
+ siteIndex: number;
334
+ sequence: number;
335
+ label: string | null;
336
+ source: OndaLogSiteMetadata["source"];
337
+ lexicalOwner: string;
338
+ declaration: string | null;
339
+ values: Array<{ type: "f32" | "f64" | "i32" | "i64" | "bool"; value: number | bigint | boolean }>;
340
+ }
341
+
342
+ export interface OndaDelegateOccurrence {
343
+ delegateIndex: number;
344
+ sequence: number;
345
+ name: string;
346
+ payloadByteLength: number;
347
+ payload: Uint8Array;
348
+ values: Record<string, number | bigint | boolean | Array<number | bigint | boolean>>;
349
+ }
350
+
351
+ /** Initialize one reusable wasm32 batch descriptor and clear its result counters. */
352
+ export function writeDelegateBatch(
353
+ memory: WebAssembly.Memory | ArrayBuffer | ArrayBufferView | DataView,
354
+ batchAddress: number,
355
+ storageAddress: number,
356
+ capacityBytes: number,
357
+ ): void;
358
+ /** Read and validate the result descriptor after successful generated execution. */
359
+ export function readDelegateBatch(
360
+ memory: WebAssembly.Memory | ArrayBuffer | ArrayBufferView | DataView,
361
+ batchAddress: number,
362
+ ): OndaDelegateBatch;
363
+ export function writePrintBatch(
364
+ memory: WebAssembly.Memory | ArrayBuffer | ArrayBufferView | DataView,
365
+ batchAddress: number,
366
+ storageAddress: number,
367
+ capacityBytes: number,
368
+ ): void;
369
+ export function readPrintBatch(
370
+ memory: WebAssembly.Memory | ArrayBuffer | ArrayBufferView | DataView,
371
+ batchAddress: number,
372
+ ): OndaPrintBatch;
373
+ export function writeExecutionOutput(
374
+ memory: WebAssembly.Memory | ArrayBuffer | ArrayBufferView | DataView,
375
+ outputAddress: number,
376
+ delegateBatchAddress?: number,
377
+ printBatchAddress?: number,
378
+ ): void;
379
+ /** Prepare every present batch and the shared sequence for one processor entry call. */
380
+ export function resetExecutionOutput(
381
+ memory: WebAssembly.Memory | ArrayBuffer | ArrayBufferView | DataView,
382
+ outputAddress: number,
383
+ ): void;
384
+ export function decodePrintRecords(
385
+ storage: Uint8Array | ArrayBuffer | ArrayBufferView,
386
+ usedBytes: number,
387
+ logSites: OndaLogSiteMetadata[],
388
+ byteOrder?: "little_endian" | "big_endian",
389
+ ): OndaPrintEntry[];
390
+ export function formatPrintBatch(
391
+ memory: WebAssembly.Memory,
392
+ printBatchAddress: number,
393
+ metadata: OndaProcessorMetadata | { log_sites: OndaLogSiteMetadata[]; target?: OndaTargetInfo },
394
+ ): { text: string; entries: OndaPrintEntry[]; overflowCount: number };
395
+ export function formatPrintRecords(
396
+ storage: Uint8Array | ArrayBuffer | ArrayBufferView,
397
+ usedBytes: number,
398
+ metadata: OndaProcessorMetadata | { log_sites: OndaLogSiteMetadata[]; target?: OndaTargetInfo },
399
+ overflowCount?: number,
400
+ ): { text: string; entries: OndaPrintEntry[]; overflowCount: number };
401
+ /** Decode every complete record in used storage according to delegate metadata. */
402
+ export function decodeDelegateRecords(
403
+ storage: Uint8Array | ArrayBuffer | ArrayBufferView,
404
+ usedBytes: number,
405
+ delegates: OndaDelegateMetadata[],
406
+ byteOrder?: "little_endian" | "big_endian",
407
+ ): OndaDelegateOccurrence[];
package/src/index.js CHANGED
@@ -4,11 +4,18 @@ const PARAM_CONTROL = globalThis.__ONDA_PARAM_CONTROL_V2__;
4
4
 
5
5
  export const PROCESSOR_ARTIFACT_FORMAT = "onda-processor";
6
6
  // Synchronized from format-versions.json; do not edit these copies directly.
7
- export const PROCESSOR_ARTIFACT_FORMAT_VERSION = 4;
8
- export const PROCESSOR_ABI_VERSION = 4;
7
+ export const PROCESSOR_ARTIFACT_FORMAT_VERSION = 5;
8
+ export const PROCESSOR_ABI_VERSION = 5;
9
9
  export const PROCESSOR_EXECUTION_OK = 0;
10
10
  export const PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE = 1;
11
+ export const PROCESSOR_INIT_PRESERVE_PINNED = 0;
12
+ export const PROCESSOR_INIT_FULL = 1;
11
13
  export const PROCESSOR_SNAPSHOT_FORMAT_VERSION = 1;
14
+ export const DELEGATE_RECORD_HEADER_SIZE_BYTES = 12;
15
+ export const DELEGATE_BATCH_SIZE_BYTES = 20;
16
+ export const PRINT_RECORD_HEADER_SIZE_BYTES = 12;
17
+ export const PRINT_BATCH_SIZE_BYTES = 20;
18
+ export const EXECUTION_OUTPUT_SIZE_BYTES = 12;
12
19
 
13
20
  export const {
14
21
  createParamDomain,
@@ -114,7 +121,17 @@ export function validateProcessorMetadata(metadata, expectedKind = null) {
114
121
  "runtime.snapshot_restore_base",
115
122
  "post_init_physical_state_image",
116
123
  );
124
+ requireLiteral(
125
+ metadata.runtime?.print_record_header_size_bytes,
126
+ "runtime.print_record_header_size_bytes",
127
+ PRINT_RECORD_HEADER_SIZE_BYTES,
128
+ );
117
129
  requireBoolean(metadata.runtime?.requires_full_blocks, "runtime.requires_full_blocks");
130
+ requireLiteral(
131
+ metadata.runtime?.delegate_record_header_size_bytes,
132
+ "runtime.delegate_record_header_size_bytes",
133
+ DELEGATE_RECORD_HEADER_SIZE_BYTES,
134
+ );
118
135
  requireString(metadata.exports?.init, "exports.init");
119
136
  requireString(metadata.exports?.process, "exports.process");
120
137
  if (!Array.isArray(metadata.exports?.events)) {
@@ -206,6 +223,9 @@ export function validateProcessorMetadata(metadata, expectedKind = null) {
206
223
  "params",
207
224
  "buffers",
208
225
  "events",
226
+ "delegates",
227
+ "source_files",
228
+ "log_sites",
209
229
  ]) {
210
230
  if (!Array.isArray(metadata.metadata[field])) {
211
231
  throw new OndaArtifactError(`metadata.${field} must be an array`);
@@ -261,6 +281,50 @@ export function validateProcessorMetadata(metadata, expectedKind = null) {
261
281
  metadata.metadata.events.forEach((entry, index) =>
262
282
  validateEventMetadata(entry, `metadata.events[${index}]`)
263
283
  );
284
+ metadata.metadata.delegates.forEach((entry, index) =>
285
+ validateDelegateMetadata(entry, index, `metadata.delegates[${index}]`)
286
+ );
287
+ metadata.metadata.source_files.forEach((entry, index) =>
288
+ requireString(entry?.path, `metadata.source_files[${index}].path`, true)
289
+ );
290
+ metadata.metadata.log_sites.forEach((entry, index) => {
291
+ const path = `metadata.log_sites[${index}]`;
292
+ requireInteger(entry?.index, `${path}.index`, 0);
293
+ if (entry.index !== index) {
294
+ throw new OndaArtifactError(`${path}.index must equal its descriptor index`);
295
+ }
296
+ if (entry.label !== null) requireString(entry.label, `${path}.label`, true);
297
+ if (entry.declaration !== null) requireString(entry.declaration, `${path}.declaration`, true);
298
+ requireString(entry?.lexical_owner, `${path}.lexical_owner`);
299
+ requireInteger(entry?.payload_size_bytes, `${path}.payload_size_bytes`, 0);
300
+ if (!Array.isArray(entry?.argument_types)) {
301
+ throw new OndaArtifactError(`${path}.argument_types must be an array`);
302
+ }
303
+ entry.argument_types.forEach((scalar, scalarIndex) => {
304
+ if (!["f32", "f64", "i32", "i64", "bool"].includes(scalar)) {
305
+ throw new OndaArtifactError(`${path}.argument_types[${scalarIndex}] is not printable`);
306
+ }
307
+ });
308
+ const expectedPayloadSize = entry.argument_types.reduce(
309
+ (size, scalar) => size + (scalar === "f64" || scalar === "i64" ? 8 : scalar === "bool" ? 1 : 4),
310
+ 0,
311
+ );
312
+ if (entry.payload_size_bytes !== expectedPayloadSize) {
313
+ throw new OndaArtifactError(
314
+ `${path}.payload_size_bytes must be ${expectedPayloadSize} for its argument_types`,
315
+ );
316
+ }
317
+ const source = entry?.source;
318
+ if (source?.file !== null) {
319
+ requireInteger(source?.file, `${path}.source.file`, 0);
320
+ if (source.file >= metadata.metadata.source_files.length) {
321
+ throw new OndaArtifactError(`${path}.source.file references a missing source file`);
322
+ }
323
+ }
324
+ for (const field of ["line", "column", "end_line", "end_column"]) {
325
+ requireInteger(source?.[field], `${path}.source.${field}`, 0);
326
+ }
327
+ });
264
328
  const describedEventExports = metadata.metadata.events.map((event) => event.export);
265
329
  if (
266
330
  describedEventExports.length !== metadata.exports.events.length
@@ -295,6 +359,15 @@ export function validateProcessorMetadata(metadata, expectedKind = null) {
295
359
  return metadata;
296
360
  }
297
361
 
362
+ function validateDelegateMetadata(value, index, path) {
363
+ requireInteger(value?.index, `${path}.index`, 0);
364
+ if (value.index !== index) {
365
+ throw new OndaArtifactError(`${path}.index must match declaration order`);
366
+ }
367
+ requireString(value?.name, `${path}.name`);
368
+ validatePayloadMetadata(value, path, false);
369
+ }
370
+
298
371
  function validateIoMetadata(value, path, isParameter) {
299
372
  requireString(value?.name, `${path}.name`);
300
373
  requireString(value?.type_repr, `${path}.type_repr`);
@@ -406,6 +479,10 @@ function validateBufferMetadata(value, path) {
406
479
  function validateEventMetadata(value, path) {
407
480
  requireString(value?.name, `${path}.name`);
408
481
  requireString(value?.export, `${path}.export`);
482
+ validatePayloadMetadata(value, path, true);
483
+ }
484
+
485
+ function validatePayloadMetadata(value, path, supportsDefaults) {
409
486
  requireNullableInteger(value?.payload_size_bytes, `${path}.payload_size_bytes`, 0);
410
487
  requireInteger(value?.payload_min_size_bytes, `${path}.payload_min_size_bytes`, 0);
411
488
  requireBoolean(value?.has_dynamic_payload, `${path}.has_dynamic_payload`);
@@ -420,33 +497,52 @@ function validateEventMetadata(value, path) {
420
497
  requireString(param?.type_repr, `${paramPath}.type_repr`);
421
498
  requireScalar(param?.scalar, `${paramPath}.scalar`);
422
499
  requireInteger(param?.array_len, `${paramPath}.array_len`, 0);
500
+ requireBoolean(param?.is_array, `${paramPath}.is_array`);
423
501
  requireBoolean(param?.is_slice, `${paramPath}.is_slice`);
424
502
  requireNullableInteger(param?.byte_offset, `${paramPath}.byte_offset`, 0);
425
503
  requireNullableInteger(param?.byte_size, `${paramPath}.byte_size`, 0);
426
504
  requireInteger(param?.element_size_bytes, `${paramPath}.element_size_bytes`, 1);
427
- requireBoolean(param?.has_default, `${paramPath}.has_default`);
428
- requireNullableStringArray(param?.default_reprs, `${paramPath}.default_reprs`);
505
+ if (supportsDefaults) {
506
+ requireBoolean(param?.has_default, `${paramPath}.has_default`);
507
+ requireNullableStringArray(param?.default_reprs, `${paramPath}.default_reprs`);
508
+ }
429
509
  requireScalarElementSize(param, paramPath);
430
510
  if (hasDynamicParam ? param.byte_offset !== null : param.byte_offset !== minimumSize) {
431
511
  throw new OndaArtifactError(`${paramPath}.byte_offset is inconsistent with event layout`);
432
512
  }
433
513
  if (param.is_slice) {
434
- if (param.array_len !== 0 || param.byte_size !== null || param.has_default) {
514
+ if (
515
+ param.is_array
516
+ || param.type_repr !== `${param.scalar}[]`
517
+ || param.array_len !== 0
518
+ || param.byte_size !== null
519
+ || (supportsDefaults && param.has_default)
520
+ ) {
435
521
  throw new OndaArtifactError(`${paramPath} has an invalid slice descriptor`);
436
522
  }
437
523
  minimumSize += 4;
438
524
  hasDynamicParam = true;
439
525
  } else {
440
- if (param.array_len < 1 || param.byte_size !== param.element_size_bytes * param.array_len) {
526
+ const expectedType = param.is_array
527
+ ? `${param.scalar}[${param.array_len}]`
528
+ : param.scalar;
529
+ if (
530
+ param.array_len < 1
531
+ || (!param.is_array && param.array_len !== 1)
532
+ || param.type_repr !== expectedType
533
+ || param.byte_size !== param.element_size_bytes * param.array_len
534
+ ) {
441
535
  throw new OndaArtifactError(`${paramPath} has an invalid fixed-size descriptor`);
442
536
  }
443
537
  minimumSize += param.byte_size;
444
538
  }
445
- if (param.has_default !== (param.default_reprs !== null)) {
446
- throw new OndaArtifactError(`${paramPath}.has_default must reflect default_reprs`);
447
- }
448
- if (param.default_reprs !== null && param.default_reprs.length !== param.array_len) {
449
- throw new OndaArtifactError(`${paramPath}.default_reprs must contain one value per element`);
539
+ if (supportsDefaults) {
540
+ if (param.has_default !== (param.default_reprs !== null)) {
541
+ throw new OndaArtifactError(`${paramPath}.has_default must reflect default_reprs`);
542
+ }
543
+ if (param.default_reprs !== null && param.default_reprs.length !== param.array_len) {
544
+ throw new OndaArtifactError(`${paramPath}.default_reprs must contain one value per element`);
545
+ }
450
546
  }
451
547
  });
452
548
  if (value.payload_min_size_bytes !== minimumSize) {
@@ -466,6 +562,9 @@ function validateEventMetadata(value, path) {
466
562
 
467
563
  function validateStateMetadata(value, path) {
468
564
  requireString(value?.name, `${path}.name`);
565
+ if (value?.authored !== undefined) {
566
+ requireBoolean(value.authored, `${path}.authored`);
567
+ }
469
568
  requireString(value?.type_repr, `${path}.type_repr`);
470
569
  requireScalar(value?.scalar, `${path}.scalar`);
471
570
  requireInteger(value?.array_len, `${path}.array_len`, 1);
@@ -793,6 +892,428 @@ export async function loadProcessorArtifactFiles(
793
892
  return artifact;
794
893
  }
795
894
 
895
+ export function writeDelegateBatch(
896
+ memory,
897
+ batchAddress,
898
+ storageAddress,
899
+ capacityBytes,
900
+ ) {
901
+ const view = writableDataView(memory);
902
+ requireMemoryRange(view, batchAddress, DELEGATE_BATCH_SIZE_BYTES, "delegate batch");
903
+ requireInteger(storageAddress, "storageAddress", 0);
904
+ requireInteger(capacityBytes, "capacityBytes", 0);
905
+ if (storageAddress > 0xffff_ffff || capacityBytes > 0xffff_ffff) {
906
+ throw new OndaArtifactError("delegate batch addresses and sizes must fit u32");
907
+ }
908
+ view.setUint32(batchAddress, storageAddress, true);
909
+ view.setUint32(batchAddress + 4, capacityBytes, true);
910
+ view.setUint32(batchAddress + 8, 0, true);
911
+ view.setUint32(batchAddress + 12, 0, true);
912
+ view.setUint32(batchAddress + 16, 0, true);
913
+ }
914
+
915
+ export function readDelegateBatch(memory, batchAddress) {
916
+ const view = writableDataView(memory);
917
+ requireMemoryRange(view, batchAddress, DELEGATE_BATCH_SIZE_BYTES, "delegate batch");
918
+ return {
919
+ storageAddress: view.getUint32(batchAddress, true),
920
+ capacityBytes: view.getUint32(batchAddress + 4, true),
921
+ usedBytes: view.getUint32(batchAddress + 8, true),
922
+ recordCount: view.getUint32(batchAddress + 12, true),
923
+ overflowCount: view.getUint32(batchAddress + 16, true),
924
+ };
925
+ }
926
+
927
+ export function writePrintBatch(memory, batchAddress, storageAddress, capacityBytes) {
928
+ const view = writableDataView(memory);
929
+ requireMemoryRange(view, batchAddress, PRINT_BATCH_SIZE_BYTES, "print batch");
930
+ requireInteger(storageAddress, "storageAddress", 0);
931
+ requireInteger(capacityBytes, "capacityBytes", 0);
932
+ if (storageAddress > 0xffff_ffff || capacityBytes > 0xffff_ffff) {
933
+ throw new OndaArtifactError("print batch addresses and sizes must fit u32");
934
+ }
935
+ view.setUint32(batchAddress, storageAddress, true);
936
+ view.setUint32(batchAddress + 4, capacityBytes, true);
937
+ view.setUint32(batchAddress + 8, 0, true);
938
+ view.setUint32(batchAddress + 12, 0, true);
939
+ view.setUint32(batchAddress + 16, 0, true);
940
+ }
941
+
942
+ export function readPrintBatch(memory, batchAddress) {
943
+ const view = writableDataView(memory);
944
+ requireMemoryRange(view, batchAddress, PRINT_BATCH_SIZE_BYTES, "print batch");
945
+ return {
946
+ storageAddress: view.getUint32(batchAddress, true),
947
+ capacityBytes: view.getUint32(batchAddress + 4, true),
948
+ usedBytes: view.getUint32(batchAddress + 8, true),
949
+ recordCount: view.getUint32(batchAddress + 12, true),
950
+ overflowCount: view.getUint32(batchAddress + 16, true),
951
+ };
952
+ }
953
+
954
+ export function writeExecutionOutput(
955
+ memory,
956
+ outputAddress,
957
+ delegateBatchAddress = 0,
958
+ printBatchAddress = 0,
959
+ ) {
960
+ const view = writableDataView(memory);
961
+ requireMemoryRange(view, outputAddress, EXECUTION_OUTPUT_SIZE_BYTES, "execution output");
962
+ requireInteger(delegateBatchAddress, "delegateBatchAddress", 0);
963
+ requireInteger(printBatchAddress, "printBatchAddress", 0);
964
+ if (delegateBatchAddress > 0xffff_ffff || printBatchAddress > 0xffff_ffff) {
965
+ throw new OndaArtifactError("execution output addresses must fit u32");
966
+ }
967
+ view.setUint32(outputAddress, delegateBatchAddress, true);
968
+ view.setUint32(outputAddress + 4, printBatchAddress, true);
969
+ view.setUint32(outputAddress + 8, 0, true);
970
+ }
971
+
972
+ export function resetExecutionOutput(memory, outputAddress) {
973
+ const view = writableDataView(memory);
974
+ requireMemoryRange(view, outputAddress, EXECUTION_OUTPUT_SIZE_BYTES, "execution output");
975
+ const delegateBatchAddress = view.getUint32(outputAddress, true);
976
+ const printBatchAddress = view.getUint32(outputAddress + 4, true);
977
+ for (const [batchAddress, sizeBytes, label] of [
978
+ [delegateBatchAddress, DELEGATE_BATCH_SIZE_BYTES, "delegate batch"],
979
+ [printBatchAddress, PRINT_BATCH_SIZE_BYTES, "print batch"],
980
+ ]) {
981
+ if (batchAddress !== 0) {
982
+ requireMemoryRange(view, batchAddress, sizeBytes, label);
983
+ }
984
+ }
985
+ for (const batchAddress of [delegateBatchAddress, printBatchAddress]) {
986
+ if (batchAddress === 0) continue;
987
+ view.setUint32(batchAddress + 8, 0, true);
988
+ view.setUint32(batchAddress + 12, 0, true);
989
+ view.setUint32(batchAddress + 16, 0, true);
990
+ }
991
+ view.setUint32(outputAddress + 8, 0, true);
992
+ }
993
+
994
+ export function decodePrintRecords(
995
+ storage,
996
+ usedBytes,
997
+ logSites,
998
+ byteOrder = "little_endian",
999
+ ) {
1000
+ const bytes = asUint8Array(storage);
1001
+ requireInteger(usedBytes, "usedBytes", 0);
1002
+ if (usedBytes > bytes.byteLength) {
1003
+ throw new OndaArtifactError("print batch usedBytes exceeds storage");
1004
+ }
1005
+ if (!Array.isArray(logSites)) {
1006
+ throw new OndaArtifactError("log-site metadata must be an array");
1007
+ }
1008
+ const littleEndian = byteOrder === "little_endian";
1009
+ if (!littleEndian && byteOrder !== "big_endian") {
1010
+ throw new OndaArtifactError("byteOrder must be little_endian or big_endian");
1011
+ }
1012
+ const view = new DataView(bytes.buffer, bytes.byteOffset, usedBytes);
1013
+ const records = [];
1014
+ let cursor = 0;
1015
+ while (cursor < usedBytes) {
1016
+ if (usedBytes - cursor < PRINT_RECORD_HEADER_SIZE_BYTES) {
1017
+ throw new OndaArtifactError("print storage ends in a partial record header");
1018
+ }
1019
+ const siteIndex = view.getUint32(cursor, littleEndian);
1020
+ const payloadByteLength = view.getUint32(cursor + 4, littleEndian);
1021
+ const sequence = view.getUint32(cursor + 8, littleEndian);
1022
+ const payloadOffset = cursor + PRINT_RECORD_HEADER_SIZE_BYTES;
1023
+ const end = payloadOffset + payloadByteLength;
1024
+ if (!Number.isSafeInteger(end) || end > usedBytes) {
1025
+ throw new OndaArtifactError("print storage ends in a partial payload");
1026
+ }
1027
+ const site = logSites[siteIndex];
1028
+ if (!site) {
1029
+ throw new OndaArtifactError(`print record references unknown log site ${siteIndex}`);
1030
+ }
1031
+ if (payloadByteLength !== site.payload_size_bytes) {
1032
+ throw new OndaArtifactError(
1033
+ `print record ${siteIndex} has ${payloadByteLength} payload bytes; expected ${site.payload_size_bytes}`,
1034
+ );
1035
+ }
1036
+ const values = [];
1037
+ let valueOffset = payloadOffset;
1038
+ for (const scalar of site.argument_types) {
1039
+ switch (scalar) {
1040
+ case "f32":
1041
+ values.push({ type: scalar, value: view.getFloat32(valueOffset, littleEndian) });
1042
+ valueOffset += 4;
1043
+ break;
1044
+ case "f64":
1045
+ values.push({ type: scalar, value: view.getFloat64(valueOffset, littleEndian) });
1046
+ valueOffset += 8;
1047
+ break;
1048
+ case "i32":
1049
+ values.push({ type: scalar, value: view.getInt32(valueOffset, littleEndian) });
1050
+ valueOffset += 4;
1051
+ break;
1052
+ case "i64":
1053
+ values.push({ type: scalar, value: view.getBigInt64(valueOffset, littleEndian) });
1054
+ valueOffset += 8;
1055
+ break;
1056
+ case "bool": {
1057
+ const value = view.getUint8(valueOffset);
1058
+ if (value > 1) throw new OndaArtifactError("print payload contains an invalid bool");
1059
+ values.push({ type: scalar, value: value !== 0 });
1060
+ valueOffset += 1;
1061
+ break;
1062
+ }
1063
+ default:
1064
+ throw new OndaArtifactError(`unsupported print scalar '${String(scalar)}'`);
1065
+ }
1066
+ }
1067
+ if (valueOffset !== end) {
1068
+ throw new OndaArtifactError(`print record ${siteIndex} payload has trailing bytes`);
1069
+ }
1070
+ records.push({
1071
+ siteIndex,
1072
+ sequence,
1073
+ label: site.label,
1074
+ source: site.source,
1075
+ lexicalOwner: site.lexical_owner,
1076
+ declaration: site.declaration,
1077
+ values,
1078
+ });
1079
+ cursor = end;
1080
+ }
1081
+ return records;
1082
+ }
1083
+
1084
+ function shortestF32(value) {
1085
+ for (let precision = 1; precision <= 9; precision += 1) {
1086
+ const candidate = value.toPrecision(precision);
1087
+ if (Object.is(Math.fround(Number(candidate)), value)) return candidate;
1088
+ }
1089
+ return value.toPrecision(9);
1090
+ }
1091
+
1092
+ function canonicalFloat(value, width) {
1093
+ if (Number.isNaN(value)) return "NaN";
1094
+ if (value === Infinity) return "inf";
1095
+ if (value === -Infinity) return "-inf";
1096
+ if (Object.is(value, -0)) return "-0.0";
1097
+ if (value === 0) return "0.0";
1098
+ const negative = value < 0;
1099
+ const shortest = width === 32 ? shortestF32(Math.fround(Math.abs(value))) : Math.abs(value).toString();
1100
+ const [mantissa, exponentText] = shortest.toLowerCase().split("e");
1101
+ let digits = mantissa.replace(".", "");
1102
+ const leading = digits.match(/^0*/u)[0].length;
1103
+ digits = digits.slice(leading);
1104
+ const decimalPosition = (mantissa.indexOf(".") < 0 ? mantissa.length : mantissa.indexOf("."))
1105
+ + (exponentText === undefined ? 0 : Number(exponentText)) - leading;
1106
+ const magnitude = Math.abs(value);
1107
+ let rendered;
1108
+ if (magnitude >= 1e-6 && magnitude < 1e21) {
1109
+ if (decimalPosition <= 0) {
1110
+ rendered = `0.${"0".repeat(-decimalPosition)}${digits}`;
1111
+ } else if (decimalPosition >= digits.length) {
1112
+ rendered = `${digits}${"0".repeat(decimalPosition - digits.length)}.0`;
1113
+ } else {
1114
+ rendered = `${digits.slice(0, decimalPosition)}.${digits.slice(decimalPosition)}`;
1115
+ }
1116
+ } else {
1117
+ digits = digits.replace(/0+$/u, "");
1118
+ const coefficient = digits.length === 1 ? digits : `${digits[0]}.${digits.slice(1)}`;
1119
+ rendered = `${coefficient}e${decimalPosition - 1}`;
1120
+ }
1121
+ return negative ? `-${rendered}` : rendered;
1122
+ }
1123
+
1124
+ function canonicalPrintValue(entry) {
1125
+ switch (entry.type) {
1126
+ case "f32": return canonicalFloat(entry.value, 32);
1127
+ case "f64": return canonicalFloat(entry.value, 64);
1128
+ case "i32": return String(entry.value);
1129
+ case "i64": return entry.value.toString();
1130
+ case "bool": return entry.value ? "true" : "false";
1131
+ default: throw new OndaArtifactError(`unsupported print scalar '${String(entry.type)}'`);
1132
+ }
1133
+ }
1134
+
1135
+ function escapedPrintLabel(label) {
1136
+ let escaped = "";
1137
+ for (const character of label) {
1138
+ switch (character) {
1139
+ case "\0": escaped += "\\0"; break;
1140
+ case "\\": escaped += "\\\\"; break;
1141
+ case "\n": escaped += "\\n"; break;
1142
+ case "\r": escaped += "\\r"; break;
1143
+ case "\t": escaped += "\\t"; break;
1144
+ default: {
1145
+ const codePoint = character.codePointAt(0);
1146
+ const mustEscape = codePoint <= 0x1f
1147
+ || (codePoint >= 0x7f && codePoint <= 0x9f)
1148
+ || codePoint === 0x2028
1149
+ || codePoint === 0x2029;
1150
+ escaped += mustEscape ? `\\u{${codePoint.toString(16)}}` : character;
1151
+ }
1152
+ }
1153
+ }
1154
+ return escaped;
1155
+ }
1156
+
1157
+ export function formatPrintBatch(memory, printBatchAddress, metadata) {
1158
+ const batch = readPrintBatch(memory, printBatchAddress);
1159
+ const bytes = asUint8Array(memory.buffer ?? memory);
1160
+ if (batch.usedBytes > batch.capacityBytes) {
1161
+ throw new OndaArtifactError("print batch usedBytes exceeds capacityBytes");
1162
+ }
1163
+ if (batch.storageAddress + batch.usedBytes > bytes.byteLength) {
1164
+ throw new OndaArtifactError("print batch storage exceeds WebAssembly memory");
1165
+ }
1166
+ const formatted = formatPrintRecords(
1167
+ bytes.subarray(batch.storageAddress, batch.storageAddress + batch.usedBytes),
1168
+ batch.usedBytes,
1169
+ metadata,
1170
+ batch.overflowCount,
1171
+ );
1172
+ if (formatted.entries.length !== batch.recordCount) {
1173
+ throw new OndaArtifactError("print batch recordCount does not match packed storage");
1174
+ }
1175
+ return formatted;
1176
+ }
1177
+
1178
+ export function formatPrintRecords(storage, usedBytes, metadata, overflowCount = 0) {
1179
+ requireInteger(overflowCount, "overflowCount", 0);
1180
+ const records = decodePrintRecords(
1181
+ storage,
1182
+ usedBytes,
1183
+ metadata.metadata?.log_sites ?? metadata.log_sites,
1184
+ metadata.target?.byte_order ?? "little_endian",
1185
+ );
1186
+ let text = "";
1187
+ for (const record of records) {
1188
+ const values = record.values.map(canonicalPrintValue).join(" ");
1189
+ if (record.label !== null) {
1190
+ text += escapedPrintLabel(record.label);
1191
+ if (values.length > 0) text += `: ${values}`;
1192
+ } else {
1193
+ text += values;
1194
+ }
1195
+ text += "\n";
1196
+ }
1197
+ return { text, entries: records, overflowCount };
1198
+ }
1199
+
1200
+ export function decodeDelegateRecords(
1201
+ storage,
1202
+ usedBytes,
1203
+ delegates,
1204
+ byteOrder = "little_endian",
1205
+ ) {
1206
+ const bytes = asUint8Array(storage);
1207
+ requireInteger(usedBytes, "usedBytes", 0);
1208
+ if (usedBytes > bytes.byteLength) {
1209
+ throw new OndaArtifactError("delegate batch usedBytes exceeds storage");
1210
+ }
1211
+ if (!Array.isArray(delegates)) {
1212
+ throw new OndaArtifactError("delegate metadata must be an array");
1213
+ }
1214
+ const littleEndian = byteOrder === "little_endian";
1215
+ if (!littleEndian && byteOrder !== "big_endian") {
1216
+ throw new OndaArtifactError("byteOrder must be little_endian or big_endian");
1217
+ }
1218
+ const view = new DataView(bytes.buffer, bytes.byteOffset, usedBytes);
1219
+ const records = [];
1220
+ let cursor = 0;
1221
+ while (cursor < usedBytes) {
1222
+ if (usedBytes - cursor < DELEGATE_RECORD_HEADER_SIZE_BYTES) {
1223
+ throw new OndaArtifactError("delegate storage ends in a partial record header");
1224
+ }
1225
+ const delegateIndex = view.getUint32(cursor, littleEndian);
1226
+ const payloadByteLength = view.getUint32(cursor + 4, littleEndian);
1227
+ const sequence = view.getUint32(cursor + 8, littleEndian);
1228
+ const payloadOffset = cursor + DELEGATE_RECORD_HEADER_SIZE_BYTES;
1229
+ const end = payloadOffset + payloadByteLength;
1230
+ if (!Number.isSafeInteger(end) || end > usedBytes) {
1231
+ throw new OndaArtifactError("delegate storage ends in a partial payload");
1232
+ }
1233
+ const delegate = delegates[delegateIndex];
1234
+ if (!delegate) {
1235
+ throw new OndaArtifactError(`delegate record references unknown delegate ${delegateIndex}`);
1236
+ }
1237
+ records.push({
1238
+ delegateIndex,
1239
+ sequence,
1240
+ name: delegate.name,
1241
+ payloadByteLength,
1242
+ payload: bytes.slice(payloadOffset, end),
1243
+ values: decodeDelegatePayload(
1244
+ view,
1245
+ payloadOffset,
1246
+ payloadByteLength,
1247
+ delegate,
1248
+ littleEndian,
1249
+ ),
1250
+ });
1251
+ cursor = end;
1252
+ }
1253
+ return records;
1254
+ }
1255
+
1256
+ function decodeDelegatePayload(view, start, size, delegate, littleEndian) {
1257
+ let cursor = start;
1258
+ const end = start + size;
1259
+ const values = {};
1260
+ for (const param of delegate.params) {
1261
+ let count = param.array_len;
1262
+ if (param.is_slice) {
1263
+ if (cursor + 4 > end) {
1264
+ throw new OndaArtifactError(`delegate '${delegate.name}' has a truncated slice length`);
1265
+ }
1266
+ count = view.getInt32(cursor, littleEndian);
1267
+ cursor += 4;
1268
+ if (count < 0) {
1269
+ throw new OndaArtifactError(`delegate '${delegate.name}' has a negative slice length`);
1270
+ }
1271
+ }
1272
+ const byteLength = count * param.element_size_bytes;
1273
+ if (!Number.isSafeInteger(byteLength) || cursor + byteLength > end) {
1274
+ throw new OndaArtifactError(`delegate '${delegate.name}' has a truncated '${param.name}' payload`);
1275
+ }
1276
+ const entries = [];
1277
+ for (let index = 0; index < count; index += 1) {
1278
+ entries.push(readPayloadScalar(view, cursor, param.scalar, littleEndian));
1279
+ cursor += param.element_size_bytes;
1280
+ }
1281
+ values[param.name] = param.is_array || param.is_slice ? entries : entries[0];
1282
+ }
1283
+ if (cursor !== end) {
1284
+ throw new OndaArtifactError(`delegate '${delegate.name}' payload has trailing bytes`);
1285
+ }
1286
+ return values;
1287
+ }
1288
+
1289
+ function readPayloadScalar(view, address, scalar, littleEndian) {
1290
+ switch (scalar) {
1291
+ case "bool": return view.getUint8(address) !== 0;
1292
+ case "i32": return view.getInt32(address, littleEndian);
1293
+ case "i64": return view.getBigInt64(address, littleEndian);
1294
+ case "f32": return view.getFloat32(address, littleEndian);
1295
+ case "f64": return view.getFloat64(address, littleEndian);
1296
+ default: throw new OndaArtifactError(`unsupported delegate scalar '${String(scalar)}'`);
1297
+ }
1298
+ }
1299
+
1300
+ function writableDataView(memory) {
1301
+ if (memory instanceof DataView) return memory;
1302
+ if (memory instanceof WebAssembly.Memory) return new DataView(memory.buffer);
1303
+ if (memory instanceof ArrayBuffer) return new DataView(memory);
1304
+ if (ArrayBuffer.isView(memory)) {
1305
+ return new DataView(memory.buffer, memory.byteOffset, memory.byteLength);
1306
+ }
1307
+ throw new OndaArtifactError("delegate batch memory must be WebAssembly memory or a buffer view");
1308
+ }
1309
+
1310
+ function requireMemoryRange(view, address, size, label) {
1311
+ requireInteger(address, `${label} address`, 0);
1312
+ if (address + size > view.byteLength) {
1313
+ throw new OndaArtifactError(`${label} exceeds memory`);
1314
+ }
1315
+ }
1316
+
796
1317
  function asUint8Array(value) {
797
1318
  if (value instanceof Uint8Array) return value;
798
1319
  if (value instanceof ArrayBuffer) return new Uint8Array(value);