@syntropika/tembra-sdk 0.2.2 → 0.3.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 +43 -17
- package/dist/authoring/types.d.ts +64 -3
- package/dist/authoring/wit.d.ts +6 -0
- package/dist/bridge/commands.d.ts +1190 -0
- package/dist/bridge/identifiers.d.ts +2 -0
- package/dist/bridge/kernel.d.ts +18 -107
- package/dist/bridge/protocol.d.ts +3 -138
- package/dist/browser.d.ts +14 -1
- package/dist/browser.js +141 -3332
- package/dist/chunks/browser-b8jamxw2.js +3399 -0
- package/dist/chunks/execution-nsqc6nrt.js +1419 -0
- package/dist/chunks/index-01zk0xqx.js +160 -0
- package/dist/chunks/index-3fjdfdfd.js +152 -0
- package/dist/chunks/index-aaymjn7v.js +787 -0
- package/dist/chunks/index-c1w7z9hx.js +356 -0
- package/dist/chunks/index-h8t0n42q.js +738 -0
- package/dist/chunks/index-hfds9mzp.js +308 -0
- package/dist/chunks/index-kr4x67wt.js +177 -0
- package/dist/chunks/index-kr6bnh34.js +117 -0
- package/dist/chunks/index-kyt9dj0a.js +1421 -0
- package/dist/chunks/index-n1wxzc9w.js +830 -0
- package/dist/chunks/index-pvac426d.js +74 -0
- package/dist/chunks/index-smyds5ce.js +3234 -0
- package/dist/chunks/index-sse8aapb.js +121 -0
- package/dist/chunks/index-v6heph77.js +643 -0
- package/dist/chunks/index-xrdvnv37.js +3448 -0
- package/dist/chunks/index-za4mg94e.js +26 -0
- package/dist/chunks/index-zkqmnjj8.js +167 -0
- package/dist/coordinator.js +9 -500
- package/dist/error.d.ts +2 -0
- package/dist/errors.d.ts +3 -0
- package/dist/guest.d.ts +173 -0
- package/dist/guest.js +26 -0
- package/dist/host.d.ts +36 -30
- package/dist/host.js +37 -3310
- package/dist/http/bytes.d.ts +8 -0
- package/dist/http/events.d.ts +7 -0
- package/dist/http.d.ts +45 -0
- package/dist/http.js +291 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +49 -862
- package/dist/infrastructure/rpc/client.d.ts +2 -1
- package/dist/infrastructure/rpc/resources.d.ts +28 -0
- package/dist/interpreter/abi.d.ts +54 -0
- package/dist/interpreter/acquire.d.ts +18 -0
- package/dist/interpreter/browser-network.d.ts +52 -0
- package/dist/interpreter/browser-port.d.ts +55 -0
- package/dist/interpreter/browser.d.ts +79 -0
- package/dist/interpreter/cli.d.ts +5 -0
- package/dist/interpreter/codec.d.ts +42 -0
- package/dist/interpreter/component/execution.d.ts +42 -0
- package/dist/interpreter/component/host.d.ts +69 -0
- package/dist/interpreter/component/instance.d.ts +40 -0
- package/dist/interpreter/component/kernel.d.ts +120 -0
- package/dist/interpreter/component/names.d.ts +5 -0
- package/dist/interpreter/component/port.d.ts +85 -0
- package/dist/interpreter/component/prepared.d.ts +97 -0
- package/dist/interpreter/component/resources.d.ts +45 -0
- package/dist/interpreter/component/revision.d.ts +87 -0
- package/dist/interpreter/component/scope.d.ts +116 -0
- package/dist/interpreter/component/streams.d.ts +28 -0
- package/dist/interpreter/component/values.d.ts +79 -0
- package/dist/interpreter/component/wasi-filesystem.d.ts +21 -0
- package/dist/interpreter/component/wasi-host.d.ts +64 -0
- package/dist/interpreter/component/wasi-http.d.ts +33 -0
- package/dist/interpreter/component/wasi-sockets.d.ts +183 -0
- package/dist/interpreter/component/wasi.d.ts +41 -0
- package/dist/interpreter/core.d.ts +64 -0
- package/dist/interpreter/fetch-http-provider.d.ts +17 -0
- package/dist/interpreter/filesystem/contract.d.ts +85 -0
- package/dist/interpreter/filesystem/memory.d.ts +3 -0
- package/dist/interpreter/filesystem/opfs.d.ts +3 -0
- package/dist/interpreter/filesystem/scope.d.ts +35 -0
- package/dist/interpreter/filesystem.d.ts +8 -0
- package/dist/interpreter/gate.d.ts +6 -0
- package/dist/interpreter/host-protocol.d.ts +100 -0
- package/dist/interpreter/http-ingress-fetch.d.ts +7 -0
- package/dist/interpreter/http-ingress.d.ts +96 -0
- package/dist/interpreter/http-provider.d.ts +85 -0
- package/dist/interpreter/io.d.ts +20 -0
- package/dist/interpreter/mobile.d.ts +149 -0
- package/dist/interpreter/native-ingress.d.ts +95 -0
- package/dist/interpreter/node-port.d.ts +25 -0
- package/dist/interpreter/node.d.ts +36 -0
- package/dist/interpreter/revision.d.ts +64 -0
- package/dist/interpreter/scope.d.ts +89 -0
- package/dist/interpreter/socket-addresses.d.ts +50 -0
- package/dist/interpreter/socket-provider.d.ts +110 -0
- package/dist/interpreter/standard-cli.d.ts +34 -0
- package/dist/interpreter/standard-codec.d.ts +96 -0
- package/dist/interpreter/standard-filesystem.d.ts +47 -0
- package/dist/interpreter/standard-host.d.ts +71 -0
- package/dist/interpreter/standard-http-values.d.ts +159 -0
- package/dist/interpreter/standard-http.d.ts +9 -0
- package/dist/interpreter/standard-ingress.d.ts +63 -0
- package/dist/interpreter/standard-sockets.d.ts +177 -0
- package/dist/interpreter/standard-streams.d.ts +218 -0
- package/dist/interpreter/standard-system.d.ts +35 -0
- package/dist/interpreter/standard-utf8.d.ts +4 -0
- package/dist/interpreter/standard.d.ts +18 -0
- package/dist/interpreter/types.d.ts +152 -0
- package/dist/interpreter/wit-shape.d.ts +92 -0
- package/dist/manager.js +5 -332
- package/dist/msgpack.js +9 -615
- package/dist/node.d.ts +8 -1
- package/dist/node.js +248 -3321
- package/dist/rpc.js +196 -699
- package/dist/runtime/adapters.d.ts +120 -0
- package/dist/runtime/adapters.js +38 -0
- package/dist/runtime/calls.d.ts +7 -6
- package/dist/runtime/lifecycle.d.ts +3 -1
- package/dist/runtime/orbs.d.ts +5 -4
- package/dist/runtime/references.d.ts +27 -1
- package/dist/runtime/reload.d.ts +5 -3
- package/dist/runtime/scopes.d.ts +1 -1
- package/dist/runtime/signals.d.ts +4 -0
- package/dist/runtime/wit-client.d.ts +38 -0
- package/dist/telemetry.js +4 -25
- package/dist/tooling/build.d.ts +2 -2
- package/dist/tooling/client-resources.d.ts +23 -0
- package/dist/tooling/client.d.ts +10 -0
- package/dist/tooling/component-glue.d.ts +17 -0
- package/dist/tooling/component.d.ts +11 -0
- package/dist/tooling/index.d.ts +3 -1
- package/dist/tooling/index.js +1155 -102
- package/dist/tooling/resolver.d.ts +4 -4
- package/dist/tooling/typecheck.d.ts +2 -1
- package/dist/tooling/types.d.ts +27 -12
- package/dist/tooling/wit.d.ts +9 -0
- package/dist/wasi/wasi-clocks-types.d.ts +2 -0
- package/dist/wasi/wasi-http-client.d.ts +5 -0
- package/dist/wasi/wasi-http-types.d.ts +285 -0
- package/dist/wasi/wasi-sockets-ip-name-lookup.d.ts +23 -0
- package/dist/wasi/wasi-sockets-types.d.ts +146 -0
- package/package.json +62 -35
- package/src/authoring/declaration.ts +1 -1
- package/src/authoring/types.ts +53 -3
- package/src/authoring/wit.ts +15 -0
- package/src/bridge/commands.ts +1105 -0
- package/src/bridge/identifiers.ts +2 -0
- package/src/bridge/kernel.ts +56 -98
- package/src/bridge/protocol.ts +3 -142
- package/src/browser.ts +90 -6
- package/src/context-key.ts +4 -7
- package/src/error.ts +1 -1
- package/src/errors.ts +7 -0
- package/src/guest.ts +327 -0
- package/src/host.ts +128 -23
- package/src/http/bytes.ts +87 -0
- package/src/http/events.ts +34 -0
- package/src/http.ts +272 -0
- package/src/index.ts +3 -0
- package/src/infrastructure/rpc/client.ts +136 -17
- package/src/infrastructure/rpc/resources.ts +123 -0
- package/src/interpreter/abi.ts +69 -0
- package/src/interpreter/acquire.ts +58 -0
- package/src/interpreter/browser-network.ts +170 -0
- package/src/interpreter/browser-port.ts +425 -0
- package/src/interpreter/browser.ts +340 -0
- package/src/interpreter/cli.ts +30 -0
- package/src/interpreter/codec.ts +298 -0
- package/src/interpreter/component/execution.ts +264 -0
- package/src/interpreter/component/host.ts +409 -0
- package/src/interpreter/component/instance.ts +138 -0
- package/src/interpreter/component/kernel.ts +611 -0
- package/src/interpreter/component/names.ts +13 -0
- package/src/interpreter/component/port.ts +598 -0
- package/src/interpreter/component/prepared.ts +194 -0
- package/src/interpreter/component/resources.ts +345 -0
- package/src/interpreter/component/revision.ts +702 -0
- package/src/interpreter/component/scope.ts +447 -0
- package/src/interpreter/component/streams.ts +180 -0
- package/src/interpreter/component/values.ts +254 -0
- package/src/interpreter/component/wasi-filesystem.ts +472 -0
- package/src/interpreter/component/wasi-host.ts +197 -0
- package/src/interpreter/component/wasi-http.ts +939 -0
- package/src/interpreter/component/wasi-sockets.ts +958 -0
- package/src/interpreter/component/wasi.ts +238 -0
- package/src/interpreter/core.ts +386 -0
- package/src/interpreter/fetch-http-provider.ts +98 -0
- package/src/interpreter/filesystem/contract.ts +138 -0
- package/src/interpreter/filesystem/memory.ts +180 -0
- package/src/interpreter/filesystem/opfs.ts +294 -0
- package/src/interpreter/filesystem/scope.ts +390 -0
- package/src/interpreter/filesystem.ts +20 -0
- package/src/interpreter/gate.ts +55 -0
- package/src/interpreter/host-protocol.ts +242 -0
- package/src/interpreter/http-ingress-fetch.ts +133 -0
- package/src/interpreter/http-ingress.ts +203 -0
- package/src/interpreter/http-provider.ts +105 -0
- package/src/interpreter/io.ts +66 -0
- package/src/interpreter/mobile.ts +385 -0
- package/src/interpreter/native-ingress.ts +550 -0
- package/src/interpreter/node-port.ts +218 -0
- package/src/interpreter/node.ts +114 -0
- package/src/interpreter/revision.ts +450 -0
- package/src/interpreter/scope.ts +453 -0
- package/src/interpreter/socket-addresses.ts +246 -0
- package/src/interpreter/socket-provider.ts +126 -0
- package/src/interpreter/standard-cli.ts +184 -0
- package/src/interpreter/standard-codec.ts +403 -0
- package/src/interpreter/standard-filesystem.ts +545 -0
- package/src/interpreter/standard-host.ts +840 -0
- package/src/interpreter/standard-http-values.ts +624 -0
- package/src/interpreter/standard-http.ts +622 -0
- package/src/interpreter/standard-ingress.ts +344 -0
- package/src/interpreter/standard-sockets.ts +847 -0
- package/src/interpreter/standard-streams.ts +710 -0
- package/src/interpreter/standard-system.ts +182 -0
- package/src/interpreter/standard-utf8.ts +72 -0
- package/src/interpreter/standard.ts +283 -0
- package/src/interpreter/types.ts +163 -0
- package/src/interpreter/wit-shape.ts +175 -0
- package/src/node.ts +43 -14
- package/src/runtime/activities.ts +6 -6
- package/src/runtime/adapters.ts +314 -0
- package/src/runtime/calls.ts +213 -90
- package/src/runtime/context.ts +7 -7
- package/src/runtime/lifecycle.ts +36 -17
- package/src/runtime/orbs.ts +81 -39
- package/src/runtime/programs.ts +16 -8
- package/src/runtime/references.ts +128 -11
- package/src/runtime/reload.ts +71 -30
- package/src/runtime/resources.ts +2 -2
- package/src/runtime/scopes.ts +17 -17
- package/src/runtime/session.ts +3 -1
- package/src/runtime/signals.ts +31 -0
- package/src/runtime/wit-client.ts +228 -0
- package/src/tooling/build.ts +152 -54
- package/src/tooling/client-resources.ts +74 -0
- package/src/tooling/client.ts +531 -0
- package/src/tooling/component-glue.ts +288 -0
- package/src/tooling/component.ts +225 -0
- package/src/tooling/index.ts +3 -7
- package/src/tooling/resolver.ts +42 -25
- package/src/tooling/typecheck.ts +59 -4
- package/src/tooling/types.ts +27 -12
- package/src/tooling/wit.ts +188 -0
- package/dist/embedded.d.ts +0 -1
- package/dist/embedded.js +0 -1
- package/src/embedded.ts +0 -301
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import type { OrbDefinition, OrbArtifact, LoadOptions } from "../authoring/types.ts";
|
|
2
|
+
import { BrowserPort } from "./browser-port.ts";
|
|
3
|
+
import { checkInterpreter, CoreGuest } from "./core.ts";
|
|
4
|
+
import type { BrowserNetworkProviders } from "./browser-network.ts";
|
|
5
|
+
import type { FilesystemProvider } from "./filesystem.ts";
|
|
6
|
+
import { BrowserCapabilities } from "./io.ts";
|
|
7
|
+
import { exportedFunctions, Revision } from "./revision.ts";
|
|
8
|
+
import { StandardHost } from "./standard-host.ts";
|
|
9
|
+
import type { SystemProviders } from "./standard-system.ts";
|
|
10
|
+
import { CLOCK_MONOTONIC } from "./abi.ts";
|
|
11
|
+
import type { StdioProvider, StdioStreams } from "./standard-cli.ts";
|
|
12
|
+
import { query, type ContractPort, type InstallationPlan } from "./types.ts";
|
|
13
|
+
import type { PreparedContract } from "./component/execution.ts";
|
|
14
|
+
import {
|
|
15
|
+
preparedRegistry,
|
|
16
|
+
type PreparedComponent,
|
|
17
|
+
type PreparedRecord,
|
|
18
|
+
} from "./component/prepared.ts";
|
|
19
|
+
|
|
20
|
+
export interface BrowserInterpreterOptions {
|
|
21
|
+
/** URL of the interpreter core module; defaults to the packaged `interpreter.wasm`. */
|
|
22
|
+
engine?: string | URL;
|
|
23
|
+
providers?: BrowserNetworkProviders &
|
|
24
|
+
SystemProviders & {
|
|
25
|
+
filesystem?: Readonly<Record<string, FilesystemProvider>>;
|
|
26
|
+
stdio?: StdioProvider;
|
|
27
|
+
};
|
|
28
|
+
limits?: {
|
|
29
|
+
/**
|
|
30
|
+
* Guest linear memory of one instance in bytes. A compiled component spends whole 64 KiB
|
|
31
|
+
* pages: initial memories of every core instantiation plus `memory.grow`.
|
|
32
|
+
*/
|
|
33
|
+
memoryBytes?: number;
|
|
34
|
+
/** Wall time of one guest callback, including its host work until physical completion. */
|
|
35
|
+
timeoutMs?: number;
|
|
36
|
+
instructionTicks?: number;
|
|
37
|
+
packetBytes?: number;
|
|
38
|
+
/**
|
|
39
|
+
* Compiled components: fuel of one admitted callback, and separately of instantiation
|
|
40
|
+
* (function entries and loop iterations). Exhaustion traps and quarantines the revision.
|
|
41
|
+
*/
|
|
42
|
+
fuel?: number;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Application-owned adapters generated by Tembra tooling (`browser: true`) for the compiled
|
|
46
|
+
* Orbs this host may install. Source Orbs need none.
|
|
47
|
+
*/
|
|
48
|
+
components?: readonly PreparedComponent[];
|
|
49
|
+
onLog?: (record: { orb: string; level: string; message: string }) => void;
|
|
50
|
+
contractsInput?: unknown;
|
|
51
|
+
}
|
|
52
|
+
interface BrowserArtifact extends ContractPort {
|
|
53
|
+
description(): string;
|
|
54
|
+
source(): string;
|
|
55
|
+
free(): void;
|
|
56
|
+
}
|
|
57
|
+
interface ContractModule {
|
|
58
|
+
WasmArtifact: new (bytes: Uint8Array) => BrowserArtifact;
|
|
59
|
+
WasmPreparedComponent: new (
|
|
60
|
+
bytes: Uint8Array,
|
|
61
|
+
digests: string[],
|
|
62
|
+
) => PreparedContract & { free(): void };
|
|
63
|
+
compiledArtifact(bytes: Uint8Array): boolean;
|
|
64
|
+
default(input?: unknown): Promise<unknown>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Compile the trusted interpreter once; a failed request may be retried by a later Orb. */
|
|
68
|
+
async function compileEngine(url: URL): Promise<WebAssembly.Module> {
|
|
69
|
+
const response = await fetch(url);
|
|
70
|
+
if (!response.ok) throw new Error("Engine module request failed");
|
|
71
|
+
const module = await WebAssembly.compile(await response.arrayBuffer());
|
|
72
|
+
checkInterpreter(module);
|
|
73
|
+
return module;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A browser backend instantiates one isolated core module, memory and heap per Orb. */
|
|
77
|
+
export class BrowserExecution {
|
|
78
|
+
#engine: Promise<WebAssembly.Module> | undefined;
|
|
79
|
+
/** Application-owned prepared compiled components, by original artifact digest. */
|
|
80
|
+
readonly #components: ReadonlyMap<string, PreparedRecord>;
|
|
81
|
+
|
|
82
|
+
/** Keep the prepared-contract validator and trusted engine out of metadata-only hosts. */
|
|
83
|
+
constructor(
|
|
84
|
+
readonly options: BrowserInterpreterOptions,
|
|
85
|
+
readonly contracts: ContractModule,
|
|
86
|
+
) {
|
|
87
|
+
this.#components = preparedRegistry(options.components);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Share compiled code between installations; every instance still owns its state. */
|
|
91
|
+
private engine(): Promise<WebAssembly.Module> {
|
|
92
|
+
if (!this.#engine) {
|
|
93
|
+
const compiled = compileEngine(new URL(this.options.engine!));
|
|
94
|
+
this.#engine = compiled;
|
|
95
|
+
compiled.catch(() => {
|
|
96
|
+
if (this.#engine === compiled) this.#engine = undefined;
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return this.#engine;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Own one checked contract for exactly one installed revision. */
|
|
103
|
+
async materialize(definition: OrbArtifact): Promise<OrbDefinition> {
|
|
104
|
+
if (this.contracts.compiledArtifact(definition.artifact)) return this.compiled(definition);
|
|
105
|
+
const artifact = new this.contracts.WasmArtifact(definition.artifact);
|
|
106
|
+
let released = false;
|
|
107
|
+
const release = () => {
|
|
108
|
+
if (released) return;
|
|
109
|
+
released = true;
|
|
110
|
+
artifact.free();
|
|
111
|
+
};
|
|
112
|
+
try {
|
|
113
|
+
return await this.open(artifact, definition, release);
|
|
114
|
+
} catch (error) {
|
|
115
|
+
release();
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* A compiled Orb runs only through an application-registered prepared adapter. The verifier
|
|
122
|
+
* hashes the actual uploaded bytes and accepts their metadata only for a registered digest;
|
|
123
|
+
* the execution code loads on the first such installation.
|
|
124
|
+
*/
|
|
125
|
+
private async compiled(definition: OrbArtifact): Promise<OrbDefinition> {
|
|
126
|
+
if (!this.#components.size)
|
|
127
|
+
throw new Error(
|
|
128
|
+
"Compiled Orbs run in browsers only through a prepared adapter: build the Orb with " +
|
|
129
|
+
"`browser: true` and pass the generated module to " +
|
|
130
|
+
"createHost({ isolated: { components: [...] } })",
|
|
131
|
+
);
|
|
132
|
+
let contract: (PreparedContract & { free(): void }) | undefined;
|
|
133
|
+
try {
|
|
134
|
+
contract = new this.contracts.WasmPreparedComponent(definition.artifact, [
|
|
135
|
+
...this.#components.keys(),
|
|
136
|
+
]);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (!String(error).includes("no prepared browser adapter")) throw error;
|
|
139
|
+
throw new Error(
|
|
140
|
+
"This compiled Orb matches no registered prepared adapter; rebuild it with " +
|
|
141
|
+
"`browser: true` and register the module generated for exactly this artifact",
|
|
142
|
+
{ cause: error },
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
let released = false;
|
|
146
|
+
const release = () => {
|
|
147
|
+
if (released) return;
|
|
148
|
+
released = true;
|
|
149
|
+
contract.free();
|
|
150
|
+
};
|
|
151
|
+
try {
|
|
152
|
+
const record = this.#components.get(contract.digest());
|
|
153
|
+
if (!record) throw new Error("The verifier selected an unregistered prepared adapter");
|
|
154
|
+
const { openComponent } = await import("./component/execution.ts");
|
|
155
|
+
return await openComponent(record, contract, definition, this.options, release);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
release();
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Check installation authority before creating any guest heap or filesystem descriptors. */
|
|
163
|
+
private async open(
|
|
164
|
+
contract: BrowserArtifact,
|
|
165
|
+
installation: LoadOptions,
|
|
166
|
+
release: () => void,
|
|
167
|
+
): Promise<OrbDefinition> {
|
|
168
|
+
const identity = JSON.parse(contract.description()) as {
|
|
169
|
+
name: string;
|
|
170
|
+
apiVersion: number;
|
|
171
|
+
kind: string;
|
|
172
|
+
};
|
|
173
|
+
if (identity.kind !== "source")
|
|
174
|
+
throw new Error("Compiled Orb execution is unavailable in this browser backend");
|
|
175
|
+
const prepared = query<InstallationPlan>(contract, {
|
|
176
|
+
kind: "install",
|
|
177
|
+
name: identity.name,
|
|
178
|
+
apiVersion: identity.apiVersion,
|
|
179
|
+
requires: installation.requires ?? {},
|
|
180
|
+
grants: installation.grants ?? {},
|
|
181
|
+
filesystem: Object.keys(this.options.providers?.filesystem ?? {}),
|
|
182
|
+
// Network grants resolve only against socket providers and HTTP grants only against HTTP
|
|
183
|
+
// providers, so one registry never satisfies the other kind of grant.
|
|
184
|
+
network: Object.keys(this.options.providers?.network ?? {}),
|
|
185
|
+
http: Object.keys(this.options.providers?.http ?? {}),
|
|
186
|
+
});
|
|
187
|
+
// A source bundle reaches its state, resources and context through its own declaration; the
|
|
188
|
+
// kernel serves `tembra:guest` to compiled components only, so such an import would install
|
|
189
|
+
// and never be served. The native executor refuses it the same way.
|
|
190
|
+
const kernel = Object.entries(prepared.bindings).find(
|
|
191
|
+
([, binding]) => binding.kind === "kernel",
|
|
192
|
+
);
|
|
193
|
+
if (kernel)
|
|
194
|
+
throw new Error(
|
|
195
|
+
`${kernel[0]}: the kernel serves tembra:guest to compiled components only; a source Orb reaches its state, resources and context through its bundle`,
|
|
196
|
+
);
|
|
197
|
+
const options = { ...identity, grants: installation.grants };
|
|
198
|
+
let capabilities: BrowserCapabilities | undefined;
|
|
199
|
+
let stdio: StdioStreams | undefined;
|
|
200
|
+
const port = new BrowserPort(
|
|
201
|
+
this.options.limits?.timeoutMs ?? 10000,
|
|
202
|
+
async () => {
|
|
203
|
+
const cleanup: Promise<unknown>[] = [Promise.resolve().then(() => capabilities?.dispose())];
|
|
204
|
+
// Until construction succeeds, this scope owns providers returned by the factory.
|
|
205
|
+
if (stdio)
|
|
206
|
+
for (const provider of new Set([stdio.stdin, stdio.stdout, stdio.stderr]))
|
|
207
|
+
cleanup.push(Promise.resolve().then(() => provider?.close?.()));
|
|
208
|
+
const settled = await Promise.allSettled(cleanup);
|
|
209
|
+
release();
|
|
210
|
+
const failed = settled.filter(
|
|
211
|
+
(result): result is PromiseRejectedResult => result.status === "rejected",
|
|
212
|
+
);
|
|
213
|
+
if (failed.length)
|
|
214
|
+
throw new AggregateError(
|
|
215
|
+
failed.map((result) => result.reason),
|
|
216
|
+
"Provider cleanup failed",
|
|
217
|
+
);
|
|
218
|
+
},
|
|
219
|
+
(record) => {
|
|
220
|
+
if (!["log", "debug", "info", "warn", "error"].includes(record.level))
|
|
221
|
+
throw new Error("Invalid console level");
|
|
222
|
+
try {
|
|
223
|
+
this.options.onLog?.({
|
|
224
|
+
orb: options.name,
|
|
225
|
+
level: record.level,
|
|
226
|
+
message: String(record.message),
|
|
227
|
+
});
|
|
228
|
+
} catch {
|
|
229
|
+
/* Logging observers do not control the guest. */
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
this.options.limits?.packetBytes ?? 8 << 20,
|
|
233
|
+
);
|
|
234
|
+
try {
|
|
235
|
+
const memory = this.options.limits?.memoryBytes ?? 128 << 20;
|
|
236
|
+
if (!Number.isSafeInteger(memory) || memory < 2 << 20 || memory > 0xffffffff)
|
|
237
|
+
throw new Error("Invalid interpreter memory bound");
|
|
238
|
+
capabilities = await BrowserCapabilities.open(
|
|
239
|
+
options.grants ?? {},
|
|
240
|
+
this.options.providers ?? {},
|
|
241
|
+
);
|
|
242
|
+
const description = query<
|
|
243
|
+
Parameters<typeof exportedFunctions>[0] & {
|
|
244
|
+
imports: { binding: string; contract: string; type_only: boolean }[];
|
|
245
|
+
}
|
|
246
|
+
>(contract, { kind: "describe" });
|
|
247
|
+
// Each socket interface uses exactly the provider its import binding selected.
|
|
248
|
+
const bound = (name: string) => {
|
|
249
|
+
const entry = description.imports.find((item) => item.contract === name);
|
|
250
|
+
const binding = entry && prepared.bindings[entry.binding];
|
|
251
|
+
return binding?.kind === "host" ? binding.provider : undefined;
|
|
252
|
+
};
|
|
253
|
+
if (options.grants?.system?.includes("cli"))
|
|
254
|
+
stdio = this.options.providers?.stdio?.(options.name, installation.cli ?? {});
|
|
255
|
+
// Standard WASI calls reach only the interfaces this revision imported and was granted.
|
|
256
|
+
port.standard = new StandardHost(
|
|
257
|
+
new Set(
|
|
258
|
+
description.imports
|
|
259
|
+
.filter((item) => item.type_only === false)
|
|
260
|
+
.map((item) => item.contract),
|
|
261
|
+
),
|
|
262
|
+
capabilities.mounts,
|
|
263
|
+
this.options.limits?.packetBytes ?? 8 << 20,
|
|
264
|
+
{
|
|
265
|
+
clocks: this.options.providers?.clocks,
|
|
266
|
+
random: this.options.providers?.random,
|
|
267
|
+
// Standard `wasi:http` sends reach only providers granted for an exact origin.
|
|
268
|
+
http: capabilities.network,
|
|
269
|
+
sockets: {
|
|
270
|
+
types: capabilities.network.sockets(bound("wasi:sockets/types@0.3.0")),
|
|
271
|
+
lookup: capabilities.network.sockets(bound("wasi:sockets/ip-name-lookup@0.3.0")),
|
|
272
|
+
},
|
|
273
|
+
...(options.grants?.system?.includes("cli")
|
|
274
|
+
? {
|
|
275
|
+
cli: installation.cli,
|
|
276
|
+
stdio,
|
|
277
|
+
}
|
|
278
|
+
: { stdio: undefined }),
|
|
279
|
+
},
|
|
280
|
+
);
|
|
281
|
+
// The standard host now owns provider cleanup, including failed VM initialization.
|
|
282
|
+
stdio = undefined;
|
|
283
|
+
const { clocks, random } = port.standard;
|
|
284
|
+
// The instance links no filesystem, socket or environment capability.
|
|
285
|
+
port.guest = await CoreGuest.create(await this.engine(), memory, {
|
|
286
|
+
sync: (packet) => (typeof packet === "string" ? port.sync(packet) : port.sync(packet)),
|
|
287
|
+
log: (level, message) => port.log({ operation: "console", level, message }),
|
|
288
|
+
clock: (clock) => {
|
|
289
|
+
if (!options.grants?.system?.includes("clocks")) return 0n;
|
|
290
|
+
if (clock === CLOCK_MONOTONIC) return clocks.monotonicNow();
|
|
291
|
+
const instant = clocks.systemNow();
|
|
292
|
+
return instant.seconds * 1_000_000_000n + BigInt(instant.nanoseconds);
|
|
293
|
+
},
|
|
294
|
+
});
|
|
295
|
+
await port.load(
|
|
296
|
+
JSON.stringify({
|
|
297
|
+
source: contract.source(),
|
|
298
|
+
heap_bytes: Math.floor(memory / 2),
|
|
299
|
+
instruction_ticks: this.options.limits?.instructionTicks ?? 10000,
|
|
300
|
+
contract: description,
|
|
301
|
+
exports: exportedFunctions(description, contract),
|
|
302
|
+
builtins: {
|
|
303
|
+
clock: options.grants?.system?.includes("clocks") ?? false,
|
|
304
|
+
seed: options.grants?.system?.includes("random")
|
|
305
|
+
? random.insecureSeed().map(String)
|
|
306
|
+
: null,
|
|
307
|
+
},
|
|
308
|
+
}),
|
|
309
|
+
);
|
|
310
|
+
return new Revision(port, contract, this.options.limits?.timeoutMs ?? 10000).definition(
|
|
311
|
+
options,
|
|
312
|
+
prepared,
|
|
313
|
+
);
|
|
314
|
+
} catch (error) {
|
|
315
|
+
try {
|
|
316
|
+
await port.close();
|
|
317
|
+
} catch (disposal) {
|
|
318
|
+
throw new AggregateError(
|
|
319
|
+
[error, disposal],
|
|
320
|
+
"Interpreter initialization and disposal failed",
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
throw error;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Load the optional interpreter assets and prepared-contract validator behind Tembra's facade. */
|
|
329
|
+
export async function createExecution(
|
|
330
|
+
options: BrowserInterpreterOptions,
|
|
331
|
+
): Promise<BrowserExecution> {
|
|
332
|
+
// The engine package locates its own interpreter, so bundled SDK code needs no import map.
|
|
333
|
+
const engine =
|
|
334
|
+
options.engine === undefined
|
|
335
|
+
? (await import("@syntropika/tembra-engine-wasm/assets")).interpreterURL()
|
|
336
|
+
: new URL(options.engine, globalThis.location?.href);
|
|
337
|
+
const contracts = (await import("@syntropika/tembra-engine-wasm/contracts")) as ContractModule;
|
|
338
|
+
await contracts.default(options.contractsInput);
|
|
339
|
+
return new BrowserExecution({ ...options, engine }, contracts);
|
|
340
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { CliOptions } from "../authoring/types.ts";
|
|
2
|
+
|
|
3
|
+
/** Capture installation data before asynchronous preparation can observe caller mutations. */
|
|
4
|
+
export function captureCli(options: CliOptions): CliOptions {
|
|
5
|
+
const input = options.stdin;
|
|
6
|
+
return {
|
|
7
|
+
...options,
|
|
8
|
+
...(options.arguments ? { arguments: [...options.arguments] } : {}),
|
|
9
|
+
...(options.environment
|
|
10
|
+
? { environment: options.environment.map(([key, value]) => [key, value] as const) }
|
|
11
|
+
: {}),
|
|
12
|
+
...(typeof input === "object"
|
|
13
|
+
? { stdin: "bytes" in input ? { bytes: input.bytes.slice() } : { ...input } }
|
|
14
|
+
: {}),
|
|
15
|
+
...(typeof options.stdout === "object" ? { stdout: { ...options.stdout } } : {}),
|
|
16
|
+
...(typeof options.stderr === "object" ? { stderr: { ...options.stderr } } : {}),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Copy explicitly configured stdin once into the native installation's data configuration. */
|
|
21
|
+
export function cliPacket(options: CliOptions | undefined): string {
|
|
22
|
+
if (!options) return "{}";
|
|
23
|
+
const stdin = options.stdin;
|
|
24
|
+
return JSON.stringify({
|
|
25
|
+
...options,
|
|
26
|
+
...(typeof stdin === "object" && "bytes" in stdin
|
|
27
|
+
? { stdin: { bytes: Array.from(stdin.bytes) } }
|
|
28
|
+
: {}),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Portable value capture for the isolated-interpreter seam.
|
|
3
|
+
*
|
|
4
|
+
* Hostile JavaScript input is read exactly once and written directly as JSON text. Everything
|
|
5
|
+
* that `JSON.stringify` would coerce silently is refused before any text exists: non-finite
|
|
6
|
+
* numbers, negative zero, functions, symbols, accessors, `toJSON`, class instances, sparse
|
|
7
|
+
* arrays, cycles and DataView buffers. A `bigint` (or a `BigUint64Array`/`BigInt64Array`) is
|
|
8
|
+
* accepted only where the prepared signature's `Shape` marks a WIT `u64`/`s64`, and is written in
|
|
9
|
+
* the same walk as canonical decimal text; no other JavaScript kind is accepted there. This is
|
|
10
|
+
* only a data encoder; the trusted Rust prepared contract remains the single WIT validator and
|
|
11
|
+
* always checks these exact bytes.
|
|
12
|
+
*/
|
|
13
|
+
import { failure, isDescriptor } from "../error.ts";
|
|
14
|
+
import type { ContractPort } from "./types.ts";
|
|
15
|
+
import { isInteger, type IntegerKind, type Shape } from "./wit-shape.ts";
|
|
16
|
+
|
|
17
|
+
/** Default ceiling for one captured value, matching the default interpreter packet bound. */
|
|
18
|
+
export const VALUE_LIMIT = 8 << 20;
|
|
19
|
+
/** Container nesting accepted before the Rust validator's own type-depth limit applies. */
|
|
20
|
+
export const VALUE_DEPTH = 64;
|
|
21
|
+
|
|
22
|
+
const issued = Symbol("tembra.encoded");
|
|
23
|
+
const quote = JSON.stringify;
|
|
24
|
+
const descriptor = Reflect.getOwnPropertyDescriptor;
|
|
25
|
+
const ownKeys = Reflect.ownKeys;
|
|
26
|
+
const prototypeOf = Reflect.getPrototypeOf;
|
|
27
|
+
const hasOwn = Object.hasOwn;
|
|
28
|
+
const isArray = Array.isArray;
|
|
29
|
+
const isView = ArrayBuffer.isView;
|
|
30
|
+
const objectPrototype = Object.prototype;
|
|
31
|
+
const arrayPrototype = Array.prototype;
|
|
32
|
+
// Intrinsic typed-array accessors cannot be shadowed by an instance's own properties.
|
|
33
|
+
const typedArray = prototypeOf(Uint8Array.prototype) as object;
|
|
34
|
+
const typedLength = descriptor(typedArray, "length")!.get as (this: unknown) => number;
|
|
35
|
+
const typedTag = descriptor(typedArray, Symbol.toStringTag)!.get as (
|
|
36
|
+
this: unknown,
|
|
37
|
+
) => string | undefined;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* JSON text captured by `encode`. The constructor refuses foreign callers, so raw strings cannot
|
|
41
|
+
* be spliced into interpreter packets without passing through this module.
|
|
42
|
+
*/
|
|
43
|
+
export class Encoded {
|
|
44
|
+
readonly #text: string;
|
|
45
|
+
|
|
46
|
+
/** Only this module can issue captured text. */
|
|
47
|
+
constructor(token: symbol, text: string) {
|
|
48
|
+
if (token !== issued) throw new TypeError("Encoded values are issued by the value codec");
|
|
49
|
+
this.#text = text;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Read captured text; the private-field access rejects forged instances. */
|
|
53
|
+
get text(): string {
|
|
54
|
+
return this.#text;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Refuse a value before any lossy representation is produced. */
|
|
59
|
+
function refused(reason: string): never {
|
|
60
|
+
throw failure(`Portable value rejected: ${reason}`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Write one finite number exactly as JSON would, refusing values JSON would change. */
|
|
64
|
+
function number(value: number): string {
|
|
65
|
+
if (value !== value || value === Infinity || value === -Infinity)
|
|
66
|
+
refused("non-finite numbers are outside the value profile");
|
|
67
|
+
if (value === 0 && 1 / value < 0) refused("negative zero is outside the value profile");
|
|
68
|
+
return "" + value;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The 64-bit element kind of a list shape, if any. */
|
|
72
|
+
function listKind(shape: Shape | undefined): IntegerKind | undefined {
|
|
73
|
+
return typeof shape === "object" && "list" in shape && typeof shape.list === "string"
|
|
74
|
+
? shape.list
|
|
75
|
+
: undefined;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Capture `value` once, bounded by UTF-16 length and container depth. `shape` (from the prepared
|
|
80
|
+
* signature) marks WIT `u64`/`s64` positions; without one, the walk is the untyped capture.
|
|
81
|
+
*/
|
|
82
|
+
export function encode(value: unknown, limit = VALUE_LIMIT, shape?: Shape): Encoded {
|
|
83
|
+
const ancestors: object[] = [];
|
|
84
|
+
let size = 0;
|
|
85
|
+
|
|
86
|
+
/** Account every emitted fragment against the bound before concatenation continues. */
|
|
87
|
+
const emit = (text: string): string => {
|
|
88
|
+
size += text.length;
|
|
89
|
+
if (size > limit) refused("value exceeds its size bound");
|
|
90
|
+
return text;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const visit = (value: unknown, shape: Shape | undefined): string => {
|
|
94
|
+
if (typeof shape === "string") {
|
|
95
|
+
// A WIT 64-bit position accepts only an in-range bigint primitive.
|
|
96
|
+
if (!isInteger(shape, value))
|
|
97
|
+
refused(
|
|
98
|
+
typeof value === "bigint"
|
|
99
|
+
? `${shape} value is out of range`
|
|
100
|
+
: `${shape} requires a bigint, not ${value === null ? "null" : typeof value}`,
|
|
101
|
+
);
|
|
102
|
+
return emit(`"${value}"`);
|
|
103
|
+
}
|
|
104
|
+
if (shape !== undefined && "option" in shape) {
|
|
105
|
+
if (value === null || value === undefined) return emit("null");
|
|
106
|
+
shape = shape.option;
|
|
107
|
+
if (typeof shape === "string") return visit(value, shape);
|
|
108
|
+
}
|
|
109
|
+
switch (typeof value) {
|
|
110
|
+
case "string":
|
|
111
|
+
return emit(quote(value));
|
|
112
|
+
case "number":
|
|
113
|
+
return emit(number(value));
|
|
114
|
+
case "boolean":
|
|
115
|
+
return emit(value ? "true" : "false");
|
|
116
|
+
case "undefined":
|
|
117
|
+
// The official bindings spell an absent option as `undefined`; JSON spells it `null`.
|
|
118
|
+
return emit("null");
|
|
119
|
+
case "bigint":
|
|
120
|
+
return refused("BigInt is portable only in a WIT u64/s64 position");
|
|
121
|
+
case "symbol":
|
|
122
|
+
case "function":
|
|
123
|
+
return refused(`${typeof value} values are not portable data`);
|
|
124
|
+
}
|
|
125
|
+
if (value === null) return emit("null");
|
|
126
|
+
const object = value as object;
|
|
127
|
+
if (ancestors.length >= VALUE_DEPTH) refused("value nesting exceeds its limit");
|
|
128
|
+
if (ancestors.includes(object)) refused("cyclic values are not portable");
|
|
129
|
+
ancestors.push(object);
|
|
130
|
+
try {
|
|
131
|
+
if (isView(object)) return typed(object, listKind(shape));
|
|
132
|
+
if (isArray(object)) return list(object as unknown[], shape);
|
|
133
|
+
return record(object, shape);
|
|
134
|
+
} finally {
|
|
135
|
+
ancestors.pop();
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Numeric typed arrays follow the official list binding; integer-indexed reads are fixed. A WIT
|
|
141
|
+
* `list<u64>` takes a `BigUint64Array` and `list<s64>` a `BigInt64Array`, each element written
|
|
142
|
+
* as canonical decimal text; 64-bit arrays are refused anywhere else.
|
|
143
|
+
*/
|
|
144
|
+
const typed = (view: ArrayBufferView, kind: IntegerKind | undefined): string => {
|
|
145
|
+
const tag = typedTag.call(view);
|
|
146
|
+
if (tag === undefined) refused("DataView is not a portable list");
|
|
147
|
+
const wide = tag === "BigInt64Array" || tag === "BigUint64Array";
|
|
148
|
+
if (kind !== undefined && tag !== (kind === "u64" ? "BigUint64Array" : "BigInt64Array"))
|
|
149
|
+
refused(`list<${kind}> requires a ${kind === "u64" ? "BigUint64Array" : "BigInt64Array"}`);
|
|
150
|
+
if (kind === undefined && wide) refused("64-bit lists are portable only as WIT list<u64/s64>");
|
|
151
|
+
const elements = view as unknown as ArrayLike<number | bigint>;
|
|
152
|
+
const length = typedLength.call(view);
|
|
153
|
+
let text = emit("[");
|
|
154
|
+
for (let index = 0; index < length; index++) {
|
|
155
|
+
if (index) text += emit(",");
|
|
156
|
+
const element = elements[index]!;
|
|
157
|
+
text += emit(typeof element === "bigint" ? `"${element}"` : number(element));
|
|
158
|
+
}
|
|
159
|
+
return text + emit("]");
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/** Read each element once; a hole is refused instead of becoming `null`. */
|
|
163
|
+
const list = (array: unknown[], shape: Shape | undefined): string => {
|
|
164
|
+
const length = array.length;
|
|
165
|
+
if (!Number.isSafeInteger(length) || length < 0 || length > limit - size)
|
|
166
|
+
refused("list length exceeds its size bound");
|
|
167
|
+
const items = typeof shape === "object" && "items" in shape ? shape.items : undefined;
|
|
168
|
+
if (items && items.length !== length) refused("tuple length differs from WIT");
|
|
169
|
+
const item = typeof shape === "object" && "list" in shape ? shape.list : undefined;
|
|
170
|
+
let text = emit("[");
|
|
171
|
+
for (let index = 0; index < length; index++) {
|
|
172
|
+
if (index) text += emit(",");
|
|
173
|
+
const element = descriptor(array, "" + index);
|
|
174
|
+
if (!element) refused("sparse arrays are not portable");
|
|
175
|
+
if (!element.enumerable || !hasOwn(element, "value"))
|
|
176
|
+
refused("array accessors and non-enumerable elements are not portable");
|
|
177
|
+
text += visit(element.value, items ? items[index] : item);
|
|
178
|
+
}
|
|
179
|
+
if (prototypeOf(array) !== arrayPrototype) refused("array subclasses are not portable data");
|
|
180
|
+
if (ownKeys(array).length !== length + 1)
|
|
181
|
+
refused("extra array properties are not portable data");
|
|
182
|
+
return text + emit("]");
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Read each own data property once; accessors, symbols and hidden fields are refused. With a
|
|
187
|
+
* record shape, a key WIT does not declare is refused. With a variant or result shape, the at
|
|
188
|
+
* most two descriptors are read first, so `tag` selects the type of `val` in any key order.
|
|
189
|
+
*/
|
|
190
|
+
const record = (object: object, shape: Shape | undefined): string => {
|
|
191
|
+
const prototype = prototypeOf(object);
|
|
192
|
+
if (prototype !== objectPrototype && prototype !== null)
|
|
193
|
+
refused("only plain objects, arrays and numeric typed arrays are portable");
|
|
194
|
+
const fields = typeof shape === "object" && "fields" in shape ? shape.fields : undefined;
|
|
195
|
+
const cases = typeof shape === "object" && "cases" in shape ? shape.cases : undefined;
|
|
196
|
+
const property = (key: string | symbol): unknown => {
|
|
197
|
+
if (typeof key !== "string") refused("symbol-keyed properties are not portable");
|
|
198
|
+
const found = descriptor(object, key);
|
|
199
|
+
if (found === undefined || !found.enumerable || !hasOwn(found, "value"))
|
|
200
|
+
refused("accessors and non-enumerable properties are not portable");
|
|
201
|
+
return found.value;
|
|
202
|
+
};
|
|
203
|
+
let text = emit("{");
|
|
204
|
+
if (cases) {
|
|
205
|
+
const keys = ownKeys(object);
|
|
206
|
+
if (keys.length > 2) refused("WIT tagged values have only tag and val");
|
|
207
|
+
const entries = keys.map((key) => [key as string, property(key)] as const);
|
|
208
|
+
const tag = entries.find(([key]) => key === "tag")?.[1];
|
|
209
|
+
if (typeof tag !== "string" || !cases.has(tag)) refused("WIT tagged value needs a known tag");
|
|
210
|
+
entries.forEach(([key, value], index) => {
|
|
211
|
+
const type = key === "val" ? cases.get(tag) : undefined;
|
|
212
|
+
text += emit(index ? "," : "") + emit(quote(key)) + emit(":") + visit(value, type);
|
|
213
|
+
});
|
|
214
|
+
return text + emit("}");
|
|
215
|
+
}
|
|
216
|
+
let first = true;
|
|
217
|
+
for (const key of ownKeys(object)) {
|
|
218
|
+
const value = property(key);
|
|
219
|
+
if (fields && !fields.has(key as string))
|
|
220
|
+
refused(`record field ${quote(key)} is not declared by WIT`);
|
|
221
|
+
text +=
|
|
222
|
+
emit(first ? "" : ",") +
|
|
223
|
+
emit(quote(key)) +
|
|
224
|
+
emit(":") +
|
|
225
|
+
visit(value, fields?.get(key as string));
|
|
226
|
+
first = false;
|
|
227
|
+
}
|
|
228
|
+
return text + emit("}");
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
let text: string;
|
|
232
|
+
try {
|
|
233
|
+
text = visit(value, shape);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
// Revoked proxies and throwing traps surface as ordinary value rejections.
|
|
236
|
+
throw failure(error);
|
|
237
|
+
}
|
|
238
|
+
return new Encoded(issued, text);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** The prepared validator's exact success envelope; any other answer is decoded as an error. */
|
|
242
|
+
const ACCEPTED = '{"ok":null}';
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Check captured bytes through a slot bound at installation. The same `Encoded` instance is then
|
|
246
|
+
* the only value that may be spliced into a packet, so no second serialization can diverge.
|
|
247
|
+
*/
|
|
248
|
+
export function check(
|
|
249
|
+
contract: ContractPort,
|
|
250
|
+
slot: number,
|
|
251
|
+
arguments_: boolean,
|
|
252
|
+
value: Encoded,
|
|
253
|
+
): Encoded {
|
|
254
|
+
const answer = contract.validate(slot, arguments_, value.text);
|
|
255
|
+
if (answer === ACCEPTED) return value;
|
|
256
|
+
let error: unknown;
|
|
257
|
+
try {
|
|
258
|
+
error = (JSON.parse(answer) as { error?: unknown }).error;
|
|
259
|
+
} catch {
|
|
260
|
+
error = undefined;
|
|
261
|
+
}
|
|
262
|
+
throw failure(error ?? "Interpreter value validation failed");
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Check the guest's original bytes before decoding them into the outer JavaScript heap. */
|
|
266
|
+
export function checkedResult(contract: ContractPort, slot: number, text: string): Encoded {
|
|
267
|
+
return check(contract, slot, false, new Encoded(issued, text));
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Host replies preserve an already checked capture rather than decoding and serializing it. */
|
|
271
|
+
export function reply(value: unknown): string {
|
|
272
|
+
return value instanceof Encoded ? value.text : encode(value ?? null).text;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* A host refusal as the native worker reads it: a structured error with its code and reason, which
|
|
277
|
+
* the guest's request answers; any other failure as its text, which the worker answers as
|
|
278
|
+
* `invalid/platform_reply`, the host refusing the request itself.
|
|
279
|
+
*/
|
|
280
|
+
export function refusal(error: unknown): string {
|
|
281
|
+
if (!isDescriptor(error))
|
|
282
|
+
return JSON.stringify({ error: error instanceof Error ? error.message : String(error) });
|
|
283
|
+
const { code, reason, message } = error;
|
|
284
|
+
return JSON.stringify({ error: { code, reason, message } });
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Build a guest packet from fixed control fields and one captured value. Control values are
|
|
289
|
+
* primitives encoded by the platform JSON writer; the value is spliced only from `Encoded`.
|
|
290
|
+
*/
|
|
291
|
+
export function packet(
|
|
292
|
+
control: Readonly<Record<string, string | number | null>>,
|
|
293
|
+
field: string,
|
|
294
|
+
value: Encoded,
|
|
295
|
+
): string {
|
|
296
|
+
const head = quote(control);
|
|
297
|
+
return `${head.slice(0, -1)}${head.length > 2 ? "," : ""}${quote(field)}:${value.text}}`;
|
|
298
|
+
}
|