@syntropika/tembra-sdk 0.0.0-stage → 0.1.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 +47 -0
- package/dist/authoring/hooks.d.ts +11 -0
- package/dist/authoring/orb.d.ts +3 -0
- package/dist/authoring/types.d.ts +166 -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 +3282 -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 +96 -0
- package/dist/host.js +3225 -0
- package/dist/identifiers.d.ts +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +833 -0
- package/dist/infrastructure/coordinator.d.ts +13 -0
- package/dist/infrastructure/manager.d.ts +23 -0
- package/dist/infrastructure/rpc/channel.d.ts +52 -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 +3283 -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 +1036 -0
- package/dist/runtime/activities.d.ts +30 -0
- package/dist/runtime/calls.d.ts +22 -0
- package/dist/runtime/context.d.ts +37 -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 +220 -0
- package/src/authoring/hooks.ts +101 -0
- package/src/authoring/orb.ts +77 -0
- package/src/authoring/types.ts +212 -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 +142 -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 +88 -0
- package/src/infrastructure/rpc/client.ts +161 -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 +113 -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 +398 -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,157 @@
|
|
|
1
|
+
import { Errors } from "../errors.ts";
|
|
2
|
+
|
|
3
|
+
import { TembraError, refuse } from "../error.ts";
|
|
4
|
+
import { protect } from "../values.ts";
|
|
5
|
+
|
|
6
|
+
import { Selection } from "./selection.ts";
|
|
7
|
+
import type { PreparedSelection, Readable, State, StateBackend, StateOptions } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
/** One object-owned state binding, shared by compatible implementation versions. */
|
|
10
|
+
export class StateBinding<T = unknown> {
|
|
11
|
+
closed = false;
|
|
12
|
+
#value: Readonly<T>;
|
|
13
|
+
#listeners = new Set<(value: Readonly<T>) => void>();
|
|
14
|
+
#selections = new Set<WeakRef<Selection<T, unknown>>>();
|
|
15
|
+
|
|
16
|
+
/** Bind an object's current state, optionally using a staged initial value. */
|
|
17
|
+
constructor(
|
|
18
|
+
readonly backend: StateBackend,
|
|
19
|
+
readonly object: number,
|
|
20
|
+
initial?: Readonly<T>,
|
|
21
|
+
) {
|
|
22
|
+
this.#value =
|
|
23
|
+
arguments.length >= 3 ? initial! : backend.value<T>(backend.snapshot(object).value);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Reject state access after object cleanup. */
|
|
27
|
+
check(): void {
|
|
28
|
+
if (this.closed) throw new TembraError(Errors.Gone.State, "State owner is gone");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Read current state while its owner remains live. */
|
|
32
|
+
get value(): Readonly<T> {
|
|
33
|
+
this.check();
|
|
34
|
+
return this.#value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Expose validated updates under the declaring orb's state contract. */
|
|
38
|
+
view(options: StateOptions<T>, check: () => void = () => this.check()): State<T> {
|
|
39
|
+
const binding = this;
|
|
40
|
+
return {
|
|
41
|
+
/** Read adopted state after checking the view's lifetime. */
|
|
42
|
+
get value() {
|
|
43
|
+
check();
|
|
44
|
+
return binding.value;
|
|
45
|
+
},
|
|
46
|
+
/** Validate a synchronous candidate before revision-checked adoption. */
|
|
47
|
+
update(context, change) {
|
|
48
|
+
check();
|
|
49
|
+
binding.backend.check(context, binding.object);
|
|
50
|
+
const previous = binding.backend.snapshot(binding.object);
|
|
51
|
+
const current = binding.backend.value<T>(previous.value);
|
|
52
|
+
const candidate = change(current);
|
|
53
|
+
validate(candidate, options);
|
|
54
|
+
binding.backend.check(context, binding.object);
|
|
55
|
+
if (Object.is(candidate, current)) return current;
|
|
56
|
+
const selected = binding.prepare(candidate);
|
|
57
|
+
binding.backend.adopt(binding.object, context, previous.revision, candidate);
|
|
58
|
+
const publish = binding.adopt(selected, candidate);
|
|
59
|
+
binding.backend.publish(publish);
|
|
60
|
+
return candidate;
|
|
61
|
+
},
|
|
62
|
+
/** Derive a selection after checking the view's lifetime. */
|
|
63
|
+
select: (compute) => {
|
|
64
|
+
check();
|
|
65
|
+
return binding.select(compute, check);
|
|
66
|
+
},
|
|
67
|
+
/** Attach an observer only while this view remains valid. */
|
|
68
|
+
subscribe: (listener) => {
|
|
69
|
+
check();
|
|
70
|
+
return binding.subscribe(listener);
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Track a derived value without retaining unused selections strongly. */
|
|
76
|
+
select<R>(
|
|
77
|
+
compute: (value: Readonly<T>) => R,
|
|
78
|
+
check = () => this.check(),
|
|
79
|
+
cleanups?: Set<() => void>,
|
|
80
|
+
): Readable<R> {
|
|
81
|
+
check();
|
|
82
|
+
const selection = new Selection(
|
|
83
|
+
compute,
|
|
84
|
+
this.value,
|
|
85
|
+
(error) => this.backend.report(error),
|
|
86
|
+
check,
|
|
87
|
+
);
|
|
88
|
+
check();
|
|
89
|
+
const weak = new WeakRef(selection) as WeakRef<Selection<T, unknown>>;
|
|
90
|
+
this.#selections.add(weak);
|
|
91
|
+
selection.track(cleanups, () => this.#selections.delete(weak));
|
|
92
|
+
return selection;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Deliver current state immediately and report listener failures. */
|
|
96
|
+
subscribe(listener: (value: Readonly<T>) => void): () => void {
|
|
97
|
+
this.check();
|
|
98
|
+
this.#listeners.add(listener);
|
|
99
|
+
try {
|
|
100
|
+
listener(this.value);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
this.backend.report(error);
|
|
103
|
+
}
|
|
104
|
+
return () => {
|
|
105
|
+
this.#listeners.delete(listener);
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Compute live selections before changing the adopted value. */
|
|
110
|
+
prepare(candidate: Readonly<T>): PreparedSelection[] {
|
|
111
|
+
const prepared: PreparedSelection[] = [];
|
|
112
|
+
for (const weak of this.#selections) {
|
|
113
|
+
const selection = weak.deref();
|
|
114
|
+
const next = selection?.prepare(candidate);
|
|
115
|
+
if (next) prepared.push(next);
|
|
116
|
+
else this.#selections.delete(weak);
|
|
117
|
+
}
|
|
118
|
+
return prepared;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Replace state and return its deferred notification pass. */
|
|
122
|
+
adopt(prepared: PreparedSelection[], candidate: Readonly<T>): () => void {
|
|
123
|
+
this.#value = candidate;
|
|
124
|
+
const selections = prepared.map((p) => p.adopt());
|
|
125
|
+
const listeners = [...this.#listeners];
|
|
126
|
+
return () => {
|
|
127
|
+
for (const notify of selections) notify();
|
|
128
|
+
for (const listener of listeners) {
|
|
129
|
+
try {
|
|
130
|
+
listener(candidate);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
this.backend.report(error);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Release state and detach all tracked observers. */
|
|
139
|
+
close(): void {
|
|
140
|
+
this.closed = true;
|
|
141
|
+
this.#value = undefined as T;
|
|
142
|
+
this.#listeners.clear();
|
|
143
|
+
for (const weak of this.#selections) weak.deref()?.detach();
|
|
144
|
+
this.#selections.clear();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Protect plain data and apply the orb's synchronous guard. */
|
|
149
|
+
export function validate<T>(candidate: T, options: StateOptions<T>): Readonly<T> {
|
|
150
|
+
if (candidate && typeof (candidate as { then?: unknown }).then === "function")
|
|
151
|
+
refuse(Errors.Invalid.AsyncState, "State updates and migrations must be synchronous");
|
|
152
|
+
const protectedValue = protect(candidate);
|
|
153
|
+
const result = options.validate?.(protectedValue);
|
|
154
|
+
if (result !== undefined && result !== true)
|
|
155
|
+
refuse(Errors.Invalid.StateValidation, "Orb rejected the candidate state");
|
|
156
|
+
return protectedValue;
|
|
157
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { protect } from "../values.ts";
|
|
2
|
+
import type { PreparedSelection, Readable } from "./types.ts";
|
|
3
|
+
|
|
4
|
+
export class Selection<T, R> implements Readable<R> {
|
|
5
|
+
#value: Readonly<R>;
|
|
6
|
+
#listeners = new Set<(value: Readonly<R>) => void>();
|
|
7
|
+
#children = new Set<WeakRef<Selection<R, unknown>>>();
|
|
8
|
+
#active = true;
|
|
9
|
+
#cleanups: Set<() => void> | undefined;
|
|
10
|
+
#cleanup: (() => void) | undefined;
|
|
11
|
+
#remove: (() => void) | undefined;
|
|
12
|
+
|
|
13
|
+
/** Compute and protect the initial selected value. */
|
|
14
|
+
constructor(
|
|
15
|
+
readonly compute: (value: Readonly<T>) => R,
|
|
16
|
+
value: Readonly<T>,
|
|
17
|
+
readonly report: (error: unknown) => void,
|
|
18
|
+
readonly check: () => void,
|
|
19
|
+
) {
|
|
20
|
+
this.#value = protect(compute(value));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Read the cached value while its owning reference remains valid. */
|
|
24
|
+
get value(): Readonly<R> {
|
|
25
|
+
this.check();
|
|
26
|
+
return this.#value;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Attach weak cleanup so the owner can release this selection. */
|
|
30
|
+
track(cleanups: Set<() => void> | undefined, remove: () => void): void {
|
|
31
|
+
this.#cleanups = cleanups;
|
|
32
|
+
this.#remove = remove;
|
|
33
|
+
const weak = new WeakRef(this);
|
|
34
|
+
this.#cleanup = () => weak.deref()?.detach();
|
|
35
|
+
cleanups?.add(this.#cleanup);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Release listeners and child selections once. */
|
|
39
|
+
detach(): void {
|
|
40
|
+
if (!this.#active) return;
|
|
41
|
+
this.#active = false;
|
|
42
|
+
if (this.#cleanup) this.#cleanups?.delete(this.#cleanup);
|
|
43
|
+
this.#remove?.();
|
|
44
|
+
this.#listeners.clear();
|
|
45
|
+
for (const weak of this.#children) weak.deref()?.detach();
|
|
46
|
+
this.#children.clear();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Stage derived values before any state notification runs. */
|
|
50
|
+
prepare(value: Readonly<T>): PreparedSelection | undefined {
|
|
51
|
+
if (!this.#active) return;
|
|
52
|
+
try {
|
|
53
|
+
this.check();
|
|
54
|
+
} catch {
|
|
55
|
+
this.detach();
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
let next: Readonly<R>;
|
|
59
|
+
try {
|
|
60
|
+
next = protect(this.compute(value));
|
|
61
|
+
} catch (error) {
|
|
62
|
+
this.detach();
|
|
63
|
+
this.report(error);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (!this.#active) return;
|
|
67
|
+
const children: PreparedSelection[] = [];
|
|
68
|
+
if (!Object.is(next, this.#value)) {
|
|
69
|
+
for (const weak of this.#children) {
|
|
70
|
+
const child = weak.deref();
|
|
71
|
+
const prepared = child?.prepare(next);
|
|
72
|
+
if (prepared) children.push(prepared);
|
|
73
|
+
else this.#children.delete(weak);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
/** Adopt staged selections before returning their notification callbacks. */
|
|
78
|
+
adopt: () => {
|
|
79
|
+
if (!this.#active || Object.is(next, this.#value)) return () => {};
|
|
80
|
+
this.#value = next;
|
|
81
|
+
const notifyChildren = children.map((child) => child.adopt());
|
|
82
|
+
const listeners = [...this.#listeners];
|
|
83
|
+
return () => {
|
|
84
|
+
if (!this.#active) return;
|
|
85
|
+
for (const notify of notifyChildren) notify();
|
|
86
|
+
for (const listener of listeners) {
|
|
87
|
+
try {
|
|
88
|
+
listener(next);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
this.report(error);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Derive a child selection with the same validity rule. */
|
|
99
|
+
select<S>(compute: (value: Readonly<R>) => S): Readable<S> {
|
|
100
|
+
this.check();
|
|
101
|
+
const child = new Selection(compute, this.#value, this.report, this.check);
|
|
102
|
+
this.check();
|
|
103
|
+
const weak = new WeakRef(child) as WeakRef<Selection<R, unknown>>;
|
|
104
|
+
this.#children.add(weak);
|
|
105
|
+
child.track(this.#cleanups, () => this.#children.delete(weak));
|
|
106
|
+
return child;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Deliver the current value and retain a change listener. */
|
|
110
|
+
subscribe(listener: (value: Readonly<R>) => void): () => void {
|
|
111
|
+
this.check();
|
|
112
|
+
this.#listeners.add(listener);
|
|
113
|
+
try {
|
|
114
|
+
listener(this.#value);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
this.report(error);
|
|
117
|
+
}
|
|
118
|
+
return () => {
|
|
119
|
+
this.#listeners.delete(listener);
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Invocation, Snapshot } from "../bridge/kernel.ts";
|
|
2
|
+
|
|
3
|
+
export interface Readable<T> {
|
|
4
|
+
readonly value: Readonly<T>;
|
|
5
|
+
|
|
6
|
+
/** Derive a cached readable value from this source. */
|
|
7
|
+
select<R>(compute: (value: Readonly<T>) => R): Readable<R>;
|
|
8
|
+
|
|
9
|
+
/** Deliver the current value, then changes, until detached. */
|
|
10
|
+
subscribe(listener: (value: Readonly<T>) => void): () => void;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface StateOptions<T> {
|
|
14
|
+
version?: number;
|
|
15
|
+
validate?: (candidate: Readonly<T>) => boolean | void;
|
|
16
|
+
migrate?: (previous: unknown, fromVersion: number) => T;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface StateBackend {
|
|
20
|
+
/** Read value identity and revision from the kernel. */
|
|
21
|
+
snapshot(object: number): Snapshot;
|
|
22
|
+
|
|
23
|
+
/** Resolve an adapter-owned value identity. */
|
|
24
|
+
value<T>(id: number): T;
|
|
25
|
+
|
|
26
|
+
/** Adopt state only under the expected revision and admitted call. */
|
|
27
|
+
adopt(object: number, context: unknown, expected: string, candidate: unknown): Snapshot;
|
|
28
|
+
|
|
29
|
+
/** Require a live call that owns this object. */
|
|
30
|
+
check(context: unknown, object: number): Invocation;
|
|
31
|
+
|
|
32
|
+
/** Report observer failures without reverting adopted state. */
|
|
33
|
+
report(error: unknown): void;
|
|
34
|
+
|
|
35
|
+
/** Queue notifications in adoption order. */
|
|
36
|
+
publish(operation: () => void): void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface State<T> extends Readable<T> {
|
|
40
|
+
/** Validate and adopt a synchronous candidate under the supplied context. */
|
|
41
|
+
update(context: unknown, change: (current: Readonly<T>) => T): Readonly<T>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface PreparedSelection {
|
|
45
|
+
/** Publish the staged value and return its notification callback. */
|
|
46
|
+
adopt(): () => void;
|
|
47
|
+
}
|
package/src/state.ts
ADDED
package/src/telemetry.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Outcome } from "./bridge/protocol.ts";
|
|
2
|
+
export interface Trace {
|
|
3
|
+
service: string;
|
|
4
|
+
method: string;
|
|
5
|
+
root: number;
|
|
6
|
+
codeVersion: number;
|
|
7
|
+
duration: number;
|
|
8
|
+
outcome: Outcome;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Bounded opt-in timing. Exporters remain an infrastructure concern. */
|
|
12
|
+
export class Telemetry {
|
|
13
|
+
#events: Trace[] = [];
|
|
14
|
+
#next = 0;
|
|
15
|
+
|
|
16
|
+
/** Configure a bounded buffer with a fixed sampling interval. */
|
|
17
|
+
constructor(
|
|
18
|
+
readonly capacity = 256,
|
|
19
|
+
readonly sampleEvery = 1,
|
|
20
|
+
) {
|
|
21
|
+
if (
|
|
22
|
+
!Number.isInteger(capacity) ||
|
|
23
|
+
capacity <= 0 ||
|
|
24
|
+
!Number.isInteger(sampleEvery) ||
|
|
25
|
+
sampleEvery <= 0
|
|
26
|
+
)
|
|
27
|
+
throw new RangeError("Invalid telemetry limits");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Select calls at the configured sampling interval. */
|
|
31
|
+
sample(): boolean {
|
|
32
|
+
return this.#next++ % this.sampleEvery === 0;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Append one sampled call, replacing the oldest record when full. */
|
|
36
|
+
record(trace: Trace): void {
|
|
37
|
+
if (this.#events.length === this.capacity) this.#events.shift();
|
|
38
|
+
this.#events.push(trace);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Return buffered samples and clear their retained references. */
|
|
42
|
+
drain(): readonly Trace[] {
|
|
43
|
+
return this.#events.splice(0);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import ts from "typescript";
|
|
5
|
+
|
|
6
|
+
import { external, resolver } from "./resolver.ts";
|
|
7
|
+
import { typecheck } from "./typecheck.ts";
|
|
8
|
+
import { Platform, type Artifact, type BuildConfig } from "./types.ts";
|
|
9
|
+
|
|
10
|
+
/** Resolves packages at build time and emits exactly one content-addressed ESM file per target. */
|
|
11
|
+
export async function build(config: BuildConfig): Promise<readonly Artifact[]> {
|
|
12
|
+
const root = path.resolve(config.root ?? process.cwd());
|
|
13
|
+
const outDir = path.resolve(root, config.outDir ?? "dist/tembra");
|
|
14
|
+
const artifacts: Artifact[] = [];
|
|
15
|
+
for (const [name, target] of Object.entries(config.builds)) {
|
|
16
|
+
if (!/^[\w-]+$/.test(name) || !Object.values(Platform).includes(target.platform))
|
|
17
|
+
throw new Error("Invalid build name or platform");
|
|
18
|
+
const entry = path.resolve(root, target.entry);
|
|
19
|
+
if (target.typecheck !== false) typecheck(entry, root);
|
|
20
|
+
const result = await Bun.build({
|
|
21
|
+
entrypoints: [target.platform === Platform.Embedded ? "tembra:entry" : entry],
|
|
22
|
+
root,
|
|
23
|
+
format: target.platform === Platform.Embedded ? "iife" : "esm",
|
|
24
|
+
target: target.platform === Platform.Node ? "node" : "browser",
|
|
25
|
+
splitting: false,
|
|
26
|
+
minify: target.minify ?? true,
|
|
27
|
+
...(target.define ? { define: { ...target.define } } : {}),
|
|
28
|
+
plugins: [resolver(root, target)],
|
|
29
|
+
});
|
|
30
|
+
if (!result.success) throw new AggregateError(result.logs, `Build ${name} failed`);
|
|
31
|
+
if (result.outputs.length !== 1 || result.outputs[0]?.kind !== "entry-point")
|
|
32
|
+
throw new Error(
|
|
33
|
+
`Build ${name} requires external assets; publish them explicitly instead of silently expanding the orb bundle`,
|
|
34
|
+
);
|
|
35
|
+
const output = result.outputs[0]!;
|
|
36
|
+
const source = await output.text();
|
|
37
|
+
const parsed = ts.createSourceFile(
|
|
38
|
+
"bundle.js",
|
|
39
|
+
source,
|
|
40
|
+
ts.ScriptTarget.Latest,
|
|
41
|
+
true,
|
|
42
|
+
ts.ScriptKind.JS,
|
|
43
|
+
);
|
|
44
|
+
const hasDefault = parsed.statements.some(
|
|
45
|
+
(statement) =>
|
|
46
|
+
ts.isExportAssignment(statement) ||
|
|
47
|
+
(ts.isExportDeclaration(statement) &&
|
|
48
|
+
statement.exportClause &&
|
|
49
|
+
ts.isNamedExports(statement.exportClause) &&
|
|
50
|
+
statement.exportClause.elements.some((element) => element.name.text === "default")),
|
|
51
|
+
);
|
|
52
|
+
if (target.platform !== Platform.Embedded && !hasDefault)
|
|
53
|
+
throw new Error(`Build ${name} must export a default orb`);
|
|
54
|
+
/** Reject imports that the selected runtime cannot resolve. */
|
|
55
|
+
function verify(node: ts.Node): void {
|
|
56
|
+
let specifier: ts.Expression | undefined;
|
|
57
|
+
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node))
|
|
58
|
+
specifier = node.moduleSpecifier;
|
|
59
|
+
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword)
|
|
60
|
+
specifier = node.arguments[0];
|
|
61
|
+
if (specifier && (!ts.isStringLiteralLike(specifier) || !external(specifier.text, target)))
|
|
62
|
+
throw new Error(`Build ${name} contains an unresolved import`);
|
|
63
|
+
ts.forEachChild(node, verify);
|
|
64
|
+
}
|
|
65
|
+
verify(parsed);
|
|
66
|
+
const bytes = Buffer.from(source);
|
|
67
|
+
const hash = createHash("sha256").update(bytes).digest("hex");
|
|
68
|
+
const directory = path.join(outDir, name);
|
|
69
|
+
const destination = path.join(directory, `orb.${hash}.js`);
|
|
70
|
+
await mkdir(directory, { recursive: true });
|
|
71
|
+
const temporary = `${destination}.${process.pid}.tmp`;
|
|
72
|
+
await writeFile(temporary, bytes);
|
|
73
|
+
await rename(temporary, destination);
|
|
74
|
+
artifacts.push({
|
|
75
|
+
name,
|
|
76
|
+
platform: target.platform,
|
|
77
|
+
path: destination,
|
|
78
|
+
sha256: hash,
|
|
79
|
+
bytes: bytes.length,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
return artifacts;
|
|
83
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import resolve from "enhanced-resolve";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { builtinModules } from "node:module";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import ts from "typescript";
|
|
7
|
+
|
|
8
|
+
import { Platform, type BuildTarget } from "./types.ts";
|
|
9
|
+
|
|
10
|
+
/** Check whether the selected target permits this external dependency. */
|
|
11
|
+
export function external(specifier: string, target: BuildTarget): boolean {
|
|
12
|
+
return (
|
|
13
|
+
target.platform === Platform.Node &&
|
|
14
|
+
(builtinModules.includes(specifier.replace(/^node:/, "")) ||
|
|
15
|
+
(target.nativeExternals ?? []).some(
|
|
16
|
+
(name) => specifier === name || specifier.startsWith(`${name}/`),
|
|
17
|
+
))
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Resolve and bundle dependencies under the selected runtime rules. */
|
|
22
|
+
export function resolver(root: string, target: BuildTarget): Bun.BunPlugin {
|
|
23
|
+
const web = target.platform === Platform.Browser || target.platform === Platform.Worker;
|
|
24
|
+
const resolveModule = resolve.create.sync({
|
|
25
|
+
fileSystem: fs,
|
|
26
|
+
conditionNames: [
|
|
27
|
+
"source",
|
|
28
|
+
...(web
|
|
29
|
+
? ["browser"]
|
|
30
|
+
: target.platform === Platform.Node
|
|
31
|
+
? ["node", "node-addons"]
|
|
32
|
+
: ["tembra-embedded"]),
|
|
33
|
+
"import",
|
|
34
|
+
"default",
|
|
35
|
+
],
|
|
36
|
+
extensions: [".ts", ".tsx", ".mts", ".js", ".jsx", ".mjs", ".cjs", ".json"],
|
|
37
|
+
extensionAlias: { ".js": [".ts", ".tsx", ".js"], ".mjs": [".mts", ".mjs"] },
|
|
38
|
+
mainFields: web ? ["browser", "module", "main"] : ["module", "main"],
|
|
39
|
+
aliasFields: web ? ["browser"] : [],
|
|
40
|
+
});
|
|
41
|
+
return {
|
|
42
|
+
name: "tembra-platform",
|
|
43
|
+
/** Register target-specific resolution and embedded entrypoint rules. */
|
|
44
|
+
setup(builder) {
|
|
45
|
+
builder.onResolve({ filter: /^tembra:entry$/ }, () => ({
|
|
46
|
+
path: "entry",
|
|
47
|
+
namespace: "tembra-orb",
|
|
48
|
+
}));
|
|
49
|
+
builder.onLoad({ filter: /.*/, namespace: "tembra-orb" }, () => ({
|
|
50
|
+
contents: `import orb from ${JSON.stringify(path.resolve(root, target.entry))}; globalThis.__tembraOrb = orb;`,
|
|
51
|
+
loader: "js",
|
|
52
|
+
}));
|
|
53
|
+
builder.onResolve({ filter: /.*/ }, (request) => {
|
|
54
|
+
if (external(request.path, target)) return { path: request.path, external: true };
|
|
55
|
+
if (
|
|
56
|
+
request.path.startsWith("node:") ||
|
|
57
|
+
request.path.startsWith("bun:") ||
|
|
58
|
+
builtinModules.includes(request.path)
|
|
59
|
+
)
|
|
60
|
+
throw new Error(`${request.importer}: ${request.path} requires its host runtime`);
|
|
61
|
+
if (request.kind === "entry-point-build") return;
|
|
62
|
+
const resolved = resolveModule(
|
|
63
|
+
path.dirname(request.importer || path.join(root, "entry.js")),
|
|
64
|
+
request.path,
|
|
65
|
+
);
|
|
66
|
+
if (!resolved)
|
|
67
|
+
throw new Error(`${request.importer}: no compatible implementation for ${request.path}`);
|
|
68
|
+
if (resolved.endsWith(".node"))
|
|
69
|
+
throw new Error("Declare native Node packages as nativeExternals in a node build");
|
|
70
|
+
return { path: resolved };
|
|
71
|
+
});
|
|
72
|
+
builder.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (request) => {
|
|
73
|
+
const source = await readFile(request.path, "utf8");
|
|
74
|
+
const parsed = ts.createSourceFile(request.path, source, ts.ScriptTarget.Latest, true);
|
|
75
|
+
/** Reject browser and Node facilities absent from the embedded runtime. */
|
|
76
|
+
function check(node: ts.Node): void {
|
|
77
|
+
if (
|
|
78
|
+
ts.isCallExpression(node) &&
|
|
79
|
+
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
|
|
80
|
+
(ts.isIdentifier(node.expression) && node.expression.text === "require"))
|
|
81
|
+
) {
|
|
82
|
+
const argument = node.arguments[0];
|
|
83
|
+
if (!argument || !ts.isStringLiteralLike(argument))
|
|
84
|
+
throw new Error(
|
|
85
|
+
`${request.path}: dynamic module names must be resolved before publishing an orb`,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
ts.forEachChild(node, check);
|
|
89
|
+
}
|
|
90
|
+
check(parsed);
|
|
91
|
+
return undefined;
|
|
92
|
+
});
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
|
|
3
|
+
/** Check orb source types before bundling an artifact. */
|
|
4
|
+
export function typecheck(entry: string, root: string): void {
|
|
5
|
+
const configFile = ts.findConfigFile(root, ts.sys.fileExists);
|
|
6
|
+
const loaded = configFile ? ts.readConfigFile(configFile, ts.sys.readFile) : { config: {} };
|
|
7
|
+
if (loaded.error)
|
|
8
|
+
throw new Error(ts.flattenDiagnosticMessageText(loaded.error.messageText, "\n"));
|
|
9
|
+
const parsed = ts.parseJsonConfigFileContent(loaded.config, ts.sys, root);
|
|
10
|
+
const program = ts.createProgram([entry], {
|
|
11
|
+
...parsed.options,
|
|
12
|
+
target: ts.ScriptTarget.ES2023,
|
|
13
|
+
module: ts.ModuleKind.ESNext,
|
|
14
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
15
|
+
allowImportingTsExtensions: true,
|
|
16
|
+
noEmit: true,
|
|
17
|
+
strict: true,
|
|
18
|
+
skipLibCheck: true,
|
|
19
|
+
});
|
|
20
|
+
const diagnostics = ts.getPreEmitDiagnostics(program);
|
|
21
|
+
if (diagnostics.length)
|
|
22
|
+
throw new Error(
|
|
23
|
+
ts.formatDiagnosticsWithColorAndContext(diagnostics, {
|
|
24
|
+
/** Resolve diagnostics relative to the configured project root. */
|
|
25
|
+
getCurrentDirectory: () => root,
|
|
26
|
+
/** Keep file names unchanged when formatting diagnostics. */
|
|
27
|
+
getCanonicalFileName: (name) => name,
|
|
28
|
+
/** Use portable line endings in build diagnostics. */
|
|
29
|
+
getNewLine: () => "\n",
|
|
30
|
+
}),
|
|
31
|
+
);
|
|
32
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export const Platform = Object.freeze({
|
|
2
|
+
Browser: "browser",
|
|
3
|
+
Worker: "worker",
|
|
4
|
+
Node: "node",
|
|
5
|
+
Embedded: "embedded",
|
|
6
|
+
} as const);
|
|
7
|
+
export type Platform = (typeof Platform)[keyof typeof Platform];
|
|
8
|
+
export interface BuildTarget {
|
|
9
|
+
entry: string;
|
|
10
|
+
platform: Platform;
|
|
11
|
+
minify?: boolean;
|
|
12
|
+
typecheck?: boolean;
|
|
13
|
+
nativeExternals?: readonly string[];
|
|
14
|
+
define?: Readonly<Record<string, string>>;
|
|
15
|
+
}
|
|
16
|
+
export interface BuildConfig {
|
|
17
|
+
root?: string;
|
|
18
|
+
outDir?: string;
|
|
19
|
+
builds: Readonly<Record<string, BuildTarget>>;
|
|
20
|
+
}
|
|
21
|
+
export interface Artifact {
|
|
22
|
+
name: string;
|
|
23
|
+
platform: Platform;
|
|
24
|
+
path: string;
|
|
25
|
+
sha256: string;
|
|
26
|
+
bytes: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Preserve build target types in a tooling configuration. */
|
|
30
|
+
export function defineConfig<const C extends BuildConfig>(config: C): C {
|
|
31
|
+
return config;
|
|
32
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./authoring/types.ts";
|