@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.
- 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,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Locked device package loading of the headless runtime (RFC 0020).
|
|
3
|
+
*
|
|
4
|
+
* The registry owns the bytes; this module proves that a package matches its lock before any of
|
|
5
|
+
* its code is loaded: identity, version, host API range, declared paths, file sizes and SHA-256
|
|
6
|
+
* digests. The lock, the file list and every byte buffer are copied before the first `await`, so a
|
|
7
|
+
* registry that mutates its own objects cannot change what was verified.
|
|
8
|
+
*/
|
|
9
|
+
import { sha256 as packagedSha256 } from '@noble/hashes/sha2.js';
|
|
10
|
+
import { packagePathProblem, parseUnifiedManifest } from '@mica-js/document/fused';
|
|
11
|
+
import { satisfies, valid } from 'semver';
|
|
12
|
+
import { asPreparation, PreparationError, problem } from './diagnostics.js';
|
|
13
|
+
/**
|
|
14
|
+
* Host API version this runtime implements.
|
|
15
|
+
*
|
|
16
|
+
* `engines.mica` names the host API, not the npm version of this package: the fused device runtime
|
|
17
|
+
* implements API `1.0.0`, so manifests declare ranges such as `^1.0.0`. A package outside the range
|
|
18
|
+
* is rejected before anything is loaded.
|
|
19
|
+
*/
|
|
20
|
+
export const MICA_HOST_API_VERSION = '1.0.0';
|
|
21
|
+
const INTEGRITY = /^sha256:[0-9a-f]{64}$/;
|
|
22
|
+
const MANIFEST_PATH = 'package.json';
|
|
23
|
+
/** Whether `path` is a normalized package-root relative POSIX path (RFC 0020). */
|
|
24
|
+
export function isPackagePath(path) {
|
|
25
|
+
return packagePathProblem(path) === undefined;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Opens one locked package and verifies everything that does not need code execution.
|
|
29
|
+
*
|
|
30
|
+
* @throws {PreparationError} with the RFC 0020 diagnostic codes of every problem found.
|
|
31
|
+
*/
|
|
32
|
+
export async function openDevicePackage(registry, lock, hostApiVersion = MICA_HOST_API_VERSION) {
|
|
33
|
+
const requested = snapshotLock(lock);
|
|
34
|
+
let opened;
|
|
35
|
+
try {
|
|
36
|
+
opened = await registry.open(requested);
|
|
37
|
+
}
|
|
38
|
+
catch (cause) {
|
|
39
|
+
throw new PreparationError([
|
|
40
|
+
problem('package/not-found', `Cannot open ${requested.id}@${requested.version}: ${errorMessage(cause)}`),
|
|
41
|
+
]);
|
|
42
|
+
}
|
|
43
|
+
// Capture the reader and the file table before the next `await`: later mutation of the registry
|
|
44
|
+
// object must not reach the verification that follows.
|
|
45
|
+
const readFile = opened.read;
|
|
46
|
+
const table = snapshotFileTable(opened, requested);
|
|
47
|
+
await verifyReleaseIdentity(table, requested);
|
|
48
|
+
const read = async (path, maxBytes) => {
|
|
49
|
+
const record = table[path];
|
|
50
|
+
if (record === undefined) {
|
|
51
|
+
throw new PreparationError([
|
|
52
|
+
problem('package/missing-entry', `Package ${requested.id} does not declare ${path}.`),
|
|
53
|
+
]);
|
|
54
|
+
}
|
|
55
|
+
if (maxBytes !== undefined && record.size > maxBytes) {
|
|
56
|
+
throw new PreparationError([
|
|
57
|
+
problem('package/resource-limit', `${requested.id}/${path} is ${record.size} bytes, above the declared limit of ${maxBytes}.`),
|
|
58
|
+
]);
|
|
59
|
+
}
|
|
60
|
+
const returned = await readFile.call(opened, path);
|
|
61
|
+
if (!(returned instanceof Uint8Array)) {
|
|
62
|
+
throw new PreparationError([
|
|
63
|
+
problem('package/not-found', `Package ${requested.id} returned no bytes for ${path}.`),
|
|
64
|
+
]);
|
|
65
|
+
}
|
|
66
|
+
// Copy first: the digest and the caller must never share storage with the registry.
|
|
67
|
+
const owned = returned.slice();
|
|
68
|
+
if (owned.length !== record.size) {
|
|
69
|
+
throw new PreparationError([
|
|
70
|
+
problem('package/integrity-mismatch', `${requested.id}/${path} is ${owned.length} bytes but the release declares ${record.size}.`),
|
|
71
|
+
]);
|
|
72
|
+
}
|
|
73
|
+
const digest = await sha256(owned);
|
|
74
|
+
if (digest !== record.integrity) {
|
|
75
|
+
throw new PreparationError([
|
|
76
|
+
problem('package/integrity-mismatch', `${requested.id}/${path} does not match the released digest.`),
|
|
77
|
+
]);
|
|
78
|
+
}
|
|
79
|
+
return owned.slice();
|
|
80
|
+
};
|
|
81
|
+
// The text goes straight to the contract parser, which also rejects duplicate JSON keys.
|
|
82
|
+
const manifestText = new TextDecoder().decode(await read(MANIFEST_PATH)).replace(/^\uFEFF/, '');
|
|
83
|
+
const manifest = parseManifestText(manifestText);
|
|
84
|
+
verifyIdentity(manifest, requested);
|
|
85
|
+
if (!satisfiesRange(hostApiVersion, manifest.engines.mica)) {
|
|
86
|
+
throw new PreparationError([
|
|
87
|
+
problem('package/unsupported-engine', `${requested.id}@${requested.version} requires mica "${manifest.engines.mica}" ` +
|
|
88
|
+
`but this runtime implements ${hostApiVersion}.`, '/engines/mica'),
|
|
89
|
+
]);
|
|
90
|
+
}
|
|
91
|
+
const source = Object.freeze({
|
|
92
|
+
lock: requested,
|
|
93
|
+
files: table,
|
|
94
|
+
read: (path) => read(path),
|
|
95
|
+
});
|
|
96
|
+
return Object.freeze({ lock: requested, manifest, source, files: table, read });
|
|
97
|
+
}
|
|
98
|
+
function snapshotLock(lock) {
|
|
99
|
+
if (lock === null ||
|
|
100
|
+
typeof lock !== 'object' ||
|
|
101
|
+
typeof lock.id !== 'string' ||
|
|
102
|
+
typeof lock.version !== 'string') {
|
|
103
|
+
throw new PreparationError([
|
|
104
|
+
problem('package/invalid-manifest', 'A device lock needs "id" and "version" strings.'),
|
|
105
|
+
]);
|
|
106
|
+
}
|
|
107
|
+
if (!INTEGRITY.test(lock.integrity)) {
|
|
108
|
+
throw new PreparationError([
|
|
109
|
+
problem('package/integrity-mismatch', `Lock of "${lock.id}" does not carry a sha256 release identity.`),
|
|
110
|
+
]);
|
|
111
|
+
}
|
|
112
|
+
return Object.freeze({ id: lock.id, version: lock.version, integrity: lock.integrity });
|
|
113
|
+
}
|
|
114
|
+
/** Copies and validates the opened file list; the returned table is frozen. */
|
|
115
|
+
function snapshotFileTable(opened, lock) {
|
|
116
|
+
if (opened === null || typeof opened !== 'object') {
|
|
117
|
+
throw new PreparationError([
|
|
118
|
+
problem('package/not-found', `Registry returned no package for ${lock.id}.`),
|
|
119
|
+
]);
|
|
120
|
+
}
|
|
121
|
+
if (opened.lock?.id !== lock.id ||
|
|
122
|
+
opened.lock.version !== lock.version ||
|
|
123
|
+
opened.lock.integrity !== lock.integrity) {
|
|
124
|
+
throw new PreparationError([
|
|
125
|
+
problem('package/integrity-mismatch', `Registry opened a release that does not match the lock of "${lock.id}".`),
|
|
126
|
+
]);
|
|
127
|
+
}
|
|
128
|
+
if (typeof opened.read !== 'function' ||
|
|
129
|
+
opened.files === null ||
|
|
130
|
+
typeof opened.files !== 'object') {
|
|
131
|
+
throw new PreparationError([
|
|
132
|
+
problem('package/not-found', `Registry returned an unreadable release for "${lock.id}".`),
|
|
133
|
+
]);
|
|
134
|
+
}
|
|
135
|
+
const problems = [];
|
|
136
|
+
const table = Object.create(null);
|
|
137
|
+
for (const [path, record] of Object.entries(opened.files)) {
|
|
138
|
+
if (!isPackagePath(path)) {
|
|
139
|
+
problems.push(problem('package/invalid-path', `Package ${lock.id} declares the non-normalized path ${JSON.stringify(path)}.`));
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (record === null ||
|
|
143
|
+
typeof record !== 'object' ||
|
|
144
|
+
!Number.isSafeInteger(record.size) ||
|
|
145
|
+
record.size < 0 ||
|
|
146
|
+
!INTEGRITY.test(record.integrity)) {
|
|
147
|
+
problems.push(problem('package/invalid-path', `Package ${lock.id} declares an invalid entry for ${path}.`));
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
table[path] = Object.freeze({ size: record.size, integrity: record.integrity });
|
|
151
|
+
}
|
|
152
|
+
if (!Object.hasOwn(table, MANIFEST_PATH)) {
|
|
153
|
+
problems.push(problem('package/missing-entry', `Package ${lock.id} does not declare ${MANIFEST_PATH}.`));
|
|
154
|
+
}
|
|
155
|
+
if (problems.length > 0) {
|
|
156
|
+
throw new PreparationError(problems);
|
|
157
|
+
}
|
|
158
|
+
return Object.freeze(table);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Verifies the release identity of RFC 0020: the SHA-256 of the JSON Canonicalization Scheme bytes
|
|
162
|
+
* of `{ id, version, files }`, which is exactly the information a `PackageFiles` view exposes.
|
|
163
|
+
*/
|
|
164
|
+
async function verifyReleaseIdentity(table, lock) {
|
|
165
|
+
const identity = await releaseIntegrity({ id: lock.id, version: lock.version, files: table });
|
|
166
|
+
if (identity !== lock.integrity) {
|
|
167
|
+
throw new PreparationError([
|
|
168
|
+
problem('package/integrity-mismatch', `The file list of ${lock.id}@${lock.version} derives the release identity ${identity}, ` +
|
|
169
|
+
`but the document locks ${lock.integrity}.`),
|
|
170
|
+
]);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
export async function releaseIntegrity(release) {
|
|
174
|
+
return sha256(new TextEncoder().encode(canonicalJson(release)));
|
|
175
|
+
}
|
|
176
|
+
/** JSON Canonicalization Scheme subset for release manifests: sorted keys, no extra whitespace. */
|
|
177
|
+
function canonicalJson(value) {
|
|
178
|
+
if (value === null || typeof value === 'boolean' || typeof value === 'number') {
|
|
179
|
+
return JSON.stringify(value);
|
|
180
|
+
}
|
|
181
|
+
if (typeof value === 'string') {
|
|
182
|
+
return JSON.stringify(value);
|
|
183
|
+
}
|
|
184
|
+
if (Array.isArray(value)) {
|
|
185
|
+
return `[${value.map((item) => canonicalJson(item)).join(',')}]`;
|
|
186
|
+
}
|
|
187
|
+
const record = value;
|
|
188
|
+
const members = Object.keys(record)
|
|
189
|
+
.sort()
|
|
190
|
+
.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`);
|
|
191
|
+
return `{${members.join(',')}}`;
|
|
192
|
+
}
|
|
193
|
+
function parseManifestText(text) {
|
|
194
|
+
try {
|
|
195
|
+
return parseUnifiedManifest(text);
|
|
196
|
+
}
|
|
197
|
+
catch (cause) {
|
|
198
|
+
throw new PreparationError(asPreparation(cause, 'package/invalid-manifest'));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function verifyIdentity(manifest, lock) {
|
|
202
|
+
const id = `${manifest.publisher}:${manifest.name}`;
|
|
203
|
+
if (id !== lock.id) {
|
|
204
|
+
throw new PreparationError([
|
|
205
|
+
problem('package/invalid-manifest', `package.json declares ${id} but the document locks ${lock.id}.`, '/name'),
|
|
206
|
+
]);
|
|
207
|
+
}
|
|
208
|
+
if (manifest.version !== lock.version) {
|
|
209
|
+
throw new PreparationError([
|
|
210
|
+
problem('package/invalid-manifest', `package.json declares version ${manifest.version} but the document locks ${lock.version}.`, '/version'),
|
|
211
|
+
]);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* SHA-256 of one byte sequence, formatted as the RFC 0020 release digest.
|
|
216
|
+
*
|
|
217
|
+
* WebCrypto is preferred because it is native, but an opaque-origin sandbox worker has no
|
|
218
|
+
* `crypto.subtle` at all. There the packaged implementation hashes instead: verification must keep
|
|
219
|
+
* working inside the sandbox and is never skipped or weakened. When the host does expose WebCrypto,
|
|
220
|
+
* a failing digest is a real failure and is reported as such instead of being retried elsewhere.
|
|
221
|
+
*
|
|
222
|
+
* @throws {PreparationError} `package/integrity-mismatch` when the digest cannot be computed.
|
|
223
|
+
*/
|
|
224
|
+
async function sha256(bytes) {
|
|
225
|
+
const copy = new Uint8Array(bytes.byteLength);
|
|
226
|
+
copy.set(bytes);
|
|
227
|
+
return `sha256:${toHex(await digestSha256(copy))}`;
|
|
228
|
+
}
|
|
229
|
+
async function digestSha256(bytes) {
|
|
230
|
+
const subtle = globalThis.crypto?.subtle;
|
|
231
|
+
if (subtle === undefined) {
|
|
232
|
+
// An opaque-origin sandbox worker has no WebCrypto at all; the packaged SHA-256 hashes there.
|
|
233
|
+
return packagedSha256(bytes);
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
const digest = await subtle.digest('SHA-256', bytes);
|
|
237
|
+
return new Uint8Array(digest);
|
|
238
|
+
}
|
|
239
|
+
catch (cause) {
|
|
240
|
+
throw new PreparationError([
|
|
241
|
+
problem('package/integrity-mismatch', `The host WebCrypto refused to compute a SHA-256 digest: ${errorMessage(cause)}`),
|
|
242
|
+
]);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
function toHex(bytes) {
|
|
246
|
+
return [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Whether `version` satisfies the SemVer range of `engines.mica`.
|
|
250
|
+
*
|
|
251
|
+
* Delegates to the `semver` package, so prereleases, X-ranges, hyphen ranges and partial versions
|
|
252
|
+
* follow the standard semantics instead of an approximation.
|
|
253
|
+
*/
|
|
254
|
+
export function satisfiesRange(version, range) {
|
|
255
|
+
if (typeof version !== 'string' || typeof range !== 'string') {
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
if (valid(version) === null) {
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
return satisfies(version, range);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function errorMessage(cause) {
|
|
269
|
+
return cause instanceof Error ? cause.message : String(cause);
|
|
270
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { DeviceLock, DeviceRegistry, FusedDocument, FusedNet, PackageFiles } from '@mica-js/document/fused';
|
|
2
|
+
import type { DeviceIR } from '@mica-js/device-model';
|
|
3
|
+
import type { DiagnosticSink } from './diagnostics.js';
|
|
4
|
+
import type { FusedModelFactory } from './models.js';
|
|
5
|
+
import { type VerifiedPackage } from './package.js';
|
|
6
|
+
import type { ProgramSources } from './program.js';
|
|
7
|
+
import { type BoardPropertyValue, type ResourceResolver } from './properties.js';
|
|
8
|
+
export interface PrepareInput {
|
|
9
|
+
/** Document to snapshot; the caller's object is never mutated or retained. */
|
|
10
|
+
readonly document: FusedDocument;
|
|
11
|
+
readonly registry: DeviceRegistry;
|
|
12
|
+
/** Loads one declared entry of a verified package; the module namespace is validated here. */
|
|
13
|
+
readonly loadModule: (files: PackageFiles, path: string) => Promise<unknown>;
|
|
14
|
+
readonly resolveResource?: ResourceResolver;
|
|
15
|
+
readonly programs?: ProgramSources;
|
|
16
|
+
readonly onDiagnostic?: DiagnosticSink;
|
|
17
|
+
readonly hostApiVersion?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface PreparedModel {
|
|
20
|
+
readonly ir: DeviceIR;
|
|
21
|
+
readonly create: FusedModelFactory;
|
|
22
|
+
}
|
|
23
|
+
export interface PreparedDevice {
|
|
24
|
+
readonly deviceId: string;
|
|
25
|
+
readonly lock: DeviceLock;
|
|
26
|
+
readonly package: VerifiedPackage;
|
|
27
|
+
/** Present when the device declares a model; display-only devices are skipped headless. */
|
|
28
|
+
readonly model?: PreparedModel;
|
|
29
|
+
}
|
|
30
|
+
export interface PreparedInstance {
|
|
31
|
+
readonly instanceId: string;
|
|
32
|
+
readonly deviceId: string;
|
|
33
|
+
/** Resolved read-only property snapshot handed to the model factory. */
|
|
34
|
+
readonly props: Readonly<Record<string, unknown>>;
|
|
35
|
+
/** IR-declared plain properties handed to the board. */
|
|
36
|
+
readonly boardProps: Readonly<Record<string, BoardPropertyValue>>;
|
|
37
|
+
}
|
|
38
|
+
export interface PreparedSession {
|
|
39
|
+
readonly document: FusedDocument;
|
|
40
|
+
readonly devices: ReadonlyMap<string, PreparedDevice>;
|
|
41
|
+
/** Modeled instances in document order. */
|
|
42
|
+
readonly instances: readonly PreparedInstance[];
|
|
43
|
+
readonly nets: readonly FusedNet[];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Prepares one headless session.
|
|
47
|
+
*
|
|
48
|
+
* @throws {FusedPreparationError} after reporting every problem through `onDiagnostic`.
|
|
49
|
+
*/
|
|
50
|
+
export declare function prepareFusedSession(input: PrepareInput): Promise<PreparedSession>;
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Preparation of one headless fused session (RFC 0025).
|
|
3
|
+
*
|
|
4
|
+
* Everything here happens before the first model factory: the document is snapshotted, every locked
|
|
5
|
+
* package is verified, the topology and its voltage constraints are derived, model modules are
|
|
6
|
+
* loaded and their IR is checked against the manifest, and all instance properties (including
|
|
7
|
+
* resources and firmware) are captured as independent snapshots.
|
|
8
|
+
*/
|
|
9
|
+
import { deriveFusedTopology, parseFusedDocument } from '@mica-js/document/fused';
|
|
10
|
+
import { validateDeviceIR } from '@mica-js/device-model';
|
|
11
|
+
import { checkModelAgreement } from './agreement.js';
|
|
12
|
+
import { DiagnosticBatch, FusedPreparationError, problem } from './diagnostics.js';
|
|
13
|
+
import { openDevicePackage } from './package.js';
|
|
14
|
+
import { resolveInstanceProperties, } from './properties.js';
|
|
15
|
+
/**
|
|
16
|
+
* Prepares one headless session.
|
|
17
|
+
*
|
|
18
|
+
* @throws {FusedPreparationError} after reporting every problem through `onDiagnostic`.
|
|
19
|
+
*/
|
|
20
|
+
export async function prepareFusedSession(input) {
|
|
21
|
+
const batch = new DiagnosticBatch();
|
|
22
|
+
const failure = () => {
|
|
23
|
+
const diagnostics = batch.drain();
|
|
24
|
+
for (const entry of diagnostics) {
|
|
25
|
+
input.onDiagnostic?.(entry);
|
|
26
|
+
}
|
|
27
|
+
return new FusedPreparationError(diagnostics);
|
|
28
|
+
};
|
|
29
|
+
let document;
|
|
30
|
+
try {
|
|
31
|
+
document = parseFusedDocument(input.document);
|
|
32
|
+
}
|
|
33
|
+
catch (cause) {
|
|
34
|
+
batch.add(cause, 'schema/invalid-value');
|
|
35
|
+
throw failure();
|
|
36
|
+
}
|
|
37
|
+
const deviceIds = [];
|
|
38
|
+
for (const instance of document.instances) {
|
|
39
|
+
if (!deviceIds.includes(instance.device)) {
|
|
40
|
+
deviceIds.push(instance.device);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const devices = new Map();
|
|
44
|
+
const manifests = new Map();
|
|
45
|
+
for (const deviceId of deviceIds) {
|
|
46
|
+
const dependency = document.dependencies[deviceId];
|
|
47
|
+
if (dependency === undefined) {
|
|
48
|
+
batch.addProblem(problem('document/unlocked-device', `Instance device "${deviceId}" is not locked.`));
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
let verified;
|
|
52
|
+
try {
|
|
53
|
+
verified = await openDevicePackage(input.registry, { id: deviceId, version: dependency.version, integrity: dependency.integrity }, input.hostApiVersion);
|
|
54
|
+
}
|
|
55
|
+
catch (cause) {
|
|
56
|
+
batch.add(cause, 'package/not-found');
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
manifests.set(deviceId, verified.manifest);
|
|
60
|
+
devices.set(deviceId, {
|
|
61
|
+
deviceId,
|
|
62
|
+
lock: verified.lock,
|
|
63
|
+
package: verified,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
if (!batch.empty) {
|
|
67
|
+
throw failure();
|
|
68
|
+
}
|
|
69
|
+
// View layout identities need the device manifest, so they are checked here and not by the
|
|
70
|
+
// document parser; a layout that names an undeclared view would otherwise only fail on display.
|
|
71
|
+
for (const [index, instance] of document.instances.entries()) {
|
|
72
|
+
const layout = instance.viewLayout;
|
|
73
|
+
const manifest = manifests.get(instance.device);
|
|
74
|
+
if (layout === undefined || manifest === undefined) {
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const declared = manifest.view ?? {};
|
|
78
|
+
const seen = new Set();
|
|
79
|
+
layout.views.forEach((entry, at) => {
|
|
80
|
+
const pointer = `/instances/${index}/viewLayout/views/${at}/viewId`;
|
|
81
|
+
if (seen.has(entry.viewId)) {
|
|
82
|
+
batch.addProblem(problem('document/invalid-view-layout', `Instance "${instance.id}" lists the view "${entry.viewId}" more than once.`, pointer), instance.id);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
seen.add(entry.viewId);
|
|
86
|
+
if (!Object.hasOwn(declared, entry.viewId)) {
|
|
87
|
+
batch.addProblem(problem('document/invalid-view-layout', `Instance "${instance.id}" references the view "${entry.viewId}", which ${instance.device} does not declare.`, pointer), instance.id);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
if (!batch.empty) {
|
|
92
|
+
throw failure();
|
|
93
|
+
}
|
|
94
|
+
let nets;
|
|
95
|
+
try {
|
|
96
|
+
nets = deriveFusedTopology(document, manifests).nets;
|
|
97
|
+
}
|
|
98
|
+
catch (cause) {
|
|
99
|
+
batch.add(cause, 'net/reference-conflict');
|
|
100
|
+
throw failure();
|
|
101
|
+
}
|
|
102
|
+
for (const [deviceId, device] of devices) {
|
|
103
|
+
const definition = device.package.manifest.model;
|
|
104
|
+
if (definition === undefined) {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const loaded = await loadModelModule(device, definition.entry, input, batch);
|
|
108
|
+
if (loaded === undefined) {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
devices.set(deviceId, { ...device, model: loaded });
|
|
112
|
+
}
|
|
113
|
+
if (!batch.empty) {
|
|
114
|
+
throw failure();
|
|
115
|
+
}
|
|
116
|
+
const instances = [];
|
|
117
|
+
for (const [index, instance] of document.instances.entries()) {
|
|
118
|
+
const device = devices.get(instance.device);
|
|
119
|
+
const model = device?.model;
|
|
120
|
+
if (device === undefined || model === undefined) {
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
const resolution = await resolveInstanceProperties({
|
|
125
|
+
instanceId: instance.id,
|
|
126
|
+
package: device.package,
|
|
127
|
+
descriptors: device.package.manifest.properties ?? {},
|
|
128
|
+
overrides: instance.properties ?? {},
|
|
129
|
+
irProperties: propertyDeclarations(model.ir),
|
|
130
|
+
pointer: ['instances', String(index), 'properties'],
|
|
131
|
+
...(input.resolveResource === undefined ? {} : { resolveResource: input.resolveResource }),
|
|
132
|
+
...(input.programs === undefined ? {} : { programs: input.programs }),
|
|
133
|
+
});
|
|
134
|
+
instances.push({
|
|
135
|
+
instanceId: instance.id,
|
|
136
|
+
deviceId: instance.device,
|
|
137
|
+
props: resolution.props,
|
|
138
|
+
boardProps: resolution.boardProps,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
catch (cause) {
|
|
142
|
+
batch.add(cause, 'runtime/prepare-failed', instance.id);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (!batch.empty) {
|
|
146
|
+
throw failure();
|
|
147
|
+
}
|
|
148
|
+
const modeled = new Set(instances.map((instance) => instance.instanceId));
|
|
149
|
+
const boardNets = nets
|
|
150
|
+
.map((net) => ({
|
|
151
|
+
...net,
|
|
152
|
+
pins: net.pins.filter((pin) => modeled.has(pin.instance)),
|
|
153
|
+
}))
|
|
154
|
+
.filter((net) => net.pins.length > 0);
|
|
155
|
+
return Object.freeze({
|
|
156
|
+
document,
|
|
157
|
+
devices,
|
|
158
|
+
instances: Object.freeze(instances),
|
|
159
|
+
nets: Object.freeze(boardNets),
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
async function loadModelModule(device, entry, input, batch) {
|
|
163
|
+
let namespace;
|
|
164
|
+
try {
|
|
165
|
+
namespace = await input.loadModule(device.package.source, entry);
|
|
166
|
+
}
|
|
167
|
+
catch (cause) {
|
|
168
|
+
batch.addProblem(problem('model/execution-failed', `Cannot load ${device.deviceId}/${entry}: ${messageOf(cause)}`));
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
const candidate = namespace;
|
|
172
|
+
if (typeof namespace !== 'object' && typeof namespace !== 'function') {
|
|
173
|
+
batch.add(problem('model/invalid-interface', `${device.deviceId}/${entry} must export the model IR and a create factory.`), 'model/invalid-interface');
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
if (candidate?.model === undefined || candidate.create === undefined) {
|
|
177
|
+
batch.add(problem('model/invalid-interface', `${device.deviceId}/${entry} must export "model" and "create".`), 'model/invalid-interface');
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
if (typeof candidate.create !== 'function') {
|
|
181
|
+
batch.add(problem('model/invalid-interface', `${device.deviceId}/${entry} exports a non-function "create".`), 'model/invalid-interface');
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
let ir;
|
|
185
|
+
try {
|
|
186
|
+
ir = validateDeviceIR(candidate.model);
|
|
187
|
+
}
|
|
188
|
+
catch (cause) {
|
|
189
|
+
batch.add(cause, 'model/invalid-interface');
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
// Same rules as the SDK build: pins, property types, nullability, enum members and literal
|
|
193
|
+
// defaults must agree before any factory sees the module.
|
|
194
|
+
const disagreements = checkModelAgreement(device.package.manifest, ir);
|
|
195
|
+
if (disagreements.length > 0) {
|
|
196
|
+
for (const entry of disagreements) {
|
|
197
|
+
batch.addProblem(entry);
|
|
198
|
+
}
|
|
199
|
+
return undefined;
|
|
200
|
+
}
|
|
201
|
+
return { ir, create: candidate.create };
|
|
202
|
+
}
|
|
203
|
+
function propertyDeclarations(ir) {
|
|
204
|
+
const declarations = new Map();
|
|
205
|
+
for (const declaration of ir.declarations) {
|
|
206
|
+
if (declaration.kind === 'property') {
|
|
207
|
+
declarations.set(declaration.name, declaration.type);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return declarations;
|
|
211
|
+
}
|
|
212
|
+
function messageOf(cause) {
|
|
213
|
+
return cause instanceof Error ? cause.message : String(cause);
|
|
214
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { DevicePropertyDescriptor, MemoryProgram, ProgramFormat, ProgramReference } from '@mica-js/document/fused';
|
|
2
|
+
export declare function decodeMemoryProgram(format: ProgramFormat, bytes: Uint8Array, descriptor: DevicePropertyDescriptor, reference: ProgramReference): MemoryProgram;
|