@mica-js/sdk 0.3.2 → 0.4.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.
Files changed (54) hide show
  1. package/README.md +162 -24
  2. package/dist/build/cli.js +90 -26
  3. package/dist/build/config.d.ts +11 -0
  4. package/dist/build/config.js +15 -1
  5. package/dist/build/content.d.ts +2 -0
  6. package/dist/build/content.js +2 -1
  7. package/dist/build/prepare.d.ts +2 -0
  8. package/dist/build/prepare.js +2 -0
  9. package/dist/build/project.d.ts +6 -0
  10. package/dist/build/project.js +25 -8
  11. package/dist/build/unified-build.d.ts +38 -0
  12. package/dist/build/unified-build.js +65 -0
  13. package/dist/build/unified-defaults.d.ts +21 -0
  14. package/dist/build/unified-defaults.js +267 -0
  15. package/dist/build/unified-manifest.d.ts +34 -0
  16. package/dist/build/unified-manifest.js +113 -0
  17. package/dist/build/unified-package.d.ts +64 -0
  18. package/dist/build/unified-package.js +354 -0
  19. package/dist/build/unified-paths.d.ts +30 -0
  20. package/dist/build/unified-paths.js +94 -0
  21. package/dist/build/unified-prepare.d.ts +58 -0
  22. package/dist/build/unified-prepare.js +209 -0
  23. package/dist/build/unified-types.d.ts +20 -0
  24. package/dist/build/unified-types.js +253 -0
  25. package/dist/device.d.ts +13 -1
  26. package/dist/fused/agreement.d.ts +15 -0
  27. package/dist/fused/agreement.js +104 -0
  28. package/dist/fused/diagnostics.d.ts +51 -0
  29. package/dist/fused/diagnostics.js +97 -0
  30. package/dist/fused/firmware.d.ts +27 -0
  31. package/dist/fused/firmware.js +105 -0
  32. package/dist/fused/index.d.ts +29 -0
  33. package/dist/fused/index.js +11 -0
  34. package/dist/fused/model.d.ts +101 -0
  35. package/dist/fused/model.js +47 -0
  36. package/dist/fused/models.d.ts +113 -0
  37. package/dist/fused/models.js +445 -0
  38. package/dist/fused/node.d.ts +5 -0
  39. package/dist/fused/node.js +139 -0
  40. package/dist/fused/package.d.ts +40 -0
  41. package/dist/fused/package.js +270 -0
  42. package/dist/fused/prepare.d.ts +50 -0
  43. package/dist/fused/prepare.js +214 -0
  44. package/dist/fused/program-memory.d.ts +2 -0
  45. package/dist/fused/program-memory.js +174 -0
  46. package/dist/fused/program.d.ts +47 -0
  47. package/dist/fused/program.js +99 -0
  48. package/dist/fused/properties.d.ts +48 -0
  49. package/dist/fused/properties.js +465 -0
  50. package/dist/fused/runtime.d.ts +60 -0
  51. package/dist/fused/runtime.js +568 -0
  52. package/dist/fused/values.d.ts +27 -0
  53. package/dist/fused/values.js +98 -0
  54. package/package.json +20 -3
@@ -0,0 +1,465 @@
1
+ import { PreparationError, problem } from './diagnostics.js';
2
+ import { binFirmwareImage, firmwareFormatOf, isDecodedFormat, readonlyBytes, } from './firmware.js';
3
+ import { isPackagePath } from './package.js';
4
+ import { checkProgramPath, createProgramFiles, readProgramArchive, PROGRAM_LIMITS, ProgramError, } from './program.js';
5
+ import { decodeMemoryProgram } from './program-memory.js';
6
+ /**
7
+ * Resolves every declared property of one instance.
8
+ *
9
+ * @throws {PreparationError} listing every property that cannot be prepared.
10
+ */
11
+ export async function resolveInstanceProperties(input) {
12
+ const problems = [];
13
+ const props = {};
14
+ // `binary` / `image` reach the model as read-only snapshots and the core as plain bytes.
15
+ const boardBytes = new Map();
16
+ const descriptors = input.descriptors;
17
+ for (const key of Object.keys(input.overrides)) {
18
+ if (!Object.hasOwn(descriptors, key)) {
19
+ problems.push(problem('schema/invalid-value', `Instance ${input.instanceId} sets the undeclared property "${key}".`, pointerOf(input.pointer, key)));
20
+ }
21
+ }
22
+ for (const [name, descriptor] of Object.entries(descriptors)) {
23
+ const pointer = pointerOf(input.pointer, name);
24
+ const raw = Object.hasOwn(input.overrides, name)
25
+ ? input.overrides[name]
26
+ : descriptor.default;
27
+ if (raw === undefined) {
28
+ problems.push(problem('schema/missing-field', `Property "${name}" of ${input.instanceId} has neither a default nor an instance value.`, pointer));
29
+ continue;
30
+ }
31
+ if (raw === null) {
32
+ if (descriptor.nullable !== true) {
33
+ problems.push(problem('schema/invalid-value', `Property "${name}" of ${input.instanceId} is not nullable.`, pointer));
34
+ continue;
35
+ }
36
+ props[name] = null;
37
+ continue;
38
+ }
39
+ if (descriptor.type === 'program') {
40
+ const program = await resolveProgram(input, name, descriptor, raw, problems, pointer);
41
+ if (program !== undefined)
42
+ props[name] = program;
43
+ continue;
44
+ }
45
+ if (descriptor.type === 'firmware') {
46
+ const image = await resolveFirmware(input, name, descriptor, raw, problems, pointer);
47
+ if (image !== undefined) {
48
+ props[name] = image;
49
+ }
50
+ continue;
51
+ }
52
+ if (descriptor.type === 'image' || descriptor.type === 'binary') {
53
+ const bytes = await resolveBytes(input, name, descriptor, raw, problems, pointer);
54
+ if (bytes !== undefined) {
55
+ props[name] = readonlyBytes(bytes);
56
+ boardBytes.set(name, bytes);
57
+ }
58
+ continue;
59
+ }
60
+ const scalar = checkScalar(descriptor, raw, problems, pointer, input.instanceId);
61
+ if (scalar !== undefined) {
62
+ props[name] = scalar;
63
+ }
64
+ }
65
+ const boardProps = {};
66
+ for (const [name, type] of input.irProperties) {
67
+ const pointer = pointerOf(input.pointer, name);
68
+ const descriptor = descriptors[name];
69
+ if (descriptor === undefined) {
70
+ problems.push(problem('model/invalid-interface', `The model IR declares the property "${name}" but the manifest does not.`, pointer));
71
+ continue;
72
+ }
73
+ if (descriptor.type === 'firmware' || descriptor.type === 'program') {
74
+ problems.push(problem('model/invalid-interface', `Property "${name}" is a ${descriptor.type} property and must not be declared by the model IR.`, pointer));
75
+ continue;
76
+ }
77
+ const kind = type.kind === 'optional' ? type.inner.kind : type.kind;
78
+ const optional = type.kind === 'optional';
79
+ const compatible = (kind === 'number' && (descriptor.type === 'number' || descriptor.type === 'integer')) ||
80
+ (kind === 'bool' && descriptor.type === 'boolean') ||
81
+ (kind === 'string' && (descriptor.type === 'string' || descriptor.type === 'color')) ||
82
+ (kind === 'enum' && descriptor.type === 'enum') ||
83
+ (kind === 'bytes' && (descriptor.type === 'image' || descriptor.type === 'binary'));
84
+ if (!compatible) {
85
+ problems.push(problem('model/invalid-interface', `Property "${name}" is ${descriptor.type} in the manifest but ${kind} in the model IR.`, pointer));
86
+ continue;
87
+ }
88
+ if (optional !== (descriptor.nullable === true)) {
89
+ problems.push(problem('model/invalid-interface', `Property "${name}" must be declared ${optional ? 'nullable' : 'non-nullable'} in the manifest.`, pointer));
90
+ continue;
91
+ }
92
+ if (!Object.hasOwn(props, name)) {
93
+ continue;
94
+ }
95
+ const value = props[name];
96
+ if (value === null) {
97
+ boardProps[name] = value;
98
+ continue;
99
+ }
100
+ if (kind === 'bytes') {
101
+ const bytes = boardBytes.get(name);
102
+ if (bytes === undefined) {
103
+ problems.push(problem('model/invalid-interface', `Property "${name}" is a byte property the manifest value does not provide.`, pointer));
104
+ continue;
105
+ }
106
+ boardProps[name] = bytes.slice();
107
+ continue;
108
+ }
109
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string') {
110
+ boardProps[name] = value;
111
+ continue;
112
+ }
113
+ problems.push(problem('model/invalid-interface', `Property "${name}" is not a plain value the core can consume.`, pointer));
114
+ }
115
+ if (problems.length > 0) {
116
+ throw new PreparationError(problems);
117
+ }
118
+ return {
119
+ props: Object.freeze(props),
120
+ boardProps: Object.freeze(boardProps),
121
+ };
122
+ }
123
+ function pointerOf(base, key) {
124
+ const encoded = [...base, key].map((segment) => segment.replace(/~/g, '~0').replace(/\//g, '~1'));
125
+ return `/${encoded.join('/')}`;
126
+ }
127
+ function checkScalar(descriptor, raw, problems, pointer, instanceId) {
128
+ const reject = (expected) => {
129
+ problems.push(problem('schema/invalid-value', `Property "${descriptor.type}" of ${instanceId} must be ${expected}.`, pointer));
130
+ return undefined;
131
+ };
132
+ switch (descriptor.type) {
133
+ case 'string': {
134
+ if (typeof raw !== 'string') {
135
+ return reject('a string');
136
+ }
137
+ if (descriptor.maxLength !== undefined && [...raw].length > descriptor.maxLength) {
138
+ return reject(`at most ${descriptor.maxLength} characters`);
139
+ }
140
+ return raw;
141
+ }
142
+ case 'color': {
143
+ if (typeof raw !== 'string') {
144
+ return reject('a color string');
145
+ }
146
+ // RFC 0009: `alpha` also accepts 6 digits, which the editor normalizes to `#RRGGBBAA`.
147
+ const pattern = descriptor.alpha === true ? /^#[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?$/ : /^#[0-9A-Fa-f]{6}$/;
148
+ return pattern.test(raw)
149
+ ? raw
150
+ : reject(descriptor.alpha === true ? '#RRGGBB or #RRGGBBAA' : '#RRGGBB');
151
+ }
152
+ case 'integer': {
153
+ if (typeof raw !== 'number' || !Number.isSafeInteger(raw)) {
154
+ return reject('a safe integer');
155
+ }
156
+ return inBounds(descriptor, raw) ?? reject(bounds(descriptor));
157
+ }
158
+ case 'number': {
159
+ if (typeof raw !== 'number' || !Number.isFinite(raw)) {
160
+ return reject('a finite number');
161
+ }
162
+ if (descriptor.exclusiveMin !== undefined && !(raw > descriptor.exclusiveMin)) {
163
+ return reject(`greater than ${descriptor.exclusiveMin}`);
164
+ }
165
+ return inBounds(descriptor, raw) ?? reject(bounds(descriptor));
166
+ }
167
+ case 'boolean':
168
+ return typeof raw === 'boolean' ? raw : reject('a boolean');
169
+ case 'enum': {
170
+ const options = descriptor.options ?? [];
171
+ if (typeof raw !== 'string' || !options.some((option) => option.value === raw)) {
172
+ return reject(options.length === 0
173
+ ? 'one of the declared options'
174
+ : `one of ${options.map((option) => JSON.stringify(option.value)).join(', ')}`);
175
+ }
176
+ return raw;
177
+ }
178
+ default:
179
+ return reject(descriptor.type);
180
+ }
181
+ }
182
+ function inBounds(descriptor, value) {
183
+ if (descriptor.min !== undefined && value < descriptor.min) {
184
+ return undefined;
185
+ }
186
+ if (descriptor.max !== undefined && value > descriptor.max) {
187
+ return undefined;
188
+ }
189
+ return value;
190
+ }
191
+ function bounds(descriptor) {
192
+ const parts = [];
193
+ if (descriptor.min !== undefined) {
194
+ parts.push(`>= ${descriptor.min}`);
195
+ }
196
+ if (descriptor.max !== undefined) {
197
+ parts.push(`<= ${descriptor.max}`);
198
+ }
199
+ return parts.length === 0 ? 'in range' : parts.join(' and ');
200
+ }
201
+ function isRecord(value) {
202
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
203
+ }
204
+ function isResourceReference(value) {
205
+ return (isRecord(value) &&
206
+ ((value['mode'] === 'package' && typeof value['src'] === 'string') ||
207
+ (value['mode'] === 'asset' &&
208
+ typeof value['assetId'] === 'string' &&
209
+ typeof value['name'] === 'string')));
210
+ }
211
+ function isFirmwareReference(value) {
212
+ if (!isRecord(value)) {
213
+ return false;
214
+ }
215
+ const mode = value['mode'];
216
+ if (mode === 'project') {
217
+ return typeof value['projectId'] === 'string';
218
+ }
219
+ return isResourceReference(value);
220
+ }
221
+ function fileNameOf(src) {
222
+ const parts = src.split('/');
223
+ return parts[parts.length - 1];
224
+ }
225
+ async function readResourceBytes(input, name, descriptor, reference, problems, pointer) {
226
+ const maxBytes = descriptor.maxBytes;
227
+ const fail = (code, message) => {
228
+ problems.push(problem(code, message, pointer));
229
+ return undefined;
230
+ };
231
+ let bytes;
232
+ switch (reference.mode) {
233
+ case 'package': {
234
+ if (!isPackagePath(reference.src)) {
235
+ return fail('package/invalid-path', `Property "${name}" references the non-normalized package path "${reference.src}".`);
236
+ }
237
+ try {
238
+ bytes = await input.package.read(reference.src, maxBytes);
239
+ }
240
+ catch (cause) {
241
+ problems.push(...asProblems(cause, 'package/not-found'));
242
+ return undefined;
243
+ }
244
+ break;
245
+ }
246
+ case 'asset': {
247
+ const resolver = input.resolveResource;
248
+ if (resolver === undefined) {
249
+ return fail('runtime/prepare-failed', `Property "${name}" uses a "${reference.mode}" resource but the runtime was created without a resolveResource function.`);
250
+ }
251
+ let resolved;
252
+ try {
253
+ resolved = await resolver({
254
+ instanceId: input.instanceId,
255
+ property: name,
256
+ reference,
257
+ });
258
+ }
259
+ catch (cause) {
260
+ return fail('package/not-found', `Property "${name}" could not read asset "${reference.assetId}": ${messageOf(cause)}`);
261
+ }
262
+ if (!(resolved instanceof Uint8Array)) {
263
+ return fail('package/not-found', `The resolveResource function returned no bytes for property "${name}".`);
264
+ }
265
+ bytes = resolved.slice();
266
+ break;
267
+ }
268
+ default:
269
+ return fail('schema/invalid-value', `Property "${name}" uses an unknown resource mode.`);
270
+ }
271
+ if (maxBytes !== undefined && bytes.length > maxBytes) {
272
+ return fail('package/resource-limit', `Property "${name}" is ${bytes.length} bytes, above the declared limit of ${maxBytes}.`);
273
+ }
274
+ return bytes.slice();
275
+ }
276
+ async function resolveBytes(input, name, descriptor, raw, problems, pointer) {
277
+ if (isResourceReference(raw)) {
278
+ return readResourceBytes(input, name, descriptor, raw, problems, pointer);
279
+ }
280
+ problems.push(problem('schema/invalid-type', `Property "${name}" of ${input.instanceId} must be a resource reference ({"src": ..., "mode": ...}).`, pointer));
281
+ return undefined;
282
+ }
283
+ async function resolveProgram(input, name, descriptor, raw, problems, pointer) {
284
+ const fail = (code, message) => {
285
+ problems.push(problem(code, message, pointer));
286
+ return undefined;
287
+ };
288
+ if (!isFirmwareReference(raw) ||
289
+ (descriptor.loader !== 'memory' && descriptor.loader !== 'filesystem'))
290
+ return fail('schema/invalid-value', 'A program requires a valid reference and loader.');
291
+ const target = {
292
+ deviceId: input.package.lock.id,
293
+ property: name,
294
+ loader: descriptor.loader,
295
+ };
296
+ const sourceFailure = (cause, fallback) => {
297
+ const code = isRecord(cause) &&
298
+ typeof cause['code'] === 'string' &&
299
+ ['program/resource-limit', 'program/invalid-path'].includes(cause['code'])
300
+ ? cause['code']
301
+ : fallback;
302
+ return fail(code, messageOf(cause));
303
+ };
304
+ let artifact;
305
+ try {
306
+ if (raw.mode === 'project') {
307
+ const projects = input.programs?.projects;
308
+ if (projects === undefined)
309
+ return fail('program/project-resolve-failed', 'No program project provider is configured.');
310
+ let resolved;
311
+ try {
312
+ resolved =
313
+ input.signal === undefined
314
+ ? await projects.resolve(raw.projectId, target)
315
+ : await projects.resolve(raw.projectId, target, input.signal);
316
+ }
317
+ catch (cause) {
318
+ return sourceFailure(cause, 'program/project-resolve-failed');
319
+ }
320
+ if (!isRecord(resolved) ||
321
+ (resolved['kind'] !== 'memory' && resolved['kind'] !== 'filesystem'))
322
+ return fail('program/project-resolve-failed', 'The program project returned no valid artifact.');
323
+ if (resolved['kind'] !== descriptor.loader)
324
+ return fail('program/loader-mismatch', 'The project artifact does not match the program loader.');
325
+ if (resolved['kind'] === 'filesystem') {
326
+ if (!Array.isArray(resolved['files']))
327
+ return fail('program/project-resolve-failed', 'The program project returned no file set.');
328
+ artifact = { kind: 'filesystem', files: resolved['files'] };
329
+ }
330
+ else {
331
+ const format = resolved['format'];
332
+ const data = resolved['data'];
333
+ if ((format !== 'bin' && format !== 'hex' && format !== 'elf') ||
334
+ !(data instanceof Uint8Array))
335
+ return fail('program/project-resolve-failed', 'The program project returned an invalid memory artifact.');
336
+ artifact = { kind: 'memory', format, data };
337
+ }
338
+ }
339
+ else {
340
+ if (descriptor.loader === 'filesystem') {
341
+ let files;
342
+ if (raw.mode === 'package') {
343
+ checkProgramPath(raw.src);
344
+ const prefix = `${raw.src}/`;
345
+ const entries = Object.entries(input.package.files).filter(([path]) => path.startsWith(prefix));
346
+ if (entries.length === 0)
347
+ return fail('package/not-found', `Package program directory ${raw.src} does not exist.`);
348
+ if (entries.length > PROGRAM_LIMITS.maxFiles)
349
+ throw new ProgramError('program/resource-limit', 'Program file count exceeds the fixed limit.');
350
+ let total = 0;
351
+ for (const [path, record] of entries) {
352
+ checkProgramPath(path.slice(prefix.length));
353
+ total += record.size;
354
+ if (record.size > PROGRAM_LIMITS.maxFileBytes || total > PROGRAM_LIMITS.maxTotalBytes)
355
+ throw new ProgramError('program/resource-limit', 'Package program bytes exceed the fixed limits.');
356
+ }
357
+ const captured = [];
358
+ for (const [path] of entries)
359
+ captured.push({
360
+ path: path.slice(prefix.length),
361
+ data: await input.package.read(path, PROGRAM_LIMITS.maxFileBytes),
362
+ });
363
+ files = captured;
364
+ }
365
+ else {
366
+ const bytes = await readResourceBytes(input, name, descriptor, raw, problems, pointer);
367
+ if (bytes === undefined)
368
+ return undefined;
369
+ files = readProgramArchive(bytes);
370
+ }
371
+ artifact = { kind: 'filesystem', files };
372
+ }
373
+ else {
374
+ const sourceName = raw.mode === 'package' ? raw.src : raw.name;
375
+ const format = firmwareFormatOf(sourceName);
376
+ if (format === undefined)
377
+ return fail('program/unknown-format', `Unknown program file format: ${sourceName}.`);
378
+ if (!descriptor.formats?.includes(format))
379
+ return fail('program/unsupported-format', `The program property does not accept ${format}.`);
380
+ const data = await readResourceBytes(input, name, descriptor, raw, problems, pointer);
381
+ if (data === undefined)
382
+ return undefined;
383
+ if (!(data instanceof Uint8Array))
384
+ return fail('program/source-resolve-failed', 'The program file resolver returned no bytes.');
385
+ artifact = { kind: 'memory', format, data };
386
+ }
387
+ }
388
+ if (artifact.kind === 'filesystem') {
389
+ if (raw.addressSpace !== undefined || raw.loadAddress !== undefined)
390
+ return fail('schema/invalid-value', 'Filesystem programs do not accept address overrides.');
391
+ return createProgramFiles(artifact.files);
392
+ }
393
+ return decodeMemoryProgram(artifact.format, artifact.data, descriptor, raw);
394
+ }
395
+ catch (cause) {
396
+ if (cause instanceof ProgramError) {
397
+ const code = raw.mode === 'project' && cause.code === 'program/source-resolve-failed'
398
+ ? 'program/project-resolve-failed'
399
+ : cause.code;
400
+ return fail(code, cause.message);
401
+ }
402
+ if (cause instanceof PreparationError) {
403
+ for (const item of cause.problems)
404
+ problems.push(problem(item.code === 'package/resource-limit' ? 'program/resource-limit' : item.code, item.message, pointer));
405
+ return undefined;
406
+ }
407
+ throw cause;
408
+ }
409
+ }
410
+ async function resolveFirmware(input, name, descriptor, raw, problems, pointer) {
411
+ const fail = (code, message) => {
412
+ problems.push(problem(code, message, pointer));
413
+ return undefined;
414
+ };
415
+ if (!isFirmwareReference(raw) || raw.mode === 'project') {
416
+ return fail('schema/invalid-type', `Property "${name}" of ${input.instanceId} must be a firmware reference.`);
417
+ }
418
+ const maxBytes = descriptor.maxBytes;
419
+ const spaces = descriptor.addressSpaces ?? {};
420
+ const sourceName = raw.mode === 'package' ? raw.src : raw.name;
421
+ const format = firmwareFormatOf(fileNameOf(sourceName) ?? '');
422
+ if (format === undefined) {
423
+ return fail('firmware/unknown-format', `Property "${name}" names "${sourceName}" whose extension is not a known firmware format.`);
424
+ }
425
+ const bytes = await readResourceBytes(input, name, descriptor, raw, problems, pointer);
426
+ if (bytes === undefined || format === undefined) {
427
+ return undefined;
428
+ }
429
+ if (maxBytes !== undefined && bytes.length > maxBytes) {
430
+ return fail('package/resource-limit', `Property "${name}" is ${bytes.length} bytes, above the declared limit of ${maxBytes}.`);
431
+ }
432
+ const spaceId = raw.addressSpace ?? descriptor.addressSpace;
433
+ const space = spaceId === undefined ? undefined : spaces[spaceId];
434
+ if (spaceId === undefined || space === undefined) {
435
+ return fail('schema/invalid-value', `Property "${name}" selects the unknown address space ${JSON.stringify(spaceId)}.`);
436
+ }
437
+ if (format !== 'bin' && raw.loadAddress !== undefined) {
438
+ return fail('schema/invalid-value', `Property "${name}" sets loadAddress, which only BIN firmware supports.`);
439
+ }
440
+ if (format === 'elf' && raw.addressSpace !== undefined) {
441
+ return fail('schema/invalid-value', `Property "${name}" sets addressSpace, which ELF firmware does not support.`);
442
+ }
443
+ if (!isDecodedFormat(format)) {
444
+ return fail('firmware/unsupported-format', `${format.toUpperCase()} firmware of property "${name}" is not decoded by this runtime yet; provide a BIN source.`);
445
+ }
446
+ const address = raw.loadAddress ?? descriptor.loadAddress;
447
+ if (address === undefined) {
448
+ return fail('firmware/out-of-range', `Property "${name}" has no load address for its BIN firmware.`);
449
+ }
450
+ try {
451
+ return binFirmwareImage(bytes, spaceId, space, address);
452
+ }
453
+ catch (cause) {
454
+ return fail('firmware/out-of-range', `Property "${name}": ${messageOf(cause)}`);
455
+ }
456
+ }
457
+ function asProblems(cause, fallbackCode) {
458
+ if (cause instanceof PreparationError) {
459
+ return [...cause.problems];
460
+ }
461
+ return [problem(fallbackCode, messageOf(cause))];
462
+ }
463
+ function messageOf(cause) {
464
+ return cause instanceof Error ? cause.message : String(cause);
465
+ }
@@ -0,0 +1,60 @@
1
+ import type { TimePs } from '@mica-js/core';
2
+ import type { Event } from '@mica-js/core/lifecycle';
3
+ import type { DeviceRegistry, FusedDocument, PackageFiles } from '@mica-js/document/fused';
4
+ import type { DiagnosticSink, RuntimeDiagnostic } from './diagnostics.js';
5
+ import type { RuntimeModelClient, RuntimeModelEvent } from './models.js';
6
+ import type { ResourceResolver } from './properties.js';
7
+ export interface HeadlessRuntimeOptions {
8
+ /** Fused `.sch` version 2 document; snapshotted before anything runs. */
9
+ readonly document: FusedDocument;
10
+ /** Resolves the locked packages of this document. */
11
+ readonly registry: DeviceRegistry;
12
+ /** Loads one declared package entry; explicit and in-process, no implicit resolution. */
13
+ readonly loadModule: (files: PackageFiles, path: string) => Promise<unknown>;
14
+ /** Fixed positive step of every advance; constant for the whole session. */
15
+ readonly step: TimePs;
16
+ /** Explicit resolver of asset-library property resources. */
17
+ readonly resolveResource?: ResourceResolver;
18
+ /** Program project and template sources. */
19
+ readonly programs?: import('./program.js').ProgramSources;
20
+ /** Observer of every model event, installed before model initialization. */
21
+ readonly onModelEvent?: (event: RuntimeModelEvent) => void;
22
+ /** Receives preparation and runtime diagnostics that have no event subscriber yet. */
23
+ readonly onDiagnostic?: DiagnosticSink;
24
+ }
25
+ export interface RuntimeState {
26
+ readonly status: 'running' | 'paused' | 'faulted' | 'disposed';
27
+ readonly simTime: TimePs;
28
+ }
29
+ /** Thrown or rejected by runtime operations; `code` is a stable contract code. */
30
+ export declare class FusedRuntimeError extends Error {
31
+ readonly code: string;
32
+ readonly instanceId?: string;
33
+ constructor(code: string, message: string, instanceId?: string);
34
+ }
35
+ export interface HeadlessRuntime {
36
+ getState(): RuntimeState;
37
+ readonly onDidChangeState: Event<RuntimeState>;
38
+ readonly onDidReportDiagnostic: Event<RuntimeDiagnostic>;
39
+ /** Host client of one modeled instance; the same instance id keeps one client per session. */
40
+ getModel(instanceId: string): RuntimeModelClient;
41
+ /** Advances exactly one fixed step; only valid while paused. */
42
+ step(): Promise<void>;
43
+ /** Starts continuous fixed-step advancement and resolves after the first step. */
44
+ resume(): Promise<void>;
45
+ /** Stops advancement synchronously, keeping models, listeners and view state. */
46
+ pause(): void;
47
+ /** Replaces the session with fresh models built from the same captured bytes and modules. */
48
+ reset(): Promise<void>;
49
+ /** Releases the board, models, listeners and emitters; safe to call more than once. */
50
+ dispose(): Promise<void>;
51
+ }
52
+ /**
53
+ * Creates one headless runtime.
54
+ *
55
+ * Resolves paused, at simulation time zero, with models initialized and their initial events
56
+ * already delivered to `onModelEvent`. Rejects with {@link FusedPreparationError} without running
57
+ * any model factory when the document, a package, the topology, a resource or a model interface is
58
+ * invalid.
59
+ */
60
+ export declare function createHeadlessRuntime(options: HeadlessRuntimeOptions): Promise<HeadlessRuntime>;