@mica-js/testing 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/time.ts"],"sourcesContent":["import { timePs, type TimePs } from '@mica-js/core';\n\nexport const ps = timePs;\n\nfunction convert(value: number, factor: number): TimePs {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new RangeError('Test durations must be finite nonnegative numbers');\n }\n return timePs(value * factor);\n}\n\nexport const ns = (value: number): TimePs => convert(value, 1_000);\nexport const us = (value: number): TimePs => convert(value, 1_000_000);\nexport const ms = (value: number): TimePs => convert(value, 1_000_000_000);\nexport const seconds = (value: number): TimePs => convert(value, 1_000_000_000_000);\n"],"mappings":";;;AAEA,IAAa,KAAK;AAElB,SAAS,QAAQ,OAAe,QAAwB;CACtD,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAClE,MAAM,IAAI,WAAW,mDAAmD;CAE1E,OAAO,OAAO,QAAQ,MAAM;AAC9B;AAEA,IAAa,MAAM,UAA0B,QAAQ,OAAO,GAAK;AACjE,IAAa,MAAM,UAA0B,QAAQ,OAAO,GAAS;AACrE,IAAa,MAAM,UAA0B,QAAQ,OAAO,GAAa;AACzE,IAAa,WAAW,UAA0B,QAAQ,OAAO,YAAiB"}
package/dist/node.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { DeviceDependency } from '@mica-js/document/fused';
2
+ import { FusedInstance } from '@mica-js/document/fused';
3
+ import { HeadlessRuntime } from '@mica-js/sdk/fused';
4
+ import { HeadlessRuntimeOptions } from '@mica-js/sdk/fused';
5
+ import { ModelEvent } from '@mica-js/sdk/fused';
6
+ import { parseUnifiedManifest } from '@mica-js/document/fused';
7
+ import { RuntimeDiagnostic } from '@mica-js/sdk/fused';
8
+ import { RuntimeModelClient } from '@mica-js/sdk/fused';
9
+ import { TimePs } from '@mica-js/core';
10
+ import { validateModelValue } from '@mica-js/document/fused';
11
+ import { Value } from '@mica-js/document/fused';
12
+
13
+ export declare function createFileTestbench(definition: FileTestbenchDefinition, options: FileTestbenchOptions): Promise< Testbench>;
14
+
15
+ declare type DeviceFacade<M extends object, E extends object> = {
16
+ readonly methods: Readonly<M>;
17
+ readonly events: Readonly<E>;
18
+ } & Readonly<Pick<M, Exclude<keyof M, keyof E | Reserved>>> & Readonly<Pick<E, Exclude<keyof E, keyof M | Reserved>>>;
19
+
20
+ declare type DynamicDevice = DeviceFacade<RuntimeModelClient['methods'], RuntimeModelClient['events']>;
21
+
22
+ declare type EventSelector = ({
23
+ readonly instanceId: string;
24
+ readonly designator?: never;
25
+ } | {
26
+ readonly designator: string;
27
+ readonly instanceId?: never;
28
+ }) & {
29
+ readonly event: string;
30
+ };
31
+
32
+ export declare interface FileTestbenchDefinition {
33
+ readonly document: URL;
34
+ readonly devices: Readonly<Record<string, URL>>;
35
+ readonly expected: {
36
+ readonly dependencies: Readonly<Record<string, DeviceDependency>>;
37
+ readonly instances: readonly Pick<FusedInstance, 'id' | 'device' | 'designator'>[];
38
+ };
39
+ }
40
+
41
+ export declare type FileTestbenchOptions = Omit<TestbenchOptions, 'document' | 'registry' | 'loadModule'>;
42
+
43
+ export { parseUnifiedManifest }
44
+
45
+ declare type Reserved = 'methods' | 'events' | 'then';
46
+
47
+ declare interface Testbench {
48
+ readonly devices: Readonly<Record<string, DynamicDevice>>;
49
+ readonly simTime: TimePs;
50
+ readonly diagnostics: readonly RuntimeDiagnostic[];
51
+ device(designator: string): ReturnType<HeadlessRuntime['getModel']>;
52
+ deviceById(instanceId: string): ReturnType<HeadlessRuntime['getModel']>;
53
+ events(selector: EventSelector): readonly ModelEvent<Value>[];
54
+ advanceFor(duration: TimePs): Promise<void>;
55
+ advanceTo(target: TimePs): Promise<void>;
56
+ advanceUntil(predicate: () => boolean | Promise<boolean>, options: {
57
+ timeout: TimePs;
58
+ }): Promise<void>;
59
+ reset(): Promise<void>;
60
+ dispose(): Promise<void>;
61
+ }
62
+
63
+ declare interface TestbenchOptions extends Omit<HeadlessRuntimeOptions, 'onModelEvent'> {
64
+ readonly record?: readonly EventSelector[];
65
+ }
66
+
67
+ export { validateModelValue }
68
+
69
+ export { }
package/dist/node.js ADDED
@@ -0,0 +1,33 @@
1
+ import { r as createTestbench } from "./testbench-fpI2T0c6.js";
2
+ import { parseFusedDocument, parseUnifiedManifest, validateModelValue } from "@mica-js/document/fused";
3
+ import { readFile } from "node:fs/promises";
4
+ import { fileURLToPath } from "node:url";
5
+ import { createDirectoryRegistry } from "@mica-js/sdk/fused/node";
6
+ //#region src/node.ts
7
+ async function createFileTestbench(definition, options) {
8
+ const document = parseFusedDocument(await readFile(definition.document, "utf8"));
9
+ const expected = definition.expected;
10
+ const dependencies = Object.entries(document.dependencies);
11
+ if (dependencies.length !== Object.keys(expected.dependencies).length || dependencies.some(([id, lock]) => lock.version !== expected.dependencies[id]?.version || lock.integrity !== expected.dependencies[id]?.integrity)) throw new Error("Generated testbench dependencies are stale; run mitest prepare");
12
+ const inventory = new Map(expected.instances.map((instance) => [instance.id, instance]));
13
+ if (document.instances.length !== inventory.size || document.instances.some((instance) => {
14
+ const binding = inventory.get(instance.id);
15
+ return binding === void 0 || binding.device !== instance.device || binding.designator !== instance.designator;
16
+ })) throw new Error("Generated testbench device bindings are stale; run mitest prepare");
17
+ return createTestbench({
18
+ ...options,
19
+ document,
20
+ registry: createDirectoryRegistry(Object.fromEntries(Object.entries(definition.devices).map(([id, url]) => [id, fileURLToPath(url)]))),
21
+ async loadModule(files, path) {
22
+ const bytes = await files.read(path);
23
+ return import(
24
+ /* @vite-ignore */
25
+ `data:text/javascript;base64,${Buffer.from(bytes).toString("base64")}`
26
+ );
27
+ }
28
+ });
29
+ }
30
+ //#endregion
31
+ export { createFileTestbench, parseUnifiedManifest, validateModelValue };
32
+
33
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\nimport { parseFusedDocument } from '@mica-js/document/fused';\nimport type { DeviceDependency, FusedInstance } from '@mica-js/document/fused';\nimport { createDirectoryRegistry } from '@mica-js/sdk/fused/node';\nimport { createTestbench, type TestbenchOptions } from './testbench';\n\nexport { parseUnifiedManifest, validateModelValue } from '@mica-js/document/fused';\n\nexport interface FileTestbenchDefinition {\n readonly document: URL;\n readonly devices: Readonly<Record<string, URL>>;\n readonly expected: {\n readonly dependencies: Readonly<Record<string, DeviceDependency>>;\n readonly instances: readonly Pick<FusedInstance, 'id' | 'device' | 'designator'>[];\n };\n}\n\nexport type FileTestbenchOptions = Omit<TestbenchOptions, 'document' | 'registry' | 'loadModule'>;\n\nexport async function createFileTestbench(\n definition: FileTestbenchDefinition,\n options: FileTestbenchOptions,\n) {\n const document = parseFusedDocument(await readFile(definition.document, 'utf8'));\n const expected = definition.expected;\n const dependencies = Object.entries(document.dependencies);\n if (\n dependencies.length !== Object.keys(expected.dependencies).length ||\n dependencies.some(\n ([id, lock]) =>\n lock.version !== expected.dependencies[id]?.version ||\n lock.integrity !== expected.dependencies[id]?.integrity,\n )\n ) {\n throw new Error('Generated testbench dependencies are stale; run mitest prepare');\n }\n const inventory = new Map(expected.instances.map((instance) => [instance.id, instance]));\n if (\n document.instances.length !== inventory.size ||\n document.instances.some((instance) => {\n const binding = inventory.get(instance.id);\n return (\n binding === undefined ||\n binding.device !== instance.device ||\n binding.designator !== instance.designator\n );\n })\n ) {\n throw new Error('Generated testbench device bindings are stale; run mitest prepare');\n }\n return createTestbench({\n ...options,\n document,\n registry: createDirectoryRegistry(\n Object.fromEntries(\n Object.entries(definition.devices).map(([id, url]) => [id, fileURLToPath(url)]),\n ),\n ),\n async loadModule(files, path): Promise<unknown> {\n const bytes = await files.read(path);\n return import(\n /* @vite-ignore */ `data:text/javascript;base64,${Buffer.from(bytes).toString('base64')}`\n );\n },\n });\n}\n"],"mappings":";;;;;;AAoBA,eAAsB,oBACpB,YACA,SACA;CACA,MAAM,WAAW,mBAAmB,MAAM,SAAS,WAAW,UAAU,MAAM,CAAC;CAC/E,MAAM,WAAW,WAAW;CAC5B,MAAM,eAAe,OAAO,QAAQ,SAAS,YAAY;CACzD,IACE,aAAa,WAAW,OAAO,KAAK,SAAS,YAAY,CAAC,CAAC,UAC3D,aAAa,MACV,CAAC,IAAI,UACJ,KAAK,YAAY,SAAS,aAAa,GAAG,EAAE,WAC5C,KAAK,cAAc,SAAS,aAAa,GAAG,EAAE,SAClD,GAEA,MAAM,IAAI,MAAM,gEAAgE;CAElF,MAAM,YAAY,IAAI,IAAI,SAAS,UAAU,KAAK,aAAa,CAAC,SAAS,IAAI,QAAQ,CAAC,CAAC;CACvF,IACE,SAAS,UAAU,WAAW,UAAU,QACxC,SAAS,UAAU,MAAM,aAAa;EACpC,MAAM,UAAU,UAAU,IAAI,SAAS,EAAE;EACzC,OACE,YAAY,KAAA,KACZ,QAAQ,WAAW,SAAS,UAC5B,QAAQ,eAAe,SAAS;CAEpC,CAAC,GAED,MAAM,IAAI,MAAM,mEAAmE;CAErF,OAAO,gBAAgB;EACrB,GAAG;EACH;EACA,UAAU,wBACR,OAAO,YACL,OAAO,QAAQ,WAAW,OAAO,CAAC,CAAC,KAAK,CAAC,IAAI,SAAS,CAAC,IAAI,cAAc,GAAG,CAAC,CAAC,CAChF,CACF;EACA,MAAM,WAAW,OAAO,MAAwB;GAC9C,MAAM,QAAQ,MAAM,MAAM,KAAK,IAAI;GACnC,OAAO;;IACc,+BAA+B,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,QAAQ;;EAE1F;CACF,CAAC;AACH"}
@@ -0,0 +1,215 @@
1
+ import { deriveFusedTopology, parseFusedDocument, parseStrictJson } from "@mica-js/document/fused";
2
+ import { openDevicePackage } from "@mica-js/sdk/fused";
3
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import { readDirectoryPackage } from "@mica-js/sdk/fused/node";
5
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
6
+ import { renderModelTypeNamespace } from "@mica-js/sdk/prepare";
7
+ import { randomUUID } from "node:crypto";
8
+ //#region src/prepare-types.ts
9
+ function fileUrl(from, to, directory = false) {
10
+ const path = relative(dirname(from), to);
11
+ if (isAbsolute(path)) throw new Error("Testbench sources must be on the same filesystem volume as the project");
12
+ const encoded = path.replaceAll("\\", "/").split("/").map((segment) => encodeURIComponent(segment)).join("/");
13
+ return `new URL(${JSON.stringify((encoded.startsWith(".") ? encoded : `./${encoded}`) + (directory ? "/" : ""))}, import.meta.url)`;
14
+ }
15
+ function renderTestbenchModule(input) {
16
+ const definitions = [];
17
+ const factories = /* @__PURE__ */ new Map();
18
+ for (const [id, manifest] of input.manifests) {
19
+ if (manifest.model === void 0) continue;
20
+ const index = factories.size;
21
+ const namespace = `MicaDevice${index}`;
22
+ const schema = `schema${index}`;
23
+ const factory = `device${index}`;
24
+ factories.set(id, factory);
25
+ definitions.push(renderModelTypeNamespace(manifest, namespace));
26
+ definitions.push(`const ${schema} = parseUnifiedManifest(${JSON.stringify(JSON.stringify(manifest))});`);
27
+ const methods = [];
28
+ const events = [];
29
+ for (const [name] of Object.entries(manifest.model.methods ?? {})) {
30
+ const decoder = `decode${index}Method${methods.length}`;
31
+ const key = JSON.stringify(name);
32
+ const result = `Result<${namespace}.Methods[${key}]>`;
33
+ definitions.push(`function ${decoder}(value: unknown): ${result} {
34
+ validateModelValue(value, ${schema}.model!.methods![${key}]!.returns, ${schema}.model!.types);
35
+ return value as ${result};
36
+ }`);
37
+ methods.push(`${key}: async (params: Params<${namespace}.Methods[${key}]>) => ${decoder}(await modelMethod(client, ${key})(params))`);
38
+ }
39
+ for (const name of Object.keys(manifest.model.events ?? {})) {
40
+ const decoder = `decode${index}Event${events.length}`;
41
+ const key = JSON.stringify(name);
42
+ const payload = `${namespace}.Events[${key}]`;
43
+ definitions.push(`function ${decoder}(value: unknown): ${payload} {
44
+ validateModelValue(value, ${schema}.model!.events![${key}]!, ${schema}.model!.types);
45
+ return value as ${payload};
46
+ }`);
47
+ events.push(`${key}: modelEvent(client, ${key}, ${decoder})`);
48
+ }
49
+ definitions.push(`function ${factory}(client: RuntimeModelClient) {
50
+ return deviceFacade({ ${methods.join(",\n")} }, { ${events.join(",\n")} });
51
+ }`);
52
+ }
53
+ const bindings = input.document.instances.flatMap((instance) => {
54
+ const factory = factories.get(instance.device);
55
+ return instance.designator === void 0 || factory === void 0 ? [] : [`get ${JSON.stringify(instance.designator)}() { return ${factory}(bench.deviceById(${JSON.stringify(instance.id)})); }`];
56
+ });
57
+ const expected = {
58
+ dependencies: input.document.dependencies,
59
+ instances: input.document.instances.map(({ id, device, designator }) => ({
60
+ id,
61
+ device,
62
+ ...designator === void 0 ? {} : { designator }
63
+ }))
64
+ };
65
+ return [
66
+ "// Generated by mitest prepare; do not edit.",
67
+ "import type { Params, Result, RuntimeModelClient } from '@mica-js/testing';",
68
+ "import { bindTestbenchDevices, deviceFacade, modelEvent, modelMethod } from '@mica-js/testing';",
69
+ "import { createFileTestbench, parseUnifiedManifest, validateModelValue, type FileTestbenchOptions } from '@mica-js/testing/node';",
70
+ ...definitions,
71
+ `export async function createTestbench(options: FileTestbenchOptions) {
72
+ const bench = await createFileTestbench({
73
+ document: ${fileUrl(input.target, input.documentPath)},
74
+ devices: { ${Object.entries(input.directories).map(([id, path]) => `${JSON.stringify(id)}: ${fileUrl(input.target, path, true)}`).join(",\n")} },
75
+ expected: ${JSON.stringify(expected)},
76
+ }, options);
77
+ return bindTestbenchDevices(bench, { ${bindings.join(",\n")} });
78
+ }`,
79
+ "export type CircuitTestbench = Awaited<ReturnType<typeof createTestbench>>;",
80
+ "export type CircuitDevices = CircuitTestbench['devices'];",
81
+ ""
82
+ ].join("\n\n");
83
+ }
84
+ function renderTestTypeScriptConfig(sourceRoot = "..") {
85
+ return JSON.stringify({
86
+ compilerOptions: {
87
+ target: "ES2022",
88
+ module: "ESNext",
89
+ moduleResolution: "Bundler",
90
+ customConditions: ["source"],
91
+ lib: ["ES2023", "DOM"],
92
+ types: ["node"],
93
+ strict: true,
94
+ noEmit: true,
95
+ allowImportingTsExtensions: true,
96
+ allowArbitraryExtensions: true,
97
+ rootDirs: [sourceRoot, "./types"],
98
+ skipLibCheck: true,
99
+ verbatimModuleSyntax: true
100
+ },
101
+ include: [
102
+ "../tests",
103
+ "../mitest.config.ts",
104
+ "./testbenches/**/*.ts",
105
+ "./types/**/*.ts"
106
+ ]
107
+ }, null, 2) + "\n";
108
+ }
109
+ //#endregion
110
+ //#region src/prepare.ts
111
+ function record(value) {
112
+ return typeof value === "object" && value !== null && !Array.isArray(value);
113
+ }
114
+ function sourceRoot(root, documents) {
115
+ let common = resolve(root);
116
+ for (const document of documents) for (;;) {
117
+ const child = relative(common, document);
118
+ if (isAbsolute(child)) throw new Error("Testbench sources must be on the same filesystem volume as the project");
119
+ if (child !== ".." && !child.startsWith("..\\") && !child.startsWith("../")) break;
120
+ common = dirname(common);
121
+ }
122
+ return common;
123
+ }
124
+ function testbenchInputs(options) {
125
+ return Object.values(options.config.testbenches).flatMap((entry) => [resolve(options.root, entry.document), ...Object.values(entry.devices).flatMap((path) => [resolve(options.root, path, "release.json"), resolve(options.root, path, "package.json")])]);
126
+ }
127
+ async function prepareTestbenches(options) {
128
+ const outputs = /* @__PURE__ */ new Map();
129
+ const updates = /* @__PURE__ */ new Map();
130
+ const common = sourceRoot(options.root, Object.values(options.config.testbenches).map((entry) => resolve(options.root, entry.document)));
131
+ for (const [name, entry] of Object.entries(options.config.testbenches)) {
132
+ const documentPath = resolve(options.root, entry.document);
133
+ const before = await readFile(documentPath, "utf8");
134
+ const raw = parseStrictJson(before);
135
+ if (!record(raw) || !record(raw.dependencies)) throw new Error(`Invalid schematic ${documentPath}`);
136
+ const directories = Object.fromEntries(Object.entries(entry.devices).map(([id, path]) => [id, resolve(options.root, path)]));
137
+ const dependencies = { ...raw.dependencies };
138
+ const manifests = /* @__PURE__ */ new Map();
139
+ for (const [id, directory] of Object.entries(directories)) {
140
+ const source = await readDirectoryPackage(directory);
141
+ if (source.lock.id !== id) throw new Error(`Configured device ${id} is ${source.lock.id} in ${directory}`);
142
+ const verified = await openDevicePackage({ open: async () => source }, source.lock);
143
+ manifests.set(id, verified.manifest);
144
+ if (options.updateLock) dependencies[id] = {
145
+ version: source.lock.version,
146
+ integrity: source.lock.integrity
147
+ };
148
+ else {
149
+ const dependency = dependencies[id];
150
+ if (!record(dependency) || dependency.version !== source.lock.version || dependency.integrity !== source.lock.integrity) throw new Error(`Dependency ${id} differs from ${documentPath}; run mitest prepare --update-lock explicitly`);
151
+ }
152
+ }
153
+ const document = parseFusedDocument({
154
+ ...raw,
155
+ dependencies
156
+ });
157
+ for (const id of Object.keys(document.dependencies)) if (!manifests.has(id)) throw new Error(`No local device configured for ${id}`);
158
+ deriveFusedTopology(document, manifests);
159
+ const target = join(options.root, ".mitest", "testbenches", `${name}.ts`);
160
+ outputs.set(target, renderTestbenchModule({
161
+ target,
162
+ documentPath,
163
+ document,
164
+ directories,
165
+ manifests
166
+ }));
167
+ if (documentPath.endsWith(".sch")) {
168
+ const declaration = join(options.root, ".mitest", "types", relative(common, documentPath).replace(/\.sch$/, ".d.sch.ts"));
169
+ const module = relative(dirname(declaration), target).replaceAll("\\", "/");
170
+ outputs.set(declaration, `// Generated by mitest; do not edit.\nexport { createTestbench as default } from ${JSON.stringify(module.startsWith(".") ? module : `./${module}`)};\n`);
171
+ }
172
+ if (options.updateLock) {
173
+ const after = JSON.stringify({
174
+ ...raw,
175
+ dependencies
176
+ }, null, 2) + "\n";
177
+ const previous = updates.get(documentPath);
178
+ if (previous !== void 0 && previous.after !== after) throw new Error(`Conflicting dependency updates for ${documentPath}`);
179
+ updates.set(documentPath, {
180
+ before,
181
+ after
182
+ });
183
+ }
184
+ }
185
+ outputs.set(join(options.root, ".mitest", "tsconfig.json"), renderTestTypeScriptConfig(relative(join(options.root, ".mitest"), common).replaceAll("\\", "/")));
186
+ for (const [file, update] of updates) if (await readFile(file, "utf8") !== update.before) throw new Error(`Schematic changed during preparation: ${file}`);
187
+ for (const [file, update] of updates) {
188
+ if (update.before === update.after) continue;
189
+ const temporary = `${file}.${randomUUID()}.tmp`;
190
+ try {
191
+ await writeFile(temporary, update.after, {
192
+ encoding: "utf8",
193
+ flag: "wx"
194
+ });
195
+ await rename(temporary, file);
196
+ } finally {
197
+ await rm(temporary, { force: true });
198
+ }
199
+ }
200
+ for (const [file, content] of outputs) {
201
+ await mkdir(dirname(file), { recursive: true });
202
+ let current;
203
+ try {
204
+ current = await readFile(file, "utf8");
205
+ } catch (error) {
206
+ if (error.code !== "ENOENT") throw error;
207
+ }
208
+ if (current !== content) await writeFile(file, content, "utf8");
209
+ }
210
+ return [...outputs.keys()];
211
+ }
212
+ //#endregion
213
+ export { testbenchInputs as n, prepareTestbenches as t };
214
+
215
+ //# sourceMappingURL=prepare-DcWr62th.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prepare-DcWr62th.js","names":[],"sources":["../src/prepare-types.ts","../src/prepare.ts"],"sourcesContent":["import { relative, dirname, isAbsolute } from 'node:path';\nimport type { FusedDocument, UnifiedDeviceManifest } from '@mica-js/document/fused';\nimport { renderModelTypeNamespace } from '@mica-js/sdk/prepare';\n\nfunction fileUrl(from: string, to: string, directory = false): string {\n const path = relative(dirname(from), to);\n if (isAbsolute(path))\n throw new Error('Testbench sources must be on the same filesystem volume as the project');\n const encoded = path\n .replaceAll('\\\\', '/')\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n return `new URL(${JSON.stringify((encoded.startsWith('.') ? encoded : `./${encoded}`) + (directory ? '/' : ''))}, import.meta.url)`;\n}\n\nexport function renderTestbenchModule(input: {\n readonly target: string;\n readonly documentPath: string;\n readonly document: FusedDocument;\n readonly directories: Readonly<Record<string, string>>;\n readonly manifests: ReadonlyMap<string, UnifiedDeviceManifest>;\n}): string {\n const definitions: string[] = [];\n const factories = new Map<string, string>();\n for (const [id, manifest] of input.manifests) {\n if (manifest.model === undefined) continue;\n const index = factories.size;\n const namespace = `MicaDevice${index}`;\n const schema = `schema${index}`;\n const factory = `device${index}`;\n factories.set(id, factory);\n definitions.push(renderModelTypeNamespace(manifest, namespace));\n definitions.push(\n `const ${schema} = parseUnifiedManifest(${JSON.stringify(JSON.stringify(manifest))});`,\n );\n const methods: string[] = [];\n const events: string[] = [];\n for (const [name] of Object.entries(manifest.model.methods ?? {})) {\n const decoder = `decode${index}Method${methods.length}`;\n const key = JSON.stringify(name);\n const result = `Result<${namespace}.Methods[${key}]>`;\n definitions.push(`function ${decoder}(value: unknown): ${result} {\n validateModelValue(value, ${schema}.model!.methods![${key}]!.returns, ${schema}.model!.types);\n return value as ${result};\n}`);\n methods.push(\n `${key}: async (params: Params<${namespace}.Methods[${key}]>) => ${decoder}(await modelMethod(client, ${key})(params))`,\n );\n }\n for (const name of Object.keys(manifest.model.events ?? {})) {\n const decoder = `decode${index}Event${events.length}`;\n const key = JSON.stringify(name);\n const payload = `${namespace}.Events[${key}]`;\n definitions.push(`function ${decoder}(value: unknown): ${payload} {\n validateModelValue(value, ${schema}.model!.events![${key}]!, ${schema}.model!.types);\n return value as ${payload};\n}`);\n events.push(`${key}: modelEvent(client, ${key}, ${decoder})`);\n }\n definitions.push(`function ${factory}(client: RuntimeModelClient) {\n return deviceFacade({ ${methods.join(',\\n')} }, { ${events.join(',\\n')} });\n}`);\n }\n const bindings = input.document.instances.flatMap((instance) => {\n const factory = factories.get(instance.device);\n return instance.designator === undefined || factory === undefined\n ? []\n : [\n `get ${JSON.stringify(instance.designator)}() { return ${factory}(bench.deviceById(${JSON.stringify(instance.id)})); }`,\n ];\n });\n const expected = {\n dependencies: input.document.dependencies,\n instances: input.document.instances.map(({ id, device, designator }) => ({\n id,\n device,\n ...(designator === undefined ? {} : { designator }),\n })),\n };\n return [\n '// Generated by mitest prepare; do not edit.',\n \"import type { Params, Result, RuntimeModelClient } from '@mica-js/testing';\",\n \"import { bindTestbenchDevices, deviceFacade, modelEvent, modelMethod } from '@mica-js/testing';\",\n \"import { createFileTestbench, parseUnifiedManifest, validateModelValue, type FileTestbenchOptions } from '@mica-js/testing/node';\",\n ...definitions,\n `export async function createTestbench(options: FileTestbenchOptions) {\n const bench = await createFileTestbench({\n document: ${fileUrl(input.target, input.documentPath)},\n devices: { ${Object.entries(input.directories)\n .map(([id, path]) => `${JSON.stringify(id)}: ${fileUrl(input.target, path, true)}`)\n .join(',\\n')} },\n expected: ${JSON.stringify(expected)},\n }, options);\n return bindTestbenchDevices(bench, { ${bindings.join(',\\n')} });\n}`,\n 'export type CircuitTestbench = Awaited<ReturnType<typeof createTestbench>>;',\n \"export type CircuitDevices = CircuitTestbench['devices'];\",\n '',\n ].join('\\n\\n');\n}\n\nexport function renderTestTypeScriptConfig(sourceRoot = '..'): string {\n return (\n JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2022',\n module: 'ESNext',\n moduleResolution: 'Bundler',\n customConditions: ['source'],\n lib: ['ES2023', 'DOM'],\n types: ['node'],\n strict: true,\n noEmit: true,\n allowImportingTsExtensions: true,\n allowArbitraryExtensions: true,\n rootDirs: [sourceRoot, './types'],\n skipLibCheck: true,\n verbatimModuleSyntax: true,\n },\n include: ['../tests', '../mitest.config.ts', './testbenches/**/*.ts', './types/**/*.ts'],\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n","import { mkdir, readFile, writeFile, rename, rm } from 'node:fs/promises';\nimport { randomUUID } from 'node:crypto';\nimport { dirname, join, resolve, relative, isAbsolute } from 'node:path';\nimport { parseFusedDocument, parseStrictJson, deriveFusedTopology } from '@mica-js/document/fused';\nimport type { UnifiedDeviceManifest } from '@mica-js/document/fused';\nimport type { MitestConfig } from './config';\nimport { readDirectoryPackage } from '@mica-js/sdk/fused/node';\nimport { openDevicePackage } from '@mica-js/sdk/fused';\nimport { renderTestbenchModule, renderTestTypeScriptConfig } from './prepare-types';\n\nexport interface PrepareTestbenchesOptions {\n readonly root: string;\n readonly config: MitestConfig;\n readonly updateLock?: boolean;\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction sourceRoot(root: string, documents: readonly string[]): string {\n let common = resolve(root);\n for (const document of documents) {\n for (;;) {\n const child = relative(common, document);\n if (isAbsolute(child))\n throw new Error('Testbench sources must be on the same filesystem volume as the project');\n if (child !== '..' && !child.startsWith('..\\\\') && !child.startsWith('../')) break;\n common = dirname(common);\n }\n }\n return common;\n}\n\nexport function testbenchInputs(options: PrepareTestbenchesOptions): readonly string[] {\n return Object.values(options.config.testbenches).flatMap((entry) => [\n resolve(options.root, entry.document),\n ...Object.values(entry.devices).flatMap((path) => [\n resolve(options.root, path, 'release.json'),\n resolve(options.root, path, 'package.json'),\n ]),\n ]);\n}\n\nexport async function prepareTestbenches(\n options: PrepareTestbenchesOptions,\n): Promise<readonly string[]> {\n const outputs = new Map<string, string>();\n const updates = new Map<string, { before: string; after: string }>();\n const common = sourceRoot(\n options.root,\n Object.values(options.config.testbenches).map((entry) => resolve(options.root, entry.document)),\n );\n for (const [name, entry] of Object.entries(options.config.testbenches)) {\n const documentPath = resolve(options.root, entry.document);\n const before = await readFile(documentPath, 'utf8');\n const raw = parseStrictJson(before);\n if (!record(raw) || !record(raw.dependencies))\n throw new Error(`Invalid schematic ${documentPath}`);\n const directories = Object.fromEntries(\n Object.entries(entry.devices).map(([id, path]) => [id, resolve(options.root, path)]),\n );\n const dependencies = { ...raw.dependencies };\n const manifests = new Map<string, UnifiedDeviceManifest>();\n for (const [id, directory] of Object.entries(directories)) {\n const source = await readDirectoryPackage(directory);\n if (source.lock.id !== id)\n throw new Error(`Configured device ${id} is ${source.lock.id} in ${directory}`);\n const verified = await openDevicePackage({ open: async () => source }, source.lock);\n manifests.set(id, verified.manifest);\n if (options.updateLock)\n dependencies[id] = { version: source.lock.version, integrity: source.lock.integrity };\n else {\n const dependency = dependencies[id];\n if (\n !record(dependency) ||\n dependency.version !== source.lock.version ||\n dependency.integrity !== source.lock.integrity\n ) {\n throw new Error(\n `Dependency ${id} differs from ${documentPath}; run mitest prepare --update-lock explicitly`,\n );\n }\n }\n }\n const document = parseFusedDocument({ ...raw, dependencies });\n for (const id of Object.keys(document.dependencies)) {\n if (!manifests.has(id)) throw new Error(`No local device configured for ${id}`);\n }\n deriveFusedTopology(document, manifests);\n const target = join(options.root, '.mitest', 'testbenches', `${name}.ts`);\n outputs.set(\n target,\n renderTestbenchModule({ target, documentPath, document, directories, manifests }),\n );\n if (documentPath.endsWith('.sch')) {\n const declaration = join(\n options.root,\n '.mitest',\n 'types',\n relative(common, documentPath).replace(/\\.sch$/, '.d.sch.ts'),\n );\n const module = relative(dirname(declaration), target).replaceAll('\\\\', '/');\n outputs.set(\n declaration,\n `// Generated by mitest; do not edit.\\nexport { createTestbench as default } from ${JSON.stringify(module.startsWith('.') ? module : `./${module}`)};\\n`,\n );\n }\n if (options.updateLock) {\n const after = JSON.stringify({ ...raw, dependencies }, null, 2) + '\\n';\n const previous = updates.get(documentPath);\n if (previous !== undefined && previous.after !== after)\n throw new Error(`Conflicting dependency updates for ${documentPath}`);\n updates.set(documentPath, { before, after });\n }\n }\n outputs.set(\n join(options.root, '.mitest', 'tsconfig.json'),\n renderTestTypeScriptConfig(\n relative(join(options.root, '.mitest'), common).replaceAll('\\\\', '/'),\n ),\n );\n for (const [file, update] of updates) {\n if ((await readFile(file, 'utf8')) !== update.before)\n throw new Error(`Schematic changed during preparation: ${file}`);\n }\n for (const [file, update] of updates) {\n if (update.before === update.after) continue;\n const temporary = `${file}.${randomUUID()}.tmp`;\n try {\n await writeFile(temporary, update.after, { encoding: 'utf8', flag: 'wx' });\n await rename(temporary, file);\n } finally {\n await rm(temporary, { force: true });\n }\n }\n for (const [file, content] of outputs) {\n await mkdir(dirname(file), { recursive: true });\n let current: string | undefined;\n try {\n current = await readFile(file, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n if (current !== content) await writeFile(file, content, 'utf8');\n }\n return [...outputs.keys()];\n}\n"],"mappings":";;;;;;;;AAIA,SAAS,QAAQ,MAAc,IAAY,YAAY,OAAe;CACpE,MAAM,OAAO,SAAS,QAAQ,IAAI,GAAG,EAAE;CACvC,IAAI,WAAW,IAAI,GACjB,MAAM,IAAI,MAAM,wEAAwE;CAC1F,MAAM,UAAU,KACb,WAAW,MAAM,GAAG,CAAC,CACrB,MAAM,GAAG,CAAC,CACV,KAAK,YAAY,mBAAmB,OAAO,CAAC,CAAC,CAC7C,KAAK,GAAG;CACX,OAAO,WAAW,KAAK,WAAW,QAAQ,WAAW,GAAG,IAAI,UAAU,KAAK,cAAc,YAAY,MAAM,GAAG,EAAE;AAClH;AAEA,SAAgB,sBAAsB,OAM3B;CACT,MAAM,cAAwB,CAAC;CAC/B,MAAM,4BAAY,IAAI,IAAoB;CAC1C,KAAK,MAAM,CAAC,IAAI,aAAa,MAAM,WAAW;EAC5C,IAAI,SAAS,UAAU,KAAA,GAAW;EAClC,MAAM,QAAQ,UAAU;EACxB,MAAM,YAAY,aAAa;EAC/B,MAAM,SAAS,SAAS;EACxB,MAAM,UAAU,SAAS;EACzB,UAAU,IAAI,IAAI,OAAO;EACzB,YAAY,KAAK,yBAAyB,UAAU,SAAS,CAAC;EAC9D,YAAY,KACV,SAAS,OAAO,0BAA0B,KAAK,UAAU,KAAK,UAAU,QAAQ,CAAC,EAAE,GACrF;EACA,MAAM,UAAoB,CAAC;EAC3B,MAAM,SAAmB,CAAC;EAC1B,KAAK,MAAM,CAAC,SAAS,OAAO,QAAQ,SAAS,MAAM,WAAW,CAAC,CAAC,GAAG;GACjE,MAAM,UAAU,SAAS,MAAM,QAAQ,QAAQ;GAC/C,MAAM,MAAM,KAAK,UAAU,IAAI;GAC/B,MAAM,SAAS,UAAU,UAAU,WAAW,IAAI;GAClD,YAAY,KAAK,YAAY,QAAQ,oBAAoB,OA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MAAM,WAAW,eAAe,GAC7C,2BACE,SAAS,KAAK,QAAQ,MAAM,SAAS,GAAG,MAAM,CAAC,CAAC,WAAW,MAAM,GAAG,CACtE,CACF;CACA,KAAK,MAAM,CAAC,MAAM,WAAW,SAC3B,IAAK,MAAM,SAAS,MAAM,MAAM,MAAO,OAAO,QAC5C,MAAM,IAAI,MAAM,yCAAyC,MAAM;CAEnE,KAAK,MAAM,CAAC,MAAM,WAAW,SAAS;EACpC,IAAI,OAAO,WAAW,OAAO,OAAO;EACpC,MAAM,YAAY,GAAG,KAAK,GAAG,WAAW,EAAE;EAC1C,IAAI;GACF,MAAM,UAAU,WAAW,OAAO,OAAO;IAAE,UAAU;IAAQ,MAAM;GAAK,CAAC;GACzE,MAAM,OAAO,WAAW,IAAI;EAC9B,UAAU;GACR,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;EACrC;CACF;CACA,KAAK,MAAM,CAAC,MAAM,YAAY,SAAS;EACrC,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;EAC9C,IAAI;EACJ,IAAI;GACF,UAAU,MAAM,SAAS,MAAM,MAAM;EACvC,SAAS,OAAO;GACd,IAAK,MAAgC,SAAS,UAAU,MAAM;EAChE;EACA,IAAI,YAAY,SAAS,MAAM,UAAU,MAAM,SAAS,MAAM;CAChE;CACA,OAAO,CAAC,GAAG,QAAQ,KAAK,CAAC;AAC3B"}
@@ -0,0 +1,187 @@
1
+ import { addTime, timePs } from "@mica-js/core";
2
+ import { parseFusedDocument } from "@mica-js/document/fused";
3
+ import { createHeadlessRuntime } from "@mica-js/sdk/fused";
4
+ //#region src/devices.ts
5
+ function deviceFacade(methods, events) {
6
+ const flat = Object.create(null);
7
+ for (const [key, value] of Object.entries(methods)) if (!Object.hasOwn(events, key) && ![
8
+ "methods",
9
+ "events",
10
+ "then"
11
+ ].includes(key)) flat[key] = value;
12
+ for (const [key, value] of Object.entries(events)) if (!Object.hasOwn(methods, key) && ![
13
+ "methods",
14
+ "events",
15
+ "then"
16
+ ].includes(key)) flat[key] = value;
17
+ return Object.freeze({
18
+ ...flat,
19
+ methods: Object.freeze(methods),
20
+ events: Object.freeze(events)
21
+ });
22
+ }
23
+ function modelMethod(client, name) {
24
+ const method = client.methods[name];
25
+ if (method === void 0) throw new Error(`Model method ${name} is unavailable`);
26
+ return method;
27
+ }
28
+ function modelEvent(client, name, decode) {
29
+ const event = client.events[name];
30
+ if (event === void 0) throw new Error(`Model event ${name} is unavailable`);
31
+ return (listener, thisArgs, disposables) => event((entry) => listener.call(thisArgs, {
32
+ ...entry,
33
+ value: decode(entry.value)
34
+ }), void 0, disposables);
35
+ }
36
+ //#endregion
37
+ //#region src/testbench.ts
38
+ var TestbenchError = class extends Error {
39
+ code;
40
+ constructor(code, message) {
41
+ super(message);
42
+ this.code = code;
43
+ this.name = "TestbenchError";
44
+ }
45
+ };
46
+ async function createTestbench(options) {
47
+ const { record = [], onDiagnostic, ...runtimeOptions } = options;
48
+ const document = parseFusedDocument(structuredClone(options.document));
49
+ const step = timePs(options.step);
50
+ if (step === 0) throw new RangeError("Testbench step must be positive");
51
+ const instanceIdFor = (designator) => {
52
+ const instance = document.instances.find((item) => item.designator === designator);
53
+ if (!instance) throw new TestbenchError("testing/unknown-device", `Unknown device ${designator}`);
54
+ return instance.id;
55
+ };
56
+ const keyFor = (selector) => {
57
+ if (typeof selector.event !== "string" || selector.event.length === 0) throw new TypeError("Recorded event name must be nonempty");
58
+ if (selector.instanceId === void 0 === (selector.designator === void 0)) throw new TypeError("An event selector must specify exactly one instance ID or designator");
59
+ const instanceId = selector.instanceId ?? instanceIdFor(selector.designator);
60
+ if (!document.instances.some((instance) => instance.id === instanceId)) throw new TestbenchError("testing/unknown-device", `Unknown device ${instanceId}`);
61
+ return JSON.stringify([instanceId, selector.event]);
62
+ };
63
+ const recordings = /* @__PURE__ */ new Map();
64
+ const selectors = record.map((value) => {
65
+ const selector = { ...value };
66
+ return {
67
+ selector,
68
+ key: keyFor(selector)
69
+ };
70
+ });
71
+ for (const { key } of selectors) recordings.set(key, []);
72
+ const onModelEvent = (event) => {
73
+ recordings.get(JSON.stringify([event.instanceId, event.event]))?.push(structuredClone(event.payload));
74
+ };
75
+ const diagnostics = [];
76
+ const runtime = await createHeadlessRuntime({
77
+ ...runtimeOptions,
78
+ document,
79
+ onModelEvent,
80
+ onDiagnostic(diagnostic) {
81
+ diagnostics.push(structuredClone(diagnostic));
82
+ onDiagnostic?.(diagnostic);
83
+ }
84
+ });
85
+ try {
86
+ for (const { selector } of selectors) {
87
+ const id = selector.instanceId ?? instanceIdFor(selector.designator);
88
+ const client = runtime.getModel(id);
89
+ if (!Object.hasOwn(client.events, selector.event)) throw new TestbenchError("testing/unrecorded-event", `Unknown event ${selector.event} on ${id}`);
90
+ }
91
+ } catch (error) {
92
+ try {
93
+ await runtime.dispose();
94
+ } catch (cleanupError) {
95
+ throw new AggregateError([error, cleanupError], "Testbench preparation and cleanup failed", { cause: cleanupError });
96
+ }
97
+ throw error;
98
+ }
99
+ let busy = false;
100
+ let disposal;
101
+ const assertPaused = () => {
102
+ const state = runtime.getState();
103
+ if (state.status !== "paused") throw new Error(`Testbench requires a paused runtime, got ${state.status}`);
104
+ };
105
+ const exclusive = async (operation) => {
106
+ if (busy) throw new TestbenchError("testing/busy", "Await the current testbench operation first");
107
+ busy = true;
108
+ try {
109
+ await operation();
110
+ } finally {
111
+ busy = false;
112
+ }
113
+ };
114
+ const targetAfter = (duration) => {
115
+ timePs(duration);
116
+ if (duration % step !== 0) throw new RangeError("Test duration must be a multiple of the fixed step");
117
+ return addTime(runtime.getState().simTime, duration);
118
+ };
119
+ const advanceTo = async (target) => {
120
+ assertPaused();
121
+ timePs(target);
122
+ const now = runtime.getState().simTime;
123
+ if (target < now) throw new RangeError("Cannot advance virtual time backwards");
124
+ if ((target - now) % step !== 0) throw new RangeError("Target must be reachable by whole fixed steps");
125
+ while (runtime.getState().simTime < target) await runtime.step();
126
+ };
127
+ const devices = Object.create(null);
128
+ for (const instance of document.instances) {
129
+ if (instance.designator === void 0) continue;
130
+ Object.defineProperty(devices, instance.designator, {
131
+ enumerable: true,
132
+ get() {
133
+ const client = runtime.getModel(instance.id);
134
+ return deviceFacade(client.methods, client.events);
135
+ }
136
+ });
137
+ }
138
+ return {
139
+ devices: Object.freeze(devices),
140
+ get simTime() {
141
+ return runtime.getState().simTime;
142
+ },
143
+ get diagnostics() {
144
+ return structuredClone(diagnostics);
145
+ },
146
+ device: (designator) => runtime.getModel(instanceIdFor(designator)),
147
+ deviceById: (instanceId) => runtime.getModel(instanceId),
148
+ events(selector) {
149
+ const events = recordings.get(keyFor(selector));
150
+ if (!events) throw new TestbenchError("testing/unrecorded-event", "Configure event recording before creation");
151
+ return structuredClone(events);
152
+ },
153
+ advanceFor: (duration) => exclusive(() => advanceTo(targetAfter(duration))),
154
+ advanceTo: (target) => exclusive(() => advanceTo(target)),
155
+ advanceUntil: (predicate, { timeout }) => exclusive(async () => {
156
+ assertPaused();
157
+ const target = targetAfter(timeout);
158
+ for (;;) {
159
+ const matched = await predicate();
160
+ if (typeof matched !== "boolean") throw new TypeError("Wait predicate must return a boolean");
161
+ if (matched) return;
162
+ if (runtime.getState().simTime === target) throw new TestbenchError("testing/timeout", `Condition unmet at ${target} ps`);
163
+ await runtime.step();
164
+ }
165
+ }),
166
+ reset: () => exclusive(async () => {
167
+ const { status } = runtime.getState();
168
+ if (status !== "paused" && status !== "faulted") throw new Error(`Cannot reset testbench in ${status} state`);
169
+ for (const history of recordings.values()) history.length = 0;
170
+ diagnostics.length = 0;
171
+ await runtime.reset();
172
+ }),
173
+ dispose() {
174
+ if (disposal) return disposal;
175
+ if (busy) return Promise.reject(new TestbenchError("testing/busy", "Await the current operation before disposal"));
176
+ disposal = runtime.dispose();
177
+ return disposal;
178
+ }
179
+ };
180
+ }
181
+ function bindTestbenchDevices(bench, devices) {
182
+ return Object.assign(bench, { devices: Object.freeze(devices) });
183
+ }
184
+ //#endregion
185
+ export { modelEvent as a, deviceFacade as i, bindTestbenchDevices as n, modelMethod as o, createTestbench as r, TestbenchError as t };
186
+
187
+ //# sourceMappingURL=testbench-fpI2T0c6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testbench-fpI2T0c6.js","names":["base"],"sources":["../src/devices.ts","../src/testbench.ts"],"sourcesContent":["import type { Event } from '@mica-js/sdk/device';\nimport type { ModelEvent, RuntimeModelClient } from '@mica-js/sdk/fused';\n\ntype Reserved = 'methods' | 'events' | 'then';\n\nexport type DeviceFacade<M extends object, E extends object> = {\n readonly methods: Readonly<M>;\n readonly events: Readonly<E>;\n} & Readonly<Pick<M, Exclude<keyof M, keyof E | Reserved>>> &\n Readonly<Pick<E, Exclude<keyof E, keyof M | Reserved>>>;\n\nexport function deviceFacade<M extends object, E extends object>(\n methods: M,\n events: E,\n): DeviceFacade<M, E> {\n const flat: Record<string, unknown> = Object.create(null);\n for (const [key, value] of Object.entries(methods)) {\n if (!Object.hasOwn(events, key) && !['methods', 'events', 'then'].includes(key))\n flat[key] = value;\n }\n for (const [key, value] of Object.entries(events)) {\n if (!Object.hasOwn(methods, key) && !['methods', 'events', 'then'].includes(key))\n flat[key] = value;\n }\n // The key filtering above implements the same exclusions as DeviceFacade.\n return Object.freeze({\n ...flat,\n methods: Object.freeze(methods),\n events: Object.freeze(events),\n }) as DeviceFacade<M, E>;\n}\n\nexport function modelMethod(client: RuntimeModelClient, name: string) {\n const method = client.methods[name];\n if (method === undefined) throw new Error(`Model method ${name} is unavailable`);\n return method;\n}\n\nexport function modelEvent<T>(\n client: RuntimeModelClient,\n name: string,\n decode: (value: unknown) => T,\n): Event<ModelEvent<T>> {\n const event = client.events[name];\n if (event === undefined) throw new Error(`Model event ${name} is unavailable`);\n return (listener, thisArgs, disposables) =>\n event(\n (entry) => listener.call(thisArgs, { ...entry, value: decode(entry.value) }),\n undefined,\n disposables,\n );\n}\n\nexport type DynamicDevice = DeviceFacade<\n RuntimeModelClient['methods'],\n RuntimeModelClient['events']\n>;\n","import { addTime, timePs, type TimePs } from '@mica-js/core';\nimport { parseFusedDocument, type Value } from '@mica-js/document/fused';\nimport {\n createHeadlessRuntime,\n type HeadlessRuntime,\n type HeadlessRuntimeOptions,\n type ModelEvent,\n type RuntimeDiagnostic,\n type RuntimeModelEvent,\n} from '@mica-js/sdk/fused';\nimport { deviceFacade, type DynamicDevice } from './devices';\n\nexport type EventSelector = (\n | { readonly instanceId: string; readonly designator?: never }\n | { readonly designator: string; readonly instanceId?: never }\n) & { readonly event: string };\n\nexport interface TestbenchOptions extends Omit<HeadlessRuntimeOptions, 'onModelEvent'> {\n readonly record?: readonly EventSelector[];\n}\n\nexport interface Testbench {\n readonly devices: Readonly<Record<string, DynamicDevice>>;\n readonly simTime: TimePs;\n readonly diagnostics: readonly RuntimeDiagnostic[];\n device(designator: string): ReturnType<HeadlessRuntime['getModel']>;\n deviceById(instanceId: string): ReturnType<HeadlessRuntime['getModel']>;\n events(selector: EventSelector): readonly ModelEvent<Value>[];\n advanceFor(duration: TimePs): Promise<void>;\n advanceTo(target: TimePs): Promise<void>;\n advanceUntil(\n predicate: () => boolean | Promise<boolean>,\n options: { timeout: TimePs },\n ): Promise<void>;\n reset(): Promise<void>;\n dispose(): Promise<void>;\n}\n\nexport class TestbenchError extends Error {\n constructor(\n readonly code:\n 'testing/unknown-device' | 'testing/unrecorded-event' | 'testing/timeout' | 'testing/busy',\n message: string,\n ) {\n super(message);\n this.name = 'TestbenchError';\n }\n}\n\nexport async function createTestbench(options: TestbenchOptions): Promise<Testbench> {\n const { record = [], onDiagnostic, ...runtimeOptions } = options;\n const document = parseFusedDocument(structuredClone(options.document));\n const step = timePs(options.step);\n if (step === 0) throw new RangeError('Testbench step must be positive');\n\n const instanceIdFor = (designator: string): string => {\n const instance = document.instances.find((item) => item.designator === designator);\n if (!instance)\n throw new TestbenchError('testing/unknown-device', `Unknown device ${designator}`);\n return instance.id;\n };\n const keyFor = (selector: EventSelector): string => {\n if (typeof selector.event !== 'string' || selector.event.length === 0) {\n throw new TypeError('Recorded event name must be nonempty');\n }\n if ((selector.instanceId === undefined) === (selector.designator === undefined)) {\n throw new TypeError('An event selector must specify exactly one instance ID or designator');\n }\n const instanceId = selector.instanceId ?? instanceIdFor(selector.designator!);\n if (!document.instances.some((instance) => instance.id === instanceId)) {\n throw new TestbenchError('testing/unknown-device', `Unknown device ${instanceId}`);\n }\n return JSON.stringify([instanceId, selector.event]);\n };\n const recordings = new Map<string, ModelEvent<Value>[]>();\n const selectors = record.map((value) => {\n const selector = { ...value };\n return { selector, key: keyFor(selector) };\n });\n for (const { key } of selectors) recordings.set(key, []);\n\n const onModelEvent = (event: RuntimeModelEvent): void => {\n const history = recordings.get(JSON.stringify([event.instanceId, event.event]));\n history?.push(structuredClone(event.payload));\n };\n const diagnostics: RuntimeDiagnostic[] = [];\n const runtime = await createHeadlessRuntime({\n ...runtimeOptions,\n document,\n onModelEvent,\n onDiagnostic(diagnostic) {\n diagnostics.push(structuredClone(diagnostic));\n onDiagnostic?.(diagnostic);\n },\n });\n try {\n for (const { selector } of selectors) {\n const id = selector.instanceId ?? instanceIdFor(selector.designator!);\n const client = runtime.getModel(id);\n if (!Object.hasOwn(client.events, selector.event)) {\n throw new TestbenchError(\n 'testing/unrecorded-event',\n `Unknown event ${selector.event} on ${id}`,\n );\n }\n }\n } catch (error) {\n try {\n await runtime.dispose();\n } catch (cleanupError) {\n throw new AggregateError([error, cleanupError], 'Testbench preparation and cleanup failed', {\n cause: cleanupError,\n });\n }\n throw error;\n }\n\n let busy = false;\n let disposal: Promise<void> | undefined;\n\n const assertPaused = (): void => {\n const state = runtime.getState();\n if (state.status !== 'paused') {\n throw new Error(`Testbench requires a paused runtime, got ${state.status}`);\n }\n };\n const exclusive = async (operation: () => Promise<void>): Promise<void> => {\n if (busy)\n throw new TestbenchError('testing/busy', 'Await the current testbench operation first');\n busy = true;\n try {\n await operation();\n } finally {\n busy = false;\n }\n };\n const targetAfter = (duration: TimePs): TimePs => {\n timePs(duration);\n if (duration % step !== 0) {\n throw new RangeError('Test duration must be a multiple of the fixed step');\n }\n return addTime(runtime.getState().simTime, duration);\n };\n const advanceTo = async (target: TimePs): Promise<void> => {\n assertPaused();\n timePs(target);\n const now = runtime.getState().simTime;\n if (target < now) throw new RangeError('Cannot advance virtual time backwards');\n if ((target - now) % step !== 0) {\n throw new RangeError('Target must be reachable by whole fixed steps');\n }\n while (runtime.getState().simTime < target) await runtime.step();\n };\n\n const devices: Record<string, DynamicDevice> = Object.create(null);\n for (const instance of document.instances) {\n if (instance.designator === undefined) continue;\n Object.defineProperty(devices, instance.designator, {\n enumerable: true,\n get() {\n const client = runtime.getModel(instance.id);\n return deviceFacade(client.methods, client.events);\n },\n });\n }\n\n return {\n devices: Object.freeze(devices),\n get simTime() {\n return runtime.getState().simTime;\n },\n get diagnostics() {\n return structuredClone(diagnostics);\n },\n device: (designator) => runtime.getModel(instanceIdFor(designator)),\n deviceById: (instanceId) => runtime.getModel(instanceId),\n events(selector) {\n const events = recordings.get(keyFor(selector));\n if (!events) {\n throw new TestbenchError(\n 'testing/unrecorded-event',\n 'Configure event recording before creation',\n );\n }\n\n return structuredClone(events);\n },\n advanceFor: (duration) => exclusive(() => advanceTo(targetAfter(duration))),\n advanceTo: (target) => exclusive(() => advanceTo(target)),\n advanceUntil: (predicate, { timeout }) =>\n exclusive(async () => {\n assertPaused();\n const target = targetAfter(timeout);\n for (;;) {\n const matched = await predicate();\n if (typeof matched !== 'boolean')\n throw new TypeError('Wait predicate must return a boolean');\n if (matched) return;\n if (runtime.getState().simTime === target) {\n throw new TestbenchError('testing/timeout', `Condition unmet at ${target} ps`);\n }\n await runtime.step();\n }\n }),\n reset: () =>\n exclusive(async () => {\n const { status } = runtime.getState();\n if (status !== 'paused' && status !== 'faulted') {\n throw new Error(`Cannot reset testbench in ${status} state`);\n }\n for (const history of recordings.values()) history.length = 0;\n diagnostics.length = 0;\n await runtime.reset();\n }),\n dispose() {\n if (disposal) return disposal;\n if (busy)\n return Promise.reject(\n new TestbenchError('testing/busy', 'Await the current operation before disposal'),\n );\n disposal = runtime.dispose();\n return disposal;\n },\n };\n}\n\nexport function bindTestbenchDevices<D extends object>(bench: Testbench, devices: D) {\n const base: Omit<Testbench, 'devices'> = bench;\n return Object.assign(base, { devices: Object.freeze(devices) });\n}\n"],"mappings":";;;;AAWA,SAAgB,aACd,SACA,QACoB;CACpB,MAAM,OAAgC,OAAO,OAAO,IAAI;CACxD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC/C,IAAI,CAAC,OAAO,OAAO,QAAQ,GAAG,KAAK,CAAC;EAAC;EAAW;EAAU;CAAM,CAAC,CAAC,SAAS,GAAG,GAC5E,KAAK,OAAO;CAEhB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,IAAI,CAAC,OAAO,OAAO,SAAS,GAAG,KAAK,CAAC;EAAC;EAAW;EAAU;CAAM,CAAC,CAAC,SAAS,GAAG,GAC7E,KAAK,OAAO;CAGhB,OAAO,OAAO,OAAO;EACnB,GAAG;EACH,SAAS,OAAO,OAAO,OAAO;EAC9B,QAAQ,OAAO,OAAO,MAAM;CAC9B,CAAC;AACH;AAEA,SAAgB,YAAY,QAA4B,MAAc;CACpE,MAAM,SAAS,OAAO,QAAQ;CAC9B,IAAI,WAAW,KAAA,GAAW,MAAM,IAAI,MAAM,gBAAgB,KAAK,gBAAgB;CAC/E,OAAO;AACT;AAEA,SAAgB,WACd,QACA,MACA,QACsB;CACtB,MAAM,QAAQ,OAAO,OAAO;CAC5B,IAAI,UAAU,KAAA,GAAW,MAAM,IAAI,MAAM,eAAe,KAAK,gBAAgB;CAC7E,QAAQ,UAAU,UAAU,gBAC1B,OACG,UAAU,SAAS,KAAK,UAAU;EAAE,GAAG;EAAO,OAAO,OAAO,MAAM,KAAK;CAAE,CAAC,GAC3E,KAAA,GACA,WACF;AACJ;;;ACbA,IAAa,iBAAb,cAAoC,MAAM;CAE7B;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AAM,IAAI,eAAe,mBAAmB,sBAAsB,OAAO,IAAI;IAE/E,MAAM,QAAQ,KAAK;GACrB;EACF,CAAC;EACH,aACE,UAAU,YAAY;GACpB,MAAM,EAAE,WAAW,QAAQ,SAAS;GACpC,IAAI,WAAW,YAAY,WAAW,WACpC,MAAM,IAAI,MAAM,6BAA6B,OAAO,OAAO;GAE7D,KAAK,MAAM,WAAW,WAAW,OAAO,GAAG,QAAQ,SAAS;GAC5D,YAAY,SAAS;GACrB,MAAM,QAAQ,MAAM;EACtB,CAAC;EACH,UAAU;GACR,IAAI,UAAU,OAAO;GACrB,IAAI,MACF,OAAO,QAAQ,OACb,IAAI,eAAe,gBAAgB,6CAA6C,CAClF;GACF,WAAW,QAAQ,QAAQ;GAC3B,OAAO;EACT;CACF;AACF;AAEA,SAAgB,qBAAuC,OAAkB,SAAY;CAEnF,OAAO,OAAO,OAAOA,OAAM,EAAE,SAAS,OAAO,OAAO,OAAO,EAAE,CAAC;AAChE"}
package/dist/vite.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { Plugin as Plugin_2 } from 'vite';
2
+
3
+ export declare function mitest(options?: MitestPluginOptions): Plugin_2;
4
+
5
+ export declare interface MitestPluginOptions {
6
+ readonly root?: string;
7
+ readonly config?: string;
8
+ }
9
+
10
+ export { }