@telorun/sdk 0.72.0 → 0.74.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.
@@ -0,0 +1,417 @@
1
+ /**
2
+ * `x-telo-type` — the one annotation that says what the value at a slot IS,
3
+ * beyond what JSON Schema's `type` vocabulary can express, and the single
4
+ * accessor every surface reads it through (the `ref-slot.ts` precedent).
5
+ *
6
+ * It replaced three keywords that answered one question differently: a nominal
7
+ * brand from a closed kernel table (`x-telo-type: TcpPort`), raw bytes
8
+ * (`x-telo-binary: true`), and a live handle (`x-telo-stream: true`). They
9
+ * differed in POSTURE toward the JSON Schema layer — refine, replace, exempt —
10
+ * not in kind, so each spelled as its own keyword meant a fourth cost eleven
11
+ * files across four packages, and left three defects: a typo'd brand degraded
12
+ * silently, bytes had no CEL identity, and a module string-matched the keyword
13
+ * because there was nothing on its surface to read.
14
+ *
15
+ * THE VOCABULARY IS DATA; THE BINDING TO A LANGUAGE IS NOT. Entries live at
16
+ * `sdk/value-types/*.json` (see the README there) and are copied in by the SDK's
17
+ * `prepare`. Every runtime that hosts Telo reads the same files — the Rust half
18
+ * types an `!include-bytes` slot from them in a kernel with no CEL engine — so
19
+ * an entry declares a symbolic `binding`, never a constructor name, and each
20
+ * runtime carries its own table mapping that key to its own identity.
21
+ *
22
+ * THE REGISTRY IS IN THE SDK because it is dependency-free and Node-built-in-free
23
+ * (so a browser-side analyzer can read it), because `Stream` already lives here,
24
+ * and because it is the only placement a module controller can reach: a module
25
+ * may import `@telorun/sdk` and nothing else.
26
+ */
27
+
28
+ import { Stream } from "./stream.js";
29
+ import { VALUE_TYPE_ENTRY_FILES } from "./value-types/entries/index.js";
30
+
31
+ export const X_TELO_TYPE = "x-telo-type";
32
+
33
+ /** How a value is represented, which is the one thing an entry declares.
34
+ *
35
+ * - `json` — an ordinary value its declared schema already validates. The
36
+ * name adds nominal identity for static wiring, nothing else.
37
+ * - `instance` — not JSON at all. This is what makes a value unauthorable: no
38
+ * YAML literal is ever a byte buffer or a stream handle. */
39
+ export type ValueTypeRepresentation = "json" | "instance";
40
+
41
+ /** A named type parameter. Every parameter is optional and defaults to *any*,
42
+ * so an unparameterized use of a generic type stays legal. Named rather than
43
+ * positional so a diagnostic can say `of` instead of "argument 0", and so a
44
+ * second parameter can be added without a migration. */
45
+ export interface ValueTypeParameter {
46
+ readonly name: string;
47
+ /** This parameter's argument is what ITERATING a value of the type yields.
48
+ * Declared here so "what is the element of this collection" is answered by
49
+ * the vocabulary rather than by a consumer that knows one type's name — the
50
+ * same reason `live` is a field and not a check against `Telo.Stream`. At
51
+ * most one parameter per entry may carry it. */
52
+ readonly element?: boolean;
53
+ readonly description?: string;
54
+ }
55
+
56
+ /** One value type, exactly as its entry file declares it. */
57
+ export interface ValueTypeEntry {
58
+ /** `Telo.`-qualified. The closed vocabulary an author writes at the name slot. */
59
+ readonly name: string;
60
+ readonly representation: ValueTypeRepresentation;
61
+ /** `json` only — the JSON Schema type this name refines. */
62
+ readonly base?: string;
63
+ /** `instance` only — the symbolic key a runtime's binding table maps. */
64
+ readonly binding?: string;
65
+ /** An instance whose consumption has effects, so it is exempt from validation
66
+ * rather than asserted. Exemption is from VALIDATION, never from TYPING. */
67
+ readonly live: boolean;
68
+ readonly parameters: readonly ValueTypeParameter[];
69
+ readonly description: string;
70
+ }
71
+
72
+ /** What one runtime can say about an `instance` representation. Node's identity
73
+ * is a constructor (`instanceof` is the assertion) plus the CEL type an
74
+ * expression at such a slot carries. */
75
+ export interface ValueTypeBinding {
76
+ /** The constructor an assertion tests against. `Buffer` extends `Uint8Array`,
77
+ * so a Node buffer satisfies `bytes` without a second rule. */
78
+ readonly constructor: Function;
79
+ /** The CEL type a value of this representation carries. */
80
+ readonly celType: string;
81
+ /** A stand-in the analyzer substitutes for a CEL leaf at such a slot, so the
82
+ * static check and the runtime assertion agree BY CONSTRUCTION rather than by
83
+ * two rules kept in step. Absent for a `live` type, whose value is never
84
+ * validated and so needs nothing to satisfy. */
85
+ readonly placeholder?: () => unknown;
86
+ }
87
+
88
+ /**
89
+ * Node's binding table — the ONLY per-language artifact in the whole mechanism.
90
+ *
91
+ * Keyed by an entry's symbolic `binding`, never by its name, so a runtime that
92
+ * represents two entries the same way says so once and a rename of a type does
93
+ * not touch any table.
94
+ */
95
+ export const VALUE_TYPE_BINDINGS: Readonly<Record<string, ValueTypeBinding>> = {
96
+ bytes: { constructor: Uint8Array, celType: "bytes", placeholder: () => new Uint8Array() },
97
+ stream: { constructor: Stream, celType: "Stream" },
98
+ };
99
+
100
+ /** The CEL type a `json` representation's declared base carries. A brand's own
101
+ * name is the CEL type; this is what it degrades to when the consuming slot
102
+ * declares no brand of its own (gradual typing). */
103
+ const CEL_TYPE_FOR_BASE: Readonly<Record<string, string>> = {
104
+ integer: "int",
105
+ number: "double",
106
+ string: "string",
107
+ boolean: "bool",
108
+ array: "list",
109
+ object: "map",
110
+ };
111
+
112
+ class ValueTypeEntryError extends Error {
113
+ constructor(file: string, detail: string) {
114
+ super(`Invalid value-type entry '${file}': ${detail}`);
115
+ this.name = "ValueTypeEntryError";
116
+ }
117
+ }
118
+
119
+ const ENTRY_KEYS = [
120
+ "name",
121
+ "representation",
122
+ "base",
123
+ "binding",
124
+ "live",
125
+ "parameters",
126
+ "description",
127
+ "$comment",
128
+ ] as const;
129
+
130
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
131
+ return typeof value === "object" && value !== null && !Array.isArray(value);
132
+ }
133
+
134
+ function requireString(file: string, node: Record<string, unknown>, key: string): string {
135
+ const value = node[key];
136
+ if (typeof value !== "string" || value.length === 0) {
137
+ throw new ValueTypeEntryError(file, `'${key}' must be a non-empty string`);
138
+ }
139
+ return value;
140
+ }
141
+
142
+ function readParameters(file: string, raw: unknown): ValueTypeParameter[] {
143
+ if (raw === undefined) return [];
144
+ if (!Array.isArray(raw)) throw new ValueTypeEntryError(file, "'parameters' must be a sequence");
145
+ const params = raw.map((entry, i) => {
146
+ if (!isPlainObject(entry)) {
147
+ throw new ValueTypeEntryError(file, `parameters[${i}] must be a mapping`);
148
+ }
149
+ for (const key of Object.keys(entry)) {
150
+ if (key !== "name" && key !== "description" && key !== "element") {
151
+ throw new ValueTypeEntryError(file, `parameters[${i}] has no key '${key}'`);
152
+ }
153
+ }
154
+ if (entry.element !== undefined && typeof entry.element !== "boolean") {
155
+ throw new ValueTypeEntryError(file, `parameters[${i}].element must be a boolean when present`);
156
+ }
157
+ const name = requireString(file, entry, "name");
158
+ return {
159
+ name,
160
+ ...(entry.element === true ? { element: true as const } : {}),
161
+ ...(entry.description === undefined
162
+ ? {}
163
+ : { description: requireString(file, entry, "description") }),
164
+ };
165
+ });
166
+ // Two element parameters would make "the element of this value" ambiguous, and
167
+ // the reader is the only place that can refuse it — every consumer takes the
168
+ // first match and would silently pick one.
169
+ if (params.filter((p) => p.element).length > 1) {
170
+ throw new ValueTypeEntryError(file, "at most one parameter may declare 'element'");
171
+ }
172
+ return params;
173
+ }
174
+
175
+ /**
176
+ * Read one entry file's parsed data.
177
+ *
178
+ * Reading is STRICT and the vocabulary is closed at every level. A malformed or
179
+ * typo'd entry is an authoring mistake whose only other outcome is a type that
180
+ * quietly is not in the vocabulary — which reads to an author as "unknown name",
181
+ * pointing at their manifest instead of at the entry.
182
+ */
183
+ export function parseValueTypeEntry(file: string, data: unknown): ValueTypeEntry {
184
+ if (!isPlainObject(data)) throw new ValueTypeEntryError(file, "an entry must be a mapping");
185
+ for (const key of Object.keys(data)) {
186
+ if (!(ENTRY_KEYS as readonly string[]).includes(key)) {
187
+ throw new ValueTypeEntryError(
188
+ file,
189
+ `an entry has no key '${key}'. Known keys: ${ENTRY_KEYS.join(", ")}.`,
190
+ );
191
+ }
192
+ }
193
+
194
+ const name = requireString(file, data, "name");
195
+ if (!name.startsWith("Telo.")) {
196
+ throw new ValueTypeEntryError(
197
+ file,
198
+ `'name' must be Telo.-qualified — a representation is kernel-owned and cannot be module-defined`,
199
+ );
200
+ }
201
+ const representation = requireString(file, data, "representation");
202
+ if (representation !== "json" && representation !== "instance") {
203
+ throw new ValueTypeEntryError(file, `'representation' must be 'json' or 'instance'`);
204
+ }
205
+ if (data.live !== undefined && typeof data.live !== "boolean") {
206
+ throw new ValueTypeEntryError(file, "'live' must be a boolean when present");
207
+ }
208
+
209
+ // The two representations take disjoint parameters, and mixing them is a
210
+ // statement with no meaning: a `json` value has no constructor to assert, and
211
+ // an `instance` has no JSON base to refine.
212
+ if (representation === "json") {
213
+ if (data.binding !== undefined) {
214
+ throw new ValueTypeEntryError(file, "a 'json' representation takes no 'binding'");
215
+ }
216
+ const base = requireString(file, data, "base");
217
+ if (!(base in CEL_TYPE_FOR_BASE)) {
218
+ throw new ValueTypeEntryError(
219
+ file,
220
+ `'base' '${base}' is not a JSON Schema type (${Object.keys(CEL_TYPE_FOR_BASE).join(", ")})`,
221
+ );
222
+ }
223
+ if (data.live === true) {
224
+ throw new ValueTypeEntryError(file, "a 'json' representation cannot be 'live' — it is data");
225
+ }
226
+ } else {
227
+ if (data.base !== undefined) {
228
+ throw new ValueTypeEntryError(file, "an 'instance' representation takes no 'base'");
229
+ }
230
+ requireString(file, data, "binding");
231
+ }
232
+
233
+ const entry: ValueTypeEntry = {
234
+ name,
235
+ representation,
236
+ ...(representation === "json" ? { base: data.base as string } : { binding: data.binding as string }),
237
+ live: data.live === true,
238
+ parameters: readParameters(file, data.parameters),
239
+ description: requireString(file, data, "description"),
240
+ };
241
+ return entry;
242
+ }
243
+
244
+ function buildRegistry(): ReadonlyMap<string, ValueTypeEntry> {
245
+ const registry = new Map<string, ValueTypeEntry>();
246
+ for (const [file, data] of VALUE_TYPE_ENTRY_FILES) {
247
+ const entry = parseValueTypeEntry(file, data);
248
+ if (registry.has(entry.name)) {
249
+ throw new ValueTypeEntryError(file, `'${entry.name}' is already declared by another entry`);
250
+ }
251
+ // A binding with no row in THIS host's table is a hard error, never a
252
+ // skipped assertion: a type that cannot be asserted would silently exempt
253
+ // every slot declaring it, converting a contract into a hole. The same class
254
+ // of failure as an unrecognized `use` token degrading to the legacy reading.
255
+ if (entry.binding !== undefined && !(entry.binding in VALUE_TYPE_BINDINGS)) {
256
+ throw new ValueTypeEntryError(
257
+ file,
258
+ `binding '${entry.binding}' has no row in this runtime's table — a value type ` +
259
+ `whose assertion cannot be produced would silently exempt every slot that declares it`,
260
+ );
261
+ }
262
+ registry.set(entry.name, entry);
263
+ }
264
+ // Defence in depth against the packaging mistake, because the failure it
265
+ // produces is indistinguishable from an author's typo: every `x-telo-type`
266
+ // becomes an unknown name, reported against manifests that are correct. The
267
+ // build script refuses a missing source directory; this refuses the state that
268
+ // would reach a user if some other path ever produced it.
269
+ if (registry.size === 0) {
270
+ throw new Error(
271
+ "The value-type vocabulary is empty. `sdk/value-types/*.json` did not reach this " +
272
+ "build — check the file allowlist of whatever packaged it. Continuing would report " +
273
+ "every declared value type as an unknown name.",
274
+ );
275
+ }
276
+ return registry;
277
+ }
278
+
279
+ /** Every declared value type, keyed by its `Telo.`-qualified name. */
280
+ export const VALUE_TYPES: ReadonlyMap<string, ValueTypeEntry> = buildRegistry();
281
+
282
+ /** The declared names, in entry order — what `telo cel types` and the generated
283
+ * docs section enumerate. */
284
+ export function valueTypeNames(): string[] {
285
+ return [...VALUE_TYPES.keys()];
286
+ }
287
+
288
+ /** A read `x-telo-type` annotation: the type it names plus its type arguments. */
289
+ export interface ValueTypeSlot {
290
+ /** The name exactly as written, which is also the canonical one — the
291
+ * vocabulary is closed, so there is nothing to resolve. */
292
+ readonly name: string;
293
+ /** The registry entry, or undefined when the name is not a declared type.
294
+ * Present separately from `name` so a diagnostic can report the name the
295
+ * author wrote rather than swallowing an unknown one. */
296
+ readonly entry: ValueTypeEntry | undefined;
297
+ /** Type arguments by parameter name. Each value is a schema node. */
298
+ readonly args: Readonly<Record<string, unknown>>;
299
+ }
300
+
301
+ /**
302
+ * Read the annotation off a schema node.
303
+ *
304
+ * Two spellings, one meaning: a bare name (`x-telo-type: Telo.Bytes`) and the
305
+ * object form carrying arguments (`{ name: Telo.Stream, of: … }`). Returns
306
+ * undefined when the node carries no annotation at all — an unknown NAME still
307
+ * returns a slot, with `entry` undefined, because silently reading it as "no
308
+ * value type" is the degrade this annotation replaced.
309
+ */
310
+ export function readValueTypeSlot(schema: unknown): ValueTypeSlot | undefined {
311
+ if (!isPlainObject(schema)) return undefined;
312
+ const raw = schema[X_TELO_TYPE];
313
+ if (raw === undefined) return undefined;
314
+
315
+ if (typeof raw === "string") {
316
+ return { name: raw, entry: VALUE_TYPES.get(raw), args: {} };
317
+ }
318
+ if (isPlainObject(raw)) {
319
+ const name = typeof raw.name === "string" ? raw.name : "";
320
+ const args: Record<string, unknown> = {};
321
+ for (const [key, value] of Object.entries(raw)) {
322
+ if (key === "name") continue;
323
+ // A bare NAME as an argument is sugar for a schema node carrying only that
324
+ // annotation, so `of: Telo.Bytes` and `of: { x-telo-type: Telo.Bytes }`
325
+ // are one thing. Normalized HERE, in the single reader, so no consumer
326
+ // re-derives it — a comparator that saw the string form would compare a
327
+ // string against a schema and quietly conclude nothing.
328
+ args[key] = typeof value === "string" ? { [X_TELO_TYPE]: value } : value;
329
+ }
330
+ return { name, entry: VALUE_TYPES.get(name), args };
331
+ }
332
+ return { name: "", entry: undefined, args: {} };
333
+ }
334
+
335
+ /** The entry a schema node declares, or undefined. The common read. */
336
+ export function valueTypeOf(schema: unknown): ValueTypeEntry | undefined {
337
+ return readValueTypeSlot(schema)?.entry;
338
+ }
339
+
340
+ /** True when this node declares a value type at all (known or not). */
341
+ export function isValueTypeSlot(schema: unknown): boolean {
342
+ return readValueTypeSlot(schema) !== undefined;
343
+ }
344
+
345
+ /** True when the node declares a `live` type, so its value is exempt from
346
+ * validation — never traversed, never asserted. Typing is unaffected. */
347
+ export function isLiveSlot(schema: unknown): boolean {
348
+ return valueTypeOf(schema)?.live === true;
349
+ }
350
+
351
+ /** True when the node declares a type represented as a runtime instance —
352
+ * the values no manifest literal can ever be. */
353
+ export function isInstanceSlot(schema: unknown): boolean {
354
+ return valueTypeOf(schema)?.representation === "instance";
355
+ }
356
+
357
+ /**
358
+ * The schema of what iterating a value at this slot yields, or undefined when
359
+ * the slot declares no value type, or one with no element parameter.
360
+ *
361
+ * The whole point of reading it from the entry is that no consumer names a type:
362
+ * a future iterable value type is covered by declaring `element` on its own
363
+ * parameter, with nothing to change here or in the analyzer. An element
364
+ * parameter left unsupplied means *any*, exactly as every other omitted argument
365
+ * does, so an unparameterized use degrades to permissive rather than to nothing.
366
+ */
367
+ export function elementSchemaOf(schema: unknown): unknown | undefined {
368
+ const slot = readValueTypeSlot(schema);
369
+ const parameter = slot?.entry?.parameters.find((p) => p.element);
370
+ if (!parameter) return undefined;
371
+ return slot!.args[parameter.name] ?? {};
372
+ }
373
+
374
+ /** The binding row for a schema node's declared type, or undefined when it
375
+ * declares none / declares a `json` one. */
376
+ export function bindingOf(schema: unknown): ValueTypeBinding | undefined {
377
+ const binding = valueTypeOf(schema)?.binding;
378
+ return binding === undefined ? undefined : VALUE_TYPE_BINDINGS[binding];
379
+ }
380
+
381
+ /** The stand-in for a CEL leaf at this slot, or undefined when the slot declares
382
+ * no instance type (ordinary JSON, so the schema's own shape decides) or a live
383
+ * one (nothing validates it, so nothing has to satisfy anything). */
384
+ export function valueTypePlaceholder(schema: unknown): unknown | undefined {
385
+ return bindingOf(schema)?.placeholder?.();
386
+ }
387
+
388
+ /**
389
+ * The CEL type a value at this slot carries.
390
+ *
391
+ * A `json` representation carries its own NAME as a nominal brand — which is the
392
+ * whole point of one, since a `Telo.TcpPort` and a `Telo.UdpPort` are structurally
393
+ * identical. An `instance` carries whatever its binding says.
394
+ */
395
+ export function celTypeOfValueType(entry: ValueTypeEntry): string {
396
+ if (entry.representation === "json") return entry.name;
397
+ const binding = VALUE_TYPE_BINDINGS[entry.binding!];
398
+ return binding!.celType;
399
+ }
400
+
401
+ /** The CEL type a brand degrades to where the consuming slot declares none —
402
+ * gradual typing, so a `Telo.TcpPort` flows freely into a plain integer field.
403
+ * Undefined for an `instance`, which has no base to fall back to. */
404
+ export function celBaseOfValueType(entry: ValueTypeEntry): string | undefined {
405
+ return entry.representation === "json" ? CEL_TYPE_FOR_BASE[entry.base!] : undefined;
406
+ }
407
+
408
+ /** Every `json` representation's CEL brand → the base type it refines. The
409
+ * gradual-typing table, derived rather than hand-written. */
410
+ export function valueBrandBases(): Record<string, string> {
411
+ const out: Record<string, string> = {};
412
+ for (const entry of VALUE_TYPES.values()) {
413
+ const base = celBaseOfValueType(entry);
414
+ if (base !== undefined) out[entry.name] = base;
415
+ }
416
+ return out;
417
+ }
@@ -0,0 +1,14 @@
1
+ // GENERATED by scripts/copy-value-type-entries.mjs — do not edit, and do not commit.
2
+ // Source: sdk/value-types/*.json (lexically ordered).
3
+ import e0 from "./telo-bytes.json" with { type: "json" };
4
+ import e1 from "./telo-stream.json" with { type: "json" };
5
+ import e2 from "./telo-tcp-port.json" with { type: "json" };
6
+ import e3 from "./telo-udp-port.json" with { type: "json" };
7
+
8
+ /** Every value-type entry file, in the order the registry reads them. */
9
+ export const VALUE_TYPE_ENTRY_FILES: ReadonlyArray<readonly [file: string, data: unknown]> = [
10
+ ["telo-bytes.json", e0],
11
+ ["telo-stream.json", e1],
12
+ ["telo-tcp-port.json", e2],
13
+ ["telo-udp-port.json", e3],
14
+ ];
@@ -0,0 +1,7 @@
1
+ {
2
+ "$comment": "Bytes are not expressible in JSON Schema's type vocabulary. `type: object` is satisfied by every object, so a mistyped literal reached the controller instead of failing check; `type: binary` is not an option, since a validator refuses to COMPILE an unknown type and a published telo.yaml would stop being JSON Schema for the hub, the editor and every third-party reader. Declaring the representation instead is what makes the check fall out: no YAML literal is ever a byte buffer, so a literal at a byte slot is rejected statically and a value arriving by reference passes.",
3
+ "name": "Telo.Bytes",
4
+ "representation": "instance",
5
+ "binding": "bytes",
6
+ "description": "Raw bytes. Never authorable inline — a byte slot is filled by reference (an `!include-bytes` embed, a resource output, a CEL expression), and the runtime asserts the value really is a byte buffer."
7
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "$comment": "`live` is what separates a stream from bytes: consuming it has effects, so it is EXEMPT from validation rather than asserted — iterating a stream to check its elements is precisely what the exemption forbids. The exemption is from VALIDATION, never from TYPING: `of` still travels through every schema-typing walk, because that is where the argument check reads it.",
3
+ "name": "Telo.Stream",
4
+ "representation": "instance",
5
+ "binding": "stream",
6
+ "live": true,
7
+ "parameters": [
8
+ {
9
+ "name": "of",
10
+ "element": true,
11
+ "description": "The element the stream yields. Any schema node — an inline shape, a value type, a `!ref` to a named shape, or another parameterized type. Omitted means any element."
12
+ }
13
+ ],
14
+ "description": "A live handle over a sequence of values, consumed by reading. Its elements are never buffered or validated, and member access past it is rejected — a consumer iterates it instead."
15
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "$comment": "A `json` representation adds nominal identity to a value the declared schema already validates. A TcpPort and a UdpPort are both integers, so nothing structural tells them apart — the name is the whole difference, and it is what makes wiring one into the other's slot a static error.",
3
+ "name": "Telo.TcpPort",
4
+ "representation": "json",
5
+ "base": "integer",
6
+ "description": "A TCP port number. Distinct from a UDP port even though both are integers, so wiring one into the other's slot is a static error."
7
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "Telo.UdpPort",
3
+ "representation": "json",
4
+ "base": "integer",
5
+ "description": "A UDP port number. Distinct from a TCP port even though both are integers, so wiring one into the other's slot is a static error."
6
+ }