@mica-js/sdk 0.3.3 → 0.4.1
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 +162 -24
- package/dist/build/cli.js +90 -26
- package/dist/build/config.d.ts +11 -0
- package/dist/build/config.js +15 -1
- package/dist/build/content.d.ts +2 -0
- package/dist/build/content.js +2 -1
- package/dist/build/prepare.d.ts +2 -0
- package/dist/build/prepare.js +2 -0
- package/dist/build/project.d.ts +6 -0
- package/dist/build/project.js +25 -8
- package/dist/build/unified-build.d.ts +38 -0
- package/dist/build/unified-build.js +65 -0
- package/dist/build/unified-defaults.d.ts +21 -0
- package/dist/build/unified-defaults.js +267 -0
- package/dist/build/unified-manifest.d.ts +34 -0
- package/dist/build/unified-manifest.js +113 -0
- package/dist/build/unified-package.d.ts +64 -0
- package/dist/build/unified-package.js +354 -0
- package/dist/build/unified-paths.d.ts +30 -0
- package/dist/build/unified-paths.js +94 -0
- package/dist/build/unified-prepare.d.ts +58 -0
- package/dist/build/unified-prepare.js +209 -0
- package/dist/build/unified-types.d.ts +20 -0
- package/dist/build/unified-types.js +253 -0
- package/dist/device.d.ts +13 -1
- package/dist/fused/agreement.d.ts +15 -0
- package/dist/fused/agreement.js +104 -0
- package/dist/fused/diagnostics.d.ts +51 -0
- package/dist/fused/diagnostics.js +97 -0
- package/dist/fused/firmware.d.ts +27 -0
- package/dist/fused/firmware.js +105 -0
- package/dist/fused/index.d.ts +29 -0
- package/dist/fused/index.js +11 -0
- package/dist/fused/model.d.ts +101 -0
- package/dist/fused/model.js +47 -0
- package/dist/fused/models.d.ts +113 -0
- package/dist/fused/models.js +445 -0
- package/dist/fused/node.d.ts +5 -0
- package/dist/fused/node.js +139 -0
- package/dist/fused/package.d.ts +40 -0
- package/dist/fused/package.js +270 -0
- package/dist/fused/prepare.d.ts +50 -0
- package/dist/fused/prepare.js +214 -0
- package/dist/fused/program-memory.d.ts +2 -0
- package/dist/fused/program-memory.js +174 -0
- package/dist/fused/program.d.ts +47 -0
- package/dist/fused/program.js +99 -0
- package/dist/fused/properties.d.ts +48 -0
- package/dist/fused/properties.js +465 -0
- package/dist/fused/runtime.d.ts +60 -0
- package/dist/fused/runtime.js +568 -0
- package/dist/fused/values.d.ts +27 -0
- package/dist/fused/values.js +98 -0
- package/package.json +20 -3
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** Diagnostics of the headless fused runtime (RFC 0025). */
|
|
2
|
+
import { FusedDocumentError } from '@mica-js/document/fused';
|
|
3
|
+
export function diagnostic(code, message, instanceId) {
|
|
4
|
+
return instanceId === undefined ? { code, message } : { code, message, instanceId };
|
|
5
|
+
}
|
|
6
|
+
/** Thrown while preparing a session; carries every problem found before failing. */
|
|
7
|
+
export class PreparationError extends Error {
|
|
8
|
+
problems;
|
|
9
|
+
constructor(problems) {
|
|
10
|
+
const first = problems[0];
|
|
11
|
+
super(first === undefined
|
|
12
|
+
? 'Fused session preparation failed.'
|
|
13
|
+
: `${first.code}${first.pointer === '' ? '' : ` at ${first.pointer}`}: ${first.message}`);
|
|
14
|
+
this.name = 'PreparationError';
|
|
15
|
+
this.problems = problems;
|
|
16
|
+
}
|
|
17
|
+
get code() {
|
|
18
|
+
return this.problems[0]?.code ?? 'runtime/prepare-failed';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Thrown by {@link createHeadlessRuntime} when preparation fails; carries all diagnostics. */
|
|
22
|
+
export class FusedPreparationError extends Error {
|
|
23
|
+
code;
|
|
24
|
+
diagnostics;
|
|
25
|
+
constructor(diagnostics) {
|
|
26
|
+
const first = diagnostics[0];
|
|
27
|
+
super(first === undefined ? 'Fused session preparation failed.' : first.message);
|
|
28
|
+
this.name = 'FusedPreparationError';
|
|
29
|
+
this.code = first?.code ?? 'runtime/prepare-failed';
|
|
30
|
+
this.diagnostics = diagnostics;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function problem(code, message, pointer = '') {
|
|
34
|
+
return { code, message, pointer };
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Normalizes a thrown value into preparation problems.
|
|
38
|
+
*
|
|
39
|
+
* Contract violations of `@mica-js/document/fused` already carry a code and a JSON Pointer per
|
|
40
|
+
* problem, so they are forwarded one to one instead of being flattened into one message.
|
|
41
|
+
*/
|
|
42
|
+
export function asPreparation(cause, fallbackCode) {
|
|
43
|
+
if (cause instanceof PreparationError) {
|
|
44
|
+
return cause.problems;
|
|
45
|
+
}
|
|
46
|
+
if (isPreparationProblem(cause)) {
|
|
47
|
+
return [cause];
|
|
48
|
+
}
|
|
49
|
+
if (cause instanceof FusedDocumentError) {
|
|
50
|
+
const problems = cause.diagnostics
|
|
51
|
+
.filter((entry) => entry.severity === 'error')
|
|
52
|
+
.map((entry) => problem(entry.code, entry.message, entry.pointer));
|
|
53
|
+
if (problems.length > 0) {
|
|
54
|
+
return problems;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
58
|
+
return [problem(fallbackCode, message)];
|
|
59
|
+
}
|
|
60
|
+
function isPreparationProblem(value) {
|
|
61
|
+
if (typeof value !== 'object' || value === null) {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
const entry = value;
|
|
65
|
+
return (typeof entry.code === 'string' &&
|
|
66
|
+
typeof entry.message === 'string' &&
|
|
67
|
+
typeof entry.pointer === 'string');
|
|
68
|
+
}
|
|
69
|
+
/** Collects the problems of one preparation phase and attributes them to an instance. */
|
|
70
|
+
export class DiagnosticBatch {
|
|
71
|
+
problems = [];
|
|
72
|
+
instanceIds = [];
|
|
73
|
+
add(cause, fallbackCode, instanceId) {
|
|
74
|
+
for (const entry of asPreparation(cause, fallbackCode)) {
|
|
75
|
+
this.problems.push(entry);
|
|
76
|
+
this.instanceIds.push(instanceId);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
addProblem(entry, instanceId) {
|
|
80
|
+
this.problems.push(entry);
|
|
81
|
+
this.instanceIds.push(instanceId);
|
|
82
|
+
}
|
|
83
|
+
fail(cause, fallbackCode, instanceId) {
|
|
84
|
+
this.add(cause, fallbackCode, instanceId);
|
|
85
|
+
throw new PreparationError(this.problems);
|
|
86
|
+
}
|
|
87
|
+
get empty() {
|
|
88
|
+
return this.problems.length === 0;
|
|
89
|
+
}
|
|
90
|
+
/** Every collected problem as a host diagnostic, then clears the batch. */
|
|
91
|
+
drain() {
|
|
92
|
+
const diagnostics = this.problems.map((entry, index) => diagnostic(entry.code, entry.pointer === '' ? entry.message : `${entry.message} (${entry.pointer})`, this.instanceIds[index]));
|
|
93
|
+
this.problems.length = 0;
|
|
94
|
+
this.instanceIds.length = 0;
|
|
95
|
+
return diagnostics;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Firmware images of the fused runtime (RFC 0026).
|
|
3
|
+
*
|
|
4
|
+
* The framework captures the source bytes, checks `maxBytes`, decodes the declared format into a
|
|
5
|
+
* read-only segmented image and hands it to the model factory. Only BIN is decoded here; HEX and
|
|
6
|
+
* ELF are recognized and rejected explicitly instead of being passed through unparsed.
|
|
7
|
+
*/
|
|
8
|
+
import type { FirmwareAddressSpace, FirmwareImage, FirmwareSegment, ReadonlyBytes } from '@mica-js/document/fused';
|
|
9
|
+
export type FirmwareFormat = 'bin' | 'hex' | 'elf';
|
|
10
|
+
/** Format implied by a reliable file name, or `undefined` when the extension is unknown. */
|
|
11
|
+
export declare function firmwareFormatOf(fileName: string): FirmwareFormat | undefined;
|
|
12
|
+
/** Whether the format is decoded by this runtime yet. */
|
|
13
|
+
export declare function isDecodedFormat(format: FirmwareFormat): format is 'bin';
|
|
14
|
+
/** Read-only byte view whose `slice` returns an independent mutable copy (RFC 0026). */
|
|
15
|
+
export declare function readonlyBytes(source: Uint8Array): ReadonlyBytes;
|
|
16
|
+
/**
|
|
17
|
+
* Freezes one image after checking segment ranges and per-space overlap.
|
|
18
|
+
*
|
|
19
|
+
* @throws {RangeError} when a segment is empty, negative or overlaps another segment of its space.
|
|
20
|
+
*/
|
|
21
|
+
export declare function createFirmwareImage(segments: readonly FirmwareSegment[]): FirmwareImage;
|
|
22
|
+
/**
|
|
23
|
+
* Builds the image of one BIN source: the byte at index `i` loads at `address + i`.
|
|
24
|
+
*
|
|
25
|
+
* @throws {RangeError} when the full range leaves the declared address space.
|
|
26
|
+
*/
|
|
27
|
+
export declare function binFirmwareImage(bytes: Uint8Array, addressSpace: string, space: FirmwareAddressSpace, address: number): FirmwareImage;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
const EXTENSIONS = new Map([
|
|
2
|
+
['bin', 'bin'],
|
|
3
|
+
['hex', 'hex'],
|
|
4
|
+
['ihx', 'hex'],
|
|
5
|
+
['elf', 'elf'],
|
|
6
|
+
['axf', 'elf'],
|
|
7
|
+
]);
|
|
8
|
+
/** Format implied by a reliable file name, or `undefined` when the extension is unknown. */
|
|
9
|
+
export function firmwareFormatOf(fileName) {
|
|
10
|
+
const dot = fileName.lastIndexOf('.');
|
|
11
|
+
if (dot < 0) {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
return EXTENSIONS.get(fileName.slice(dot + 1).toLowerCase());
|
|
15
|
+
}
|
|
16
|
+
/** Whether the format is decoded by this runtime yet. */
|
|
17
|
+
export function isDecodedFormat(format) {
|
|
18
|
+
return format === 'bin';
|
|
19
|
+
}
|
|
20
|
+
/** Read-only byte view whose `slice` returns an independent mutable copy (RFC 0026). */
|
|
21
|
+
export function readonlyBytes(source) {
|
|
22
|
+
const bytes = source.slice();
|
|
23
|
+
const target = Object.freeze({
|
|
24
|
+
get length() {
|
|
25
|
+
return bytes.length;
|
|
26
|
+
},
|
|
27
|
+
get byteLength() {
|
|
28
|
+
return bytes.length;
|
|
29
|
+
},
|
|
30
|
+
slice(start, end) {
|
|
31
|
+
return bytes.slice(start, end);
|
|
32
|
+
},
|
|
33
|
+
*[Symbol.iterator]() {
|
|
34
|
+
for (const byte of bytes) {
|
|
35
|
+
yield byte;
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
return new Proxy(target, {
|
|
40
|
+
get(object, key, receiver) {
|
|
41
|
+
if (typeof key === 'string' && /^(0|[1-9]\d*)$/.test(key)) {
|
|
42
|
+
return bytes[Number(key)];
|
|
43
|
+
}
|
|
44
|
+
return Reflect.get(object, key, receiver);
|
|
45
|
+
},
|
|
46
|
+
set() {
|
|
47
|
+
throw new TypeError('Firmware bytes are read-only');
|
|
48
|
+
},
|
|
49
|
+
defineProperty() {
|
|
50
|
+
throw new TypeError('Firmware bytes are read-only');
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/** Copies and sorts one segment so the image keeps its contract order. */
|
|
55
|
+
function segment(space, address, bytes) {
|
|
56
|
+
return Object.freeze({ addressSpace: space, address, data: readonlyBytes(bytes) });
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Freezes one image after checking segment ranges and per-space overlap.
|
|
60
|
+
*
|
|
61
|
+
* @throws {RangeError} when a segment is empty, negative or overlaps another segment of its space.
|
|
62
|
+
*/
|
|
63
|
+
export function createFirmwareImage(segments) {
|
|
64
|
+
if (segments.length === 0) {
|
|
65
|
+
throw new RangeError('A firmware image must contain at least one segment');
|
|
66
|
+
}
|
|
67
|
+
const sorted = [...segments].sort((left, right) => {
|
|
68
|
+
if (left.addressSpace !== right.addressSpace) {
|
|
69
|
+
return left.addressSpace < right.addressSpace ? -1 : 1;
|
|
70
|
+
}
|
|
71
|
+
return left.address - right.address;
|
|
72
|
+
});
|
|
73
|
+
const ends = new Map();
|
|
74
|
+
for (const entry of sorted) {
|
|
75
|
+
if (!Number.isSafeInteger(entry.address) || entry.address < 0) {
|
|
76
|
+
throw new RangeError(`Segment address in space "${entry.addressSpace}" is not a safe integer`);
|
|
77
|
+
}
|
|
78
|
+
if (entry.data.length === 0) {
|
|
79
|
+
throw new RangeError(`Segment in space "${entry.addressSpace}" has no bytes`);
|
|
80
|
+
}
|
|
81
|
+
const end = entry.address + entry.data.length;
|
|
82
|
+
const previous = ends.get(entry.addressSpace);
|
|
83
|
+
if (previous !== undefined && entry.address < previous) {
|
|
84
|
+
throw new RangeError(`Segments of space "${entry.addressSpace}" overlap`);
|
|
85
|
+
}
|
|
86
|
+
ends.set(entry.addressSpace, end);
|
|
87
|
+
}
|
|
88
|
+
return Object.freeze({ segments: Object.freeze(sorted) });
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Builds the image of one BIN source: the byte at index `i` loads at `address + i`.
|
|
92
|
+
*
|
|
93
|
+
* @throws {RangeError} when the full range leaves the declared address space.
|
|
94
|
+
*/
|
|
95
|
+
export function binFirmwareImage(bytes, addressSpace, space, address) {
|
|
96
|
+
if (bytes.length === 0) {
|
|
97
|
+
throw new RangeError('A firmware image must not be empty');
|
|
98
|
+
}
|
|
99
|
+
const end = space.start + space.size;
|
|
100
|
+
if (address < space.start || address + bytes.length > end) {
|
|
101
|
+
throw new RangeError(`BIN range [${address}, ${address + bytes.length}) leaves address space "${addressSpace}" ` +
|
|
102
|
+
`[${space.start}, ${end})`);
|
|
103
|
+
}
|
|
104
|
+
return createFirmwareImage([segment(addressSpace, address, bytes)]);
|
|
105
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@mica-js/sdk/fused`: author API of the unified device model (RFC 0021) and the production
|
|
3
|
+
* headless runtime of the fused contract (RFC 0024 / RFC 0025 / RFC 0026).
|
|
4
|
+
*
|
|
5
|
+
* The runtime is explicit and in-process: the caller supplies the document, the locked package
|
|
6
|
+
* registry, the module loader and any external resource or firmware project sources. Untrusted
|
|
7
|
+
* browser isolation remains the editor integration's responsibility.
|
|
8
|
+
*/
|
|
9
|
+
export type { AsyncMethods, EventListeners, Methods, ModelClient, ModelContext, ModelEvent, ModelEventEmitter, ModelEvents, ModelFactory, ModelInstance, ModelModule, Params, Result, Value, ValueType, } from './model.js';
|
|
10
|
+
export { MethodError } from './model.js';
|
|
11
|
+
export { parseUnifiedManifest, validateModelValue } from '@mica-js/document/fused';
|
|
12
|
+
export type { CreatedModel, FusedModelContext, FusedModelFactory, ModelBindingOptions, ModelInterface, RuntimeMethod, RuntimeModelClient, RuntimeModelEvent, } from './models.js';
|
|
13
|
+
export { ModelBinding, ModelDisconnectedError, ModelFault } from './models.js';
|
|
14
|
+
export type { DiagnosticSink, PreparationProblem, RuntimeDiagnostic } from './diagnostics.js';
|
|
15
|
+
export { FusedPreparationError, PreparationError } from './diagnostics.js';
|
|
16
|
+
export type { FirmwareFormat } from './firmware.js';
|
|
17
|
+
export { isDecodedFormat, readonlyBytes } from './firmware.js';
|
|
18
|
+
export type { MemoryProgram, ProgramFiles, ProgramSegment, ProgramLoader, ProgramFormat, ProgramReference, } from '@mica-js/document/fused';
|
|
19
|
+
export type { ProgramArtifact, ProgramFile, ProgramTarget, ProgramProject, ProgramProjectProvider, ProgramProjectSelectionRequest, ProgramSources, } from './program.js';
|
|
20
|
+
export { PROGRAM_LIMITS, ProgramError, checkProgramPath, createProgramFiles } from './program.js';
|
|
21
|
+
export { decodeMemoryProgram } from './program-memory.js';
|
|
22
|
+
export type { BoardPropertyValue, PropertyResolution, PropertyResolutionInput, ResourceRequest, ResourceResolver, } from './properties.js';
|
|
23
|
+
export { resolveInstanceProperties } from './properties.js';
|
|
24
|
+
export type { PreparedDevice, PreparedInstance, PreparedModel, PreparedSession, } from './prepare.js';
|
|
25
|
+
export { prepareFusedSession } from './prepare.js';
|
|
26
|
+
export type { VerifiedPackage } from './package.js';
|
|
27
|
+
export { MICA_HOST_API_VERSION, isPackagePath, openDevicePackage, satisfiesRange, } from './package.js';
|
|
28
|
+
export type { HeadlessRuntime, HeadlessRuntimeOptions, RuntimeState } from './runtime.js';
|
|
29
|
+
export { createHeadlessRuntime, FusedRuntimeError } from './runtime.js';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { MethodError } from './model.js';
|
|
2
|
+
export { parseUnifiedManifest, validateModelValue } from '@mica-js/document/fused';
|
|
3
|
+
export { ModelBinding, ModelDisconnectedError, ModelFault } from './models.js';
|
|
4
|
+
export { FusedPreparationError, PreparationError } from './diagnostics.js';
|
|
5
|
+
export { isDecodedFormat, readonlyBytes } from './firmware.js';
|
|
6
|
+
export { PROGRAM_LIMITS, ProgramError, checkProgramPath, createProgramFiles } from './program.js';
|
|
7
|
+
export { decodeMemoryProgram } from './program-memory.js';
|
|
8
|
+
export { resolveInstanceProperties } from './properties.js';
|
|
9
|
+
export { prepareFusedSession } from './prepare.js';
|
|
10
|
+
export { MICA_HOST_API_VERSION, isPackagePath, openDevicePackage, satisfiesRange, } from './package.js';
|
|
11
|
+
export { createHeadlessRuntime, FusedRuntimeError } from './runtime.js';
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Author-facing surface of a unified device model (RFC 0021).
|
|
3
|
+
*
|
|
4
|
+
* A model entry is a self-contained module that exports the device `model` IR and a synchronous
|
|
5
|
+
* `create` factory. The factory receives a {@link ModelContext}: the core device context without
|
|
6
|
+
* the legacy topic bridge, plus the resolved property snapshot and the declared event outlets.
|
|
7
|
+
*/
|
|
8
|
+
import type { TimePs } from '@mica-js/core';
|
|
9
|
+
import type { Disposable, Event } from '@mica-js/core/lifecycle';
|
|
10
|
+
import type { DeviceIR } from '@mica-js/device-model';
|
|
11
|
+
import type { Value, ValueType } from '@mica-js/document/fused';
|
|
12
|
+
/** Declared method map of one model instance. */
|
|
13
|
+
export type Methods = Readonly<Record<string, (params: never) => Value>>;
|
|
14
|
+
/** Declared parameter value of one method. */
|
|
15
|
+
export type Params<F> = F extends (params: infer P) => Value ? P : never;
|
|
16
|
+
/** Declared result value of one method. */
|
|
17
|
+
export type Result<F> = F extends (params: never) => infer R ? R : never;
|
|
18
|
+
/** Host-side projection of {@link Methods}: every call is asynchronous. */
|
|
19
|
+
export type AsyncMethods<M extends Methods> = {
|
|
20
|
+
readonly [K in keyof M]: (params: Params<M[K]>) => Promise<Result<M[K]>>;
|
|
21
|
+
};
|
|
22
|
+
/** Outlet the model fires one declared event payload through. */
|
|
23
|
+
export interface ModelEventEmitter<T> {
|
|
24
|
+
/** Delivers an independent snapshot of `value` to the listeners active at that moment. */
|
|
25
|
+
fire(value: T): void;
|
|
26
|
+
/**
|
|
27
|
+
* Delivers `value` after the payload takes ownership of `buffers`.
|
|
28
|
+
*
|
|
29
|
+
* Each buffer must be covered exactly by one `Uint8Array` member of the payload; a successful
|
|
30
|
+
* call hands ownership over through the host transfer hooks.
|
|
31
|
+
*/
|
|
32
|
+
fireTransferred(value: T, buffers: readonly ArrayBuffer[]): void;
|
|
33
|
+
}
|
|
34
|
+
/** Event outlets of a model, keyed by the `model.events` declaration. */
|
|
35
|
+
export type ModelEvents<E extends Readonly<Record<string, Value>>> = {
|
|
36
|
+
readonly [K in keyof E]: ModelEventEmitter<E[K]>;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Model context: the core device context without `props` and the legacy `topics` bridge.
|
|
40
|
+
*
|
|
41
|
+
* `props` is the resolved, independent and read-only property snapshot; `events` are the declared
|
|
42
|
+
* outlets and only expose firing, never subscription.
|
|
43
|
+
*/
|
|
44
|
+
export type ModelContext<C extends object, P extends object, E extends Readonly<Record<string, Value>>> = Omit<C, 'props' | 'topics'> & {
|
|
45
|
+
readonly props: Readonly<P>;
|
|
46
|
+
readonly events: ModelEvents<E>;
|
|
47
|
+
};
|
|
48
|
+
/** Live model instance returned by the entry factory. */
|
|
49
|
+
export interface ModelInstance<M extends Methods, B> extends Disposable {
|
|
50
|
+
readonly methods: M;
|
|
51
|
+
/** Consumes the compiled adapter output of one virtual step. */
|
|
52
|
+
sync(batch: B): void;
|
|
53
|
+
}
|
|
54
|
+
/** Shape of a model entry module: the device IR plus its synchronous factory. */
|
|
55
|
+
export interface ModelModule<IR = DeviceIR, C extends object = object, P extends object = object, E extends Readonly<Record<string, Value>> = Readonly<Record<string, Value>>, M extends Methods = Methods, B = unknown> {
|
|
56
|
+
readonly model: IR;
|
|
57
|
+
create(context: ModelContext<C, P, E>): ModelInstance<M, B>;
|
|
58
|
+
}
|
|
59
|
+
/** One delivered model event: payload, production time and per-instance sequence. */
|
|
60
|
+
export interface ModelEvent<T> {
|
|
61
|
+
readonly value: T;
|
|
62
|
+
readonly simTime: TimePs;
|
|
63
|
+
/** Strictly increasing safe integer per model instance lifetime; a new model restarts at 1. */
|
|
64
|
+
readonly sequence: number;
|
|
65
|
+
}
|
|
66
|
+
/** Declared event subscriptions of one model instance. */
|
|
67
|
+
export type EventListeners<E extends Readonly<Record<string, Value>>> = {
|
|
68
|
+
readonly [K in keyof E]: Event<ModelEvent<E[K]>>;
|
|
69
|
+
};
|
|
70
|
+
/** Host-side client of one model instance. */
|
|
71
|
+
export interface ModelClient<M extends Methods, E extends Readonly<Record<string, Value>>> {
|
|
72
|
+
readonly methods: AsyncMethods<M>;
|
|
73
|
+
readonly events: EventListeners<E>;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Realm-wide marker of {@link MethodError}.
|
|
77
|
+
*
|
|
78
|
+
* A built device artifact bundles its own copy of this SDK, so `instanceof` alone cannot recognize
|
|
79
|
+
* the class it constructs. The registered symbol is shared by every copy in one realm, which is
|
|
80
|
+
* what the runtime checks first.
|
|
81
|
+
*/
|
|
82
|
+
export declare const METHOD_ERROR_TAG: unique symbol;
|
|
83
|
+
/**
|
|
84
|
+
* Business rejection of one model method (RFC 0021).
|
|
85
|
+
*
|
|
86
|
+
* The host keeps `code`, `message` and the optional `details` value intact and rejects the call
|
|
87
|
+
* without treating the model as faulted.
|
|
88
|
+
*/
|
|
89
|
+
export declare class MethodError extends Error {
|
|
90
|
+
readonly code: string;
|
|
91
|
+
readonly details?: Value;
|
|
92
|
+
constructor(code: string, message: string, details?: Value);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Whether a thrown value is a `MethodError`, including one constructed by a bundled copy of this
|
|
96
|
+
* SDK: the marker symbol or the class name plus a string `code` is enough.
|
|
97
|
+
*/
|
|
98
|
+
export declare function isMethodError(value: unknown): value is MethodError;
|
|
99
|
+
/** Signature a model factory has for one manifest interface; handy for typed implementations. */
|
|
100
|
+
export type ModelFactory<C extends object = object, P extends object = object, E extends Readonly<Record<string, Value>> = Readonly<Record<string, Value>>, M extends Methods = Methods, B = unknown> = (context: ModelContext<C, P, E>) => ModelInstance<M, B>;
|
|
101
|
+
export type { Value, ValueType };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Realm-wide marker of {@link MethodError}.
|
|
3
|
+
*
|
|
4
|
+
* A built device artifact bundles its own copy of this SDK, so `instanceof` alone cannot recognize
|
|
5
|
+
* the class it constructs. The registered symbol is shared by every copy in one realm, which is
|
|
6
|
+
* what the runtime checks first.
|
|
7
|
+
*/
|
|
8
|
+
export const METHOD_ERROR_TAG = Symbol.for('mica-js.sdk/method-error');
|
|
9
|
+
/**
|
|
10
|
+
* Business rejection of one model method (RFC 0021).
|
|
11
|
+
*
|
|
12
|
+
* The host keeps `code`, `message` and the optional `details` value intact and rejects the call
|
|
13
|
+
* without treating the model as faulted.
|
|
14
|
+
*/
|
|
15
|
+
export class MethodError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
details;
|
|
18
|
+
constructor(code, message, details) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = 'MethodError';
|
|
21
|
+
this.code = code;
|
|
22
|
+
if (details !== undefined) {
|
|
23
|
+
this.details = details;
|
|
24
|
+
}
|
|
25
|
+
Object.defineProperty(this, METHOD_ERROR_TAG, { value: true });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Whether a thrown value is a `MethodError`, including one constructed by a bundled copy of this
|
|
30
|
+
* SDK: the marker symbol or the class name plus a string `code` is enough.
|
|
31
|
+
*/
|
|
32
|
+
export function isMethodError(value) {
|
|
33
|
+
if (typeof value !== 'object' || value === null) {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
if (value instanceof MethodError) {
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
const candidate = value;
|
|
40
|
+
if (typeof candidate.code !== 'string') {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (value[METHOD_ERROR_TAG] === true) {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
return candidate.name === 'MethodError' && typeof value.message === 'string';
|
|
47
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host side of one model instance (RFC 0021).
|
|
3
|
+
*
|
|
4
|
+
* The binding wraps the author factory: it builds the model context from the core device context
|
|
5
|
+
* without the legacy topic bridge, validates the returned method interface, owns the declared event
|
|
6
|
+
* outlets, turns business rejections into `MethodError` rejections and everything else into a model
|
|
7
|
+
* fault, and keeps the client used by the host honest at runtime.
|
|
8
|
+
*/
|
|
9
|
+
import type { TimePs } from '@mica-js/core';
|
|
10
|
+
import type { Event } from '@mica-js/core/lifecycle';
|
|
11
|
+
import type { Value, ValueType } from '@mica-js/document/fused';
|
|
12
|
+
import type { DeviceAdapter, DeviceBatch, DeviceContext } from '@mica-js/simulator';
|
|
13
|
+
import type { ModelContext, ModelEvent } from './model.js';
|
|
14
|
+
import type { RuntimeDiagnostic } from './diagnostics.js';
|
|
15
|
+
/** One declared event as the host observer sees it (installed before model initialization). */
|
|
16
|
+
export interface RuntimeModelEvent {
|
|
17
|
+
readonly instanceId: string;
|
|
18
|
+
/** Declared event name, e.g. `onDidBrightnessChange`. */
|
|
19
|
+
readonly event: string;
|
|
20
|
+
readonly payload: ModelEvent<Value>;
|
|
21
|
+
}
|
|
22
|
+
/** One method of a host-side client: parameters and result are checked at runtime. */
|
|
23
|
+
export type RuntimeMethod = (params: Value) => Promise<Value>;
|
|
24
|
+
/**
|
|
25
|
+
* Dynamic client of one model instance.
|
|
26
|
+
*
|
|
27
|
+
* Only the names declared by the manifest resolve; the runtime validates parameter and result
|
|
28
|
+
* values against the declared types, so no generic type parameter pretends to know more than the
|
|
29
|
+
* running manifest does.
|
|
30
|
+
*/
|
|
31
|
+
export interface RuntimeModelClient {
|
|
32
|
+
readonly methods: Readonly<Record<string, RuntimeMethod>>;
|
|
33
|
+
readonly events: Readonly<Record<string, Event<ModelEvent<Value>> | undefined>>;
|
|
34
|
+
}
|
|
35
|
+
/** A model contract violation: its interface, payloads or execution are wrong. */
|
|
36
|
+
export declare class ModelFault extends Error {
|
|
37
|
+
readonly code: string;
|
|
38
|
+
constructor(code: string, message: string);
|
|
39
|
+
}
|
|
40
|
+
/** Raised for a client whose model was replaced, faulted or disposed. */
|
|
41
|
+
export declare class ModelDisconnectedError extends Error {
|
|
42
|
+
/** Contract diagnostic code (RFC 0021 `model/disconnected`). */
|
|
43
|
+
readonly code = "model/disconnected";
|
|
44
|
+
constructor(message?: string);
|
|
45
|
+
}
|
|
46
|
+
/** Model context as the fused runtime hands it to the author factory. */
|
|
47
|
+
export type FusedModelContext = ModelContext<DeviceContext, Record<string, unknown>, Readonly<Record<string, Value>>>;
|
|
48
|
+
/** Author factory after the module boundary check. */
|
|
49
|
+
export type FusedModelFactory = (context: FusedModelContext) => unknown;
|
|
50
|
+
/** Live model instance as this host sees it; the shape is checked before it is stored. */
|
|
51
|
+
export interface CreatedModel {
|
|
52
|
+
readonly methods: Record<string, (params: unknown) => unknown>;
|
|
53
|
+
sync(batch: DeviceBatch): unknown;
|
|
54
|
+
dispose(): unknown;
|
|
55
|
+
}
|
|
56
|
+
/** Declared interface of one model instance. */
|
|
57
|
+
export interface ModelInterface {
|
|
58
|
+
readonly methods: Readonly<Record<string, {
|
|
59
|
+
readonly params: ValueType;
|
|
60
|
+
readonly returns: ValueType;
|
|
61
|
+
}>>;
|
|
62
|
+
readonly events: Readonly<Record<string, ValueType>>;
|
|
63
|
+
readonly types: Readonly<Record<string, ValueType>>;
|
|
64
|
+
}
|
|
65
|
+
export interface ModelBindingOptions extends ModelInterface {
|
|
66
|
+
readonly instanceId: string;
|
|
67
|
+
/** Resolved property snapshot handed to the factory. */
|
|
68
|
+
readonly props: Readonly<Record<string, unknown>>;
|
|
69
|
+
readonly factory: FusedModelFactory;
|
|
70
|
+
readonly observer?: (event: RuntimeModelEvent) => void;
|
|
71
|
+
readonly report: (entry: RuntimeDiagnostic) => void;
|
|
72
|
+
/** Why model input is not allowed right now; `undefined` means it is. */
|
|
73
|
+
readonly blocked: () => string | undefined;
|
|
74
|
+
readonly now: () => TimePs;
|
|
75
|
+
}
|
|
76
|
+
export declare class ModelBinding {
|
|
77
|
+
#private;
|
|
78
|
+
constructor(options: ModelBindingOptions);
|
|
79
|
+
get instanceId(): string;
|
|
80
|
+
get live(): boolean;
|
|
81
|
+
/** Parameter and result types of one declared method, or `undefined` for an unknown name. */
|
|
82
|
+
methodDefinition(name: string): {
|
|
83
|
+
readonly params: ValueType;
|
|
84
|
+
readonly returns: ValueType;
|
|
85
|
+
} | undefined;
|
|
86
|
+
/**
|
|
87
|
+
* Creates the adapter the board registers for this instance.
|
|
88
|
+
*
|
|
89
|
+
* The factory runs here, so interface checks and initial events happen during the board's
|
|
90
|
+
* initialization phase.
|
|
91
|
+
*/
|
|
92
|
+
create(base: DeviceContext): DeviceAdapter;
|
|
93
|
+
/** Synchronous invocation used at a serialized safe boundary. */
|
|
94
|
+
invoke(name: string, params: unknown): unknown;
|
|
95
|
+
/**
|
|
96
|
+
* Captures and validates one method parameter value before it is queued.
|
|
97
|
+
*
|
|
98
|
+
* Parameter failures reject the call without executing the handler and without faulting the
|
|
99
|
+
* model, so they are reported to the caller only.
|
|
100
|
+
*/
|
|
101
|
+
prepareParams(name: string, value: unknown): Value;
|
|
102
|
+
/** Captures an independent snapshot of one method result and validates it. */
|
|
103
|
+
captureResult(name: string, value: unknown): Value;
|
|
104
|
+
/**
|
|
105
|
+
* Host client of this instance.
|
|
106
|
+
*
|
|
107
|
+
* `invoke` is the runtime scheduler entry point: every declared method resolves to a function
|
|
108
|
+
* that validates its parameters, waits for the next safe boundary and returns the result value.
|
|
109
|
+
*/
|
|
110
|
+
client(invoke: (name: string, params: Value) => Promise<Value>): RuntimeModelClient;
|
|
111
|
+
/** Marks the binding dead after its model was replaced or released. */
|
|
112
|
+
invalidate(): void;
|
|
113
|
+
}
|