@syntropika/tembra-sdk 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +47 -2
- package/dist/authoring/declaration.d.ts +48 -0
- package/dist/authoring/hooks.d.ts +11 -0
- package/dist/authoring/orb.d.ts +3 -0
- package/dist/authoring/service-identities.d.ts +7 -0
- package/dist/authoring/services.d.ts +8 -0
- package/dist/authoring/types.d.ts +181 -0
- package/dist/bridge/identifiers.d.ts +207 -0
- package/dist/bridge/kernel.d.ts +117 -0
- package/dist/bridge/protocol.d.ts +181 -0
- package/dist/browser.d.ts +21 -0
- package/dist/browser.js +3335 -0
- package/dist/codec.d.ts +1 -0
- package/dist/codecs/json.d.ts +13 -0
- package/dist/codecs/msgpack.d.ts +3 -0
- package/dist/context-key.d.ts +35 -0
- package/dist/coordinator.d.ts +1 -0
- package/dist/coordinator.js +543 -0
- package/dist/embedded.d.ts +1 -0
- package/dist/embedded.js +1 -0
- package/dist/error.d.ts +13 -0
- package/dist/errors.d.ts +122 -0
- package/dist/hooks.d.ts +1 -0
- package/dist/host.d.ts +98 -0
- package/dist/host.js +3278 -0
- package/dist/identifiers.d.ts +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +864 -0
- package/dist/infrastructure/coordinator.d.ts +13 -0
- package/dist/infrastructure/manager.d.ts +23 -0
- package/dist/infrastructure/rpc/channel.d.ts +55 -0
- package/dist/infrastructure/rpc/client.d.ts +20 -0
- package/dist/infrastructure/rpc/server.d.ts +10 -0
- package/dist/infrastructure/rpc/state.d.ts +16 -0
- package/dist/kernel.d.ts +1 -0
- package/dist/manager.d.ts +1 -0
- package/dist/manager.js +390 -0
- package/dist/msgpack.d.ts +1 -0
- package/dist/msgpack.js +635 -0
- package/dist/node.d.ts +14 -0
- package/dist/node.js +3336 -0
- package/dist/orb.d.ts +1 -0
- package/dist/protocol.d.ts +1 -0
- package/dist/rpc.d.ts +3 -0
- package/dist/rpc.js +1091 -0
- package/dist/runtime/activities.d.ts +30 -0
- package/dist/runtime/calls.d.ts +22 -0
- package/dist/runtime/context.d.ts +38 -0
- package/dist/runtime/declaration.d.ts +1 -0
- package/dist/runtime/lifecycle.d.ts +28 -0
- package/dist/runtime/orbs.d.ts +39 -0
- package/dist/runtime/programs.d.ts +31 -0
- package/dist/runtime/records.d.ts +107 -0
- package/dist/runtime/references.d.ts +38 -0
- package/dist/runtime/reload.d.ts +17 -0
- package/dist/runtime/resources.d.ts +24 -0
- package/dist/runtime/scopes.d.ts +35 -0
- package/dist/runtime/session.d.ts +69 -0
- package/dist/state/binding.d.ts +28 -0
- package/dist/state/selection.d.ts +21 -0
- package/dist/state/types.d.ts +35 -0
- package/dist/state.d.ts +2 -0
- package/dist/telemetry.d.ts +23 -0
- package/dist/telemetry.js +27 -0
- package/dist/tooling/build.d.ts +3 -0
- package/dist/tooling/index.d.ts +2 -0
- package/dist/tooling/index.js +181 -0
- package/dist/tooling/resolver.d.ts +5 -0
- package/dist/tooling/typecheck.d.ts +2 -0
- package/dist/tooling/types.d.ts +29 -0
- package/dist/types.d.ts +1 -0
- package/dist/values.d.ts +23 -0
- package/package.json +103 -4
- package/src/authoring/declaration.ts +237 -0
- package/src/authoring/hooks.ts +101 -0
- package/src/authoring/orb.ts +88 -0
- package/src/authoring/service-identities.ts +20 -0
- package/src/authoring/services.ts +46 -0
- package/src/authoring/types.ts +256 -0
- package/src/bridge/identifiers.ts +212 -0
- package/src/bridge/kernel.ts +117 -0
- package/src/bridge/protocol.ts +193 -0
- package/src/browser.ts +59 -0
- package/src/codec.ts +1 -0
- package/src/codecs/json.ts +147 -0
- package/src/codecs/msgpack.ts +26 -0
- package/src/context-key.ts +94 -0
- package/src/coordinator.ts +1 -0
- package/src/embedded.ts +293 -0
- package/src/error.ts +50 -0
- package/src/errors.ts +237 -0
- package/src/hooks.ts +1 -0
- package/src/host.ts +173 -0
- package/src/identifiers.ts +1 -0
- package/src/index.ts +22 -0
- package/src/infrastructure/coordinator.ts +76 -0
- package/src/infrastructure/manager.ts +77 -0
- package/src/infrastructure/rpc/channel.ts +107 -0
- package/src/infrastructure/rpc/client.ts +216 -0
- package/src/infrastructure/rpc/server.ts +201 -0
- package/src/infrastructure/rpc/state.ts +70 -0
- package/src/kernel.ts +1 -0
- package/src/manager.ts +1 -0
- package/src/msgpack.ts +1 -0
- package/src/node.ts +53 -0
- package/src/orb.ts +1 -0
- package/src/protocol.ts +1 -0
- package/src/rpc.ts +3 -0
- package/src/runtime/activities.ts +197 -0
- package/src/runtime/calls.ts +165 -0
- package/src/runtime/context.ts +128 -0
- package/src/runtime/declaration.ts +1 -0
- package/src/runtime/lifecycle.ts +227 -0
- package/src/runtime/orbs.ts +292 -0
- package/src/runtime/programs.ts +274 -0
- package/src/runtime/records.ts +127 -0
- package/src/runtime/references.ts +406 -0
- package/src/runtime/reload.ts +161 -0
- package/src/runtime/resources.ts +157 -0
- package/src/runtime/scopes.ts +210 -0
- package/src/runtime/session.ts +181 -0
- package/src/state/binding.ts +157 -0
- package/src/state/selection.ts +122 -0
- package/src/state/types.ts +47 -0
- package/src/state.ts +2 -0
- package/src/telemetry.ts +45 -0
- package/src/tooling/build.ts +83 -0
- package/src/tooling/index.ts +8 -0
- package/src/tooling/resolver.ts +95 -0
- package/src/tooling/typecheck.ts +32 -0
- package/src/tooling/types.ts +32 -0
- package/src/types.ts +1 -0
- package/src/values.ts +85 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { CodecId, CodecTag } from "../bridge/protocol.ts";
|
|
2
|
+
import { Errors } from "../errors.ts";
|
|
3
|
+
|
|
4
|
+
import { refuse } from "../error.ts";
|
|
5
|
+
|
|
6
|
+
/** Selected once by infrastructure. Local calls and local state reads do not use a codec. */
|
|
7
|
+
export interface Codec {
|
|
8
|
+
readonly id: string;
|
|
9
|
+
/** Encode a portable value using the host's wire contract. */
|
|
10
|
+
serialize(value: unknown): Uint8Array;
|
|
11
|
+
/** Decode bytes using the same wire contract. */
|
|
12
|
+
deserialize(bytes: Uint8Array): unknown;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const marker = "$tembra";
|
|
16
|
+
|
|
17
|
+
/** Replace non-JSON scalars with explicit tagged values. */
|
|
18
|
+
function pack(value: unknown, visiting: WeakSet<object>): unknown {
|
|
19
|
+
if (typeof value === "bigint") return { [marker]: [CodecTag.Bigint, value.toString()] };
|
|
20
|
+
if (value instanceof Uint8Array) return { [marker]: [CodecTag.Bytes, [...value]] };
|
|
21
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
22
|
+
if (typeof value === "number") {
|
|
23
|
+
if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value)))
|
|
24
|
+
refuse(Errors.Invalid.JsonNumber, "Use BigInt for integers outside the safe Number range");
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
if (typeof value !== "object")
|
|
28
|
+
refuse(Errors.Invalid.JsonValue, "This JSON codec requires explicit portable values");
|
|
29
|
+
if (visiting.has(value)) refuse(Errors.Invalid.JsonCycle);
|
|
30
|
+
const prototype = Object.getPrototypeOf(value);
|
|
31
|
+
if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
|
|
32
|
+
refuse(Errors.Invalid.JsonType, "Supply a codec for custom object types");
|
|
33
|
+
visiting.add(value);
|
|
34
|
+
try {
|
|
35
|
+
if (Array.isArray(value)) return Array.from(value, (child) => pack(child, visiting));
|
|
36
|
+
const entries = Reflect.ownKeys(value).map((key) => {
|
|
37
|
+
if (typeof key !== "string") refuse(Errors.Invalid.JsonSymbol);
|
|
38
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
|
|
39
|
+
if (!Object.hasOwn(descriptor, "value")) refuse(Errors.Invalid.JsonAccessor);
|
|
40
|
+
return [key, pack(descriptor.value, visiting)];
|
|
41
|
+
});
|
|
42
|
+
return Object.hasOwn(value, marker)
|
|
43
|
+
? { [marker]: [CodecTag.Object, entries] }
|
|
44
|
+
: Object.fromEntries(entries);
|
|
45
|
+
} finally {
|
|
46
|
+
visiting.delete(value);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Restore tagged values without losing integer precision. */
|
|
51
|
+
function unpack(value: unknown): unknown {
|
|
52
|
+
if (value === null || typeof value !== "object") {
|
|
53
|
+
if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value))
|
|
54
|
+
refuse(Errors.Invalid.JsonNumber);
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
if (Array.isArray(value)) return value.map(unpack);
|
|
58
|
+
if (Object.hasOwn(value, marker)) {
|
|
59
|
+
const tag = (value as Record<string, unknown>)[marker];
|
|
60
|
+
if (Object.keys(value).length !== 1 || !Array.isArray(tag) || tag.length !== 2)
|
|
61
|
+
refuse(Errors.Invalid.JsonTag);
|
|
62
|
+
const [type, data] = tag;
|
|
63
|
+
if (type === CodecTag.Bigint && typeof data === "string" && /^-?(0|[1-9]\d*)$/.test(data))
|
|
64
|
+
return BigInt(data);
|
|
65
|
+
if (
|
|
66
|
+
type === CodecTag.Bytes &&
|
|
67
|
+
Array.isArray(data) &&
|
|
68
|
+
data.every((v) => Number.isInteger(v) && v >= 0 && v <= 255)
|
|
69
|
+
)
|
|
70
|
+
return Uint8Array.from(data);
|
|
71
|
+
if (type === CodecTag.Object && Array.isArray(data)) {
|
|
72
|
+
if (
|
|
73
|
+
!data.every(
|
|
74
|
+
(entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string",
|
|
75
|
+
)
|
|
76
|
+
)
|
|
77
|
+
refuse(Errors.Invalid.JsonTag);
|
|
78
|
+
return Object.fromEntries(data.map(([key, child]) => [key, unpack(child)]));
|
|
79
|
+
}
|
|
80
|
+
refuse(Errors.Invalid.JsonTag, "Unknown or malformed portable type tag");
|
|
81
|
+
}
|
|
82
|
+
return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, unpack(child)]));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Also works in a minimal embedded runtime without Web APIs. */
|
|
86
|
+
export function utf8(text: string): Uint8Array {
|
|
87
|
+
const output: number[] = [];
|
|
88
|
+
for (const character of text) {
|
|
89
|
+
let point = character.codePointAt(0)!;
|
|
90
|
+
if (point >= 0xd800 && point <= 0xdfff) point = 0xfffd;
|
|
91
|
+
if (point < 0x80) output.push(point);
|
|
92
|
+
else if (point < 0x800) output.push(0xc0 | (point >> 6), 0x80 | (point & 63));
|
|
93
|
+
else if (point < 0x10000)
|
|
94
|
+
output.push(0xe0 | (point >> 12), 0x80 | ((point >> 6) & 63), 0x80 | (point & 63));
|
|
95
|
+
else
|
|
96
|
+
output.push(
|
|
97
|
+
0xf0 | (point >> 18),
|
|
98
|
+
0x80 | ((point >> 12) & 63),
|
|
99
|
+
0x80 | ((point >> 6) & 63),
|
|
100
|
+
0x80 | (point & 63),
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
return Uint8Array.from(output);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Decode UTF-8 bytes into a string. */
|
|
107
|
+
export function text(bytes: Uint8Array): string {
|
|
108
|
+
const output: string[] = [];
|
|
109
|
+
for (let index = 0; index < bytes.length;) {
|
|
110
|
+
const first = bytes[index++]!;
|
|
111
|
+
if (first < 0x80) {
|
|
112
|
+
output.push(String.fromCharCode(first));
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const count =
|
|
116
|
+
first >= 0xc2 && first <= 0xdf
|
|
117
|
+
? 1
|
|
118
|
+
: first >= 0xe0 && first <= 0xef
|
|
119
|
+
? 2
|
|
120
|
+
: first >= 0xf0 && first <= 0xf4
|
|
121
|
+
? 3
|
|
122
|
+
: -1;
|
|
123
|
+
if (count < 0 || index + count > bytes.length) refuse(Errors.Invalid.Utf8);
|
|
124
|
+
let point = first & (0x7f >> (count + 1));
|
|
125
|
+
for (let offset = 0; offset < count; offset++) {
|
|
126
|
+
const next = bytes[index++]!;
|
|
127
|
+
if ((next & 0xc0) !== 0x80) refuse(Errors.Invalid.Utf8);
|
|
128
|
+
point = (point << 6) | (next & 63);
|
|
129
|
+
}
|
|
130
|
+
if (
|
|
131
|
+
point < [0, 0x80, 0x800, 0x10000][count]! ||
|
|
132
|
+
point > 0x10ffff ||
|
|
133
|
+
(point >= 0xd800 && point <= 0xdfff)
|
|
134
|
+
)
|
|
135
|
+
refuse(Errors.Invalid.Utf8);
|
|
136
|
+
output.push(String.fromCodePoint(point));
|
|
137
|
+
}
|
|
138
|
+
return output.join("");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export const jsonCodec: Codec = Object.freeze({
|
|
142
|
+
id: CodecId.Json,
|
|
143
|
+
/** Encode supported portable scalars without losing integer precision. */
|
|
144
|
+
serialize: (value: unknown) => utf8(JSON.stringify(pack(value, new WeakSet()))),
|
|
145
|
+
/** Restore explicit portable tags from strict UTF-8 JSON. */
|
|
146
|
+
deserialize: (bytes: Uint8Array) => unpack(JSON.parse(text(bytes))),
|
|
147
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { decode, encode, ExtensionCodec } from "@msgpack/msgpack";
|
|
2
|
+
import { CodecId } from "../bridge/protocol.ts";
|
|
3
|
+
import type { Codec } from "./json.ts";
|
|
4
|
+
import { text, utf8 } from "./json.ts";
|
|
5
|
+
|
|
6
|
+
const extensions = new ExtensionCodec();
|
|
7
|
+
extensions.register({
|
|
8
|
+
type: 1,
|
|
9
|
+
/** Encode arbitrary-size integers as decimal UTF-8 text. */
|
|
10
|
+
encode(value) {
|
|
11
|
+
return typeof value === "bigint" ? utf8(value.toString()) : null;
|
|
12
|
+
},
|
|
13
|
+
/** Restore a BigInt without passing through a floating-point number. */
|
|
14
|
+
decode(bytes) {
|
|
15
|
+
return BigInt(text(bytes));
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
/** Numbers remain Numbers; extension 1 preserves arbitrary BigInts independently of integer size. */
|
|
20
|
+
export const messagePackCodec: Codec = Object.freeze({
|
|
21
|
+
id: CodecId.MessagePack,
|
|
22
|
+
/** Encode portable data with the shared BigInt extension. */
|
|
23
|
+
serialize: (value: unknown) => encode(value, { extensionCodec: extensions }),
|
|
24
|
+
/** Restore portable data with the matching extension codec. */
|
|
25
|
+
deserialize: (bytes: Uint8Array) => decode(bytes, { extensionCodec: extensions }),
|
|
26
|
+
});
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/** Stable scalar keys shared across bundles and languages. */
|
|
2
|
+
import type { Context } from "./runtime/context.ts";
|
|
3
|
+
import { KernelOp } from "./bridge/protocol.ts";
|
|
4
|
+
|
|
5
|
+
export const ContextKind = Object.freeze({
|
|
6
|
+
Text: "text",
|
|
7
|
+
Integer: "integer",
|
|
8
|
+
Boolean: "boolean",
|
|
9
|
+
Opaque: "opaque",
|
|
10
|
+
} as const);
|
|
11
|
+
export type ContextKind = (typeof ContextKind)[keyof typeof ContextKind];
|
|
12
|
+
/** An owner-issued reference. Its token does not retain the source frame. */
|
|
13
|
+
export interface OpaqueContextValue {
|
|
14
|
+
readonly opaque: true;
|
|
15
|
+
}
|
|
16
|
+
export class ContextKey<T> {
|
|
17
|
+
declare private readonly type: T;
|
|
18
|
+
|
|
19
|
+
/** Retain a frozen key contract; Rust validates its use. */
|
|
20
|
+
private constructor(
|
|
21
|
+
readonly name: string,
|
|
22
|
+
readonly version: number,
|
|
23
|
+
readonly kind: ContextKind,
|
|
24
|
+
) {
|
|
25
|
+
Object.freeze(this);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Declare a text binding with stable identity. */
|
|
29
|
+
static text(name: string, version = 1) {
|
|
30
|
+
return new ContextKey<string>(name, version, ContextKind.Text);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Declare an integer binding with stable identity. */
|
|
34
|
+
static integer(name: string, version = 1) {
|
|
35
|
+
return new ContextKey<number>(name, version, ContextKind.Integer);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Declare a boolean binding with stable identity. */
|
|
39
|
+
static boolean(name: string, version = 1) {
|
|
40
|
+
return new ContextKey<boolean>(name, version, ContextKind.Boolean);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Declare an opaque binding with stable identity. */
|
|
44
|
+
static opaque(name: string, version = 1) {
|
|
45
|
+
return new ContextKey<OpaqueContextValue>(name, version, ContextKind.Opaque);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Resolve a token issued by the owner in this host and root. */
|
|
49
|
+
source(value: T, ctx: Context): number | undefined {
|
|
50
|
+
if (this.kind !== ContextKind.Opaque) return undefined;
|
|
51
|
+
const token =
|
|
52
|
+
typeof value === "object" && value !== null
|
|
53
|
+
? ctx.session.contextTokens.get(value)
|
|
54
|
+
: undefined;
|
|
55
|
+
if (!token || token.root !== ctx.root)
|
|
56
|
+
throw new TypeError("An owner-issued opaque reference from this host and root is required");
|
|
57
|
+
return token.source;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Read metadata or wrap an owner-issued local reference. */
|
|
62
|
+
export function readContextValue<T>(
|
|
63
|
+
ctx: Context,
|
|
64
|
+
key: ContextKey<T>,
|
|
65
|
+
frame: number,
|
|
66
|
+
): T | undefined {
|
|
67
|
+
const entry = ctx.session.kernel.command<{
|
|
68
|
+
kind: ContextKind;
|
|
69
|
+
value?: T;
|
|
70
|
+
source?: number;
|
|
71
|
+
} | null>(KernelOp.ContextValue, {
|
|
72
|
+
root: ctx.root,
|
|
73
|
+
context: frame,
|
|
74
|
+
call: ctx.invocation?.id,
|
|
75
|
+
key,
|
|
76
|
+
});
|
|
77
|
+
if (!entry) return undefined;
|
|
78
|
+
if (entry.kind !== ContextKind.Opaque) return entry.value;
|
|
79
|
+
const token = Object.freeze({ opaque: true as const });
|
|
80
|
+
ctx.session.contextTokens.set(token, { root: ctx.root, source: entry.source! });
|
|
81
|
+
// SAFETY: Rust matched the opaque binding to the supplied typed key.
|
|
82
|
+
return token as T;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Read an owner-issued reference from a live source frame. */
|
|
86
|
+
export function opaqueFrom(
|
|
87
|
+
ctx: Context,
|
|
88
|
+
key: ContextKey<OpaqueContextValue>,
|
|
89
|
+
issuedFrame: number,
|
|
90
|
+
): OpaqueContextValue {
|
|
91
|
+
const token = readContextValue(ctx, key, issuedFrame);
|
|
92
|
+
if (!token) throw new TypeError("The owner did not issue a reference");
|
|
93
|
+
return token;
|
|
94
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./infrastructure/coordinator.ts";
|
package/src/embedded.ts
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import type { HostOptions } from "./authoring/types.ts";
|
|
2
|
+
import {
|
|
3
|
+
Code,
|
|
4
|
+
HookCapability,
|
|
5
|
+
Lifetime,
|
|
6
|
+
Reason,
|
|
7
|
+
ReloadStatus,
|
|
8
|
+
Status,
|
|
9
|
+
} from "./bridge/identifiers.ts";
|
|
10
|
+
import { jsonCodec } from "./codecs/json.ts";
|
|
11
|
+
import { failure, TembraError } from "./error.ts";
|
|
12
|
+
import { ContextKey, ContextKind, opaqueFrom } from "./context-key.ts";
|
|
13
|
+
import { Errors } from "./errors.ts";
|
|
14
|
+
import { Host } from "./host.ts";
|
|
15
|
+
import { Context } from "./runtime/context.ts";
|
|
16
|
+
import { KernelOp } from "./bridge/protocol.ts";
|
|
17
|
+
import type { Invocation } from "./bridge/kernel.ts";
|
|
18
|
+
|
|
19
|
+
declare const Deno: {
|
|
20
|
+
core: {
|
|
21
|
+
ops: Record<string, (...args: any[]) => any>;
|
|
22
|
+
unrefOpPromise(promise: Promise<unknown>): void;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
const ops = Deno.core.ops;
|
|
26
|
+
const globals = globalThis as any;
|
|
27
|
+
|
|
28
|
+
// Embedded V8 has no browser or Node dependency. Scheduling belongs to this adapter.
|
|
29
|
+
globals.queueMicrotask ??= (callback: () => void) => Promise.resolve().then(callback);
|
|
30
|
+
globals.performance ??= {
|
|
31
|
+
/** Use the Rust runtime's monotonic clock. */
|
|
32
|
+
now: () => ops.op_tembra_now!(),
|
|
33
|
+
};
|
|
34
|
+
globals.AbortController ??= class {
|
|
35
|
+
signal = {
|
|
36
|
+
aborted: false,
|
|
37
|
+
reason: undefined as unknown,
|
|
38
|
+
listeners: new Set<any>(),
|
|
39
|
+
/** Retain a cancellation listener until it is removed or fired. */
|
|
40
|
+
addEventListener(_type: string, callback: any) {
|
|
41
|
+
this.listeners.add(callback);
|
|
42
|
+
},
|
|
43
|
+
/** Release a cancellation listener without invoking it. */
|
|
44
|
+
removeEventListener(_type: string, callback: any) {
|
|
45
|
+
this.listeners.delete(callback);
|
|
46
|
+
},
|
|
47
|
+
/** Reject work after cancellation has been signalled. */
|
|
48
|
+
throwIfAborted() {
|
|
49
|
+
if (this.aborted) throw this.reason;
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** Signal cancellation once without waiting for physical work. */
|
|
54
|
+
abort(reason: unknown = new Error("Aborted")) {
|
|
55
|
+
if (this.signal.aborted) return;
|
|
56
|
+
this.signal.aborted = true;
|
|
57
|
+
this.signal.reason = reason;
|
|
58
|
+
for (const callback of [...this.signal.listeners]) callback();
|
|
59
|
+
this.signal.listeners.clear();
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
let nextTimer = 0;
|
|
63
|
+
const timers = new Set<number>();
|
|
64
|
+
globals.setTimeout ??= (callback: (...args: unknown[]) => void, delay = 0, ...args: unknown[]) => {
|
|
65
|
+
const id = ++nextTimer;
|
|
66
|
+
timers.add(id);
|
|
67
|
+
void ops.op_tembra_sleep!(id, Math.max(0, Math.min(0x7fff_ffff, delay))).then(() => {
|
|
68
|
+
if (timers.delete(id)) callback(...args);
|
|
69
|
+
});
|
|
70
|
+
return id;
|
|
71
|
+
};
|
|
72
|
+
globals.clearTimeout ??= (id: number) => {
|
|
73
|
+
if (timers.delete(id)) ops.op_tembra_clear_timer!(id);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/** The same JS adapter used by Node and browsers, backed by injected Rust operations. */
|
|
77
|
+
function createHost(options: Omit<HostOptions, "kernel" | "native"> = {}): Host {
|
|
78
|
+
const codec = options.serialization ?? jsonCodec;
|
|
79
|
+
if (codec.id !== ops.op_tembra_codec!())
|
|
80
|
+
throw new TembraError(Errors.Conflict.Codec, "The Rust and JS host codecs must agree");
|
|
81
|
+
/** Decode native callback results with the agreed host codec. */
|
|
82
|
+
function answer(bytes: Uint8Array): any {
|
|
83
|
+
const envelope = codec.deserialize(bytes) as any;
|
|
84
|
+
if (envelope.error) throw new TembraError(envelope.error);
|
|
85
|
+
return envelope.ok;
|
|
86
|
+
}
|
|
87
|
+
const cooperative = ops.op_tembra_driver_enabled?.() ?? false;
|
|
88
|
+
const pending = new Map<
|
|
89
|
+
number,
|
|
90
|
+
{ resolve(value: unknown): void; reject(error: unknown): void }
|
|
91
|
+
>();
|
|
92
|
+
globals.__tembraDeliver = (batch: [number, Uint8Array | string, boolean][]) => {
|
|
93
|
+
for (const [id, payload, success] of batch) {
|
|
94
|
+
const waiter = pending.get(id);
|
|
95
|
+
if (!waiter) throw new Error("unknown native completion");
|
|
96
|
+
pending.delete(id);
|
|
97
|
+
try {
|
|
98
|
+
if (!success) throw new Error(payload as string);
|
|
99
|
+
waiter.resolve(answer(payload as Uint8Array));
|
|
100
|
+
} catch (error) {
|
|
101
|
+
waiter.reject(error);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
function submit(operation: string, payload: Uint8Array): Promise<any> {
|
|
106
|
+
const id = ops.op_tembra_submit!(operation, payload);
|
|
107
|
+
return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
|
|
108
|
+
}
|
|
109
|
+
const host = new Host({
|
|
110
|
+
...options,
|
|
111
|
+
clockOrigin: 0,
|
|
112
|
+
kernel: {
|
|
113
|
+
/** Exchange kernel metadata without encoding JS payload values. */
|
|
114
|
+
request: (metadata) => ops.op_tembra_kernel!(metadata),
|
|
115
|
+
},
|
|
116
|
+
native: {
|
|
117
|
+
...(cooperative
|
|
118
|
+
? {
|
|
119
|
+
admit: (reference: number, method: string, ctx: Context) => {
|
|
120
|
+
const result = JSON.parse(
|
|
121
|
+
ops.op_tembra_admit!(
|
|
122
|
+
JSON.stringify({
|
|
123
|
+
reference,
|
|
124
|
+
method,
|
|
125
|
+
root: ctx.root,
|
|
126
|
+
context: ctx.frame,
|
|
127
|
+
parent: ctx.invocation?.id,
|
|
128
|
+
}),
|
|
129
|
+
),
|
|
130
|
+
) as any;
|
|
131
|
+
if (result.error) throw new TembraError(result.error);
|
|
132
|
+
return result.ok;
|
|
133
|
+
},
|
|
134
|
+
finish: (call: number, now: number) => {
|
|
135
|
+
const result = JSON.parse(ops.op_tembra_finish!(call, String(now))) as any;
|
|
136
|
+
if (result.error) throw new TembraError(result.error);
|
|
137
|
+
return result.ok;
|
|
138
|
+
},
|
|
139
|
+
}
|
|
140
|
+
: {}),
|
|
141
|
+
rootEnded: (root) => ops.op_tembra_end_context!(root),
|
|
142
|
+
access: (orb, service, principal) =>
|
|
143
|
+
JSON.parse(ops.op_tembra_access!(orb, service, principal)) ?? undefined,
|
|
144
|
+
settled: () => ops.op_tembra_settled!(),
|
|
145
|
+
notify: (action) => ops.op_tembra_notify!(JSON.stringify(action)),
|
|
146
|
+
hasContribution: (operation) => ops.op_tembra_has_contribution?.(operation) ?? false,
|
|
147
|
+
contribute: async (operation, ctx, input) => {
|
|
148
|
+
const result = answer(
|
|
149
|
+
await ops.op_tembra_native!(
|
|
150
|
+
"contribute",
|
|
151
|
+
codec.serialize({
|
|
152
|
+
operation,
|
|
153
|
+
root: ctx.root,
|
|
154
|
+
frame: ctx.frame,
|
|
155
|
+
...(input === undefined ? {} : { input }),
|
|
156
|
+
}),
|
|
157
|
+
),
|
|
158
|
+
);
|
|
159
|
+
return result.value;
|
|
160
|
+
},
|
|
161
|
+
/** Check whether this realm must delegate the orb to Rust. */
|
|
162
|
+
hasOrb: (id) => ops.op_tembra_has_orb!(id),
|
|
163
|
+
/** Declare native scopes before the shared kernel activates them. */
|
|
164
|
+
activate: async (object, orb, service) => {
|
|
165
|
+
answer(await ops.op_tembra_native!("activate", codec.serialize({ object, orb, service })));
|
|
166
|
+
},
|
|
167
|
+
/** Encode only the call arguments that cross into Rust. */
|
|
168
|
+
invoke: async (invocation, arguments_) =>
|
|
169
|
+
cooperative
|
|
170
|
+
? submit("invoke", codec.serialize({ invocation, arguments: arguments_ }))
|
|
171
|
+
: answer(
|
|
172
|
+
await ops.op_tembra_native!(
|
|
173
|
+
"invoke",
|
|
174
|
+
codec.serialize({ invocation, arguments: arguments_ }),
|
|
175
|
+
),
|
|
176
|
+
),
|
|
177
|
+
/** Release native object storage after shared scope cleanup. */
|
|
178
|
+
dispose: async (object) => {
|
|
179
|
+
answer(await ops.op_tembra_native!("dispose", codec.serialize({ object })));
|
|
180
|
+
},
|
|
181
|
+
/** Delegate callback execution while Rust retains lifecycle ordering. */
|
|
182
|
+
effect: async (effect) =>
|
|
183
|
+
answer(await ops.op_tembra_native!("effect", codec.serialize(effect))),
|
|
184
|
+
/** Signal native cancellation without acknowledging physical settlement. */
|
|
185
|
+
cancelEffect: async (effect) => {
|
|
186
|
+
answer(await ops.op_tembra_native!("cancel-effect", codec.serialize(effect)));
|
|
187
|
+
},
|
|
188
|
+
/** Decode one native bridge value with the agreed codec. */
|
|
189
|
+
value: (id) => answer(ops.op_tembra_value!(id)),
|
|
190
|
+
/** Release the native value selected by a kernel action. */
|
|
191
|
+
dropValue: (id) => ops.op_tembra_drop_value!(id),
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
if (ops.op_tembra_callback_next) {
|
|
195
|
+
// Receiving is idle infrastructure; each callback is separately tracked physical work.
|
|
196
|
+
void (async () => {
|
|
197
|
+
for (;;) {
|
|
198
|
+
const receiving = ops.op_tembra_callback_next!();
|
|
199
|
+
Deno.core.unrefOpPromise(receiving);
|
|
200
|
+
const packet = (await receiving) as Uint8Array;
|
|
201
|
+
if (!packet.length) return;
|
|
202
|
+
const header = new DataView(packet.buffer, packet.byteOffset, 9);
|
|
203
|
+
const kind = header.getUint8(0);
|
|
204
|
+
const id = header.getUint32(1, true) + header.getUint32(5, true) * 2 ** 32;
|
|
205
|
+
if (kind !== 0) {
|
|
206
|
+
if (kind === 2) host.session.calls.releaseRoot(id);
|
|
207
|
+
if (kind === 3) host.session.handles.revoke(id);
|
|
208
|
+
host.session.lifecycle.flush();
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
let request: any;
|
|
212
|
+
try {
|
|
213
|
+
request = codec.deserialize(packet.subarray(9));
|
|
214
|
+
} catch (error) {
|
|
215
|
+
const { code, reason, message } = failure(error);
|
|
216
|
+
ops.op_tembra_callback_error!(id, JSON.stringify({ code, reason, message }), true);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
host.session.track(
|
|
220
|
+
(async () => {
|
|
221
|
+
let envelope: unknown;
|
|
222
|
+
try {
|
|
223
|
+
let result: unknown;
|
|
224
|
+
if (request.kind === "activate") {
|
|
225
|
+
await host.session.handles.activateAcquired(
|
|
226
|
+
request.acquired,
|
|
227
|
+
request.address,
|
|
228
|
+
request.methods,
|
|
229
|
+
);
|
|
230
|
+
result = null;
|
|
231
|
+
} else {
|
|
232
|
+
const call = request.call;
|
|
233
|
+
const invocation = host.session.kernel.command<Invocation>(KernelOp.Invocation, {
|
|
234
|
+
call,
|
|
235
|
+
});
|
|
236
|
+
const ctx = new Context(host.session, invocation.root, invocation, request.frame);
|
|
237
|
+
if (request.kind === "invoke") {
|
|
238
|
+
const object = host.session.objects.get(invocation.object);
|
|
239
|
+
const environment = object?.versions.get(invocation.orb);
|
|
240
|
+
const handle =
|
|
241
|
+
environment?.orb.definition.services?.[object!.address.service]?.methods[
|
|
242
|
+
invocation.method
|
|
243
|
+
];
|
|
244
|
+
if (!handle || !environment) throw new TembraError(Errors.Gone.Implementation);
|
|
245
|
+
result = await handle(environment.value, ctx, ...request.input);
|
|
246
|
+
} else {
|
|
247
|
+
result = await host.session.orbs.runContribution(
|
|
248
|
+
request.operation,
|
|
249
|
+
ctx,
|
|
250
|
+
request.input,
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
envelope = result === undefined ? {} : { value: result };
|
|
255
|
+
} catch (error) {
|
|
256
|
+
const normalized = failure(error);
|
|
257
|
+
envelope = {
|
|
258
|
+
error: {
|
|
259
|
+
code: normalized.code,
|
|
260
|
+
reason: normalized.reason,
|
|
261
|
+
message: normalized.message,
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
ops.op_tembra_callback_complete!(id, codec.serialize(envelope));
|
|
267
|
+
} catch (error) {
|
|
268
|
+
const { code, reason, message } = failure(error);
|
|
269
|
+
ops.op_tembra_callback_error!(id, JSON.stringify({ code, reason, message }), false);
|
|
270
|
+
}
|
|
271
|
+
})(),
|
|
272
|
+
true,
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
})();
|
|
276
|
+
}
|
|
277
|
+
return host;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
globals.Tembra = Object.freeze({
|
|
281
|
+
ContextKey,
|
|
282
|
+
ContextKind,
|
|
283
|
+
opaqueFrom,
|
|
284
|
+
createHost,
|
|
285
|
+
jsonCodec,
|
|
286
|
+
Code,
|
|
287
|
+
Reason,
|
|
288
|
+
Lifetime,
|
|
289
|
+
Status,
|
|
290
|
+
ReloadStatus,
|
|
291
|
+
HookCapability,
|
|
292
|
+
Errors,
|
|
293
|
+
});
|
package/src/error.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Code } from "./bridge/identifiers.ts";
|
|
2
|
+
import { Errors, type ErrorDescriptor } from "./errors.ts";
|
|
3
|
+
|
|
4
|
+
const codes: ReadonlySet<unknown> = new Set(Object.values(Code));
|
|
5
|
+
|
|
6
|
+
/** Check for a structured error descriptor. */
|
|
7
|
+
function isDescriptor(value: unknown): value is ErrorDescriptor {
|
|
8
|
+
return (
|
|
9
|
+
typeof value === "object" &&
|
|
10
|
+
value !== null &&
|
|
11
|
+
"code" in value &&
|
|
12
|
+
codes.has(value.code) &&
|
|
13
|
+
"reason" in value &&
|
|
14
|
+
typeof value.reason === "string" &&
|
|
15
|
+
"message" in value &&
|
|
16
|
+
typeof value.message === "string"
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A native JavaScript Error carrying the same structured failure fields as Rust. */
|
|
21
|
+
export class TembraError extends Error {
|
|
22
|
+
readonly code: Code;
|
|
23
|
+
readonly reason: string;
|
|
24
|
+
|
|
25
|
+
/** Preserve the error code and reason with a readable message. */
|
|
26
|
+
constructor(error: ErrorDescriptor, message = error.message, options?: ErrorOptions) {
|
|
27
|
+
super(message, options);
|
|
28
|
+
this.name = "TembraError";
|
|
29
|
+
this.code = error.code;
|
|
30
|
+
this.reason = error.reason;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Normalizes failures from other bundles or realms without relying on their constructors. */
|
|
35
|
+
export function failure(error: unknown): TembraError {
|
|
36
|
+
let message = Errors.Unavailable.Callback.message;
|
|
37
|
+
try {
|
|
38
|
+
if (error instanceof TembraError) return error;
|
|
39
|
+
if (isDescriptor(error)) return new TembraError(error, error.message, { cause: error });
|
|
40
|
+
message = String(error instanceof Error ? error.message : error);
|
|
41
|
+
} catch {
|
|
42
|
+
// Arbitrary thrown values must not interrupt error reporting or effect acknowledgement.
|
|
43
|
+
}
|
|
44
|
+
return new TembraError(Errors.Unavailable.Callback, message, { cause: error });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Throw a structured error for a rejected operation. */
|
|
48
|
+
export function refuse(error: ErrorDescriptor, message = error.message): never {
|
|
49
|
+
throw new TembraError(error, message);
|
|
50
|
+
}
|