@mica-js/simulator 0.3.0 → 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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/unified-ir/validation.ts","../src/unified-ir/pin-space.ts","../src/unified-ir/compiler/types.ts","../src/unified-ir/compiler/allocator.ts","../src/unified-ir/compiler/device-gen.ts","../src/unified-ir/compiler/mainloop-gen.ts","../src/unified-ir/compiler/solver-gen.ts","../src/unified-ir/compiler/topology.ts","../src/unified-ir/compiler/index.ts","../src/unified-ir/runtime/types.ts","../src/unified-ir/runtime/accessors.ts","../src/unified-ir/runtime/circuit.ts","../src/unified-ir/runtime/factory.ts","../src/host/circuit-host.ts","../src/host/runtime.ts","../src/host/guest.ts"],"sourcesContent":["import type { BytesRef, IRModule, IRResourcePermission, IRValidationOptions } from '@mica-js/ir';\n\n/**\n * Builds the validation grants a module needs to run on the reference engine or\n * the JIT: every instruction the model uses, authorized once, plus a grant for\n * each declared memory.\n *\n * `@mica-js/ir` deliberately keeps its core instruction list internal, so the\n * names are collected from the generated bodies instead of being restated here.\n *\n * @param module - Generated module whose bodies and memories are granted.\n * @param updateResources - Read-only byte regions that opt into the host-only\n * versioned update path (for example MCU firmware patching).\n */\nexport function createModuleValidation(\n module: IRModule,\n updateResources: readonly BytesRef[] = [],\n): IRValidationOptions {\n const names = new Set<string>();\n for (const fn of module.functions) {\n const body = fn.body;\n if (body === undefined) continue;\n // `body.blocks` already contains the entry block.\n for (const block of body.blocks) {\n for (const instruction of block.instructions) names.add(instruction.op);\n if (block.terminator !== undefined) names.add(block.terminator.kind);\n }\n }\n const instructions = Object.freeze([...names]);\n const resources: IRResourcePermission[] = module.memories.map((memory) =>\n Object.freeze({\n ref: memory.ref,\n access: memory.writable ? ('read-write' as const) : ('read' as const),\n }),\n );\n // Read-only byte regions such as firmware stay unreadable to guest stores but\n // can opt into the host-only versioned update path (`patchFirmware`).\n const memories = new Set(module.memories.map((memory) => memory.ref));\n for (const ref of new Set(updateResources)) {\n if (!memories.has(ref)) continue;\n resources.push(Object.freeze({ ref, access: 'update' as const }));\n }\n return Object.freeze({\n supportedInstructions: instructions,\n authorizedInstructions: instructions,\n resources: Object.freeze(resources),\n });\n}\n","/**\n * Shared memory-layout constants of the unified IR compiler and devices.\n *\n * Every device of a circuit shares one global pin address space, so the\n * compiler and every device kernel must agree on the capacity, the per-device\n * stride and the meaning of a `pin_mode` slot. The values are part of the\n * generated module's memory layout and must stay stable across releases.\n */\n\n/** Global pin addresses available to one circuit (8 devices x 32 pins). */\nexport const UNIFIED_PIN_CAPACITY = 256;\n\n/** Global pin addresses reserved per device (one 32-pin port). */\nexport const DEVICE_PIN_STRIDE = 32;\n\n/** Values stored in the global `pin_mode` array. */\nexport const PIN_MODE = Object.freeze({\n highZ: 0,\n pushPull: 1,\n openDrain: 2,\n analog: 3,\n} as const);\n\n/** One value of the global `pin_mode` array. */\nexport type PinMode = (typeof PIN_MODE)[keyof typeof PIN_MODE];\n","import type {\n ArrayRef,\n BytesRef,\n FunctionBuilder,\n FunctionRef,\n IRModule,\n IRValidationOptions,\n ScalarType,\n Value,\n} from '@mica-js/ir';\n\n/**\n * Types for the unified IR compiler (U01).\n *\n * The compiler turns several device descriptions plus a pin-to-pin netlist into\n * one `@mica-js/ir` module. Device logic, the electrical solve and the main\n * loop all share one global pin space, one state space and one engine entry, so\n * a tick costs one interpreter/JIT call for the whole circuit.\n *\n * The shared constants (`UNIFIED_PIN_CAPACITY`, `DEVICE_PIN_STRIDE`, `PIN_MODE`)\n * live in `../pin-space` and are reused here. The compiler ships no device\n * models: every description is supplied by the caller.\n */\n\n/** Electrical intent of one device pin. */\nexport type DevicePinDirection = 'input' | 'output' | 'bidirectional' | 'passive';\n\n/** Role a pin plays on its net; v1 supports one driver per net. */\nexport type CompiledPinRole = 'driver' | 'load';\n\n/** One pin declared by a device description. */\nexport interface DevicePinDescription {\n /** Defaults to `'passive'`: the pin only senses the net. */\n readonly direction?: DevicePinDirection;\n /** Overrides the role derived from `direction`. */\n readonly role?: CompiledPinRole;\n /** Purely informational kind, e.g. `'signal'`, `'power'`, `'gnd'`. */\n readonly kind?: string;\n}\n\n/**\n * Declared pins of one device. A `Map` keeps duplicate names impossible and an\n * object keeps authored descriptions terse; both preserve declaration order.\n */\nexport type DevicePinMap =\n ReadonlyMap<string, DevicePinDescription> | Readonly<Record<string, DevicePinDescription>>;\n\n/** One scalar internal state of a device, allocated in the global state space. */\nexport interface DeviceStateDescription {\n readonly type: ScalarType;\n readonly initial: boolean | number;\n}\n\n/** Pin operations a behavior may use; each call inlines into global memory. */\nexport interface DevicePinHandle {\n readonly name: string;\n readonly globalId: number;\n /** `pin.configure`: writes `pin_mode[globalId]`. */\n configure(mode: number): void;\n /** `pin.write_digital`: writes `pin_output[globalId]`. */\n writeDigital(level: Value<'bool'>): void;\n /** `pin.sample_digital`: reads the solved `pin_input[globalId]`. */\n sampleDigital(): Value<'bool'>;\n /** Reads the device's own `pin_output[globalId]`. */\n readDrivenDigital(): Value<'bool'>;\n}\n\n/** Internal state slot a behavior may read and write. */\nexport interface DeviceStateHandle<T extends ScalarType = ScalarType> {\n readonly name: string;\n readonly type: T;\n /** Index inside the generated `device_state_<type>` array. */\n readonly index: number;\n load(): Value<T>;\n store(value: Value<T>): void;\n}\n\n/** One pin as seen by a device kernel factory (no builder attached yet). */\nexport interface DeviceKernelPin {\n readonly name: string;\n readonly globalPinId: number;\n readonly role: CompiledPinRole;\n}\n\n/**\n * Everything a complex device kernel needs to declare its own IR before any\n * phase function body is opened: the module (for `array`/`bytes`/`provider`),\n * the shared pin memories and the allocated pin ids.\n */\nexport interface DeviceKernelContext {\n readonly deviceId: string;\n readonly config: Readonly<Record<string, unknown>> | undefined;\n readonly module: IRModule;\n readonly memory: CompiledCircuitMemory;\n readonly pins: readonly DeviceKernelPin[];\n}\n\n/**\n * Direct phase refs a complex kernel may return instead of behaviour hooks.\n * The compiler then uses these functions as the device's loop entries, with\n * no wrapper phase around them.\n */\nexport interface DeviceKernelRuntime {\n readonly initialize?: FunctionRef<readonly [], readonly []>;\n readonly tick?: FunctionRef<readonly [], readonly []>;\n readonly update?: FunctionRef<readonly [], readonly []>;\n}\n\n/**\n * Builds the phase hooks of a complex device after resource allocation but\n * before phase functions are generated. Declaring arrays, byte memories and\n * providers is only legal here (never inside a function body).\n *\n * Returning {@link DeviceKernelRuntime} lets the kernel own its phase\n * functions directly; returning {@link DeviceBehaviors} asks the compiler to\n * generate `<id>_initialize` / `<id>_tick` / `<id>_update` wrappers.\n */\nexport type DeviceKernelFactory = (\n context: DeviceKernelContext,\n) => DeviceBehaviors | DeviceKernelRuntime;\n\n/** Build surface handed to one device behavior. */\nexport interface DeviceBehaviorApi {\n readonly deviceId: string;\n readonly builder: FunctionBuilder<readonly []>;\n /**\n * Module the phase is generated into. Complex devices use it to declare\n * their own typed arrays (`module.array`, `module.bytes`) and providers;\n * simple devices never need to touch it.\n */\n readonly module: IRModule;\n /** Shared `pin_mode` / `pin_output` / `pin_input` memories. */\n readonly memory: CompiledCircuitMemory;\n /** Instance configuration from {@link DeviceConfig.config}. */\n readonly config: Readonly<Record<string, unknown>> | undefined;\n /** Every declared pin of the device, in declaration order. */\n readonly pins: readonly DevicePinHandle[];\n /** Pins whose role is `driver`. */\n readonly outputs: readonly DevicePinHandle[];\n pin(name: string): DevicePinHandle;\n state<T extends ScalarType = ScalarType>(name: string): DeviceStateHandle<T>;\n}\n\n/**\n * Structural surface every device accessor exposes.\n *\n * The compiler keeps this declaration independent from the runtime's\n * `DeviceAccessor` so a device kernel can ship its own typed accessor without\n * making the compiler depend on the runtime module.\n */\nexport interface DeviceAccessorSurface {\n readonly deviceId: string;\n readonly type: string;\n readonly pinNames: readonly string[];\n readonly stateNames: readonly string[];\n readPin(pinName: string): boolean;\n writePin(pinName: string, value: boolean): void;\n getState(name: string): unknown;\n setState(name: string, value: unknown): void;\n}\n\n/** Host services handed to a device accessor factory at circuit creation. */\nexport interface DeviceAccessorFactoryContext {\n readonly deviceId: string;\n /** Live engine storage (`IRStorage` in practice). */\n readonly storage: unknown;\n /** Throws once the owning circuit has been disposed. */\n readonly assertActive: () => void;\n /** Advances the owning circuit by one tick. */\n readonly step: () => void;\n /** Advances the owning circuit by `count` ticks. */\n readonly runBatch: (count: number) => void;\n}\n\n/**\n * Builds the typed accessor of a device after its module is compiled.\n *\n * A description that supplies `accessor` replaces the generic accessor the\n * runtime would otherwise synthesize from `type`. The factory runs once per\n * circuit and closes over the layout its IR factory allocated.\n */\nexport type DeviceAccessorFactory = (\n context: DeviceAccessorFactoryContext,\n) => DeviceAccessorSurface;\n\n/**\n * Per-device behavior hooks. The compiler emits one IR function per hook:\n * `initialize` -> `<id>_initialize`, `tick` -> `<id>_tick`,\n * `update` -> `<id>_update`. Missing hooks simply produce no function.\n */\nexport interface DeviceBehaviors {\n readonly initialize?: (api: DeviceBehaviorApi) => void;\n readonly tick?: (api: DeviceBehaviorApi) => void;\n readonly update?: (api: DeviceBehaviorApi) => void;\n}\n\n/** IR-level device description consumed by the compiler. */\nexport interface DeviceDescription {\n readonly name?: string;\n readonly pins: DevicePinMap;\n readonly states?: Readonly<Record<string, DeviceStateDescription>>;\n readonly behaviors?: DeviceBehaviors;\n /**\n * Complex-kernel hook. Runs once per module before phase generation so the\n * kernel may declare typed arrays, byte memories and providers, then return\n * the behaviour hooks the compiler should call inside each phase.\n */\n readonly kernel?: DeviceKernelFactory;\n /**\n * Optional typed accessor factory. Kernels with a richer surface than the\n * generic state/pin accessor (a register file, a memory map) use it.\n */\n readonly accessor?: DeviceAccessorFactory;\n /**\n * Read-only byte regions the kernel wants host updates for. The compiler\n * grants `update` access on top of the normal `read` grant so kernels can\n * expose firmware patching without allowing guest stores.\n */\n readonly updateResources?: readonly BytesRef[];\n}\n\n/** One device instance of the circuit. */\nexport interface DeviceConfig {\n /** Circuit-unique identity; prefix of every generated function name. */\n readonly id: string;\n /** Device type, e.g. `'push-pull-driver'`; free-form label of the device model. */\n readonly type: string;\n readonly description: DeviceDescription;\n /** Instance configuration; reserved for device kernels that take parameters. */\n readonly config?: Readonly<Record<string, unknown>>;\n}\n\n/** One pin-to-pin (or pin-to-rail) connection. */\nexport interface Connection {\n /** `'mcu1.PA0'` or a rail name such as `'GND'`. */\n readonly from: string;\n readonly to: string;\n}\n\n/** Options for the compiler. */\nexport interface CircuitCompilationOptions {\n /** Named fixed-level rails; merged over `GND`/`VCC`/`VDD`. */\n readonly rails?: Readonly<Record<string, boolean>>;\n /**\n * Accept nets with more than one driver pin and solve them as a wired-OR.\n * Defaults to `false`, which reports a `driver-conflict` instead.\n */\n readonly allowMultiDriver?: boolean;\n /** Runs `validateIR` over the generated module. Defaults to `true`. */\n readonly validate?: boolean;\n /** Overrides for the generated entry-point names. */\n readonly entryPointNames?: {\n readonly tick?: string;\n readonly initialize?: string;\n readonly batch?: string;\n };\n}\n\n/** Compiler input: devices plus the connections between their pins. */\nexport interface CircuitCompilationInput {\n readonly devices: readonly DeviceConfig[];\n readonly connections: readonly Connection[];\n}\n\n/** One resolved pin in the global pin space. */\nexport interface ResolvedDevicePin {\n readonly name: string;\n readonly deviceId: string;\n readonly globalPinId: number;\n readonly direction: DevicePinDirection;\n readonly role: CompiledPinRole;\n /** Whether the device reads the solved value of this pin. */\n readonly senses: boolean;\n}\n\n/** Pins of one device mapped into the global pin space. */\nexport interface DevicePinAllocation {\n readonly deviceId: string;\n /** First global pin id of the device. */\n readonly offset: number;\n readonly pins: ReadonlyMap<string, number>;\n readonly resolved: ReadonlyMap<string, ResolvedDevicePin>;\n}\n\n/** Result of the global pin allocation. */\nexport interface GlobalPinMap {\n /** `'mcu1.PA0'` -> global pin id. */\n readonly pins: ReadonlyMap<string, number>;\n readonly devices: ReadonlyMap<string, DevicePinAllocation>;\n readonly totalPins: number;\n readonly capacity: number;\n}\n\n/** One device state slot inside the global state space. */\nexport interface DeviceStateSlot {\n readonly name: string;\n readonly deviceId: string;\n readonly type: ScalarType;\n /** Generated array that holds the slot. */\n readonly array: ArrayRef;\n /** Index inside {@link array}. */\n readonly index: number;\n /** Ordinal in the whole state space, across scalar types. */\n readonly slot: number;\n}\n\n/** Result of the global state allocation. */\nexport interface GlobalStateMap {\n readonly devices: ReadonlyMap<string, ReadonlyMap<string, DeviceStateSlot>>;\n /** One generated array per scalar type actually used. */\n readonly arrays: ReadonlyMap<ScalarType, ArrayRef>;\n /** Slot count per scalar type. */\n readonly totals: ReadonlyMap<ScalarType, number>;\n readonly totalStates: number;\n}\n\n/** Pin memories every device and every net solver shares. */\nexport interface CompiledCircuitMemory {\n readonly mode: ArrayRef<'u8'>;\n readonly output: ArrayRef<'bool'>;\n readonly input: ArrayRef<'bool'>;\n}\n\n/** One pin resolved onto a net. */\nexport interface CompiledPinConnection {\n /** `'mcu1.PA0'`. */\n readonly endpoint: string;\n readonly deviceId: string;\n readonly pinName: string;\n readonly globalPinId: number;\n readonly role: CompiledPinRole;\n readonly senses: boolean;\n}\n\n/** One fixed-level rail on a net, e.g. `GND` (low) or `VCC` (high). */\nexport interface CompiledRail {\n readonly name: string;\n readonly level: boolean;\n}\n\n/** Where a net's level comes from. */\nexport type CompiledNetSource = 'driver' | 'rail' | 'floating';\n\n/** One electrical net: a connected component of pins and rails. */\nexport interface CompiledNet {\n readonly netId: number;\n readonly pins: readonly CompiledPinConnection[];\n readonly rails: readonly CompiledRail[];\n readonly drivers: readonly CompiledPinConnection[];\n /** Pins whose role is `load`. */\n readonly loads: readonly CompiledPinConnection[];\n /** Every pin that reads the solved level, including bidirectional drivers. */\n readonly sinks: readonly CompiledPinConnection[];\n readonly source: CompiledNetSource;\n /** Constant level of a driver-less net; unused when `source === 'driver'`. */\n readonly level: boolean;\n}\n\n/** Diagnostic codes produced by the compiler's electrical analysis. */\nexport type CompilationDiagnosticCode =\n 'driver-conflict' | 'power-short' | 'rail-conflict' | 'floating-net';\n\nexport type CompilationDiagnosticSeverity = 'error' | 'warning';\n\n/** One electrical-analysis finding; errors abort `compileCircuit`. */\nexport interface CompilationDiagnostic {\n readonly code: CompilationDiagnosticCode;\n readonly severity: CompilationDiagnosticSeverity;\n readonly message: string;\n readonly netId: number | undefined;\n readonly endpoints: readonly string[];\n}\n\n/** Result of the network topology analysis. */\nexport interface CompiledNetlist {\n readonly nets: readonly CompiledNet[];\n readonly diagnostics: readonly CompilationDiagnostic[];\n}\n\n/** Metadata of one compiled device. */\nexport interface DeviceMetadata {\n readonly deviceId: string;\n readonly type: string;\n /** First global pin id of the device. */\n readonly pinOffset: number;\n /** First slot ordinal of the device in the global state space. */\n readonly stateOffset: number;\n readonly pins: ReadonlyMap<string, number>;\n readonly states: ReadonlyMap<string, DeviceStateSlot>;\n /** Every IR function generated for this device. */\n readonly functions: readonly string[];\n readonly initialize: string | undefined;\n readonly tick: string | undefined;\n readonly update: string | undefined;\n /** Typed accessor factory supplied by the device description, if any. */\n readonly accessor: DeviceAccessorFactory | undefined;\n /** Kernel factory that generated the device's extra IR resources. */\n readonly kernel: DeviceKernelFactory | undefined;\n}\n\n/** Generated entry points, both by name and as executable refs. */\nexport interface CompiledEntryPoints {\n readonly tick: string;\n readonly initialize: string;\n readonly batch: string;\n readonly refs: {\n readonly tick: FunctionRef<readonly [], readonly []>;\n readonly initialize: FunctionRef<readonly [], readonly []>;\n readonly batch: FunctionRef<readonly ['u32'], readonly []>;\n };\n}\n\n/** The compiled circuit: one module for every device, net and the main loop. */\nexport interface CompiledCircuit {\n readonly module: IRModule;\n readonly entryPoints: CompiledEntryPoints;\n /** `'mcu1.PA0'` -> global pin id. */\n readonly pinMap: ReadonlyMap<string, number>;\n readonly deviceMap: ReadonlyMap<string, DeviceMetadata>;\n readonly netlist: CompiledNetlist;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n readonly memory: CompiledCircuitMemory;\n /** Validation grants covering every instruction and memory of the module. */\n readonly validation: IRValidationOptions;\n /** Device ids in dependency order (drivers before the devices they feed). */\n readonly executionOrder: readonly string[];\n /** Every generated function name, in definition order. */\n readonly functions: readonly string[];\n}\n\n/** Error codes raised by {@link UnifiedIRCompilerError}. */\nexport type UnifiedIRCompilerErrorCode =\n | 'invalid-input'\n | 'duplicate-device'\n | 'unknown-device'\n | 'pin-not-found'\n | 'state-not-found'\n | 'invalid-connection'\n | 'capacity-exceeded'\n | 'unsupported-device'\n | 'driver-conflict'\n | 'power-short'\n | 'rail-conflict'\n | 'invalid-ir';\n\nexport interface UnifiedIRCompilerErrorOptions {\n readonly deviceId?: string;\n readonly pinName?: string;\n readonly netId?: number;\n readonly diagnostics?: readonly CompilationDiagnostic[];\n readonly cause?: unknown;\n}\n\n/** Error raised while compiling a circuit. */\nexport class UnifiedIRCompilerError extends Error {\n override readonly name = 'UnifiedIRCompilerError';\n readonly code: UnifiedIRCompilerErrorCode;\n readonly deviceId: string | undefined;\n readonly pinName: string | undefined;\n readonly netId: number | undefined;\n readonly diagnostics: readonly CompilationDiagnostic[];\n\n constructor(\n code: UnifiedIRCompilerErrorCode,\n message: string,\n options: UnifiedIRCompilerErrorOptions = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.code = code;\n this.deviceId = options.deviceId;\n this.pinName = options.pinName;\n this.netId = options.netId;\n this.diagnostics = options.diagnostics ?? [];\n }\n}\n","import { INTEGER_TYPES, SCALAR_TYPES } from '@mica-js/ir';\nimport type { ArrayRef, IRModule, ScalarType } from '@mica-js/ir';\nimport { DEVICE_PIN_STRIDE, PIN_MODE, UNIFIED_PIN_CAPACITY } from '../pin-space';\nimport {\n UnifiedIRCompilerError,\n type CompiledCircuitMemory,\n type DeviceConfig,\n type DevicePinAllocation,\n type DevicePinDescription,\n type DevicePinDirection,\n type DeviceStateDescription,\n type DeviceStateSlot,\n type GlobalPinMap,\n type GlobalStateMap,\n type ResolvedDevicePin,\n} from './types';\n\n/** Generated device ids prefix IR function names, so they must be identifiers. */\nconst DEVICE_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Everything the compiler allocates before a single instruction is generated. */\nexport interface ResourceAllocation {\n readonly memory: CompiledCircuitMemory;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n}\n\n/**\n * Allocates the circuit-wide pin and state address spaces.\n *\n * ```\n * ids: 0 = drive1.PA0 1 = drive1.PA1 2 = sink1.anode 3 = sink1.cathode\n * |<-- drive1 -->| |<----------- sink1 ----------->|\n *\n * pin_mode[256] u8 pin_output[256] bool pin_input[256] bool\n * device_state_bool[n] / device_state_u32[m] / ... (one array per used type)\n * ```\n *\n * Pins are packed in declaration order across devices — the addresses the\n * device IR and every net solver embed as constants. States are packed per\n * scalar type into one shared array, so a device's slot stays typed while all\n * devices share one storage region.\n */\nexport class GlobalResourceAllocator {\n private readonly module: IRModule;\n\n constructor(module: IRModule) {\n this.module = module;\n }\n\n /** Allocates the shared pin memories, the pin space and the state space. */\n allocate(devices: readonly DeviceConfig[]): ResourceAllocation {\n const memory = createPinMemory(this.module);\n return Object.freeze({\n memory,\n pins: this.allocatePins(devices),\n states: this.allocateStates(devices),\n });\n }\n\n /**\n * Packs every device pin into one contiguous global address space.\n *\n * @throws {UnifiedIRCompilerError} on invalid or duplicate device ids, more\n * than {@link DEVICE_PIN_STRIDE} pins for one device, or more than\n * {@link UNIFIED_PIN_CAPACITY} pins for the circuit.\n */\n allocatePins(devices: readonly DeviceConfig[]): GlobalPinMap {\n assertDeviceList(devices);\n\n let totalPins = 0;\n const pins = new Map<string, number>();\n const allocations = new Map<string, DevicePinAllocation>();\n\n for (const device of devices) {\n const entries = pinEntries(device);\n if (entries.length > DEVICE_PIN_STRIDE) {\n throw new UnifiedIRCompilerError(\n 'capacity-exceeded',\n `Device \"${device.id}\" declares ${entries.length} pins; one device may own at most ${DEVICE_PIN_STRIDE}`,\n { deviceId: device.id },\n );\n }\n if (totalPins + entries.length > UNIFIED_PIN_CAPACITY) {\n throw new UnifiedIRCompilerError(\n 'capacity-exceeded',\n `Device \"${device.id}\" does not fit: the circuit already uses ${totalPins} of ${UNIFIED_PIN_CAPACITY} global pins`,\n { deviceId: device.id },\n );\n }\n\n const offset = totalPins;\n const devicePins = new Map<string, number>();\n const resolved = new Map<string, ResolvedDevicePin>();\n\n for (const [name, descriptor] of entries) {\n const globalPinId = totalPins;\n totalPins += 1;\n const direction = resolvePinDirection(descriptor, device.id, name);\n const { role, senses } = resolvePinRole(direction, descriptor?.role, device.id, name);\n devicePins.set(name, globalPinId);\n resolved.set(\n name,\n Object.freeze({\n name,\n deviceId: device.id,\n globalPinId,\n direction,\n role,\n senses,\n }),\n );\n pins.set(`${device.id}.${name}`, globalPinId);\n }\n\n allocations.set(\n device.id,\n Object.freeze({ deviceId: device.id, offset, pins: devicePins, resolved }),\n );\n }\n\n return Object.freeze({\n pins,\n devices: allocations,\n totalPins,\n capacity: UNIFIED_PIN_CAPACITY,\n });\n }\n\n /**\n * Allocates one typed slot per declared device state and creates the backing\n * `device_state_<type>` arrays.\n *\n * @throws {UnifiedIRCompilerError} when a state declaration is malformed.\n */\n allocateStates(devices: readonly DeviceConfig[]): GlobalStateMap {\n assertDeviceList(devices);\n\n interface StatePlan {\n readonly deviceId: string;\n readonly name: string;\n readonly type: ScalarType;\n readonly initial: boolean | number;\n readonly slot: number;\n }\n\n const plans: StatePlan[] = [];\n const slotsByDevice = new Map<string, Map<string, DeviceStateSlot>>();\n const plansByType = new Map<ScalarType, StatePlan[]>();\n\n for (const device of devices) {\n // Every device owns a block in the state table, even when it is empty.\n const slots = new Map<string, DeviceStateSlot>();\n slotsByDevice.set(device.id, slots);\n for (const [name, declaration] of stateEntries(device)) {\n const plan: StatePlan = {\n deviceId: device.id,\n name,\n type: declaration.type,\n initial: declaration.initial,\n slot: plans.length,\n };\n plans.push(plan);\n const typePlans = plansByType.get(plan.type);\n if (typePlans === undefined) {\n plansByType.set(plan.type, [plan]);\n } else {\n typePlans.push(plan);\n }\n }\n }\n\n const arrays = new Map<ScalarType, ArrayRef>();\n const totals = new Map<ScalarType, number>();\n for (const [type, typePlans] of plansByType) {\n const array = this.module.array(\n `device_state_${type}`,\n type,\n typePlans.map((plan) => plan.initial),\n );\n arrays.set(type, array);\n totals.set(type, typePlans.length);\n typePlans.forEach((plan, index) => {\n const slot: DeviceStateSlot = Object.freeze({\n name: plan.name,\n deviceId: plan.deviceId,\n type,\n array,\n index,\n slot: plan.slot,\n });\n slotsByDevice.get(plan.deviceId)?.set(plan.name, slot);\n });\n }\n\n const devicesMap = new Map<string, ReadonlyMap<string, DeviceStateSlot>>();\n for (const [deviceId, slots] of slotsByDevice) devicesMap.set(deviceId, slots);\n\n return Object.freeze({\n devices: devicesMap,\n arrays,\n totals,\n totalStates: plans.length,\n });\n }\n}\n\n/** Declares the three pin memories shared by every device and net solver. */\nexport function createPinMemory(module: IRModule): CompiledCircuitMemory {\n return Object.freeze({\n mode: module.array(\n 'pin_mode',\n 'u8',\n Array.from({ length: UNIFIED_PIN_CAPACITY }, () => PIN_MODE.highZ),\n ),\n output: module.array(\n 'pin_output',\n 'bool',\n Array.from({ length: UNIFIED_PIN_CAPACITY }, () => false),\n ),\n input: module.array(\n 'pin_input',\n 'bool',\n Array.from({ length: UNIFIED_PIN_CAPACITY }, () => false),\n ),\n });\n}\n\n/** First state slot ordinal of every device; used for `DeviceMetadata.stateOffset`. */\nexport function stateOffsetOf(states: GlobalStateMap, deviceId: string): number {\n let offset = 0;\n for (const [id, slots] of states.devices) {\n if (id === deviceId) return offset;\n offset += slots.size;\n }\n return offset;\n}\n\nfunction assertDeviceList(devices: readonly DeviceConfig[]): void {\n if (!Array.isArray(devices) || devices.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.devices must be a non-empty array',\n );\n }\n const ids = new Set<string>();\n for (const device of devices as readonly unknown[]) {\n if (device === null || typeof device !== 'object' || Array.isArray(device)) {\n throw new UnifiedIRCompilerError('invalid-input', 'Every device must be an object');\n }\n const { id, type, description } = device as Partial<DeviceConfig>;\n if (typeof id !== 'string' || !DEVICE_ID_PATTERN.test(id)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device id ${JSON.stringify(id)} must be an identifier ([A-Za-z_][A-Za-z0-9_]*) because it prefixes generated IR function names`,\n );\n }\n if (ids.has(id)) {\n throw new UnifiedIRCompilerError(\n 'duplicate-device',\n `Duplicate device id \"${id}\"; every device id must be unique`,\n { deviceId: id },\n );\n }\n ids.add(id);\n if (typeof type !== 'string' || type.length === 0) {\n throw new UnifiedIRCompilerError('invalid-input', `Device \"${id}\" needs a non-empty type`, {\n deviceId: id,\n });\n }\n if (description === null || typeof description !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${id}\" needs a description object with a pins map`,\n { deviceId: id },\n );\n }\n }\n}\n\nfunction pinEntries(\n device: DeviceConfig,\n): readonly (readonly [string, DevicePinDescription | undefined])[] {\n const raw: unknown = device.description.pins;\n let entries: (readonly [string, DevicePinDescription | undefined])[];\n if (raw instanceof Map) {\n entries = [...(raw as ReadonlyMap<string, DevicePinDescription>).entries()];\n } else if (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) {\n entries = Object.entries(raw as Record<string, DevicePinDescription>) as (readonly [\n string,\n DevicePinDescription | undefined,\n ])[];\n } else {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" needs description.pins as a Map or a plain object`,\n { deviceId: device.id },\n );\n }\n for (const [name, descriptor] of entries) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" declares a pin with an empty name`,\n { deviceId: device.id },\n );\n }\n if (name.includes('.')) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" pin \"${name}\" may not contain \".\": connection endpoints use \"device.pin\"`,\n { deviceId: device.id, pinName: name },\n );\n }\n if (descriptor !== undefined && (descriptor === null || typeof descriptor !== 'object')) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" pin \"${name}\" description must be an object`,\n { deviceId: device.id, pinName: name },\n );\n }\n }\n return entries;\n}\n\nconst PIN_DIRECTIONS: ReadonlySet<string> = new Set([\n 'input',\n 'output',\n 'bidirectional',\n 'passive',\n]);\n\nfunction resolvePinDirection(\n descriptor: DevicePinDescription | undefined,\n deviceId: string,\n pinName: string,\n): DevicePinDirection {\n const direction = descriptor?.direction ?? 'passive';\n if (!PIN_DIRECTIONS.has(direction)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" pin \"${pinName}\" has direction ${JSON.stringify(direction)}; expected input, output, bidirectional or passive`,\n { deviceId, pinName },\n );\n }\n return direction;\n}\n\n/**\n * Derives the electrical role and the read behavior of a pin.\n *\n * `output` drives only, `input`/`passive` sense only, `bidirectional` drives and\n * senses. An explicit `role` overrides the derived drive role while\n * `bidirectional` keeps its sense side.\n */\nfunction resolvePinRole(\n direction: DevicePinDirection,\n explicit: DevicePinDescription['role'],\n deviceId: string,\n pinName: string,\n): { readonly role: 'driver' | 'load'; readonly senses: boolean } {\n if (explicit !== undefined && explicit !== 'driver' && explicit !== 'load') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" pin \"${pinName}\" has role ${JSON.stringify(explicit)}; expected driver or load`,\n { deviceId, pinName },\n );\n }\n if (explicit === 'driver') return { role: 'driver', senses: direction === 'bidirectional' };\n if (explicit === 'load') return { role: 'load', senses: true };\n if (direction === 'output') return { role: 'driver', senses: false };\n if (direction === 'bidirectional') return { role: 'driver', senses: true };\n return { role: 'load', senses: true };\n}\n\nfunction stateEntries(\n device: DeviceConfig,\n): readonly (readonly [string, DeviceStateDescription])[] {\n const raw: unknown = device.description.states;\n if (raw === undefined) return [];\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" needs description.states as a plain object`,\n { deviceId: device.id },\n );\n }\n return Object.entries(raw as Record<string, DeviceStateDescription>).map(\n ([name, declaration]) => {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" declares a state with an empty name`,\n { deviceId: device.id },\n );\n }\n if (declaration === null || typeof declaration !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" state \"${name}\" must be an object with type and initial`,\n { deviceId: device.id },\n );\n }\n const type: unknown = declaration.type;\n if (typeof type !== 'string' || !(SCALAR_TYPES as readonly string[]).includes(type)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" state \"${name}\" has type ${JSON.stringify(type)}; expected one of ${SCALAR_TYPES.join(', ')}`,\n { deviceId: device.id },\n );\n }\n assertStateInitial(device.id, name, type as ScalarType, declaration.initial);\n return [name, declaration] as const;\n },\n );\n}\n\nfunction assertStateInitial(\n deviceId: string,\n name: string,\n type: ScalarType,\n initial: unknown,\n): void {\n if (type === 'bool') {\n if (typeof initial !== 'boolean') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (bool) needs a boolean initial value`,\n { deviceId },\n );\n }\n return;\n }\n if (typeof initial !== 'number' || !Number.isFinite(initial)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (${type}) needs a finite numeric initial value`,\n { deviceId },\n );\n }\n if ((INTEGER_TYPES as readonly string[]).includes(type) && !Number.isInteger(initial)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (${type}) needs an integer initial value`,\n { deviceId },\n );\n }\n}\n","import type {\n ArrayRef,\n FunctionBuilder,\n FunctionRef,\n IRModule,\n ScalarType,\n Value,\n} from '@mica-js/ir';\nimport { PIN_MODE } from '../pin-space';\nimport { stateOffsetOf } from './allocator';\nimport {\n UnifiedIRCompilerError,\n type CompiledCircuitMemory,\n type DeviceBehaviorApi,\n type DeviceBehaviors,\n type DeviceConfig,\n type DeviceKernelRuntime,\n type DeviceMetadata,\n type DevicePinAllocation,\n type DevicePinHandle,\n type DeviceStateHandle,\n type DeviceStateSlot,\n type GlobalPinMap,\n type GlobalStateMap,\n} from './types';\n\n/** Refs the main loop calls for one device; `undefined` means \"no such phase\". */\nexport interface DeviceLoopEntry {\n readonly deviceId: string;\n readonly initialize: FunctionRef<readonly [], readonly []> | undefined;\n readonly tick: FunctionRef<readonly [], readonly []> | undefined;\n readonly update: FunctionRef<readonly [], readonly []> | undefined;\n}\n\n/** One generated device: public metadata plus the refs the main loop needs. */\nexport interface GeneratedDevice {\n readonly metadata: DeviceMetadata;\n readonly entry: DeviceLoopEntry;\n}\n\ninterface GeneratedPhase {\n readonly name: string;\n readonly ref: FunctionRef<readonly [], readonly []>;\n}\n\n/** Everything the device generator reads from the prior compilation stages. */\nexport interface DeviceGenerationContext {\n readonly module: IRModule;\n readonly memory: CompiledCircuitMemory;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n}\n\n/**\n * Generates one IR function per device phase into the unified module.\n *\n * Domain operations are inlined while the behavior runs: `pin.configure`,\n * `pin.writeDigital` and `pin.sampleDigital` become `array.store`/`array.load`\n * on the shared `pin_mode` / `pin_output` / `pin_input` memories, so no device\n * keeps its own module, protocol or host hop. A device without an explicit\n * `initialize` still gets one that configures its output pins as push-pull.\n *\n * The compiler ships no device models: every description must declare its own\n * pins, states and behaviors (or a `kernel`) before it reaches this generator.\n */\nexport class DeviceIRGenerator {\n private readonly context: DeviceGenerationContext;\n\n constructor(context: DeviceGenerationContext) {\n this.context = context;\n }\n\n /**\n * @throws {UnifiedIRCompilerError} when the device has no kernel/behaviors or\n * a behavior reaches for a pin or state the description does not declare.\n */\n generate(device: DeviceConfig): GeneratedDevice {\n const allocation = this.context.pins.devices.get(device.id);\n if (allocation === undefined) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" has no pin allocation; allocate resources before generating IR`,\n { deviceId: device.id },\n );\n }\n const kernelResult = device.description.kernel?.({\n deviceId: device.id,\n config: device.config,\n module: this.context.module,\n memory: this.context.memory,\n pins: [...allocation.resolved.values()].map((pin) =>\n Object.freeze({\n name: pin.name,\n globalPinId: pin.globalPinId,\n role: pin.role,\n }),\n ),\n });\n const kernelRuntime =\n kernelResult !== undefined && isKernelRuntime(kernelResult) ? kernelResult : undefined;\n const behaviors =\n kernelRuntime === undefined\n ? ((kernelResult as DeviceBehaviors | undefined) ?? device.description.behaviors)\n : undefined;\n\n let initialize: GeneratedPhase | undefined;\n let tick: GeneratedPhase | undefined;\n let update: GeneratedPhase | undefined;\n if (kernelRuntime !== undefined) {\n initialize = phaseFromRef(this.context.module, device.id, kernelRuntime.initialize);\n tick = phaseFromRef(this.context.module, device.id, kernelRuntime.tick);\n update = phaseFromRef(this.context.module, device.id, kernelRuntime.update);\n } else {\n if (behaviors === undefined || !hasAnyBehavior(behaviors)) {\n throw new UnifiedIRCompilerError(\n 'unsupported-device',\n `Device \"${device.id}\" of type \"${device.type}\" declares no behaviors. Provide description.behaviors or description.kernel`,\n { deviceId: device.id },\n );\n }\n initialize =\n this.generatePhase(device, allocation, 'initialize', behaviors.initialize) ??\n this.generateDefaultInitialize(device, allocation);\n tick = this.generatePhase(device, allocation, 'tick', behaviors.tick);\n update = this.generatePhase(device, allocation, 'update', behaviors.update);\n }\n\n const functions: string[] = [];\n for (const phase of [initialize, tick, update]) {\n if (phase !== undefined) functions.push(phase.name);\n }\n\n const metadata: DeviceMetadata = Object.freeze({\n deviceId: device.id,\n type: device.type,\n pinOffset: allocation.offset,\n stateOffset: stateOffsetOf(this.context.states, device.id),\n pins: allocation.pins,\n states: this.context.states.devices.get(device.id) ?? new Map(),\n functions: Object.freeze(functions),\n initialize: initialize?.name,\n tick: tick?.name,\n update: update?.name,\n accessor: device.description.accessor,\n kernel: device.description.kernel,\n });\n\n return Object.freeze({\n metadata,\n entry: Object.freeze({\n deviceId: device.id,\n initialize: initialize?.ref,\n tick: tick?.ref,\n update: update?.ref,\n }),\n });\n }\n\n private generatePhase(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n phase: 'initialize' | 'tick' | 'update',\n behavior: ((api: DeviceBehaviorApi) => void) | undefined,\n ): GeneratedPhase | undefined {\n if (behavior === undefined) return undefined;\n const name = `${device.id}_${phase}`;\n const ref = this.context.module.func(name, { params: [], results: [] });\n ref.body((b) => {\n behavior(this.createApi(device, allocation, b));\n b.return([]);\n });\n return { name, ref };\n }\n\n private generateDefaultInitialize(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n ): GeneratedPhase | undefined {\n const outputs = [...allocation.resolved.values()].filter((pin) => pin.role === 'driver');\n if (outputs.length === 0) return undefined;\n const name = `${device.id}_initialize`;\n const ref = this.context.module.func(name, { params: [], results: [] });\n ref.body((b) => {\n for (const pin of outputs) {\n b.array.store(\n this.context.memory.mode,\n b.const('u32', pin.globalPinId),\n b.const('u8', PIN_MODE.pushPull),\n );\n }\n b.return([]);\n });\n return { name, ref };\n }\n\n private createApi(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n builder: FunctionBuilder<readonly []>,\n ): DeviceBehaviorApi {\n const handles = new Map<string, DevicePinHandle>();\n const pins: DevicePinHandle[] = [];\n const outputs: DevicePinHandle[] = [];\n for (const pin of allocation.resolved.values()) {\n const handle = this.createPinHandle(pin.globalPinId, pin.name, builder);\n handles.set(pin.name, handle);\n pins.push(handle);\n if (pin.role === 'driver') outputs.push(handle);\n }\n const slots = this.context.states.devices.get(device.id);\n return Object.freeze({\n deviceId: device.id,\n builder,\n module: this.context.module,\n memory: this.context.memory,\n config: device.config,\n pins: Object.freeze(pins),\n outputs: Object.freeze(outputs),\n pin(name: string): DevicePinHandle {\n const handle = handles.get(name);\n if (handle === undefined) {\n const available = [...handles.keys()].map((entry) => `${device.id}.${entry}`);\n throw new UnifiedIRCompilerError(\n 'pin-not-found',\n `Pin '${device.id}.${name}' not found. Available: [${available.join(', ')}]`,\n { deviceId: device.id, pinName: name },\n );\n }\n return handle;\n },\n state<T extends ScalarType = ScalarType>(name: string): DeviceStateHandle<T> {\n const slot = slots?.get(name);\n if (slot === undefined) {\n throw new UnifiedIRCompilerError(\n 'state-not-found',\n `Device \"${device.id}\" has no state \"${name}\". Available: [${[...(slots?.keys() ?? [])].join(', ')}]`,\n { deviceId: device.id },\n );\n }\n return createStateHandle<T>(device.id, slot, builder);\n },\n });\n }\n\n private createPinHandle(\n globalId: number,\n name: string,\n builder: FunctionBuilder<readonly []>,\n ): DevicePinHandle {\n const memory = this.context.memory;\n // Resolved lazily so a behavior that only samples a pin does not also emit\n // an unused constant for every other pin of the device.\n const index = (): Value<'u32'> => builder.const('u32', globalId);\n return Object.freeze({\n name,\n globalId,\n configure(mode: number): void {\n if (!Number.isInteger(mode) || mode < 0 || mode > 0xff) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Pin \"${name}\" configure(${String(mode)}) needs a u8 pin mode`,\n );\n }\n builder.array.store(memory.mode, index(), builder.const('u8', mode));\n },\n writeDigital(level: Value<'bool'>): void {\n builder.array.store(memory.output, index(), level);\n },\n sampleDigital(): Value<'bool'> {\n return builder.array.load(memory.input, index());\n },\n readDrivenDigital(): Value<'bool'> {\n return builder.array.load(memory.output, index());\n },\n });\n }\n}\n\nfunction createStateHandle<T extends ScalarType>(\n deviceId: string,\n slot: DeviceStateSlot,\n builder: FunctionBuilder<readonly []>,\n): DeviceStateHandle<T> {\n // The array was declared with `slot.type`, so a matching `T` is exactly the\n // array's element type; the cast only recovers that from the untied slot.\n const array = slot.array as unknown as ArrayRef<T>;\n const index = builder.const('u32', slot.index);\n return Object.freeze({\n name: slot.name,\n type: slot.type as T,\n index: slot.index,\n load(): Value<T> {\n return builder.array.load(array, index);\n },\n store(value: Value<T>): void {\n builder.array.store(array, index, value);\n },\n });\n}\n\nfunction hasAnyBehavior(behaviors: DeviceBehaviors): boolean {\n return (\n behaviors.initialize !== undefined ||\n behaviors.tick !== undefined ||\n behaviors.update !== undefined\n );\n}\n\n/** Bulk kernel results carry phase refs; behaviour hooks are plain functions. */\nfunction isKernelRuntime(\n value: DeviceBehaviors | DeviceKernelRuntime,\n): value is DeviceKernelRuntime {\n if (value === null || typeof value !== 'object') return false;\n // A kernel may own any subset of the phases (a passive sink only needs\n // `update`), so the first phase ref that is an object — not a behaviour\n // callback — decides.\n const phases: readonly (keyof DeviceKernelRuntime)[] = ['initialize', 'tick', 'update'];\n return phases.some((phase) => typeof value[phase] === 'object');\n}\n\n/** Resolves one kernel phase ref to its generated function name. */\nfunction phaseFromRef(\n module: IRModule,\n deviceId: string,\n ref: FunctionRef<readonly [], readonly []> | undefined,\n): GeneratedPhase | undefined {\n if (ref === undefined) return undefined;\n const definition = module.functions.find((fn) => fn.ref === ref);\n if (definition === undefined) {\n throw new UnifiedIRCompilerError(\n 'invalid-ir',\n `Device \"${deviceId}\" returned a kernel phase ref that is not part of the module`,\n { deviceId },\n );\n }\n return { name: definition.name, ref };\n}\n","import type { FunctionBuilder, FunctionRef, IRModule } from '@mica-js/ir';\nimport type { DeviceLoopEntry } from './device-gen';\nimport type { NetSolverRuntime } from './solver-gen';\nimport type { CompiledNetlist } from './types';\n\n/** Generated entry-point names. */\nexport interface MainLoopNames {\n readonly tick: string;\n readonly initialize: string;\n readonly batch: string;\n}\n\n/** Names used when the caller does not override them. */\nexport const DEFAULT_ENTRY_POINT_NAMES: MainLoopNames = Object.freeze({\n tick: 'unified_tick',\n initialize: 'unified_initialize',\n batch: 'unified_tick_batch',\n});\n\n/** The generated main loop. */\nexport interface MainLoopOutput {\n readonly names: MainLoopNames;\n readonly initialize: FunctionRef<readonly [], readonly []>;\n readonly tick: FunctionRef<readonly [], readonly []>;\n readonly batch: FunctionRef<readonly ['u32'], readonly []>;\n /** Device ids in dependency order. */\n readonly order: readonly string[];\n}\n\n/**\n * Generates the circuit entries.\n *\n * ```text\n * unified_initialize: // once, before the first tick\n * drive1_initialize()\n * sink1_initialize() // if the device has one\n *\n * unified_tick: // one simulation step\n * drive1_tick() // drivers publish their outputs\n * solve_net_0() // the electrical network resolves\n * sink1_update() // loads observe the solved inputs\n *\n * unified_tick_batch(count): // the same step, looped inside the IR\n * for i in 0 .. count { <step> }\n * ```\n *\n * Devices run in dependency order: a device that drives a net executes before\n * every device that senses it. Feedback loops fall back to declaration order\n * after the topological prefix, so clock cycles stay valid.\n */\nexport class MainLoopGenerator {\n private readonly module: IRModule;\n\n constructor(module: IRModule) {\n this.module = module;\n }\n\n /** Stable topological order of the devices; cycles fall back to declaration order. */\n order(entries: readonly DeviceLoopEntry[], netlist: CompiledNetlist): readonly string[] {\n const indexById = new Map(entries.map((entry, index) => [entry.deviceId, index]));\n const consumers = new Map<string, Set<string>>();\n const indegree = new Map<string, number>(entries.map((entry) => [entry.deviceId, 0]));\n\n for (const net of netlist.nets) {\n const driverDevices = new Set(net.drivers.map((pin) => pin.deviceId));\n const sinkDevices = new Set(net.sinks.map((pin) => pin.deviceId));\n for (const driver of driverDevices) {\n for (const sink of sinkDevices) {\n if (driver === sink) continue;\n let targets = consumers.get(driver);\n if (targets === undefined) {\n targets = new Set();\n consumers.set(driver, targets);\n }\n if (targets.has(sink)) continue;\n targets.add(sink);\n indegree.set(sink, (indegree.get(sink) ?? 0) + 1);\n }\n }\n }\n\n const ready = new Set(\n entries\n .filter((entry) => (indegree.get(entry.deviceId) ?? 0) === 0)\n .map((entry) => entry.deviceId),\n );\n const order: string[] = [];\n while (ready.size > 0) {\n let nextId: string | undefined;\n let nextIndex = Number.POSITIVE_INFINITY;\n for (const id of ready) {\n const index = indexById.get(id) ?? 0;\n if (index < nextIndex) {\n nextIndex = index;\n nextId = id;\n }\n }\n if (nextId === undefined) break;\n ready.delete(nextId);\n order.push(nextId);\n for (const consumer of consumers.get(nextId) ?? []) {\n const remaining = (indegree.get(consumer) ?? 0) - 1;\n indegree.set(consumer, remaining);\n if (remaining === 0) ready.add(consumer);\n }\n }\n for (const entry of entries) {\n if (!order.includes(entry.deviceId)) order.push(entry.deviceId);\n }\n return Object.freeze(order);\n }\n\n /** Generates `initialize`, `tick` and the batched tick loop. */\n generate(\n entries: readonly DeviceLoopEntry[],\n solvers: readonly NetSolverRuntime[],\n netlist: CompiledNetlist,\n names: MainLoopNames = DEFAULT_ENTRY_POINT_NAMES,\n ): MainLoopOutput {\n const order = this.order(entries, netlist);\n const byId = new Map(entries.map((entry) => [entry.deviceId, entry]));\n\n const emitStep = (b: FunctionBuilder<readonly []>): void => {\n for (const deviceId of order) {\n const entry = byId.get(deviceId);\n if (entry?.tick !== undefined) b.call(entry.tick, []);\n }\n for (const solver of solvers) b.call(solver.solve, []);\n for (const deviceId of order) {\n const entry = byId.get(deviceId);\n if (entry?.update !== undefined) b.call(entry.update, []);\n }\n };\n\n const initialize = this.module.func(names.initialize, { params: [], results: [] });\n initialize.body((b) => {\n for (const deviceId of order) {\n const entry = byId.get(deviceId);\n if (entry?.initialize !== undefined) b.call(entry.initialize, []);\n }\n b.return([]);\n });\n\n const tick = this.module.func(names.tick, { params: [], results: [] });\n tick.body((b) => {\n emitStep(b);\n b.return([]);\n });\n\n // The batch entry keeps the loop inside the IR: one engine call per batch\n // instead of one host entry per tick, which is the throughput path.\n const batch = this.module.func(names.batch, { params: ['u32'], results: [] });\n batch.body((b, [count]) => {\n const header = b.block(['u32']);\n const body = b.block(['u32']);\n const done = b.block([]);\n b.jump(header, [b.const('u32', 0)]);\n b.at(header, (ib, [index]) =>\n ib.branch(\n ib.int.cmp('lt', index, count),\n { target: body, args: [index] },\n { target: done, args: [] },\n ),\n );\n b.at(body, (ib, [index]) => {\n emitStep(ib);\n ib.jump(header, [ib.int.add(index, ib.const('u32', 1))]);\n });\n b.at(done, (ib) => ib.return([]));\n });\n\n return Object.freeze({\n names,\n initialize,\n tick,\n batch,\n order,\n });\n }\n}\n","import type { FunctionBuilder, FunctionRef, IRModule, Value } from '@mica-js/ir';\nimport { PIN_MODE } from '../pin-space';\nimport type {\n CompiledCircuitMemory,\n CompiledNet,\n CompiledNetlist,\n CompiledPinConnection,\n} from './types';\n\n/** One generated net solver. */\nexport interface NetSolverRuntime {\n readonly netId: number;\n /** Generated `solve_net_<id>`. */\n readonly name: string;\n readonly net: CompiledNet;\n readonly solve: FunctionRef<readonly [], readonly []>;\n}\n\n/** Everything the solver generator reads from the prior compilation stages. */\nexport interface SolverGenerationContext {\n readonly module: IRModule;\n readonly memory: CompiledCircuitMemory;\n}\n\n/**\n * Generates the electrical solve, one `solve_net_<id>` function per net.\n *\n * Single driver — the only shape v1 compiles without `allowMultiDriver` — is a\n * branch-free path:\n *\n * ```text\n * solve_net_0:\n * let mode = PIN_MODE[driver]\n * let output = PIN_OUTPUT[driver]\n * let driven = mode == PUSH_PULL && output\n * PIN_INPUT[load] = driven // once per sink\n * ```\n *\n * Only a push-pull driver holds its net; high-z, open-drain and analog modes\n * leave it floating. A driver-less net loads the constant of its rail, or\n * `false` when it is truly floating.\n */\nexport class ElectricalSolverGenerator {\n private readonly context: SolverGenerationContext;\n\n constructor(context: SolverGenerationContext) {\n this.context = context;\n }\n\n generate(netlist: CompiledNetlist): readonly NetSolverRuntime[] {\n return Object.freeze(netlist.nets.map((net) => this.generateNetSolver(net)));\n }\n\n private generateNetSolver(net: CompiledNet): NetSolverRuntime {\n const name = `solve_net_${net.netId}`;\n const solve = this.context.module.func(name, { params: [], results: [] });\n\n solve.body((b) => {\n if (net.sinks.length > 0) {\n const driven =\n net.drivers.length === 0\n ? b.const('bool', net.level)\n : this.combineDrivers(b, net.drivers);\n if (driven !== undefined) {\n for (const sink of net.sinks) {\n b.array.store(this.context.memory.input, b.const('u32', sink.globalPinId), driven);\n }\n }\n }\n b.return([]);\n });\n\n return Object.freeze({ netId: net.netId, name, net, solve });\n }\n\n /**\n * Folds the drivers of one net into the level its sinks observe.\n *\n * A single driver yields `mode == push-pull && output`; several drivers (only\n * reachable with `allowMultiDriver`) are OR-ed into a wired-OR level.\n */\n private combineDrivers(\n b: FunctionBuilder<readonly []>,\n drivers: readonly CompiledPinConnection[],\n ): Value<'bool'> | undefined {\n let driven: Value<'bool'> | undefined;\n for (const driver of drivers) {\n const index = b.const('u32', driver.globalPinId);\n const mode = b.array.load(this.context.memory.mode, index);\n const output = b.array.load(this.context.memory.output, index);\n const pushed = b.int.cmp('eq', mode, b.const('u8', PIN_MODE.pushPull));\n const value = b.bool.and(pushed, output);\n driven = driven === undefined ? value : b.bool.or(driven, value);\n }\n return driven;\n }\n}\n","import {\n UnifiedIRCompilerError,\n type CompilationDiagnostic,\n type CompiledNet,\n type CompiledNetlist,\n type CompiledPinConnection,\n type CompiledRail,\n type Connection,\n type GlobalPinMap,\n type ResolvedDevicePin,\n} from './types';\n\n/** Rails every circuit understands without declaring them. */\nexport const DEFAULT_RAILS: Readonly<Record<string, boolean>> = Object.freeze({\n GND: false,\n VCC: true,\n VDD: true,\n});\n\n/** Options for {@link NetworkTopologyAnalyzer}. */\nexport interface TopologyOptions {\n /** Extra or overriding rails; merged over {@link DEFAULT_RAILS}. */\n readonly rails?: Readonly<Record<string, boolean>>;\n /** Treat several drivers on one net as a wired-OR instead of a conflict. */\n readonly allowMultiDriver?: boolean;\n}\n\ninterface ResolvedPinEndpoint {\n readonly kind: 'pin';\n readonly nodeId: number;\n readonly pin: ResolvedDevicePin;\n}\n\ninterface ResolvedRailEndpoint {\n readonly kind: 'rail';\n readonly nodeId: number;\n readonly name: string;\n readonly level: boolean;\n}\n\ntype ResolvedEndpoint = ResolvedPinEndpoint | ResolvedRailEndpoint;\n\ninterface ComponentPins {\n readonly pins: CompiledPinConnection[];\n readonly rails: CompiledRail[];\n readonly endpoints: string[];\n}\n\n/**\n * Analyses the pin-to-pin connections of a circuit.\n *\n * 1. every connection edge joins two nodes (pins and rails);\n * 2. a union-find pass collapses them into electrical nets (connected components);\n * 3. each net gets an id in first-appearance order and is split into drivers,\n * loads and sinks;\n * 4. electrical conflicts (several drivers, a driver against a rail, two rails\n * of opposite level) become diagnostics instead of silently wrong IR.\n *\n * The v1 electrical model supports one driver per net. `allowMultiDriver`\n * accepts more and the solver then emits a wired-OR instead of failing.\n */\nexport class NetworkTopologyAnalyzer {\n private readonly rails: ReadonlyMap<string, boolean>;\n private readonly allowMultiDriver: boolean;\n\n constructor(options: TopologyOptions = {}) {\n this.rails = new Map([\n ...Object.entries(DEFAULT_RAILS),\n ...Object.entries(options.rails ?? {}),\n ]);\n this.allowMultiDriver = options.allowMultiDriver ?? false;\n }\n\n /**\n * @throws {UnifiedIRCompilerError} when a connection is malformed, names an\n * unknown device, or names a pin the device does not declare.\n */\n analyze(connections: readonly Connection[], pins: GlobalPinMap): CompiledNetlist {\n if (!Array.isArray(connections)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.connections must be an array',\n );\n }\n\n const set = new DisjointSet();\n const pinNodes = new Map<number, CompiledPinConnection>();\n const railNodes = new Map<number, CompiledRail>();\n const railNodeIds = new Map<string, number>();\n const connectionOrder: number[] = [];\n\n for (const [index, connection] of connections.entries()) {\n if (connection === null || typeof connection !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-connection',\n `Connection[${index}] must be an object with \"from\" and \"to\"`,\n );\n }\n const from = this.resolveEndpoint(connection.from, pins, railNodeIds, index);\n const to = this.resolveEndpoint(connection.to, pins, railNodeIds, index);\n set.union(from.nodeId, to.nodeId);\n connectionOrder.push(from.nodeId);\n if (from.kind === 'pin') pinNodes.set(from.pin.globalPinId, toConnection(from.pin));\n else railNodes.set(from.nodeId, Object.freeze({ name: from.name, level: from.level }));\n if (to.kind === 'pin') pinNodes.set(to.pin.globalPinId, toConnection(to.pin));\n else railNodes.set(to.nodeId, Object.freeze({ name: to.name, level: to.level }));\n }\n\n // Component identity is the union-find root; the first connection that\n // touches a component decides its net id, which keeps ids stable.\n const components = new Map<number, ComponentPins>();\n const componentOf = (nodeId: number): ComponentPins => {\n const root = set.find(nodeId);\n let component = components.get(root);\n if (component === undefined) {\n component = { pins: [], rails: [], endpoints: [] };\n components.set(root, component);\n }\n return component;\n };\n\n for (const [pinId, connection] of pinNodes) componentOf(pinId).pins.push(connection);\n for (const [nodeId, rail] of railNodes) {\n const component = componentOf(nodeId);\n component.rails.push(rail);\n component.endpoints.push(rail.name);\n }\n\n const orderedRoots: number[] = [];\n const seen = new Set<number>();\n for (const nodeId of connectionOrder) {\n const root = set.find(nodeId);\n if (seen.has(root)) continue;\n seen.add(root);\n orderedRoots.push(root);\n }\n\n const diagnostics: CompilationDiagnostic[] = [];\n const nets: CompiledNet[] = [];\n for (const root of orderedRoots) {\n const component = components.get(root);\n if (component === undefined) continue;\n component.pins.sort((left, right) => left.globalPinId - right.globalPinId);\n component.rails.sort((left, right) => left.name.localeCompare(right.name));\n const endpoints = [...component.endpoints, ...component.pins.map((pin) => pin.endpoint)];\n\n if (component.pins.length === 0) {\n // Rail-to-rail wiring only: report a short, never emit a net.\n const levels = new Set(component.rails.map((rail) => rail.level));\n if (levels.size > 1) {\n diagnostics.push(\n diagnostic(\n 'rail-conflict',\n 'error',\n `Rails ${component.rails.map((rail) => rail.name).join(' and ')} are wired together with opposite levels`,\n undefined,\n endpoints,\n ),\n );\n }\n continue;\n }\n\n const netId = nets.length;\n const net = this.classify(netId, component.pins, component.rails, diagnostics);\n nets.push(net);\n }\n\n return Object.freeze({ nets: Object.freeze(nets), diagnostics: Object.freeze(diagnostics) });\n }\n\n private classify(\n netId: number,\n pins: readonly CompiledPinConnection[],\n rails: readonly CompiledRail[],\n diagnostics: CompilationDiagnostic[],\n ): CompiledNet {\n const drivers = pins.filter((pin) => pin.role === 'driver');\n const loads = pins.filter((pin) => pin.role === 'load');\n const sinks = pins.filter((pin) => pin.senses);\n const endpoints = [...rails.map((rail) => rail.name), ...pins.map((pin) => pin.endpoint)];\n const levels = new Set(rails.map((rail) => rail.level));\n\n if (rails.length > 1 && levels.size > 1) {\n diagnostics.push(\n diagnostic(\n 'rail-conflict',\n 'error',\n `Net ${netId} ties rails ${rails.map((rail) => rail.name).join(' and ')} with opposite levels`,\n netId,\n endpoints,\n ),\n );\n }\n if (drivers.length > 1) {\n const names = drivers.map((driver) => driver.endpoint).join(', ');\n diagnostics.push(\n diagnostic(\n 'driver-conflict',\n this.allowMultiDriver ? 'warning' : 'error',\n this.allowMultiDriver\n ? `Net ${netId} has ${drivers.length} drivers (${names}); solving them as a wired-OR`\n : `Net ${netId} has ${drivers.length} drivers (${names}); v1 supports one driver per net (set allowMultiDriver to solve them as a wired-OR)`,\n netId,\n endpoints,\n ),\n );\n }\n if (drivers.length > 0 && rails.length > 0) {\n diagnostics.push(\n diagnostic(\n 'power-short',\n 'error',\n `Net ${netId} shorts rail ${rails[0]?.name ?? '?'} against driver ${drivers[0]?.endpoint ?? '?'}`,\n netId,\n endpoints,\n ),\n );\n }\n if (drivers.length === 0 && rails.length === 0) {\n diagnostics.push(\n diagnostic(\n 'floating-net',\n 'warning',\n `Net ${netId} has no driver and no rail; its loads read a constant low`,\n netId,\n endpoints,\n ),\n );\n }\n\n const source = drivers.length > 0 ? 'driver' : rails.length > 0 ? 'rail' : 'floating';\n const level = rails[0]?.level ?? false;\n\n return Object.freeze({\n netId,\n pins: Object.freeze([...pins]),\n rails: Object.freeze([...rails]),\n drivers: Object.freeze(drivers),\n loads: Object.freeze(loads),\n sinks: Object.freeze(sinks),\n source,\n level,\n });\n }\n\n private resolveEndpoint(\n raw: unknown,\n pins: GlobalPinMap,\n railNodeIds: Map<string, number>,\n index: number,\n ): ResolvedEndpoint {\n if (typeof raw !== 'string' || raw.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-connection',\n `Connection[${index}] endpoint must be a non-empty \"device.pin\" string or a rail name`,\n );\n }\n const railLevel = this.rails.get(raw);\n if (railLevel !== undefined) {\n let nodeId = railNodeIds.get(raw);\n if (nodeId === undefined) {\n nodeId = pins.totalPins + railNodeIds.size;\n railNodeIds.set(raw, nodeId);\n }\n return { kind: 'rail', nodeId, name: raw, level: railLevel };\n }\n\n const dot = raw.indexOf('.');\n if (dot <= 0 || dot === raw.length - 1) {\n throw new UnifiedIRCompilerError(\n 'invalid-connection',\n `Connection endpoint \"${raw}\" must be \"device.pin\" or a known rail (${[...this.rails.keys()].join(', ')})`,\n );\n }\n const deviceId = raw.slice(0, dot);\n const pinName = raw.slice(dot + 1);\n const allocation = pins.devices.get(deviceId);\n if (allocation === undefined) {\n throw new UnifiedIRCompilerError(\n 'unknown-device',\n `Connection endpoint \"${raw}\" references unknown device \"${deviceId}\". Available: [${[...pins.devices.keys()].join(', ')}]`,\n { deviceId },\n );\n }\n const pin = allocation.resolved.get(pinName);\n if (pin === undefined) {\n const available = [...allocation.resolved.keys()].map((name) => `${deviceId}.${name}`);\n throw new UnifiedIRCompilerError(\n 'pin-not-found',\n `Pin '${raw}' not found. Available: [${available.join(', ')}]`,\n { deviceId, pinName },\n );\n }\n return { kind: 'pin', nodeId: pin.globalPinId, pin };\n }\n}\n\n/**\n * Throws the first error diagnostic of a netlist, or returns it unchanged.\n *\n * @throws {UnifiedIRCompilerError} carrying every diagnostic for inspection.\n */\nexport function assertNoElectricalErrors(netlist: CompiledNetlist): CompiledNetlist {\n const errors = netlist.diagnostics.filter((entry) => entry.severity === 'error');\n const first = errors[0];\n if (first === undefined) return netlist;\n throw new UnifiedIRCompilerError(mapErrorCode(first.code), first.message, {\n ...(first.netId === undefined ? {} : { netId: first.netId }),\n diagnostics: netlist.diagnostics,\n });\n}\n\nfunction mapErrorCode(\n code: CompilationDiagnostic['code'],\n): 'driver-conflict' | 'power-short' | 'rail-conflict' {\n if (code === 'driver-conflict') return 'driver-conflict';\n if (code === 'rail-conflict') return 'rail-conflict';\n return 'power-short';\n}\n\nfunction diagnostic(\n code: CompilationDiagnostic['code'],\n severity: CompilationDiagnostic['severity'],\n message: string,\n netId: number | undefined,\n endpoints: readonly string[],\n): CompilationDiagnostic {\n return Object.freeze({\n code,\n severity,\n message,\n netId,\n endpoints: Object.freeze([...endpoints]),\n });\n}\n\nfunction toConnection(pin: ResolvedDevicePin): CompiledPinConnection {\n return Object.freeze({\n endpoint: `${pin.deviceId}.${pin.name}`,\n deviceId: pin.deviceId,\n pinName: pin.name,\n globalPinId: pin.globalPinId,\n role: pin.role,\n senses: pin.senses,\n });\n}\n\n/** Union-find over pin ids and rail node ids. */\nclass DisjointSet {\n private readonly parent = new Map<number, number>();\n private readonly rank = new Map<number, number>();\n\n find(id: number): number {\n const parent = this.parent.get(id);\n if (parent === undefined) {\n this.parent.set(id, id);\n this.rank.set(id, 0);\n return id;\n }\n if (parent === id) return id;\n const root = this.find(parent);\n this.parent.set(id, root);\n return root;\n }\n\n union(left: number, right: number): void {\n const leftRoot = this.find(left);\n const rightRoot = this.find(right);\n if (leftRoot === rightRoot) return;\n const leftRank = this.rank.get(leftRoot) ?? 0;\n const rightRank = this.rank.get(rightRoot) ?? 0;\n if (leftRank < rightRank) {\n this.parent.set(leftRoot, rightRoot);\n return;\n }\n this.parent.set(rightRoot, leftRoot);\n if (leftRank === rightRank) this.rank.set(leftRoot, leftRank + 1);\n }\n}\n","import { createIRModule, validateIR } from '@mica-js/ir';\nimport type { IRModule, IRValidationOptions } from '@mica-js/ir';\nimport { createModuleValidation } from '../validation';\nimport { GlobalResourceAllocator } from './allocator';\nimport { DeviceIRGenerator } from './device-gen';\nimport { DEFAULT_ENTRY_POINT_NAMES, MainLoopGenerator, type MainLoopNames } from './mainloop-gen';\nimport { ElectricalSolverGenerator } from './solver-gen';\nimport {\n NetworkTopologyAnalyzer,\n assertNoElectricalErrors,\n type TopologyOptions,\n} from './topology';\nimport {\n UnifiedIRCompilerError,\n type CircuitCompilationInput,\n type CircuitCompilationOptions,\n type CompiledCircuit,\n type Connection,\n type DeviceConfig,\n} from './types';\n\n/**\n * Compiles several devices and their wiring into one unified IR module (U01).\n *\n * Device models are caller-supplied: every entry of `devices` carries the pins,\n * states and behaviors (or `kernel`) its type needs.\n *\n * ```ts\n * const circuit = compileCircuit({\n * devices: [\n * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },\n * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },\n * ],\n * connections: [\n * { from: 'drive1.channel0', to: 'sink1.anode' },\n * { from: 'sink1.cathode', to: 'GND' },\n * ],\n * });\n *\n * const jit = createIRJIT(circuit.module, { validation: circuit.validation });\n * jit.execute(circuit.entryPoints.refs.initialize, []);\n * jit.execute(circuit.entryPoints.refs.tick, []); // drive1 + nets + sink1\n * ```\n *\n * The pipeline is: validate the input, allocate the global pin and state\n * spaces, analyse the electrical topology, generate one function per device\n * phase, generate one solver per net, generate the main loop, then validate the\n * resulting module with `validateIR`.\n *\n * @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown\n * pins, electrical conflicts, or when the generated module fails validation.\n */\nexport function compileCircuit(\n input: CircuitCompilationInput,\n options: CircuitCompilationOptions = {},\n): CompiledCircuit {\n const { devices, connections } = validateInput(input);\n const resolvedOptions = validateOptions(options);\n const names = resolveEntryNames(resolvedOptions);\n\n const module = createIRModule();\n const allocation = new GlobalResourceAllocator(module).allocate(devices);\n\n const topologyOptions: TopologyOptions = {\n ...(resolvedOptions.rails === undefined ? {} : { rails: resolvedOptions.rails }),\n ...(resolvedOptions.allowMultiDriver === undefined\n ? {}\n : { allowMultiDriver: resolvedOptions.allowMultiDriver }),\n };\n const netlist = new NetworkTopologyAnalyzer(topologyOptions).analyze(\n connections,\n allocation.pins,\n );\n assertNoElectricalErrors(netlist);\n\n const generator = new DeviceIRGenerator({\n module,\n memory: allocation.memory,\n pins: allocation.pins,\n states: allocation.states,\n });\n const generated = devices.map((device) => generator.generate(device));\n\n const solvers = new ElectricalSolverGenerator({\n module,\n memory: allocation.memory,\n }).generate(netlist);\n\n assertNoNameCollisions(\n devices,\n solvers.map((solver) => solver.name),\n names,\n );\n\n const loop = new MainLoopGenerator(module).generate(\n generated.map((device) => device.entry),\n solvers,\n netlist,\n names,\n );\n\n const validation = createModuleValidation(\n module,\n devices.flatMap((device) => device.description.updateResources ?? []),\n );\n if (resolvedOptions.validate !== false) validateModule(module, validation);\n\n const deviceMap = new Map(generated.map((device) => [device.metadata.deviceId, device.metadata]));\n\n return Object.freeze({\n module,\n entryPoints: Object.freeze({\n tick: loop.names.tick,\n initialize: loop.names.initialize,\n batch: loop.names.batch,\n refs: Object.freeze({\n tick: loop.tick,\n initialize: loop.initialize,\n batch: loop.batch,\n }),\n }),\n pinMap: allocation.pins.pins,\n deviceMap,\n netlist,\n pins: allocation.pins,\n states: allocation.states,\n memory: allocation.memory,\n validation,\n executionOrder: loop.order,\n functions: Object.freeze(module.functions.map((fn) => fn.name)),\n });\n}\n\nfunction validateInput(input: unknown): {\n readonly devices: readonly DeviceConfig[];\n readonly connections: readonly Connection[];\n} {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput must be an object with devices and connections',\n );\n }\n const { devices, connections } = input as Partial<CircuitCompilationInput>;\n if (!Array.isArray(devices) || devices.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.devices must be a non-empty array',\n );\n }\n if (!Array.isArray(connections)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.connections must be an array',\n );\n }\n return { devices, connections };\n}\n\nfunction validateOptions(options: unknown): CircuitCompilationOptions {\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw new UnifiedIRCompilerError('invalid-input', 'Compile options must be an object');\n }\n const resolved = options as CircuitCompilationOptions;\n if (resolved.validate !== undefined && typeof resolved.validate !== 'boolean') {\n throw new UnifiedIRCompilerError('invalid-input', 'options.validate must be a boolean');\n }\n if (resolved.allowMultiDriver !== undefined && typeof resolved.allowMultiDriver !== 'boolean') {\n throw new UnifiedIRCompilerError('invalid-input', 'options.allowMultiDriver must be a boolean');\n }\n if (resolved.rails !== undefined) {\n if (\n resolved.rails === null ||\n typeof resolved.rails !== 'object' ||\n Array.isArray(resolved.rails)\n ) {\n throw new UnifiedIRCompilerError('invalid-input', 'options.rails must be a plain object');\n }\n for (const [name, level] of Object.entries(resolved.rails)) {\n if (name.length === 0 || typeof level !== 'boolean') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `options.rails[\"${name}\"] must be a boolean`,\n );\n }\n }\n }\n return resolved;\n}\n\nfunction resolveEntryNames(options: CircuitCompilationOptions): MainLoopNames {\n const names: MainLoopNames = {\n tick: options.entryPointNames?.tick ?? DEFAULT_ENTRY_POINT_NAMES.tick,\n initialize: options.entryPointNames?.initialize ?? DEFAULT_ENTRY_POINT_NAMES.initialize,\n batch: options.entryPointNames?.batch ?? DEFAULT_ENTRY_POINT_NAMES.batch,\n };\n for (const [role, name] of Object.entries(names)) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Entry point names.${role} must be a non-empty string`,\n );\n }\n }\n if (new Set(Object.values(names)).size !== 3) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Entry point names must be distinct: ${JSON.stringify(names)}`,\n );\n }\n return Object.freeze(names);\n}\n\nfunction assertNoNameCollisions(\n devices: readonly DeviceConfig[],\n solverNames: readonly string[],\n names: MainLoopNames,\n): void {\n const reserved = new Set<string>([names.tick, names.initialize, names.batch, ...solverNames]);\n for (const device of devices) {\n for (const phase of ['initialize', 'tick', 'update'] as const) {\n const generated = `${device.id}_${phase}`;\n if (reserved.has(generated)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" generates \"${generated}\", which collides with another generated function; rename the device or the entry point`,\n { deviceId: device.id },\n );\n }\n }\n }\n}\n\nfunction validateModule(module: IRModule, validation: IRValidationOptions): void {\n const result = validateIR(module, validation);\n if (result.ok) return;\n const details = result.diagnostics\n .map((entry) => `- [${entry.code}] ${entry.message} at ${entry.location.path}`)\n .join('\\n');\n throw new UnifiedIRCompilerError(\n 'invalid-ir',\n `Generated IR failed validateIR (${result.diagnostics.length} diagnostic(s)):\\n${details}`,\n );\n}\n\nexport * from './types';\nexport { GlobalResourceAllocator, createPinMemory, stateOffsetOf } from './allocator';\nexport type { ResourceAllocation } from './allocator';\nexport { DEFAULT_RAILS, NetworkTopologyAnalyzer, assertNoElectricalErrors } from './topology';\nexport type { TopologyOptions } from './topology';\nexport { DeviceIRGenerator } from './device-gen';\nexport type { DeviceGenerationContext, DeviceLoopEntry, GeneratedDevice } from './device-gen';\nexport { ElectricalSolverGenerator } from './solver-gen';\nexport type { NetSolverRuntime, SolverGenerationContext } from './solver-gen';\nexport { DEFAULT_ENTRY_POINT_NAMES, MainLoopGenerator } from './mainloop-gen';\nexport type { MainLoopNames, MainLoopOutput } from './mainloop-gen';\n","import type { IRJITTuning } from '@mica-js/ir';\nimport type { CircuitCompilationInput } from '../compiler';\n\n/**\n * Types of the unified circuit runtime (U02).\n *\n * `Circuit` is the host-facing facade over one compiled unified IR module: it\n * owns the engine instance, exposes typed per-device accessors and keeps the\n * tick counter. Everything here is transport-neutral; no type mentions the\n * scheduler, the device host or the schematic editor.\n */\n\n/** Execution engine a `Circuit` runs on. */\nexport type CircuitEngine = 'jit' | 'reference';\n\n/** Electrical-solve options forwarded to `compileCircuit`. */\nexport interface CircuitElectricalOptions {\n /**\n * Accept nets with more than one driver and solve them as a wired-OR.\n * Defaults to `false`, which reports a `driver-conflict` at compile time.\n */\n readonly allowMultiDriver?: boolean;\n /** Named fixed-level rails; merged over `GND`/`VCC`/`VDD`. */\n readonly rails?: Readonly<Record<string, boolean>>;\n}\n\n/**\n * Options for `Circuit.create`.\n *\n * @example\n * const circuit = await Circuit.create(input, { engine: 'reference' });\n */\nexport interface CircuitRuntimeOptions {\n /** Execution engine. Defaults to `'jit'`; `'reference'` runs the interpreter. */\n readonly engine?: CircuitEngine;\n /** JIT tuning. The runtime always supplies the module's own validation grant. */\n readonly jit?: IRJITTuning;\n /**\n * Run `validateIR` over the generated module during compilation.\n * Defaults to `true`; pass `false` only for measured warm paths.\n */\n readonly validateIR?: boolean;\n /** Electrical-solve options. */\n readonly electrical?: CircuitElectricalOptions;\n /** Instance id reported to the engine. Defaults to `'unified-circuit'`. */\n readonly instanceId?: string;\n}\n\n/** Error codes raised by `CircuitError`. */\nexport type CircuitErrorCode =\n | 'invalid-options'\n | 'invalid-count'\n | 'pin-not-found'\n | 'pin-not-writable'\n | 'state-not-found'\n | 'invalid-state-value'\n | 'unresolved-device'\n | 'disposed';\n\nexport interface CircuitErrorOptions {\n readonly deviceId?: string;\n readonly pinName?: string;\n readonly stateName?: string;\n readonly cause?: unknown;\n}\n\n/**\n * Error raised while driving a `Circuit`.\n *\n * The code is stable and machine-checkable, and the message always names the\n * offending device/pin/state plus the values that would have been accepted.\n */\nexport class CircuitError extends Error {\n override readonly name = 'CircuitError';\n readonly code: CircuitErrorCode;\n readonly deviceId: string | undefined;\n readonly pinName: string | undefined;\n readonly stateName: string | undefined;\n\n constructor(code: CircuitErrorCode, message: string, options: CircuitErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.code = code;\n this.deviceId = options.deviceId;\n this.pinName = options.pinName;\n this.stateName = options.stateName;\n }\n}\n\n/**\n * What every device accessor offers, whatever its type.\n *\n * `readPin` returns the level the *device* drives onto one of its pins (its\n * output latch), while `Circuit.getPin('device.pin')` returns the level the pin\n * *observes* after the electrical solve. Writing a pin only makes sense for\n * driver pins, so `writePin` rejects load and passive pins.\n */\nexport interface DeviceAccessor {\n /** Circuit-unique device id. */\n readonly deviceId: string;\n /** Device type, e.g. `'push-pull-driver'`. */\n readonly type: string;\n /** Declared pin names, in declaration order. */\n readonly pinNames: readonly string[];\n /** Declared internal state names, in declaration order. */\n readonly stateNames: readonly string[];\n /** Reads the level the device drives onto `pinName`. */\n readPin(pinName: string): boolean;\n /** Writes the level the device drives onto `pinName`. */\n writePin(pinName: string, value: boolean): void;\n /** Reads one declared internal state. */\n getState(name: string): unknown;\n /** Writes one declared internal state. */\n setState(name: string, value: unknown): void;\n}\n\n/** Every accessor of one circuit, keyed by device id. */\nexport type DeviceAccessors = Readonly<Record<string, DeviceAccessor>>;\n\n/**\n * Accessor map derived from a literal compilation input.\n *\n * `Circuit.create` infers the device ids of a `const` input, so\n * `circuit.devices.<id>` is typed without a cast. A device package that wants a\n * richer surface builds it through `DeviceDescription.accessor` and casts at\n * the call site.\n */\nexport type DeviceAccessorsOf<I extends CircuitCompilationInput> = {\n readonly [D in I['devices'][number] as D['id']]: DeviceAccessor;\n};\n","import type { FloatBits, IRInterpreter, RuntimeScalar } from '@mica-js/ir';\nimport type {\n CompiledCircuit,\n DeviceMetadata,\n DeviceStateSlot,\n ResolvedDevicePin,\n} from '../compiler';\nimport { CircuitError, type DeviceAccessor, type DeviceAccessors } from './types';\n\n/** Everything the accessor builders read from one live circuit. */\nexport interface DeviceAccessorContext {\n readonly compiled: CompiledCircuit;\n readonly jit: IRInterpreter;\n /** Invoked before every read or write; throws once the circuit is disposed. */\n readonly assertActive: () => void;\n /** Advances the circuit by one tick; used by custom accessors. */\n readonly step: () => void;\n /** Advances the circuit by `count` ticks; used by custom accessors. */\n readonly runBatch: (count: number) => void;\n}\n\n/**\n * Builds one accessor per compiled device.\n *\n * A description that declares `accessor` owns its surface; every other device\n * keeps the generic state/pin accessor. The returned record is frozen and keyed\n * by device id.\n */\nexport function buildDeviceAccessors(context: DeviceAccessorContext): DeviceAccessors {\n const entries: [string, DeviceAccessor][] = [];\n for (const device of context.compiled.deviceMap.values()) {\n const base = createBaseAccessor(context, device);\n if (device.accessor !== undefined) {\n // A custom kernel owns its accessor: the factory closes over the layout\n // its IR factory allocated in this module.\n entries.push([\n device.deviceId,\n device.accessor({\n deviceId: device.deviceId,\n storage: context.jit.storage,\n assertActive: context.assertActive,\n step: context.step,\n runBatch: context.runBatch,\n }) as unknown as DeviceAccessor,\n ]);\n } else {\n entries.push([device.deviceId, base]);\n }\n }\n // `Object.fromEntries` defines own data properties, so ids such as\n // `__proto__` stay ordinary keys instead of reaching the prototype chain.\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction createBaseAccessor(\n context: DeviceAccessorContext,\n device: DeviceMetadata,\n): DeviceAccessor {\n const { jit } = context;\n const storage = jit.storage;\n const memory = context.compiled.memory;\n const resolved = context.compiled.pins.devices.get(device.deviceId)?.resolved;\n\n const accessor: DeviceAccessor = {\n deviceId: device.deviceId,\n type: device.type,\n pinNames: Object.freeze([...device.pins.keys()]),\n stateNames: Object.freeze([...device.states.keys()]),\n readPin(pinName: string): boolean {\n context.assertActive();\n const pin = pinOf(device, resolved, pinName);\n return storage.loadArray(memory.output, pin.globalPinId) === true;\n },\n writePin(pinName: string, value: boolean): void {\n context.assertActive();\n const pin = pinOf(device, resolved, pinName);\n if (pin.role !== 'driver') {\n throw new CircuitError(\n 'pin-not-writable',\n `Pin \"${device.deviceId}.${pinName}\" has role \"${pin.role}\"; only driver pins can be written. Use Circuit.setPin to override a sensed level`,\n { deviceId: device.deviceId, pinName },\n );\n }\n assertBoolean(device.deviceId, pinName, value);\n storage.storeArray(memory.output, pin.globalPinId, value);\n },\n getState(name: string): unknown {\n context.assertActive();\n const slot = stateOf(device, name);\n return storage.loadArray(slot.array, slot.index);\n },\n setState(name: string, value: unknown): void {\n context.assertActive();\n const slot = stateOf(device, name);\n const accepted = coerceStateValue(device, slot, value);\n try {\n storage.storeArray(slot.array, slot.index, accepted);\n } catch (cause) {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${name}\" (${slot.type}) rejected ${String(value)}`,\n { deviceId: device.deviceId, stateName: name, cause },\n );\n }\n },\n };\n return Object.freeze(accessor);\n}\n\n/** Resolves one pin of `device`, or throws with every pin the device declares. */\nfunction pinOf(\n device: DeviceMetadata,\n resolved: ReadonlyMap<string, ResolvedDevicePin> | undefined,\n pinName: string,\n): ResolvedDevicePin {\n const pin = resolved?.get(pinName);\n if (pin === undefined) {\n throw new CircuitError(\n 'pin-not-found',\n `Device \"${device.deviceId}\" (${device.type}) has no pin \"${pinName}\". Available: ${formatNames(device.pins.keys())}`,\n { deviceId: device.deviceId, pinName },\n );\n }\n return pin;\n}\n\n/** Resolves one state slot of `device`, or throws with every state it declares. */\nfunction stateOf(device: DeviceMetadata, name: string): DeviceStateSlot {\n const slot = device.states.get(name);\n if (slot === undefined) {\n throw new CircuitError(\n 'state-not-found',\n `Device \"${device.deviceId}\" (${device.type}) has no state \"${name}\". Available: ${formatNames(device.states.keys())}`,\n { deviceId: device.deviceId, stateName: name },\n );\n }\n return slot;\n}\n\nfunction assertBoolean(\n deviceId: string,\n pinName: string,\n value: unknown,\n): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new CircuitError(\n 'invalid-state-value',\n `Pin \"${deviceId}.${pinName}\" needs a boolean level, received ${typeof value}`,\n { deviceId, pinName },\n );\n }\n}\n\n/**\n * Validates a host-written state value against the declared scalar type.\n * Range checks stay in storage, which owns the encoding.\n */\nfunction coerceStateValue(\n device: DeviceMetadata,\n slot: DeviceStateSlot,\n value: unknown,\n): RuntimeScalar {\n if (slot.type === 'bool') {\n if (typeof value !== 'boolean') {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is bool and needs true or false, received ${String(value)}`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n return value;\n }\n if (slot.type === 'f32' || slot.type === 'f64') {\n if (typeof value === 'number' || isFloatBits(value)) return value;\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is ${slot.type} and needs a number or FloatBits`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is ${slot.type} and needs an integer, received ${String(value)}`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n return value;\n}\n\nfunction isFloatBits(value: unknown): value is FloatBits {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as { readonly type?: unknown; readonly bits?: unknown };\n return (\n (candidate.type === 'f32' || candidate.type === 'f64') && typeof candidate.bits === 'string'\n );\n}\n\nfunction formatNames(names: Iterable<string>): string {\n const list = [...names];\n return list.length === 0 ? '(none)' : `[${list.join(', ')}]`;\n}\n","import { createIRInterpreter, createIRJIT } from '@mica-js/ir';\nimport type {\n ArrayRef,\n BytesRef,\n IRInterpreter,\n IRJITTuning,\n RuntimeScalar,\n StateRef,\n} from '@mica-js/ir';\nimport { compileCircuit } from '../compiler';\nimport type {\n CircuitCompilationInput,\n CircuitCompilationOptions,\n CompiledCircuit,\n} from '../compiler';\nimport { PIN_MODE } from '../pin-space';\nimport { buildDeviceAccessors } from './accessors';\nimport {\n CircuitError,\n type CircuitEngine,\n type CircuitRuntimeOptions,\n type DeviceAccessorsOf,\n} from './types';\n\n/** Every generated entry takes no arguments, so one frozen array is reused. */\nconst NO_ARGS: readonly RuntimeScalar[] = Object.freeze([]);\n\n/** `unified_tick_batch` takes a u32 tick count. */\nconst MAX_BATCH_TICKS = 0xffff_ffff;\n\n/** Virtual time is a JS number, so it wraps before losing integer precision. */\nconst MAX_VIRTUAL_TIME = Number.MAX_SAFE_INTEGER;\n\nconst DEFAULT_INSTANCE_ID = 'unified-circuit';\n\n/**\n * Mutable execution context. `IRExecutionContext` is readonly for callers; the\n * runtime owns this object and updates `virtualTime` in place so that `step()`\n * allocates nothing on the hot path.\n */\ninterface RuntimeContext {\n instanceId: string;\n virtualTime: number;\n}\n\n/** One pin of the global address space, resolved at construction time. */\ninterface PinRuntime {\n readonly globalPinId: number;\n readonly role: 'driver' | 'load';\n /** Whether the device reads the solved level of this pin. */\n readonly senses: boolean;\n}\n\n/** Declared initial value of one memory resource, replayed by `reset()`. */\ntype ResetSeed =\n | { readonly kind: 'array'; readonly ref: ArrayRef; readonly values: readonly RuntimeScalar[] }\n | { readonly kind: 'state'; readonly ref: StateRef; readonly value: RuntimeScalar }\n | {\n readonly kind: 'bytes';\n readonly ref: BytesRef<false>;\n readonly values: readonly RuntimeScalar[];\n }\n | {\n readonly kind: 'readonly-bytes';\n readonly ref: BytesRef<true>;\n readonly values: Uint8Array;\n };\n\ninterface ResolvedRuntimeOptions {\n readonly engine: CircuitEngine;\n readonly jit: IRJITTuning | undefined;\n readonly validateIR: boolean;\n readonly allowMultiDriver: boolean;\n readonly rails: Readonly<Record<string, boolean>> | undefined;\n readonly instanceId: string;\n}\n\n/**\n * Host-facing runtime of one compiled unified circuit (U02).\n *\n * ```ts\n * const circuit = await Circuit.create({\n * devices: [\n * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },\n * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },\n * ],\n * connections: [\n * { from: 'drive1.PA0', to: 'sink1.anode' },\n * { from: 'sink1.cathode', to: 'GND' },\n * ],\n * });\n *\n * circuit.runBatch(1_000_000); // one engine call\n * expect(circuit.tickCount).toBe(1_000_000n);\n *\n * circuit.reset();\n * circuit.setPin('drive1.PA0', true); // host drives the pin\n * circuit.step();\n * expect(circuit.devices.sink1.getState('lamp')).toBe(true);\n * ```\n *\n * `Circuit` owns the engine instance and the tick counter; the compiled module\n * keeps every device, net and the main loop in one `@mica-js/ir` module, so a\n * batch is one interpreter/JIT call for the whole circuit.\n */\nexport class Circuit<I extends CircuitCompilationInput = CircuitCompilationInput> {\n /** Typed per-device accessors, keyed by device id. */\n readonly devices: DeviceAccessorsOf<I>;\n\n readonly #compiled: CompiledCircuit;\n readonly #jit: IRInterpreter;\n readonly #context: RuntimeContext;\n readonly #pins: ReadonlyMap<string, PinRuntime>;\n readonly #pinNames: readonly string[];\n readonly #seeds: readonly ResetSeed[];\n #tickCount = 0n;\n #virtualTime = 0;\n #disposed = false;\n\n private constructor(\n compiled: CompiledCircuit,\n jit: IRInterpreter,\n instanceId: string,\n accessors: DeviceAccessorsOf<I>,\n pins: ReadonlyMap<string, PinRuntime>,\n seeds: readonly ResetSeed[],\n ) {\n this.#compiled = compiled;\n this.#jit = jit;\n this.#context = { instanceId, virtualTime: 0 };\n this.devices = accessors;\n this.#pins = pins;\n this.#pinNames = Object.freeze([...pins.keys()]);\n this.#seeds = seeds;\n }\n\n /**\n * Compiles `input`, builds the engine instance and runs the generated\n * `initialize` entry once.\n *\n * The input is inferred as a `const` type, so a literal device list keeps its\n * ids and `circuit.devices.<id>` is typed without a cast.\n *\n * @throws {UnifiedIRCompilerError} when the circuit cannot be compiled.\n * @throws {CircuitError} for invalid options.\n */\n static async create<const I extends CircuitCompilationInput>(\n input: I,\n options: CircuitRuntimeOptions = {},\n ): Promise<Circuit<I>> {\n const resolved = resolveOptions(options);\n const compiled = compileCircuit(input, compileOptionsOf(resolved));\n const jit = createEngine(compiled, resolved);\n // The accessor factories run inside `buildDeviceAccessors`, which happens\n // before `circuit` is assigned. They only close over this holder; the\n // callbacks are invoked after construction.\n const host: { circuit: Circuit<I> | undefined } = { circuit: undefined };\n const circuit = new Circuit<I>(\n compiled,\n jit,\n resolved.instanceId,\n buildDeviceAccessors({\n compiled,\n jit,\n assertActive: () => {\n circuit.#assertActive();\n },\n step: () => {\n host.circuit?.step();\n },\n runBatch: (count) => {\n host.circuit?.runBatch(count);\n },\n }) as DeviceAccessorsOf<I>,\n pinRuntimeOf(compiled),\n resetSeedsOf(compiled),\n );\n host.circuit = circuit;\n // `initialize` runs once at creation; `reset()` replays the same sequence\n // after restoring every memory to its declared initial value.\n jit.execute(compiled.entryPoints.refs.initialize, NO_ARGS, circuit.#context);\n return circuit;\n }\n\n /**\n * Runs `count` ticks inside one generated loop — the throughput path.\n *\n * The whole batch is one engine call; `tickCount` grows by `count` once the\n * call returns, so a failed batch never advances the clock.\n *\n * @throws {CircuitError} with code `invalid-count` unless `count` is a u32.\n */\n runBatch(count: number): void {\n this.#assertActive();\n if (\n typeof count !== 'number' ||\n !Number.isSafeInteger(count) ||\n count < 0 ||\n count > MAX_BATCH_TICKS\n ) {\n throw new CircuitError(\n 'invalid-count',\n `runBatch(count) needs an integer in [0, ${MAX_BATCH_TICKS}], received ${String(count)}`,\n );\n }\n if (count === 0) return;\n this.#context.virtualTime = this.#virtualTime;\n this.#jit.execute(this.#compiled.entryPoints.refs.batch, [count], this.#context);\n this.#advance(count);\n }\n\n /**\n * Advances exactly one tick — the debugging path.\n *\n * Every call is one engine entry, so prefer `runBatch` for throughput.\n */\n step(): void {\n this.#assertActive();\n this.#context.virtualTime = this.#virtualTime;\n this.#jit.execute(this.#compiled.entryPoints.refs.tick, NO_ARGS, this.#context);\n this.#advance(1);\n }\n\n /**\n * Restores every memory to its declared initial value, re-runs `initialize`\n * and resets `tickCount` to `0n`.\n *\n * Device state written by earlier ticks is discarded, so the circuit behaves\n * exactly like a freshly created one.\n */\n reset(): void {\n this.#assertActive();\n for (const seed of this.#seeds) {\n if (seed.kind === 'state') {\n this.#jit.storage.storeState(seed.ref, seed.value);\n continue;\n }\n if (seed.kind === 'bytes') {\n for (let index = 0; index < seed.values.length; index += 1) {\n this.#jit.storage.storeBytes(\n 'u8',\n 'little',\n seed.ref,\n index,\n seed.values[index] as RuntimeScalar,\n );\n }\n continue;\n }\n if (seed.kind === 'readonly-bytes') {\n try {\n this.#jit.storage.updateBytesFromBytes(seed.ref, 0, seed.values);\n } catch {\n // Read-only memories are constants unless their device explicitly\n // grants host update access (for example MCU firmware patching).\n }\n continue;\n }\n for (let index = 0; index < seed.values.length; index += 1) {\n this.#jit.storage.storeArray(seed.ref, index, seed.values[index] as RuntimeScalar);\n }\n }\n this.#tickCount = 0n;\n this.#virtualTime = 0;\n this.#context.virtualTime = 0;\n this.#jit.execute(this.#compiled.entryPoints.refs.initialize, NO_ARGS, this.#context);\n }\n\n /**\n * Reads the level one pin observes.\n *\n * A sensing pin (input, passive or bidirectional) reports the solved net\n * level; a pure driver pin reports the level it actually drives, which is\n * `false` unless it is configured push-pull.\n *\n * @throws {CircuitError} with code `pin-not-found`.\n */\n getPin(pinName: string): boolean {\n this.#assertActive();\n const pin = this.#pinRuntime(pinName);\n const storage = this.#jit.storage;\n if (pin.senses) {\n return storage.loadArray(this.#compiled.memory.input, pin.globalPinId) === true;\n }\n const mode = Number(storage.loadArray(this.#compiled.memory.mode, pin.globalPinId));\n return (\n mode === PIN_MODE.pushPull &&\n storage.loadArray(this.#compiled.memory.output, pin.globalPinId) === true\n );\n }\n\n /**\n * Forces the level of one pin from the host.\n *\n * A driver pin gets its output latch written, so the level survives the next\n * electrical solve. A sensing pin gets the solved-value slot overridden, which\n * lasts until the next tick recomputes its net.\n *\n * @throws {CircuitError} with code `pin-not-found`.\n */\n setPin(pinName: string, value: boolean): void {\n this.#assertActive();\n const pin = this.#pinRuntime(pinName);\n if (typeof value !== 'boolean') {\n throw new CircuitError(\n 'invalid-state-value',\n `Pin \"${pinName}\" needs a boolean level, received ${typeof value}`,\n { pinName },\n );\n }\n const target =\n pin.role === 'driver' ? this.#compiled.memory.output : this.#compiled.memory.input;\n this.#jit.storage.storeArray(target, pin.globalPinId, value);\n }\n\n /** Number of ticks completed since creation or the last `reset()`. */\n get tickCount(): bigint {\n this.#assertActive();\n return this.#tickCount;\n }\n\n /** Virtual tick time completed since creation or the last `reset()`. */\n get virtualTime(): number {\n this.#assertActive();\n return this.#virtualTime;\n }\n\n /** Underlying engine instance, e.g. for diagnostics or custom entries. */\n get jit(): IRInterpreter {\n this.#assertActive();\n return this.#jit;\n }\n\n /** Whether `dispose()` already ran. */\n get disposed(): boolean {\n return this.#disposed;\n }\n\n /**\n * Releases the runtime. Idempotent; every later call throws a `CircuitError`\n * with code `disposed`, including stale device accessors.\n */\n dispose(): void {\n this.#disposed = true;\n this.#tickCount = 0n;\n this.#virtualTime = 0;\n }\n\n /** @internal Shared guard of the circuit and all of its accessors. */\n #assertActive(): void {\n if (this.#disposed) {\n throw new CircuitError(\n 'disposed',\n 'Circuit has been disposed; create a new circuit to keep simulating',\n );\n }\n }\n\n #advance(count: number): void {\n this.#tickCount += BigInt(count);\n const next = this.#virtualTime + count;\n this.#virtualTime = next > MAX_VIRTUAL_TIME ? 0 : next;\n }\n\n #pinRuntime(pinName: string): PinRuntime {\n const pin = this.#pins.get(pinName);\n if (pin === undefined) {\n throw new CircuitError(\n 'pin-not-found',\n `Pin \"${pinName}\" not found. Available: ${this.#pinNames.length === 0 ? '(none)' : `[${this.#pinNames.join(', ')}]`}`,\n { pinName },\n );\n }\n return pin;\n }\n}\n\n/** Resolves every pin of the global address space into its runtime view. */\nfunction pinRuntimeOf(compiled: CompiledCircuit): ReadonlyMap<string, PinRuntime> {\n const pins = new Map<string, PinRuntime>();\n for (const [deviceId, allocation] of compiled.pins.devices) {\n for (const [pinName, pin] of allocation.resolved) {\n pins.set(\n `${deviceId}.${pinName}`,\n Object.freeze({\n globalPinId: pin.globalPinId,\n role: pin.role,\n senses: pin.senses,\n }),\n );\n }\n }\n return pins;\n}\n\n/**\n * Captures the declared initial value of every scalar memory, which is what\n * `reset()` restores before the generated `initialize` runs again.\n */\nfunction resetSeedsOf(compiled: CompiledCircuit): readonly ResetSeed[] {\n const seeds: ResetSeed[] = [];\n for (const memory of compiled.module.memories) {\n if (memory.kind === 'array') {\n seeds.push({\n kind: 'array',\n ref: memory.ref as ArrayRef,\n values: memory.initial as readonly RuntimeScalar[],\n });\n } else if (memory.kind === 'state') {\n seeds.push({\n kind: 'state',\n ref: memory.ref as StateRef,\n value: memory.initial[0] as RuntimeScalar,\n });\n } else if (memory.kind === 'bytes') {\n if (memory.writable) {\n seeds.push({\n kind: 'bytes',\n ref: memory.ref as BytesRef<false>,\n values: memory.initial as readonly RuntimeScalar[],\n });\n } else {\n seeds.push({\n kind: 'readonly-bytes',\n ref: memory.ref as BytesRef<true>,\n values: Uint8Array.from(memory.initial as readonly number[]),\n });\n }\n }\n }\n return Object.freeze(seeds);\n}\n\nfunction createEngine(compiled: CompiledCircuit, options: ResolvedRuntimeOptions): IRInterpreter {\n const base = {\n validation: compiled.validation,\n // One batch can execute hundreds of millions of instructions; the default\n // step budget is tuned for single entries, not for a loop in the IR.\n maxSteps: Number.MAX_SAFE_INTEGER,\n };\n if (options.engine === 'reference') {\n return createIRInterpreter(compiled.module, base);\n }\n return createIRJIT(compiled.module, {\n ...base,\n jit: { tierUpThreshold: 0, ...options.jit },\n });\n}\n\nfunction compileOptionsOf(options: ResolvedRuntimeOptions): CircuitCompilationOptions {\n return {\n validate: options.validateIR,\n allowMultiDriver: options.allowMultiDriver,\n ...(options.rails === undefined ? {} : { rails: options.rails }),\n };\n}\n\nfunction resolveOptions(options: unknown): ResolvedRuntimeOptions {\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw new CircuitError('invalid-options', 'Circuit options must be a plain object');\n }\n const candidate = options as CircuitRuntimeOptions;\n\n const engine = candidate.engine ?? 'jit';\n if (engine !== 'jit' && engine !== 'reference') {\n throw new CircuitError(\n 'invalid-options',\n `engine=${String(engine)} must be \"jit\" or \"reference\"`,\n );\n }\n\n if (candidate.validateIR !== undefined && typeof candidate.validateIR !== 'boolean') {\n throw new CircuitError('invalid-options', 'validateIR must be a boolean');\n }\n\n if (candidate.instanceId !== undefined && candidate.instanceId.length === 0) {\n throw new CircuitError('invalid-options', 'instanceId must be a non-empty string');\n }\n\n if (candidate.jit !== undefined) {\n if (\n candidate.jit === null ||\n typeof candidate.jit !== 'object' ||\n Array.isArray(candidate.jit)\n ) {\n throw new CircuitError('invalid-options', 'jit must be a JIT tuning object');\n }\n }\n\n let allowMultiDriver = false;\n let rails: Readonly<Record<string, boolean>> | undefined;\n if (candidate.electrical !== undefined) {\n const electrical = candidate.electrical;\n if (electrical === null || typeof electrical !== 'object' || Array.isArray(electrical)) {\n throw new CircuitError('invalid-options', 'electrical must be a plain object');\n }\n if (electrical.allowMultiDriver !== undefined) {\n if (typeof electrical.allowMultiDriver !== 'boolean') {\n throw new CircuitError('invalid-options', 'electrical.allowMultiDriver must be a boolean');\n }\n allowMultiDriver = electrical.allowMultiDriver;\n }\n rails = electrical.rails;\n }\n\n return Object.freeze({\n engine,\n jit: candidate.jit,\n validateIR: candidate.validateIR ?? true,\n allowMultiDriver,\n rails,\n instanceId: candidate.instanceId ?? DEFAULT_INSTANCE_ID,\n });\n}\n","import type { PayloadType } from '@mica-js/core/canvas';\nimport { deriveSchematicTopology, parseDeviceReference, symbolRole } from '@mica-js/core/schematic';\nimport type {\n DeviceReference,\n DeviceSymbolProvider,\n SchematicDocument,\n} from '@mica-js/core/schematic';\nimport { DEFAULT_RAILS } from '../compiler';\nimport type {\n CircuitCompilationInput,\n Connection,\n DeviceConfig,\n DeviceDescription,\n} from '../compiler';\nimport { Circuit } from './circuit';\nimport { CircuitError, type CircuitRuntimeOptions, type DeviceAccessor } from './types';\n\n/**\n * One endpoint a caller-supplied device declares to the simulation host.\n *\n * The simulator never guesses ports from a device type: the package that\n * resolves the reference states which payloads the device accepts and which it\n * publishes, in the same place it supplies the IR description.\n */\nexport interface SchematicDeviceTopic {\n readonly port: string;\n readonly direction: 'input' | 'output';\n readonly type: PayloadType;\n readonly title?: string;\n}\n\n/** Runtime behaviour of one schematic device package. */\nexport interface SchematicDeviceBinding {\n /** Device type, e.g. `'counter-ir'`. */\n readonly type: string;\n /** IR description: pins, states and behaviours. */\n readonly description: DeviceDescription;\n /** Instance configuration reserved for device kernels. */\n readonly config?: Readonly<Record<string, unknown>>;\n /** Endpoints the simulation host exposes; absent means the device has none. */\n readonly topics?: readonly SchematicDeviceTopic[];\n /** Bridges one input topic payload onto the compiled device accessor. */\n deliver?(accessor: DeviceAccessor, port: string, payload: unknown): void;\n /** Reads one output topic from the compiled device accessor. */\n read?(accessor: DeviceAccessor, port: string): unknown;\n}\n\n/** Options for {@link createCircuitFromSchematic}. */\nexport interface SchematicCircuitOptions extends CircuitRuntimeOptions {\n /**\n * Symbol geometry provider — pass the same provider that authored the\n * schematic. Without it the derived topology contains no pins.\n */\n readonly devices?: DeviceSymbolProvider;\n /** Resolves a schematic device reference to its runtime description. */\n readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n /** Coordinate tolerance used when matching pins to wires. */\n readonly tolerance?: number;\n}\n\n/**\n * Compiles a schematic sheet into a circuit.\n *\n * Nets come from `deriveSchematicTopology`, so wires, junctions, labels and\n * power symbols keep their usual meaning: a net that names a rail connects\n * every member to that rail, and any other net joins its pins pairwise (the\n * compiler merges transitively).\n *\n * ```ts\n * const circuit = await createCircuitFromSchematic(schematic, {\n * devices: symbolProvider,\n * resolveDevice: (reference) => bindings.get(reference.deviceId),\n * });\n * ```\n *\n * @throws {CircuitError} with code `unresolved-device` when a component symbol\n * has no binding; `SchematicError` for malformed sheets.\n */\nexport async function createCircuitFromSchematic(\n schematic: SchematicDocument,\n options: SchematicCircuitOptions,\n): Promise<Circuit> {\n return (await createSchematicCircuit(schematic, options)).circuit;\n}\n\n/** One component symbol of a compiled schematic. */\nexport interface SchematicCircuitBinding {\n /** Symbol id as written in the schematic. */\n readonly symbolId: string;\n /** Compiler-safe device id assigned to the symbol. */\n readonly deviceId: string;\n /** Parsed `\"<packageId>:<deviceId>\"` reference. */\n readonly reference: DeviceReference;\n /** Device type from the resolved runtime binding. */\n readonly type: string;\n}\n\n/** A compiled schematic circuit plus the symbol-to-device mapping it produced. */\nexport interface SchematicCircuitResult {\n readonly circuit: Circuit;\n /** Component symbols in schematic order; non-component symbols are absent. */\n readonly bindings: readonly SchematicCircuitBinding[];\n}\n\n/**\n * Compiles a schematic and reports which circuit device each symbol became.\n *\n * {@link createCircuitFromSchematic} returns only the circuit; hosts that route\n * schematic endpoints to circuit accessors need the mapping as well.\n */\nexport async function createSchematicCircuit(\n schematic: SchematicDocument,\n options: SchematicCircuitOptions,\n): Promise<SchematicCircuitResult> {\n if (\n schematic === null ||\n typeof schematic !== 'object' ||\n schematic.sheet === null ||\n typeof schematic.sheet !== 'object' ||\n !Array.isArray(schematic.sheet.symbols) ||\n !Array.isArray(schematic.sheet.wires) ||\n !Array.isArray(schematic.sheet.junctions)\n ) {\n throw new CircuitError(\n 'invalid-options',\n 'createSchematicCircuit needs a schematic with sheet.symbols, sheet.wires and sheet.junctions',\n );\n }\n if (options === null || typeof options !== 'object') {\n throw new CircuitError('invalid-options', 'createSchematicCircuit needs options');\n }\n const { resolveDevice, devices, tolerance, ...runtime } = options;\n if (typeof resolveDevice !== 'function') {\n throw new CircuitError('invalid-options', 'resolveDevice must be a function');\n }\n\n const usedIds = new Set<string>();\n const deviceIdBySymbol = new Map<string, string>();\n const deviceConfigs: DeviceConfig[] = [];\n const bindings: SchematicCircuitBinding[] = [];\n let componentCount = 0;\n\n for (const symbol of schematic.sheet.symbols) {\n if (symbolRole(symbol.device) !== 'component') continue;\n componentCount += 1;\n const reference = parseDeviceReference(symbol.device);\n const binding = reference === undefined ? undefined : resolveDevice(reference);\n if (binding === undefined) {\n throw new CircuitError(\n 'unresolved-device',\n `Symbol \"${symbol.id}\" (${symbol.device}) has no runtime device binding; resolve it in resolveDevice`,\n { deviceId: symbol.id },\n );\n }\n const deviceId = uniqueDeviceId(symbol.designator ?? symbol.id, usedIds);\n usedIds.add(deviceId);\n deviceIdBySymbol.set(symbol.id, deviceId);\n deviceConfigs.push({\n id: deviceId,\n type: binding.type,\n description: binding.description,\n ...(binding.config === undefined ? {} : { config: binding.config }),\n });\n if (reference !== undefined) {\n bindings.push({\n symbolId: symbol.id,\n deviceId,\n reference,\n type: binding.type,\n });\n }\n }\n\n const topology = deriveSchematicTopology(schematic, {\n ...(devices === undefined ? {} : { devices }),\n ...(tolerance === undefined ? {} : { tolerance }),\n });\n if (componentCount > 0 && topology.pins.length === 0) {\n throw new CircuitError(\n 'invalid-options',\n 'The derived topology has no pins; pass the DeviceSymbolProvider that authored the schematic so pins can be located',\n );\n }\n\n const railNames = new Set([\n ...Object.keys(DEFAULT_RAILS),\n ...Object.keys(options.electrical?.rails ?? {}),\n ]);\n const connections: Connection[] = [];\n\n for (const net of topology.nets) {\n const endpoints: string[] = [];\n let rail: string | undefined;\n for (const member of net.members) {\n if (member.kind === 'pin') {\n const deviceId = deviceIdBySymbol.get(member.symbolId);\n if (deviceId === undefined) {\n throw new CircuitError(\n 'unresolved-device',\n `Net \"${net.name ?? 'anonymous'}\" references pin \"${member.pinId}\" of symbol \"${member.symbolId}\", which has no runtime device`,\n { deviceId: member.symbolId },\n );\n }\n endpoints.push(`${deviceId}.${member.pinId}`);\n continue;\n }\n if (member.kind === 'power' || member.kind === 'ground') {\n rail = net.name ?? rail;\n }\n }\n if (endpoints.length === 0) continue;\n // A named net that matches a rail ties its pins to that rail; everything\n // else is joined to the first pin, which the compiler merges transitively.\n const railName = rail ?? (net.name !== null && railNames.has(net.name) ? net.name : undefined);\n if (railName !== undefined) {\n for (const endpoint of endpoints) connections.push({ from: endpoint, to: railName });\n continue;\n }\n const first = endpoints[0] as string;\n for (const endpoint of endpoints.slice(1)) connections.push({ from: first, to: endpoint });\n }\n\n const input: CircuitCompilationInput = {\n devices: Object.freeze(deviceConfigs),\n connections: Object.freeze(connections),\n };\n const circuit = await Circuit.create(input, runtime);\n return Object.freeze({ circuit, bindings: Object.freeze(bindings) });\n}\n\n/**\n * Turns a designator or symbol id into a compiler-safe device id.\n *\n * Device ids prefix generated IR function names, so they must be identifiers.\n */\nfunction uniqueDeviceId(preferred: string, used: ReadonlySet<string>): string {\n const base = sanitizeDeviceId(preferred);\n if (!used.has(base)) return base;\n for (let suffix = 2; ; suffix += 1) {\n const candidate = `${base}_${suffix}`;\n if (!used.has(candidate)) return candidate;\n }\n}\n\nfunction sanitizeDeviceId(value: string): string {\n const cleaned = value.replace(/[^A-Za-z0-9_]/g, '_');\n if (cleaned.length === 0) return 'device';\n return /^[A-Za-z_]/.test(cleaned) ? cleaned : `d_${cleaned}`;\n}\n","import type { SchematicDocument } from '@mica-js/core/schematic';\nimport type { CanvasBindingTarget } from '@mica-js/core/canvas';\nimport { toDisposable } from '@mica-js/core/lifecycle';\nimport type { Circuit } from '../unified-ir/runtime';\nimport type { DeviceSimulationHost, DeviceSimTickReport, DeviceTopic } from './types';\n\n/** Picoseconds per circuit step used when mapping `Circuit.virtualTime` to simulation time. */\nconst DEFAULT_STEP_PS = 10_000;\n\nexport interface CircuitDeviceSimulationHostOptions {\n /** Circuit the caller already created. */\n readonly circuit: Circuit;\n /** Whether `dispose()` also disposes the circuit. Defaults to `true`. */\n readonly ownsCircuit?: boolean;\n /** Schematic the circuit was built from, reported through `getSchematic`. */\n readonly schematic?: SchematicDocument;\n /** Endpoints the running devices expose. */\n readonly topics?: readonly DeviceTopic[];\n /** Picoseconds per circuit step. Defaults to 10 ns. */\n readonly stepPs?: number;\n /** Routes one widget payload into the caller's device layer. */\n readonly deliver: (symbol: string, port: string, payload: unknown) => void;\n}\n\n/**\n * Adapts one already-loaded unified-IR circuit to the RFC 0018 device host.\n *\n * This is the same-thread adapter for an owner that keeps `Circuit` accessors for itself (a\n * diagnostics bench, for example). Application/canvas integration uses\n * `createDeviceSimulationHostFromSandbox` from `@mica-js/simulator/sandbox` and never holds a circuit.\n */\nexport function createCircuitDeviceSimulationHost({\n circuit,\n ownsCircuit = true,\n schematic,\n topics = [],\n stepPs = DEFAULT_STEP_PS,\n deliver,\n}: CircuitDeviceSimulationHostOptions): DeviceSimulationHost {\n const simTime = (): number => circuit.virtualTime * stepPs;\n\n return {\n async loadSchematic() {\n // The caller built the circuit before constructing this adapter.\n },\n async reset() {\n circuit.reset();\n },\n async tick(dt: number): Promise<DeviceSimTickReport> {\n if (!Number.isSafeInteger(dt) || dt <= 0) {\n throw new TypeError(\n `DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`,\n );\n }\n circuit.runBatch(1);\n return { simTime: simTime(), executed: 1 };\n },\n async deliver(target: CanvasBindingTarget, payload: unknown) {\n deliver(target.symbol, target.port, payload);\n },\n onDidPublish: () =>\n toDisposable(() => {\n // The owner drives publishing through its own device layer.\n }),\n async getTopics() {\n return topics;\n },\n async getSimTime() {\n return simTime();\n },\n async getSchematic() {\n return schematic;\n },\n async dispose() {\n if (ownsCircuit) circuit.dispose();\n },\n };\n}\n","import type { DeviceReference, DeviceSymbolProvider } from '@mica-js/core/schematic';\nimport { parseSchematic } from '@mica-js/core/schematic';\nimport type { SchematicDocument } from '@mica-js/core/schematic';\nimport type { CanvasBindingTarget, PayloadType } from '@mica-js/core/canvas';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport { createSchematicCircuit } from '../unified-ir/runtime';\nimport type { Circuit, SchematicDeviceBinding, SchematicDeviceTopic } from '../unified-ir/runtime';\nimport type { DeviceAccessor } from '../unified-ir/runtime/types';\nimport type {\n DeviceSimulationHost,\n DeviceSimTickReport,\n DeviceTopic,\n SimulationPublish,\n} from './types';\n\n/** Reads the bytes of one schematic URI; the caller resolves relative references. */\nexport interface SchematicDeviceSimulationHostOptions {\n readonly read: (uri: string) => Promise<Uint8Array>;\n /**\n * Symbol geometry of the schematics this host loads. Pass the same provider the schematic was\n * authored with; without it the derived topology contains no pins. A factory is called when a\n * schematic loads, so a caller can read its device library first.\n */\n readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);\n /**\n * Resolves one schematic device reference to its runtime description and endpoints.\n *\n * The host ships no device models: the package that owns the devices decides which references\n * exist, what they look like and which topics they expose.\n */\n readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n}\n\ninterface LoadedDevice {\n readonly symbol: string;\n readonly designator: string;\n readonly binding: SchematicDeviceBinding;\n readonly accessor: DeviceAccessor;\n}\n\ninterface LoadedRuntime {\n readonly circuit: Circuit;\n readonly schematic: SchematicDocument;\n readonly devices: readonly LoadedDevice[];\n readonly topics: readonly DeviceTopic[];\n readonly inputs: ReadonlyMap<string, InputBinding>;\n}\n\ninterface InputBinding {\n readonly device: LoadedDevice;\n readonly topic: SchematicDeviceTopic;\n}\n\ninterface PendingDelivery {\n readonly device: LoadedDevice;\n readonly port: string;\n readonly payload: unknown;\n}\n\nconst INSTANCE_ID = 'device-simulation-host';\n\nfunction targetKey(deviceId: string, port: string): string {\n return `${deviceId}\\u0000${port}`;\n}\n\n/**\n * Value equality of two topic payloads.\n *\n * A canvas topic is a `level` unless it carries text or bytes (RFC 0017), so re-sending the value a\n * device already published only costs a widget repaint. Byte payloads compare by content because a\n * device may hand out a fresh buffer per step.\n */\nfunction samePayload(previous: unknown, next: unknown): boolean {\n if (Object.is(previous, next)) return true;\n if (previous instanceof Uint8Array && next instanceof Uint8Array) {\n if (previous.length !== next.length) return false;\n for (let index = 0; index < previous.length; index += 1) {\n if (previous[index] !== next[index]) return false;\n }\n return true;\n }\n if (typeof previous !== 'object' || previous === null) return false;\n if (typeof next !== 'object' || next === null) return false;\n const a = previous as { readonly x?: unknown; readonly y?: unknown; readonly z?: unknown };\n const b = next as { readonly x?: unknown; readonly y?: unknown; readonly z?: unknown };\n return a.x === b.x && a.y === b.y && a.z === b.z;\n}\n\nfunction isVec2d(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) return false;\n const point = value as { readonly x?: unknown; readonly y?: unknown };\n return typeof point.x === 'number' && typeof point.y === 'number';\n}\n\nfunction payloadMatches(type: PayloadType, payload: unknown): boolean {\n switch (type) {\n case 'boolean':\n return typeof payload === 'boolean';\n case 'number':\n return typeof payload === 'number';\n case 'string':\n return typeof payload === 'string';\n case 'bytes':\n case 'bytes<rgb565>':\n case 'bytes<segments>':\n return payload instanceof Uint8Array;\n case 'vec2d':\n return isVec2d(payload);\n case 'vec3d':\n return isVec2d(payload) && typeof (payload as { readonly z?: unknown }).z === 'number';\n }\n}\n\nfunction decodeSchematic(bytes: Uint8Array): SchematicDocument {\n return parseSchematic(new TextDecoder().decode(bytes));\n}\n\nfunction buildRuntime(\n circuit: Circuit,\n schematic: SchematicDocument,\n bindings: Awaited<ReturnType<typeof createSchematicCircuit>>['bindings'],\n resolveDevice: SchematicDeviceSimulationHostOptions['resolveDevice'],\n): LoadedRuntime {\n const symbols = new Map(schematic.sheet.symbols.map((symbol) => [symbol.id, symbol]));\n const devices: LoadedDevice[] = [];\n const topics: DeviceTopic[] = [];\n const inputs = new Map<string, InputBinding>();\n\n for (const binding of bindings) {\n const deviceBinding = resolveDevice(binding.reference);\n const accessor = circuit.devices[binding.deviceId];\n if (deviceBinding === undefined || accessor === undefined) continue;\n const symbol = symbols.get(binding.symbolId);\n const designator = symbol?.designator ?? binding.symbolId;\n const device: LoadedDevice = {\n symbol: binding.symbolId,\n designator,\n binding: deviceBinding,\n accessor,\n };\n devices.push(device);\n for (const topic of deviceBinding.topics ?? []) {\n topics.push({\n symbol: binding.symbolId,\n designator,\n port: topic.port,\n direction: topic.direction,\n type: topic.type,\n ...(topic.title === undefined ? {} : { title: topic.title }),\n });\n if (topic.direction === 'input')\n inputs.set(targetKey(binding.symbolId, topic.port), { device, topic });\n }\n }\n\n return {\n circuit,\n schematic,\n devices,\n topics: Object.freeze(topics),\n inputs,\n };\n}\n\n/**\n * Same-thread `DeviceSimulationHost` over a schematic compiled by the unified-IR runtime.\n *\n * The host owns the circuit: `loadSchematic` reads, parses and compiles it, `tick` advances one\n * circuit step and publishes the output topics that changed, and `deliver` queues widget payloads\n * for the next step. Device models and their endpoints come from `resolveDevice`, so the host stays\n * generic. Nothing here touches the DOM, so the sandbox guest and a Node test use the same\n * implementation.\n */\nexport function createSchematicDeviceSimulationHost(\n options: SchematicDeviceSimulationHostOptions,\n): DeviceSimulationHost {\n if (typeof options?.resolveDevice !== 'function') {\n throw new TypeError('createSchematicDeviceSimulationHost needs a resolveDevice function');\n }\n const { read, devices: symbols, resolveDevice } = options;\n const publishes = new Emitter<SimulationPublish>();\n const pending: PendingDelivery[] = [];\n /** Last payload published per endpoint, so an unchanged level topic stays silent. */\n const published = new Map<string, unknown>();\n let runtime: LoadedRuntime | undefined;\n let simTimePs = 0;\n let disposed = false;\n\n const publishOutputs = (active: LoadedRuntime): void => {\n if (!publishes.hasListeners) return;\n for (const device of active.devices) {\n for (const topic of device.binding.topics ?? []) {\n if (topic.direction !== 'output' || device.binding.read === undefined) continue;\n const key = targetKey(device.symbol, topic.port);\n const payload = device.binding.read(device.accessor, topic.port);\n // Only a change is news to a level port; repeating it would make every widget repaint on\n // every step the circuit does not touch.\n if (published.has(key) && samePayload(published.get(key), payload)) continue;\n published.set(key, payload);\n const publish: SimulationPublish = {\n target: { symbol: device.symbol, port: topic.port },\n payload,\n simTime: simTimePs,\n };\n publishes.fire(publish);\n }\n }\n };\n\n const clearRuntime = (): void => {\n runtime?.circuit.dispose();\n runtime = undefined;\n pending.length = 0;\n published.clear();\n simTimePs = 0;\n };\n\n return {\n async loadSchematic(uri: string | undefined): Promise<void> {\n if (disposed) return;\n if (uri === undefined) {\n clearRuntime();\n return;\n }\n const bytes = await read(uri);\n const schematic = decodeSchematic(bytes);\n const symbolProvider = typeof symbols === 'function' ? symbols() : symbols;\n const compiled = await createSchematicCircuit(schematic, {\n ...(symbolProvider === undefined ? {} : { devices: symbolProvider }),\n resolveDevice,\n instanceId: INSTANCE_ID,\n });\n const next = buildRuntime(compiled.circuit, schematic, compiled.bindings, resolveDevice);\n runtime?.circuit.dispose();\n pending.length = 0;\n // A fresh runtime starts from its initial state, so the first step after it publishes again.\n published.clear();\n simTimePs = 0;\n runtime = next;\n },\n\n async reset(): Promise<void> {\n if (disposed) return;\n pending.length = 0;\n published.clear();\n simTimePs = 0;\n runtime?.circuit.reset();\n },\n\n async tick(dt: number): Promise<DeviceSimTickReport> {\n if (!Number.isSafeInteger(dt) || dt <= 0) {\n throw new TypeError(\n `DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`,\n );\n }\n if (disposed) {\n return { simTime: simTimePs, executed: 0 };\n }\n const active = runtime;\n if (active === undefined) {\n simTimePs += dt;\n return { simTime: simTimePs, executed: 0 };\n }\n const queued = pending.splice(0, pending.length);\n for (const delivery of queued) {\n if (delivery.device.binding.deliver === undefined) {\n throw new TypeError(\n `${delivery.device.binding.type} has no writable topic ${JSON.stringify(delivery.port)}`,\n );\n }\n delivery.device.binding.deliver(delivery.device.accessor, delivery.port, delivery.payload);\n }\n active.circuit.runBatch(1);\n simTimePs += dt;\n publishOutputs(active);\n return { simTime: simTimePs, executed: 1 };\n },\n\n async deliver(target: CanvasBindingTarget, payload: unknown): Promise<void> {\n if (disposed) return;\n const active = runtime;\n if (active === undefined) {\n throw new Error('DeviceSimulationHost has no loaded schematic');\n }\n const binding = active.inputs.get(targetKey(target.symbol, target.port));\n if (binding === undefined) {\n throw new Error(`Unknown device input ${target.symbol}.${target.port}`);\n }\n if (!payloadMatches(binding.topic.type, payload)) {\n throw new TypeError(\n `${target.symbol}.${target.port} expects a ${binding.topic.type} payload`,\n );\n }\n const device = binding.device;\n if (device.binding.deliver === undefined) {\n throw new Error(\n `${device.binding.type} has no writable topic ${JSON.stringify(target.port)}`,\n );\n }\n pending.push({ device, port: target.port, payload });\n },\n\n onDidPublish: publishes.event,\n\n async getTopics(): Promise<readonly DeviceTopic[]> {\n return runtime?.topics ?? [];\n },\n\n async getSimTime(): Promise<number> {\n return simTimePs;\n },\n\n async getSchematic(): Promise<SchematicDocument | undefined> {\n return runtime?.schematic;\n },\n\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n publishes.dispose();\n clearRuntime();\n },\n };\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport { loggerService } from '@mica-js/core/logging';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { DeviceReference, DeviceSymbolProvider } from '@mica-js/core/schematic';\nimport type { SchematicDeviceBinding } from '../unified-ir/runtime';\nimport { deviceSimulationHostFileSystemService, deviceSimulationHostGuestService } from './rpc';\nimport type { DeviceSimulationHostRpc } from './rpc';\nimport { createSchematicDeviceSimulationHost } from './runtime';\n\n/**\n * Device wiring a worker script hands to {@link startDeviceSimulationHostGuest}.\n *\n * The simulator ships no device models, so every option defaults to \"knows no references\": a\n * package that owns devices bundles its own worker script and supplies these.\n */\nexport interface DeviceSimulationHostGuestOptions {\n /** Symbol geometry of the schematics this guest loads, or a factory called per load. */\n readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);\n /** Resolves a schematic device reference; when omitted every reference stays unresolved. */\n readonly resolveDevice?: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n /**\n * Awaited before the first schematic load, so a device library can be read through the host file\n * system before anything compiles. Runs at most once.\n */\n readonly prepare?: () => Promise<void>;\n /**\n * Extra ports the worker received in the first ordinary message. The RPC port comes first, so these are\n * `event.ports` from index 1 onward, in the order the caller transferred them. The first one is\n * the direct topic channel (RFC 0018): the widget guest holds the other end and talks to this\n * guest without the host relaying.\n */\n readonly ports?: readonly MessagePort[];\n}\n\n/** Running guest: where the typed services live and which ports the worker was handed. */\nexport interface DeviceSimulationHostGuest {\n /**\n * Endpoint the typed device simulation services are registered on. A worker script that owns\n * further capabilities registers them here instead of opening a second sandbox channel.\n */\n readonly rpc: RpcEndpoint;\n /** Extra startup ports, in the order the worker received them. */\n readonly ports: readonly MessagePort[];\n /** Releases the circuit and closes the endpoint. */\n dispose(): Promise<void>;\n}\n\n/**\n * Registers RFC 0018's device simulation services on a sandbox RPC port.\n *\n * A worker script obtains the port from `event.ports[0]` and calls this function; nothing else is\n * needed, because the guest is a plain module the `@mica-js/sandbox/vite` plugin bundles into a\n * self-contained script. The guest registers `deviceSimulationHostGuestService` and reads schematics\n * through `deviceSimulationHostFileSystemService`, so schematic bytes never enter the guest's own\n * message handling and every payload is a typed RPC DTO.\n */\nexport function startDeviceSimulationHostGuest(\n port: MessagePort,\n options: DeviceSimulationHostGuestOptions = {},\n): DeviceSimulationHostGuest {\n const { devices, resolveDevice, prepare, ports = [] } = options;\n const rpc = createRpc(port);\n const logger = rpc.getProxy(loggerService);\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'guest-started',\n data: [{ extraPortCount: ports.length }],\n })\n .catch(() => undefined);\n const files = rpc.getProxy(deviceSimulationHostFileSystemService);\n const host = createSchematicDeviceSimulationHost({\n async read(uri: string): Promise<Uint8Array> {\n const bytes = await files.read(uri);\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError(`DeviceSimulationHost file system returned ${typeof bytes} for ${uri}`);\n }\n return bytes;\n },\n ...(devices === undefined ? {} : { devices }),\n resolveDevice: resolveDevice ?? (() => undefined),\n });\n\n let prepared: Promise<void> | undefined;\n const ensurePrepared = async (): Promise<void> => {\n if (prepare === undefined) return;\n prepared ??= prepare();\n try {\n await prepared;\n } catch (error) {\n // A failed preparation must not poison later loads: forget it so the next call retries.\n prepared = undefined;\n throw error;\n }\n };\n\n const service: DeviceSimulationHostRpc = {\n async loadSchematic(uri: string | undefined): Promise<void> {\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'load-schematic-start',\n data: [uri],\n })\n .catch(() => undefined);\n try {\n if (uri !== undefined) await ensurePrepared();\n await host.loadSchematic(uri);\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'load-schematic-end',\n data: [uri],\n })\n .catch(() => undefined);\n } catch (error) {\n void logger\n .write({\n level: 'error',\n scope: 'device-simulation',\n message: 'load-schematic-failed',\n data: [uri, String(error)],\n })\n .catch(() => undefined);\n throw error;\n }\n },\n async reset(): Promise<void> {\n await ensurePrepared();\n return host.reset();\n },\n tick: (dt: number) => host.tick(dt),\n deliver: (target, payload, simTime) => host.deliver(target, payload, simTime),\n onDidPublish: (listener) => {\n const subscription = host.onDidPublish(listener);\n return () => subscription.dispose();\n },\n getTopics: () => host.getTopics(),\n getSimTime: () => host.getSimTime(),\n getSchematic: () => host.getSchematic(),\n dispose: () => host.dispose(),\n };\n\n const registration = rpc.register(deviceSimulationHostGuestService, service);\n\n // The direct topic channel registers the same contract on the extra port, so the widget guest can\n // deliver and subscribe without the host in between. It only calls `deliver` and `onDidPublish`;\n // schematic, topics and the clock stay the host's business.\n const topicPort = ports[0];\n const topicRpc = topicPort === undefined ? undefined : createRpc(topicPort);\n const topicRegistration = topicRpc?.register(deviceSimulationHostGuestService, service);\n\n let disposed = false;\n return {\n rpc,\n ports,\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n topicRegistration?.dispose();\n topicRpc?.dispose();\n registration.dispose();\n await host.dispose();\n rpc.dispose();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAcA,SAAgB,uBACd,QACA,kBAAuC,CAAC,GACnB;CACrB,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,MAAM,OAAO,W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,IAAI,QAAQ,KAAA,GAAW,MAAM,eAAe;IAC5C,MAAM,KAAK,cAAc,GAAG;IAC5B,OACG,MAAM;KACL,OAAO;KACP,OAAO;KACP,SAAS;KACT,MAAM,CAAC,GAAG;IACZ,CAAC,CAAC,CACD,YAAY,KAAA,CAAS;GAC1B,SAAS,OAAO;IACd,OACG,MAAM;KACL,OAAO;KACP,OAAO;KACP,SAAS;KACT,MAAM,CAAC,KAAK,OAAO,KAAK,CAAC;IAC3B,CAAC,CAAC,CACD,YAAY,KAAA,CAAS;IACxB,MAAM;GACR;EACF;EACA,MAAM,QAAuB;GAC3B,MAAM,eAAe;GACrB,OAAO,KAAK,MAAM;EACpB;EACA,OAAO,OAAe,KAAK,KAAK,EAAE;EAClC,UAAU,QAAQ,SAAS,YAAY,KAAK,QAAQ,QAAQ,SAAS,OAAO;EAC5E,eAAe,aAAa;GAC1B,MAAM,eAAe,KAAK,aAAa,QAAQ;GAC/C,aAAa,aAAa,QAAQ;EACpC;EACA,iBAAiB,KAAK,UAAU;EAChC,kBAAkB,KAAK,WAAW;EAClC,oBAAoB,KAAK,aAAa;EACtC,eAAe,KAAK,QAAQ;CAC9B;CAEA,MAAM,eAAe,IAAI,SAAS,kCAAkC,OAAO;CAK3E,MAAM,YAAY,MAAM;CACxB,MAAM,WAAW,cAAc,KAAA,IAAY,KAAA,IAAY,UAAU,SAAS;CAC1E,MAAM,oBAAoB,UAAU,SAAS,kCAAkC,OAAO;CAEtF,IAAI,WAAW;CACf,OAAO;EACL;EACA;EACA,MAAM,UAAyB;GAC7B,IAAI,UAAU;GACd,WAAW;GACX,mBAAmB,QAAQ;GAC3B,UAAU,QAAQ;GAClB,aAAa,QAAQ;GACrB,MAAM,KAAK,QAAQ;GACnB,IAAI,QAAQ;EACd;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/unified-ir/validation.ts","../src/unified-ir/pin-space.ts","../src/unified-ir/compiler/types.ts","../src/unified-ir/compiler/allocator.ts","../src/unified-ir/compiler/device-gen.ts","../src/unified-ir/compiler/mainloop-gen.ts","../src/unified-ir/compiler/solver-gen.ts","../src/unified-ir/compiler/topology.ts","../src/unified-ir/compiler/index.ts","../src/unified-ir/runtime/types.ts","../src/unified-ir/runtime/accessors.ts","../src/unified-ir/runtime/circuit.ts","../src/unified-ir/runtime/factory.ts","../src/host/circuit-host.ts","../src/host/runtime.ts","../src/host/guest.ts"],"sourcesContent":["import type { BytesRef, IRModule, IRResourcePermission, IRValidationOptions } from '@mica-js/ir';\n\n/**\n * Builds the validation grants a module needs to run on the reference engine or\n * the JIT: every instruction the model uses, authorized once, plus a grant for\n * each declared memory.\n *\n * `@mica-js/ir` deliberately keeps its core instruction list internal, so the\n * names are collected from the generated bodies instead of being restated here.\n *\n * @param module - Generated module whose bodies and memories are granted.\n * @param updateResources - Read-only byte regions that opt into the host-only\n * versioned update path (for example MCU firmware patching).\n */\nexport function createModuleValidation(\n module: IRModule,\n updateResources: readonly BytesRef[] = [],\n): IRValidationOptions {\n const names = new Set<string>();\n for (const fn of module.functions) {\n const body = fn.body;\n if (body === undefined) continue;\n // `body.blocks` already contains the entry block.\n for (const block of body.blocks) {\n for (const instruction of block.instructions) names.add(instruction.op);\n if (block.terminator !== undefined) names.add(block.terminator.kind);\n }\n }\n const instructions = Object.freeze([...names]);\n const resources: IRResourcePermission[] = module.memories.map((memory) =>\n Object.freeze({\n ref: memory.ref,\n access: memory.writable ? ('read-write' as const) : ('read' as const),\n }),\n );\n // Read-only byte regions such as firmware stay unreadable to guest stores but\n // can opt into the host-only versioned update path (`patchFirmware`).\n const memories = new Set(module.memories.map((memory) => memory.ref));\n for (const ref of new Set(updateResources)) {\n if (!memories.has(ref)) continue;\n resources.push(Object.freeze({ ref, access: 'update' as const }));\n }\n return Object.freeze({\n supportedInstructions: instructions,\n authorizedInstructions: instructions,\n resources: Object.freeze(resources),\n });\n}\n","/**\n * Shared memory-layout constants of the unified IR compiler and devices.\n *\n * Every device of a circuit shares one global pin address space, so the\n * compiler and every device kernel must agree on the capacity, the per-device\n * stride and the meaning of a `pin_mode` slot. Capacity and stride are limits\n * checked at allocation time; the shared pin memories are sized to the pins a\n * circuit actually declares, so a larger ceiling costs no runtime memory.\n */\n\n/** Global pin addresses available to one circuit (8 devices x 512 pins). */\nexport const UNIFIED_PIN_CAPACITY = 4096;\n\n/** Global pin addresses one device may own; enough for the largest packages. */\nexport const DEVICE_PIN_STRIDE = 512;\n\n/** Values stored in the global `pin_mode` array. */\nexport const PIN_MODE = Object.freeze({\n highZ: 0,\n pushPull: 1,\n openDrain: 2,\n analog: 3,\n} as const);\n\n/** One value of the global `pin_mode` array. */\nexport type PinMode = (typeof PIN_MODE)[keyof typeof PIN_MODE];\n","import type {\n ArrayRef,\n BytesRef,\n FunctionBuilder,\n FunctionRef,\n IRModule,\n IRValidationOptions,\n ScalarType,\n Value,\n} from '@mica-js/ir';\n\n/**\n * Types for the unified IR compiler (U01).\n *\n * The compiler turns several device descriptions plus a pin-to-pin netlist into\n * one `@mica-js/ir` module. Device logic, the electrical solve and the main\n * loop all share one global pin space, one state space and one engine entry, so\n * a tick costs one interpreter/JIT call for the whole circuit.\n *\n * The shared constants (`UNIFIED_PIN_CAPACITY`, `DEVICE_PIN_STRIDE`, `PIN_MODE`)\n * live in `../pin-space` and are reused here. The compiler ships no device\n * models: every description is supplied by the caller.\n */\n\n/** Electrical intent of one device pin. */\nexport type DevicePinDirection = 'input' | 'output' | 'bidirectional' | 'passive';\n\n/** Role a pin plays on its net; v1 supports one driver per net. */\nexport type CompiledPinRole = 'driver' | 'load';\n\n/** One pin declared by a device description. */\nexport interface DevicePinDescription {\n /** Defaults to `'passive'`: the pin only senses the net. */\n readonly direction?: DevicePinDirection;\n /** Overrides the role derived from `direction`. */\n readonly role?: CompiledPinRole;\n /** Purely informational kind, e.g. `'signal'`, `'power'`, `'gnd'`. */\n readonly kind?: string;\n}\n\n/**\n * Declared pins of one device. A `Map` keeps duplicate names impossible and an\n * object keeps authored descriptions terse; both preserve declaration order.\n */\nexport type DevicePinMap =\n ReadonlyMap<string, DevicePinDescription> | Readonly<Record<string, DevicePinDescription>>;\n\n/** One scalar internal state of a device, allocated in the global state space. */\nexport interface DeviceStateDescription {\n readonly type: ScalarType;\n readonly initial: boolean | number;\n}\n\n/** Pin operations a behavior may use; each call inlines into global memory. */\nexport interface DevicePinHandle {\n readonly name: string;\n readonly globalId: number;\n /** `pin.configure`: writes `pin_mode[globalId]`. */\n configure(mode: number): void;\n /** `pin.write_digital`: writes `pin_output[globalId]`. */\n writeDigital(level: Value<'bool'>): void;\n /** `pin.sample_digital`: reads the solved `pin_input[globalId]`. */\n sampleDigital(): Value<'bool'>;\n /** Reads the device's own `pin_output[globalId]`. */\n readDrivenDigital(): Value<'bool'>;\n}\n\n/** Internal state slot a behavior may read and write. */\nexport interface DeviceStateHandle<T extends ScalarType = ScalarType> {\n readonly name: string;\n readonly type: T;\n /** Index inside the generated `device_state_<type>` array. */\n readonly index: number;\n load(): Value<T>;\n store(value: Value<T>): void;\n}\n\n/** One pin as seen by a device kernel factory (no builder attached yet). */\nexport interface DeviceKernelPin {\n readonly name: string;\n readonly globalPinId: number;\n readonly role: CompiledPinRole;\n}\n\n/**\n * Everything a complex device kernel needs to declare its own IR before any\n * phase function body is opened: the module (for `array`/`bytes`/`provider`),\n * the shared pin memories and the allocated pin ids.\n */\nexport interface DeviceKernelContext {\n readonly deviceId: string;\n readonly config: Readonly<Record<string, unknown>> | undefined;\n readonly module: IRModule;\n readonly memory: CompiledCircuitMemory;\n readonly pins: readonly DeviceKernelPin[];\n}\n\n/**\n * Direct phase refs a complex kernel may return instead of behaviour hooks.\n * The compiler then uses these functions as the device's loop entries, with\n * no wrapper phase around them.\n */\nexport interface DeviceKernelRuntime {\n readonly initialize?: FunctionRef<readonly [], readonly []>;\n readonly tick?: FunctionRef<readonly [], readonly []>;\n readonly update?: FunctionRef<readonly [], readonly []>;\n}\n\n/**\n * Builds the phase hooks of a complex device after resource allocation but\n * before phase functions are generated. Declaring arrays, byte memories and\n * providers is only legal here (never inside a function body).\n *\n * Returning {@link DeviceKernelRuntime} lets the kernel own its phase\n * functions directly; returning {@link DeviceBehaviors} asks the compiler to\n * generate `<id>_initialize` / `<id>_tick` / `<id>_update` wrappers.\n */\nexport type DeviceKernelFactory = (\n context: DeviceKernelContext,\n) => DeviceBehaviors | DeviceKernelRuntime;\n\n/** Build surface handed to one device behavior. */\nexport interface DeviceBehaviorApi {\n readonly deviceId: string;\n readonly builder: FunctionBuilder<readonly []>;\n /**\n * Module the phase is generated into. Complex devices use it to declare\n * their own typed arrays (`module.array`, `module.bytes`) and providers;\n * simple devices never need to touch it.\n */\n readonly module: IRModule;\n /** Shared `pin_mode` / `pin_output` / `pin_input` memories. */\n readonly memory: CompiledCircuitMemory;\n /** Instance configuration from {@link DeviceConfig.config}. */\n readonly config: Readonly<Record<string, unknown>> | undefined;\n /** Every declared pin of the device, in declaration order. */\n readonly pins: readonly DevicePinHandle[];\n /** Pins whose role is `driver`. */\n readonly outputs: readonly DevicePinHandle[];\n pin(name: string): DevicePinHandle;\n state<T extends ScalarType = ScalarType>(name: string): DeviceStateHandle<T>;\n}\n\n/**\n * Structural surface every device accessor exposes.\n *\n * The compiler keeps this declaration independent from the runtime's\n * `DeviceAccessor` so a device kernel can ship its own typed accessor without\n * making the compiler depend on the runtime module.\n */\nexport interface DeviceAccessorSurface {\n readonly deviceId: string;\n readonly type: string;\n readonly pinNames: readonly string[];\n readonly stateNames: readonly string[];\n readPin(pinName: string): boolean;\n writePin(pinName: string, value: boolean): void;\n getState(name: string): unknown;\n setState(name: string, value: unknown): void;\n}\n\n/** Host services handed to a device accessor factory at circuit creation. */\nexport interface DeviceAccessorFactoryContext {\n readonly deviceId: string;\n /** Live engine storage (`IRStorage` in practice). */\n readonly storage: unknown;\n /** Throws once the owning circuit has been disposed. */\n readonly assertActive: () => void;\n /** Advances the owning circuit by one tick. */\n readonly step: () => void;\n /** Advances the owning circuit by `count` ticks. */\n readonly runBatch: (count: number) => void;\n}\n\n/**\n * Builds the typed accessor of a device after its module is compiled.\n *\n * A description that supplies `accessor` replaces the generic accessor the\n * runtime would otherwise synthesize from `type`. The factory runs once per\n * circuit and closes over the layout its IR factory allocated.\n */\nexport type DeviceAccessorFactory = (\n context: DeviceAccessorFactoryContext,\n) => DeviceAccessorSurface;\n\n/**\n * Per-device behavior hooks. The compiler emits one IR function per hook:\n * `initialize` -> `<id>_initialize`, `tick` -> `<id>_tick`,\n * `update` -> `<id>_update`. Missing hooks simply produce no function.\n */\nexport interface DeviceBehaviors {\n readonly initialize?: (api: DeviceBehaviorApi) => void;\n readonly tick?: (api: DeviceBehaviorApi) => void;\n readonly update?: (api: DeviceBehaviorApi) => void;\n}\n\n/** IR-level device description consumed by the compiler. */\nexport interface DeviceDescription {\n readonly name?: string;\n readonly pins: DevicePinMap;\n readonly states?: Readonly<Record<string, DeviceStateDescription>>;\n readonly behaviors?: DeviceBehaviors;\n /**\n * Complex-kernel hook. Runs once per module before phase generation so the\n * kernel may declare typed arrays, byte memories and providers, then return\n * the behaviour hooks the compiler should call inside each phase.\n */\n readonly kernel?: DeviceKernelFactory;\n /**\n * Optional typed accessor factory. Kernels with a richer surface than the\n * generic state/pin accessor (a register file, a memory map) use it.\n */\n readonly accessor?: DeviceAccessorFactory;\n /**\n * Read-only byte regions the kernel wants host updates for. The compiler\n * grants `update` access on top of the normal `read` grant so kernels can\n * expose firmware patching without allowing guest stores.\n */\n readonly updateResources?: readonly BytesRef[];\n}\n\n/** One device instance of the circuit. */\nexport interface DeviceConfig {\n /** Circuit-unique identity; prefix of every generated function name. */\n readonly id: string;\n /** Device type, e.g. `'push-pull-driver'`; free-form label of the device model. */\n readonly type: string;\n readonly description: DeviceDescription;\n /** Instance configuration; reserved for device kernels that take parameters. */\n readonly config?: Readonly<Record<string, unknown>>;\n}\n\n/** One pin-to-pin (or pin-to-rail) connection. */\nexport interface Connection {\n /** `'mcu1.PA0'` or a rail name such as `'GND'`. */\n readonly from: string;\n readonly to: string;\n}\n\n/** Options for the compiler. */\nexport interface CircuitCompilationOptions {\n /** Named fixed-level rails; merged over `GND`/`VCC`/`VDD`. */\n readonly rails?: Readonly<Record<string, boolean>>;\n /** Runs `validateIR` over the generated module. Defaults to `true`. */\n readonly validate?: boolean;\n /** Overrides for the generated entry-point names. */\n readonly entryPointNames?: {\n readonly tick?: string;\n readonly initialize?: string;\n readonly batch?: string;\n };\n}\n\n/** Compiler input: devices plus the connections between their pins. */\nexport interface CircuitCompilationInput {\n readonly devices: readonly DeviceConfig[];\n readonly connections: readonly Connection[];\n}\n\n/** One resolved pin in the global pin space. */\nexport interface ResolvedDevicePin {\n readonly name: string;\n readonly deviceId: string;\n readonly globalPinId: number;\n readonly direction: DevicePinDirection;\n readonly role: CompiledPinRole;\n /** Whether the device reads the solved value of this pin. */\n readonly senses: boolean;\n}\n\n/** Pins of one device mapped into the global pin space. */\nexport interface DevicePinAllocation {\n readonly deviceId: string;\n /** First global pin id of the device. */\n readonly offset: number;\n readonly pins: ReadonlyMap<string, number>;\n readonly resolved: ReadonlyMap<string, ResolvedDevicePin>;\n}\n\n/** Result of the global pin allocation. */\nexport interface GlobalPinMap {\n /** `'mcu1.PA0'` -> global pin id. */\n readonly pins: ReadonlyMap<string, number>;\n readonly devices: ReadonlyMap<string, DevicePinAllocation>;\n readonly totalPins: number;\n readonly capacity: number;\n}\n\n/** One device state slot inside the global state space. */\nexport interface DeviceStateSlot {\n readonly name: string;\n readonly deviceId: string;\n readonly type: ScalarType;\n /** Generated array that holds the slot. */\n readonly array: ArrayRef;\n /** Index inside {@link array}. */\n readonly index: number;\n /** Ordinal in the whole state space, across scalar types. */\n readonly slot: number;\n}\n\n/** Result of the global state allocation. */\nexport interface GlobalStateMap {\n readonly devices: ReadonlyMap<string, ReadonlyMap<string, DeviceStateSlot>>;\n /** One generated array per scalar type actually used. */\n readonly arrays: ReadonlyMap<ScalarType, ArrayRef>;\n /** Slot count per scalar type. */\n readonly totals: ReadonlyMap<ScalarType, number>;\n readonly totalStates: number;\n}\n\n/** Pin memories every device and every net solver shares. */\nexport interface CompiledCircuitMemory {\n readonly mode: ArrayRef<'u8'>;\n readonly output: ArrayRef<'bool'>;\n readonly input: ArrayRef<'bool'>;\n}\n\n/** One pin resolved onto a net. */\nexport interface CompiledPinConnection {\n /** `'mcu1.PA0'`. */\n readonly endpoint: string;\n readonly deviceId: string;\n readonly pinName: string;\n readonly globalPinId: number;\n readonly role: CompiledPinRole;\n readonly senses: boolean;\n}\n\n/** One fixed-level rail on a net, e.g. `GND` (low) or `VCC` (high). */\nexport interface CompiledRail {\n readonly name: string;\n readonly level: boolean;\n}\n\n/** Where a net's level comes from. */\nexport type CompiledNetSource = 'driver' | 'rail' | 'floating';\n\n/** One electrical net: a connected component of pins and rails. */\nexport interface CompiledNet {\n readonly netId: number;\n readonly pins: readonly CompiledPinConnection[];\n readonly rails: readonly CompiledRail[];\n readonly drivers: readonly CompiledPinConnection[];\n /** Pins whose role is `load`. */\n readonly loads: readonly CompiledPinConnection[];\n /** Every pin that reads the solved level, including bidirectional drivers. */\n readonly sinks: readonly CompiledPinConnection[];\n readonly source: CompiledNetSource;\n /** Constant level of a driver-less net; unused when `source === 'driver'`. */\n readonly level: boolean;\n}\n\n/** Diagnostic codes produced by the compiler's electrical analysis. */\nexport type CompilationDiagnosticCode = 'power-short' | 'rail-conflict' | 'floating-net';\n\nexport type CompilationDiagnosticSeverity = 'error' | 'warning';\n\n/** One electrical-analysis finding; errors abort `compileCircuit`. */\nexport interface CompilationDiagnostic {\n readonly code: CompilationDiagnosticCode;\n readonly severity: CompilationDiagnosticSeverity;\n readonly message: string;\n readonly netId: number | undefined;\n readonly endpoints: readonly string[];\n}\n\n/** Result of the network topology analysis. */\nexport interface CompiledNetlist {\n readonly nets: readonly CompiledNet[];\n readonly diagnostics: readonly CompilationDiagnostic[];\n}\n\n/** Metadata of one compiled device. */\nexport interface DeviceMetadata {\n readonly deviceId: string;\n readonly type: string;\n /** First global pin id of the device. */\n readonly pinOffset: number;\n /** First slot ordinal of the device in the global state space. */\n readonly stateOffset: number;\n readonly pins: ReadonlyMap<string, number>;\n readonly states: ReadonlyMap<string, DeviceStateSlot>;\n /** Every IR function generated for this device. */\n readonly functions: readonly string[];\n readonly initialize: string | undefined;\n readonly tick: string | undefined;\n readonly update: string | undefined;\n /** Typed accessor factory supplied by the device description, if any. */\n readonly accessor: DeviceAccessorFactory | undefined;\n /** Kernel factory that generated the device's extra IR resources. */\n readonly kernel: DeviceKernelFactory | undefined;\n}\n\n/** Generated entry points, both by name and as executable refs. */\nexport interface CompiledEntryPoints {\n readonly tick: string;\n readonly initialize: string;\n readonly batch: string;\n readonly refs: {\n readonly tick: FunctionRef<readonly [], readonly []>;\n readonly initialize: FunctionRef<readonly [], readonly []>;\n readonly batch: FunctionRef<readonly ['u32'], readonly []>;\n };\n}\n\n/** The compiled circuit: one module for every device, net and the main loop. */\nexport interface CompiledCircuit {\n readonly module: IRModule;\n readonly entryPoints: CompiledEntryPoints;\n /** `'mcu1.PA0'` -> global pin id. */\n readonly pinMap: ReadonlyMap<string, number>;\n readonly deviceMap: ReadonlyMap<string, DeviceMetadata>;\n readonly netlist: CompiledNetlist;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n readonly memory: CompiledCircuitMemory;\n /** Validation grants covering every instruction and memory of the module. */\n readonly validation: IRValidationOptions;\n /** Device ids in dependency order (drivers before the devices they feed). */\n readonly executionOrder: readonly string[];\n /** Every generated function name, in definition order. */\n readonly functions: readonly string[];\n}\n\n/** Error codes raised by {@link UnifiedIRCompilerError}. */\nexport type UnifiedIRCompilerErrorCode =\n | 'invalid-input'\n | 'duplicate-device'\n | 'unknown-device'\n | 'pin-not-found'\n | 'state-not-found'\n | 'invalid-connection'\n | 'capacity-exceeded'\n | 'unsupported-device'\n | 'power-short'\n | 'rail-conflict'\n | 'invalid-ir';\n\nexport interface UnifiedIRCompilerErrorOptions {\n readonly deviceId?: string;\n readonly pinName?: string;\n readonly netId?: number;\n readonly diagnostics?: readonly CompilationDiagnostic[];\n readonly cause?: unknown;\n}\n\n/** Error raised while compiling a circuit. */\nexport class UnifiedIRCompilerError extends Error {\n override readonly name = 'UnifiedIRCompilerError';\n readonly code: UnifiedIRCompilerErrorCode;\n readonly deviceId: string | undefined;\n readonly pinName: string | undefined;\n readonly netId: number | undefined;\n readonly diagnostics: readonly CompilationDiagnostic[];\n\n constructor(\n code: UnifiedIRCompilerErrorCode,\n message: string,\n options: UnifiedIRCompilerErrorOptions = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.code = code;\n this.deviceId = options.deviceId;\n this.pinName = options.pinName;\n this.netId = options.netId;\n this.diagnostics = options.diagnostics ?? [];\n }\n}\n","import { INTEGER_TYPES, SCALAR_TYPES } from '@mica-js/ir';\nimport type { ArrayRef, IRModule, ScalarType } from '@mica-js/ir';\nimport { DEVICE_PIN_STRIDE, PIN_MODE, UNIFIED_PIN_CAPACITY } from '../pin-space';\nimport {\n UnifiedIRCompilerError,\n type CompiledCircuitMemory,\n type DeviceConfig,\n type DevicePinAllocation,\n type DevicePinDescription,\n type DevicePinDirection,\n type DeviceStateDescription,\n type DeviceStateSlot,\n type GlobalPinMap,\n type GlobalStateMap,\n type ResolvedDevicePin,\n} from './types';\n\n/** Generated device ids prefix IR function names, so they must be identifiers. */\nconst DEVICE_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Everything the compiler allocates before a single instruction is generated. */\nexport interface ResourceAllocation {\n readonly memory: CompiledCircuitMemory;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n}\n\n/**\n * Allocates the circuit-wide pin and state address spaces.\n *\n * ```\n * ids: 0 = drive1.PA0 1 = drive1.PA1 2 = sink1.anode 3 = sink1.cathode\n * |<-- drive1 -->| |<----------- sink1 ----------->|\n *\n * pin_mode[n] u8 pin_output[n] bool pin_input[n] bool (n = totalPins)\n * device_state_bool[n] / device_state_u32[m] / ... (one array per used type)\n * ```\n *\n * Pins are packed in declaration order across devices — the addresses the\n * device IR and every net solver embed as constants. States are packed per\n * scalar type into one shared array, so a device's slot stays typed while all\n * devices share one storage region.\n */\nexport class GlobalResourceAllocator {\n private readonly module: IRModule;\n\n constructor(module: IRModule) {\n this.module = module;\n }\n\n /** Allocates the shared pin memories, the pin space and the state space. */\n allocate(devices: readonly DeviceConfig[]): ResourceAllocation {\n const pins = this.allocatePins(devices);\n return Object.freeze({\n memory: createPinMemory(this.module, Math.max(1, pins.totalPins)),\n pins,\n states: this.allocateStates(devices),\n });\n }\n\n /**\n * Packs every device pin into one contiguous global address space.\n *\n * @throws {UnifiedIRCompilerError} on invalid or duplicate device ids, more\n * than {@link DEVICE_PIN_STRIDE} pins for one device, or more than\n * {@link UNIFIED_PIN_CAPACITY} pins for the circuit.\n */\n allocatePins(devices: readonly DeviceConfig[]): GlobalPinMap {\n assertDeviceList(devices);\n\n let totalPins = 0;\n const pins = new Map<string, number>();\n const allocations = new Map<string, DevicePinAllocation>();\n\n for (const device of devices) {\n const entries = pinEntries(device);\n if (entries.length > DEVICE_PIN_STRIDE) {\n throw new UnifiedIRCompilerError(\n 'capacity-exceeded',\n `Device \"${device.id}\" declares ${entries.length} pins; one device may own at most ${DEVICE_PIN_STRIDE}`,\n { deviceId: device.id },\n );\n }\n if (totalPins + entries.length > UNIFIED_PIN_CAPACITY) {\n throw new UnifiedIRCompilerError(\n 'capacity-exceeded',\n `Device \"${device.id}\" does not fit: the circuit already uses ${totalPins} of ${UNIFIED_PIN_CAPACITY} global pins`,\n { deviceId: device.id },\n );\n }\n\n const offset = totalPins;\n const devicePins = new Map<string, number>();\n const resolved = new Map<string, ResolvedDevicePin>();\n\n for (const [name, descriptor] of entries) {\n const globalPinId = totalPins;\n totalPins += 1;\n const direction = resolvePinDirection(descriptor, device.id, name);\n const { role, senses } = resolvePinRole(direction, descriptor?.role, device.id, name);\n devicePins.set(name, globalPinId);\n resolved.set(\n name,\n Object.freeze({\n name,\n deviceId: device.id,\n globalPinId,\n direction,\n role,\n senses,\n }),\n );\n pins.set(`${device.id}.${name}`, globalPinId);\n }\n\n allocations.set(\n device.id,\n Object.freeze({ deviceId: device.id, offset, pins: devicePins, resolved }),\n );\n }\n\n return Object.freeze({\n pins,\n devices: allocations,\n totalPins,\n capacity: UNIFIED_PIN_CAPACITY,\n });\n }\n\n /**\n * Allocates one typed slot per declared device state and creates the backing\n * `device_state_<type>` arrays.\n *\n * @throws {UnifiedIRCompilerError} when a state declaration is malformed.\n */\n allocateStates(devices: readonly DeviceConfig[]): GlobalStateMap {\n assertDeviceList(devices);\n\n interface StatePlan {\n readonly deviceId: string;\n readonly name: string;\n readonly type: ScalarType;\n readonly initial: boolean | number;\n readonly slot: number;\n }\n\n const plans: StatePlan[] = [];\n const slotsByDevice = new Map<string, Map<string, DeviceStateSlot>>();\n const plansByType = new Map<ScalarType, StatePlan[]>();\n\n for (const device of devices) {\n // Every device owns a block in the state table, even when it is empty.\n const slots = new Map<string, DeviceStateSlot>();\n slotsByDevice.set(device.id, slots);\n for (const [name, declaration] of stateEntries(device)) {\n const plan: StatePlan = {\n deviceId: device.id,\n name,\n type: declaration.type,\n initial: declaration.initial,\n slot: plans.length,\n };\n plans.push(plan);\n const typePlans = plansByType.get(plan.type);\n if (typePlans === undefined) {\n plansByType.set(plan.type, [plan]);\n } else {\n typePlans.push(plan);\n }\n }\n }\n\n const arrays = new Map<ScalarType, ArrayRef>();\n const totals = new Map<ScalarType, number>();\n for (const [type, typePlans] of plansByType) {\n const array = this.module.array(\n `device_state_${type}`,\n type,\n typePlans.map((plan) => plan.initial),\n );\n arrays.set(type, array);\n totals.set(type, typePlans.length);\n typePlans.forEach((plan, index) => {\n const slot: DeviceStateSlot = Object.freeze({\n name: plan.name,\n deviceId: plan.deviceId,\n type,\n array,\n index,\n slot: plan.slot,\n });\n slotsByDevice.get(plan.deviceId)?.set(plan.name, slot);\n });\n }\n\n const devicesMap = new Map<string, ReadonlyMap<string, DeviceStateSlot>>();\n for (const [deviceId, slots] of slotsByDevice) devicesMap.set(deviceId, slots);\n\n return Object.freeze({\n devices: devicesMap,\n arrays,\n totals,\n totalStates: plans.length,\n });\n }\n}\n\n/**\n * Declares the three pin memories shared by every device and net solver.\n *\n * The memories are sized to the pins the circuit declares, never to\n * {@link UNIFIED_PIN_CAPACITY}: the capacity only bounds how many pins a\n * circuit may have, so a large ceiling costs neither memory nor setup time.\n */\nexport function createPinMemory(\n module: IRModule,\n capacity: number = UNIFIED_PIN_CAPACITY,\n): CompiledCircuitMemory {\n return Object.freeze({\n mode: module.array(\n 'pin_mode',\n 'u8',\n Array.from({ length: capacity }, () => PIN_MODE.highZ),\n ),\n output: module.array(\n 'pin_output',\n 'bool',\n Array.from({ length: capacity }, () => false),\n ),\n input: module.array(\n 'pin_input',\n 'bool',\n Array.from({ length: capacity }, () => false),\n ),\n });\n}\n\n/** First state slot ordinal of every device; used for `DeviceMetadata.stateOffset`. */\nexport function stateOffsetOf(states: GlobalStateMap, deviceId: string): number {\n let offset = 0;\n for (const [id, slots] of states.devices) {\n if (id === deviceId) return offset;\n offset += slots.size;\n }\n return offset;\n}\n\nfunction assertDeviceList(devices: readonly DeviceConfig[]): void {\n if (!Array.isArray(devices) || devices.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.devices must be a non-empty array',\n );\n }\n const ids = new Set<string>();\n for (const device of devices as readonly unknown[]) {\n if (device === null || typeof device !== 'object' || Array.isArray(device)) {\n throw new UnifiedIRCompilerError('invalid-input', 'Every device must be an object');\n }\n const { id, type, description } = device as Partial<DeviceConfig>;\n if (typeof id !== 'string' || !DEVICE_ID_PATTERN.test(id)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device id ${JSON.stringify(id)} must be an identifier ([A-Za-z_][A-Za-z0-9_]*) because it prefixes generated IR function names`,\n );\n }\n if (ids.has(id)) {\n throw new UnifiedIRCompilerError(\n 'duplicate-device',\n `Duplicate device id \"${id}\"; every device id must be unique`,\n { deviceId: id },\n );\n }\n ids.add(id);\n if (typeof type !== 'string' || type.length === 0) {\n throw new UnifiedIRCompilerError('invalid-input', `Device \"${id}\" needs a non-empty type`, {\n deviceId: id,\n });\n }\n if (description === null || typeof description !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${id}\" needs a description object with a pins map`,\n { deviceId: id },\n );\n }\n }\n}\n\nfunction pinEntries(\n device: DeviceConfig,\n): readonly (readonly [string, DevicePinDescription | undefined])[] {\n const raw: unknown = device.description.pins;\n let entries: (readonly [string, DevicePinDescription | undefined])[];\n if (raw instanceof Map) {\n entries = [...(raw as ReadonlyMap<string, DevicePinDescription>).entries()];\n } else if (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) {\n entries = Object.entries(raw as Record<string, DevicePinDescription>) as (readonly [\n string,\n DevicePinDescription | undefined,\n ])[];\n } else {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" needs description.pins as a Map or a plain object`,\n { deviceId: device.id },\n );\n }\n for (const [name, descriptor] of entries) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" declares a pin with an empty name`,\n { deviceId: device.id },\n );\n }\n if (name.includes('.')) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" pin \"${name}\" may not contain \".\": connection endpoints use \"device.pin\"`,\n { deviceId: device.id, pinName: name },\n );\n }\n if (descriptor !== undefined && (descriptor === null || typeof descriptor !== 'object')) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" pin \"${name}\" description must be an object`,\n { deviceId: device.id, pinName: name },\n );\n }\n }\n return entries;\n}\n\nconst PIN_DIRECTIONS: ReadonlySet<string> = new Set([\n 'input',\n 'output',\n 'bidirectional',\n 'passive',\n]);\n\nfunction resolvePinDirection(\n descriptor: DevicePinDescription | undefined,\n deviceId: string,\n pinName: string,\n): DevicePinDirection {\n const direction = descriptor?.direction ?? 'passive';\n if (!PIN_DIRECTIONS.has(direction)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" pin \"${pinName}\" has direction ${JSON.stringify(direction)}; expected input, output, bidirectional or passive`,\n { deviceId, pinName },\n );\n }\n return direction;\n}\n\n/**\n * Derives the electrical role and the read behavior of a pin.\n *\n * `output` drives only, `input`/`passive` sense only, `bidirectional` drives and\n * senses. An explicit `role` overrides the derived drive role while\n * `bidirectional` keeps its sense side.\n */\nfunction resolvePinRole(\n direction: DevicePinDirection,\n explicit: DevicePinDescription['role'],\n deviceId: string,\n pinName: string,\n): { readonly role: 'driver' | 'load'; readonly senses: boolean } {\n if (explicit !== undefined && explicit !== 'driver' && explicit !== 'load') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" pin \"${pinName}\" has role ${JSON.stringify(explicit)}; expected driver or load`,\n { deviceId, pinName },\n );\n }\n if (explicit === 'driver') return { role: 'driver', senses: direction === 'bidirectional' };\n if (explicit === 'load') return { role: 'load', senses: true };\n if (direction === 'output') return { role: 'driver', senses: false };\n if (direction === 'bidirectional') return { role: 'driver', senses: true };\n return { role: 'load', senses: true };\n}\n\nfunction stateEntries(\n device: DeviceConfig,\n): readonly (readonly [string, DeviceStateDescription])[] {\n const raw: unknown = device.description.states;\n if (raw === undefined) return [];\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" needs description.states as a plain object`,\n { deviceId: device.id },\n );\n }\n return Object.entries(raw as Record<string, DeviceStateDescription>).map(\n ([name, declaration]) => {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" declares a state with an empty name`,\n { deviceId: device.id },\n );\n }\n if (declaration === null || typeof declaration !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" state \"${name}\" must be an object with type and initial`,\n { deviceId: device.id },\n );\n }\n const type: unknown = declaration.type;\n if (typeof type !== 'string' || !(SCALAR_TYPES as readonly string[]).includes(type)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" state \"${name}\" has type ${JSON.stringify(type)}; expected one of ${SCALAR_TYPES.join(', ')}`,\n { deviceId: device.id },\n );\n }\n assertStateInitial(device.id, name, type as ScalarType, declaration.initial);\n return [name, declaration] as const;\n },\n );\n}\n\nfunction assertStateInitial(\n deviceId: string,\n name: string,\n type: ScalarType,\n initial: unknown,\n): void {\n if (type === 'bool') {\n if (typeof initial !== 'boolean') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (bool) needs a boolean initial value`,\n { deviceId },\n );\n }\n return;\n }\n if (typeof initial !== 'number' || !Number.isFinite(initial)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (${type}) needs a finite numeric initial value`,\n { deviceId },\n );\n }\n if ((INTEGER_TYPES as readonly string[]).includes(type) && !Number.isInteger(initial)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (${type}) needs an integer initial value`,\n { deviceId },\n );\n }\n}\n","import type {\n ArrayRef,\n FunctionBuilder,\n FunctionRef,\n IRModule,\n ScalarType,\n Value,\n} from '@mica-js/ir';\nimport { PIN_MODE } from '../pin-space';\nimport { stateOffsetOf } from './allocator';\nimport {\n UnifiedIRCompilerError,\n type CompiledCircuitMemory,\n type DeviceBehaviorApi,\n type DeviceBehaviors,\n type DeviceConfig,\n type DeviceKernelRuntime,\n type DeviceMetadata,\n type DevicePinAllocation,\n type DevicePinHandle,\n type DeviceStateHandle,\n type DeviceStateSlot,\n type GlobalPinMap,\n type GlobalStateMap,\n} from './types';\n\n/** Refs the main loop calls for one device; `undefined` means \"no such phase\". */\nexport interface DeviceLoopEntry {\n readonly deviceId: string;\n readonly initialize: FunctionRef<readonly [], readonly []> | undefined;\n readonly tick: FunctionRef<readonly [], readonly []> | undefined;\n readonly update: FunctionRef<readonly [], readonly []> | undefined;\n}\n\n/** One generated device: public metadata plus the refs the main loop needs. */\nexport interface GeneratedDevice {\n readonly metadata: DeviceMetadata;\n readonly entry: DeviceLoopEntry;\n}\n\ninterface GeneratedPhase {\n readonly name: string;\n readonly ref: FunctionRef<readonly [], readonly []>;\n}\n\n/** Everything the device generator reads from the prior compilation stages. */\nexport interface DeviceGenerationContext {\n readonly module: IRModule;\n readonly memory: CompiledCircuitMemory;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n}\n\n/**\n * Generates one IR function per device phase into the unified module.\n *\n * Domain operations are inlined while the behavior runs: `pin.configure`,\n * `pin.writeDigital` and `pin.sampleDigital` become `array.store`/`array.load`\n * on the shared `pin_mode` / `pin_output` / `pin_input` memories, so no device\n * keeps its own module, protocol or host hop. A device without an explicit\n * `initialize` still gets one that configures its output pins as push-pull.\n *\n * The compiler ships no device models: every description must declare its own\n * pins, states and behaviors (or a `kernel`) before it reaches this generator.\n */\nexport class DeviceIRGenerator {\n private readonly context: DeviceGenerationContext;\n\n constructor(context: DeviceGenerationContext) {\n this.context = context;\n }\n\n /**\n * @throws {UnifiedIRCompilerError} when the device has no kernel/behaviors or\n * a behavior reaches for a pin or state the description does not declare.\n */\n generate(device: DeviceConfig): GeneratedDevice {\n const allocation = this.context.pins.devices.get(device.id);\n if (allocation === undefined) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" has no pin allocation; allocate resources before generating IR`,\n { deviceId: device.id },\n );\n }\n const kernelResult = device.description.kernel?.({\n deviceId: device.id,\n config: device.config,\n module: this.context.module,\n memory: this.context.memory,\n pins: [...allocation.resolved.values()].map((pin) =>\n Object.freeze({\n name: pin.name,\n globalPinId: pin.globalPinId,\n role: pin.role,\n }),\n ),\n });\n const kernelRuntime =\n kernelResult !== undefined && isKernelRuntime(kernelResult) ? kernelResult : undefined;\n const behaviors =\n kernelRuntime === undefined\n ? ((kernelResult as DeviceBehaviors | undefined) ?? device.description.behaviors)\n : undefined;\n\n let initialize: GeneratedPhase | undefined;\n let tick: GeneratedPhase | undefined;\n let update: GeneratedPhase | undefined;\n if (kernelRuntime !== undefined) {\n initialize = phaseFromRef(this.context.module, device.id, kernelRuntime.initialize);\n tick = phaseFromRef(this.context.module, device.id, kernelRuntime.tick);\n update = phaseFromRef(this.context.module, device.id, kernelRuntime.update);\n } else {\n if (behaviors === undefined || !hasAnyBehavior(behaviors)) {\n throw new UnifiedIRCompilerError(\n 'unsupported-device',\n `Device \"${device.id}\" of type \"${device.type}\" declares no behaviors. Provide description.behaviors or description.kernel`,\n { deviceId: device.id },\n );\n }\n initialize =\n this.generatePhase(device, allocation, 'initialize', behaviors.initialize) ??\n this.generateDefaultInitialize(device, allocation);\n tick = this.generatePhase(device, allocation, 'tick', behaviors.tick);\n update = this.generatePhase(device, allocation, 'update', behaviors.update);\n }\n\n const functions: string[] = [];\n for (const phase of [initialize, tick, update]) {\n if (phase !== undefined) functions.push(phase.name);\n }\n\n const metadata: DeviceMetadata = Object.freeze({\n deviceId: device.id,\n type: device.type,\n pinOffset: allocation.offset,\n stateOffset: stateOffsetOf(this.context.states, device.id),\n pins: allocation.pins,\n states: this.context.states.devices.get(device.id) ?? new Map(),\n functions: Object.freeze(functions),\n initialize: initialize?.name,\n tick: tick?.name,\n update: update?.name,\n accessor: device.description.accessor,\n kernel: device.description.kernel,\n });\n\n return Object.freeze({\n metadata,\n entry: Object.freeze({\n deviceId: device.id,\n initialize: initialize?.ref,\n tick: tick?.ref,\n update: update?.ref,\n }),\n });\n }\n\n private generatePhase(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n phase: 'initialize' | 'tick' | 'update',\n behavior: ((api: DeviceBehaviorApi) => void) | undefined,\n ): GeneratedPhase | undefined {\n if (behavior === undefined) return undefined;\n const name = `${device.id}_${phase}`;\n const ref = this.context.module.func(name, { params: [], results: [] });\n ref.body((b) => {\n behavior(this.createApi(device, allocation, b));\n b.return([]);\n });\n return { name, ref };\n }\n\n private generateDefaultInitialize(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n ): GeneratedPhase | undefined {\n const outputs = [...allocation.resolved.values()].filter((pin) => pin.role === 'driver');\n if (outputs.length === 0) return undefined;\n const name = `${device.id}_initialize`;\n const ref = this.context.module.func(name, { params: [], results: [] });\n ref.body((b) => {\n for (const pin of outputs) {\n b.array.store(\n this.context.memory.mode,\n b.const('u32', pin.globalPinId),\n b.const('u8', PIN_MODE.pushPull),\n );\n }\n b.return([]);\n });\n return { name, ref };\n }\n\n private createApi(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n builder: FunctionBuilder<readonly []>,\n ): DeviceBehaviorApi {\n const handles = new Map<string, DevicePinHandle>();\n const pins: DevicePinHandle[] = [];\n const outputs: DevicePinHandle[] = [];\n for (const pin of allocation.resolved.values()) {\n const handle = this.createPinHandle(pin.globalPinId, pin.name, builder);\n handles.set(pin.name, handle);\n pins.push(handle);\n if (pin.role === 'driver') outputs.push(handle);\n }\n const slots = this.context.states.devices.get(device.id);\n return Object.freeze({\n deviceId: device.id,\n builder,\n module: this.context.module,\n memory: this.context.memory,\n config: device.config,\n pins: Object.freeze(pins),\n outputs: Object.freeze(outputs),\n pin(name: string): DevicePinHandle {\n const handle = handles.get(name);\n if (handle === undefined) {\n const available = [...handles.keys()].map((entry) => `${device.id}.${entry}`);\n throw new UnifiedIRCompilerError(\n 'pin-not-found',\n `Pin '${device.id}.${name}' not found. Available: [${available.join(', ')}]`,\n { deviceId: device.id, pinName: name },\n );\n }\n return handle;\n },\n state<T extends ScalarType = ScalarType>(name: string): DeviceStateHandle<T> {\n const slot = slots?.get(name);\n if (slot === undefined) {\n throw new UnifiedIRCompilerError(\n 'state-not-found',\n `Device \"${device.id}\" has no state \"${name}\". Available: [${[...(slots?.keys() ?? [])].join(', ')}]`,\n { deviceId: device.id },\n );\n }\n return createStateHandle<T>(device.id, slot, builder);\n },\n });\n }\n\n private createPinHandle(\n globalId: number,\n name: string,\n builder: FunctionBuilder<readonly []>,\n ): DevicePinHandle {\n const memory = this.context.memory;\n // Resolved lazily so a behavior that only samples a pin does not also emit\n // an unused constant for every other pin of the device.\n const index = (): Value<'u32'> => builder.const('u32', globalId);\n return Object.freeze({\n name,\n globalId,\n configure(mode: number): void {\n if (!Number.isInteger(mode) || mode < 0 || mode > 0xff) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Pin \"${name}\" configure(${String(mode)}) needs a u8 pin mode`,\n );\n }\n builder.array.store(memory.mode, index(), builder.const('u8', mode));\n },\n writeDigital(level: Value<'bool'>): void {\n builder.array.store(memory.output, index(), level);\n },\n sampleDigital(): Value<'bool'> {\n return builder.array.load(memory.input, index());\n },\n readDrivenDigital(): Value<'bool'> {\n return builder.array.load(memory.output, index());\n },\n });\n }\n}\n\nfunction createStateHandle<T extends ScalarType>(\n deviceId: string,\n slot: DeviceStateSlot,\n builder: FunctionBuilder<readonly []>,\n): DeviceStateHandle<T> {\n // The array was declared with `slot.type`, so a matching `T` is exactly the\n // array's element type; the cast only recovers that from the untied slot.\n const array = slot.array as unknown as ArrayRef<T>;\n const index = builder.const('u32', slot.index);\n return Object.freeze({\n name: slot.name,\n type: slot.type as T,\n index: slot.index,\n load(): Value<T> {\n return builder.array.load(array, index);\n },\n store(value: Value<T>): void {\n builder.array.store(array, index, value);\n },\n });\n}\n\nfunction hasAnyBehavior(behaviors: DeviceBehaviors): boolean {\n return (\n behaviors.initialize !== undefined ||\n behaviors.tick !== undefined ||\n behaviors.update !== undefined\n );\n}\n\n/** Bulk kernel results carry phase refs; behaviour hooks are plain functions. */\nfunction isKernelRuntime(\n value: DeviceBehaviors | DeviceKernelRuntime,\n): value is DeviceKernelRuntime {\n if (value === null || typeof value !== 'object') return false;\n // A kernel may own any subset of the phases (a passive sink only needs\n // `update`), so the first phase ref that is an object — not a behaviour\n // callback — decides.\n const phases: readonly (keyof DeviceKernelRuntime)[] = ['initialize', 'tick', 'update'];\n return phases.some((phase) => typeof value[phase] === 'object');\n}\n\n/** Resolves one kernel phase ref to its generated function name. */\nfunction phaseFromRef(\n module: IRModule,\n deviceId: string,\n ref: FunctionRef<readonly [], readonly []> | undefined,\n): GeneratedPhase | undefined {\n if (ref === undefined) return undefined;\n const definition = module.functions.find((fn) => fn.ref === ref);\n if (definition === undefined) {\n throw new UnifiedIRCompilerError(\n 'invalid-ir',\n `Device \"${deviceId}\" returned a kernel phase ref that is not part of the module`,\n { deviceId },\n );\n }\n return { name: definition.name, ref };\n}\n","import type { FunctionBuilder, FunctionRef, IRModule } from '@mica-js/ir';\nimport type { DeviceLoopEntry } from './device-gen';\nimport type { NetSolverRuntime } from './solver-gen';\nimport type { CompiledNetlist } from './types';\n\n/** Generated entry-point names. */\nexport interface MainLoopNames {\n readonly tick: string;\n readonly initialize: string;\n readonly batch: string;\n}\n\n/** Names used when the caller does not override them. */\nexport const DEFAULT_ENTRY_POINT_NAMES: MainLoopNames = Object.freeze({\n tick: 'unified_tick',\n initialize: 'unified_initialize',\n batch: 'unified_tick_batch',\n});\n\n/** The generated main loop. */\nexport interface MainLoopOutput {\n readonly names: MainLoopNames;\n readonly initialize: FunctionRef<readonly [], readonly []>;\n readonly tick: FunctionRef<readonly [], readonly []>;\n readonly batch: FunctionRef<readonly ['u32'], readonly []>;\n /** Device ids in dependency order. */\n readonly order: readonly string[];\n}\n\n/**\n * Generates the circuit entries.\n *\n * ```text\n * unified_initialize: // once, before the first tick\n * drive1_initialize()\n * sink1_initialize() // if the device has one\n *\n * unified_tick: // one simulation step\n * drive1_tick() // drivers publish their outputs\n * solve_net_0() // the electrical network resolves\n * sink1_update() // loads observe the solved inputs\n *\n * unified_tick_batch(count): // the same step, looped inside the IR\n * for i in 0 .. count { <step> }\n * ```\n *\n * Devices run in dependency order: a device that drives a net executes before\n * every device that senses it. Feedback loops fall back to declaration order\n * after the topological prefix, so clock cycles stay valid.\n */\nexport class MainLoopGenerator {\n private readonly module: IRModule;\n\n constructor(module: IRModule) {\n this.module = module;\n }\n\n /** Stable topological order of the devices; cycles fall back to declaration order. */\n order(entries: readonly DeviceLoopEntry[], netlist: CompiledNetlist): readonly string[] {\n const indexById = new Map(entries.map((entry, index) => [entry.deviceId, index]));\n const consumers = new Map<string, Set<string>>();\n const indegree = new Map<string, number>(entries.map((entry) => [entry.deviceId, 0]));\n\n for (const net of netlist.nets) {\n const driverDevices = new Set(net.drivers.map((pin) => pin.deviceId));\n const sinkDevices = new Set(net.sinks.map((pin) => pin.deviceId));\n for (const driver of driverDevices) {\n for (const sink of sinkDevices) {\n if (driver === sink) continue;\n let targets = consumers.get(driver);\n if (targets === undefined) {\n targets = new Set();\n consumers.set(driver, targets);\n }\n if (targets.has(sink)) continue;\n targets.add(sink);\n indegree.set(sink, (indegree.get(sink) ?? 0) + 1);\n }\n }\n }\n\n const ready = new Set(\n entries\n .filter((entry) => (indegree.get(entry.deviceId) ?? 0) === 0)\n .map((entry) => entry.deviceId),\n );\n const order: string[] = [];\n while (ready.size > 0) {\n let nextId: string | undefined;\n let nextIndex = Number.POSITIVE_INFINITY;\n for (const id of ready) {\n const index = indexById.get(id) ?? 0;\n if (index < nextIndex) {\n nextIndex = index;\n nextId = id;\n }\n }\n if (nextId === undefined) break;\n ready.delete(nextId);\n order.push(nextId);\n for (const consumer of consumers.get(nextId) ?? []) {\n const remaining = (indegree.get(consumer) ?? 0) - 1;\n indegree.set(consumer, remaining);\n if (remaining === 0) ready.add(consumer);\n }\n }\n for (const entry of entries) {\n if (!order.includes(entry.deviceId)) order.push(entry.deviceId);\n }\n return Object.freeze(order);\n }\n\n /** Generates `initialize`, `tick` and the batched tick loop. */\n generate(\n entries: readonly DeviceLoopEntry[],\n solvers: readonly NetSolverRuntime[],\n netlist: CompiledNetlist,\n names: MainLoopNames = DEFAULT_ENTRY_POINT_NAMES,\n ): MainLoopOutput {\n const order = this.order(entries, netlist);\n const byId = new Map(entries.map((entry) => [entry.deviceId, entry]));\n\n const emitStep = (b: FunctionBuilder<readonly []>): void => {\n for (const deviceId of order) {\n const entry = byId.get(deviceId);\n if (entry?.tick !== undefined) b.call(entry.tick, []);\n }\n for (const solver of solvers) b.call(solver.solve, []);\n for (const deviceId of order) {\n const entry = byId.get(deviceId);\n if (entry?.update !== undefined) b.call(entry.update, []);\n }\n };\n\n const initialize = this.module.func(names.initialize, { params: [], results: [] });\n initialize.body((b) => {\n for (const deviceId of order) {\n const entry = byId.get(deviceId);\n if (entry?.initialize !== undefined) b.call(entry.initialize, []);\n }\n b.return([]);\n });\n\n const tick = this.module.func(names.tick, { params: [], results: [] });\n tick.body((b) => {\n emitStep(b);\n b.return([]);\n });\n\n // The batch entry keeps the loop inside the IR: one engine call per batch\n // instead of one host entry per tick, which is the throughput path.\n const batch = this.module.func(names.batch, { params: ['u32'], results: [] });\n batch.body((b, [count]) => {\n const header = b.block(['u32']);\n const body = b.block(['u32']);\n const done = b.block([]);\n b.jump(header, [b.const('u32', 0)]);\n b.at(header, (ib, [index]) =>\n ib.branch(\n ib.int.cmp('lt', index, count),\n { target: body, args: [index] },\n { target: done, args: [] },\n ),\n );\n b.at(body, (ib, [index]) => {\n emitStep(ib);\n ib.jump(header, [ib.int.add(index, ib.const('u32', 1))]);\n });\n b.at(done, (ib) => ib.return([]));\n });\n\n return Object.freeze({\n names,\n initialize,\n tick,\n batch,\n order,\n });\n }\n}\n","import type { FunctionBuilder, FunctionRef, IRModule, Value } from '@mica-js/ir';\nimport { PIN_MODE } from '../pin-space';\nimport type {\n CompiledCircuitMemory,\n CompiledNet,\n CompiledNetlist,\n CompiledPinConnection,\n} from './types';\n\n/** One generated net solver. */\nexport interface NetSolverRuntime {\n readonly netId: number;\n /** Generated `solve_net_<id>`. */\n readonly name: string;\n readonly net: CompiledNet;\n readonly solve: FunctionRef<readonly [], readonly []>;\n}\n\n/** Everything the solver generator reads from the prior compilation stages. */\nexport interface SolverGenerationContext {\n readonly module: IRModule;\n readonly memory: CompiledCircuitMemory;\n}\n\n/**\n * Generates the electrical solve, one `solve_net_<id>` function per net.\n *\n * Each net solves as a branch-free function. One driver is the common shape:\n *\n * ```text\n * solve_net_0:\n * let mode = PIN_MODE[driver]\n * let output = PIN_OUTPUT[driver]\n * let driven = mode == PUSH_PULL && output\n * PIN_INPUT[load] = driven // once per sink\n * ```\n *\n * Only a push-pull driver holds its net; high-z, open-drain and analog modes\n * leave it floating. A driver-less net loads the constant of its rail, or\n * `false` when it is truly floating. Several drivers OR into a wired-OR level.\n */\nexport class ElectricalSolverGenerator {\n private readonly context: SolverGenerationContext;\n\n constructor(context: SolverGenerationContext) {\n this.context = context;\n }\n\n generate(netlist: CompiledNetlist): readonly NetSolverRuntime[] {\n return Object.freeze(netlist.nets.map((net) => this.generateNetSolver(net)));\n }\n\n private generateNetSolver(net: CompiledNet): NetSolverRuntime {\n const name = `solve_net_${net.netId}`;\n const solve = this.context.module.func(name, { params: [], results: [] });\n\n solve.body((b) => {\n if (net.sinks.length > 0) {\n const driven =\n net.drivers.length === 0\n ? b.const('bool', net.level)\n : this.combineDrivers(b, net.drivers);\n if (driven !== undefined) {\n for (const sink of net.sinks) {\n b.array.store(this.context.memory.input, b.const('u32', sink.globalPinId), driven);\n }\n }\n }\n b.return([]);\n });\n\n return Object.freeze({ netId: net.netId, name, net, solve });\n }\n\n /**\n * Folds the drivers of one net into the level its sinks observe.\n *\n * A single driver yields `mode == push-pull && output`; several drivers are\n * OR-ed into a wired-OR level.\n */\n private combineDrivers(\n b: FunctionBuilder<readonly []>,\n drivers: readonly CompiledPinConnection[],\n ): Value<'bool'> | undefined {\n let driven: Value<'bool'> | undefined;\n for (const driver of drivers) {\n const index = b.const('u32', driver.globalPinId);\n const mode = b.array.load(this.context.memory.mode, index);\n const output = b.array.load(this.context.memory.output, index);\n const pushed = b.int.cmp('eq', mode, b.const('u8', PIN_MODE.pushPull));\n const value = b.bool.and(pushed, output);\n driven = driven === undefined ? value : b.bool.or(driven, value);\n }\n return driven;\n }\n}\n","import {\n UnifiedIRCompilerError,\n type CompilationDiagnostic,\n type CompiledNet,\n type CompiledNetlist,\n type CompiledPinConnection,\n type CompiledRail,\n type Connection,\n type GlobalPinMap,\n type ResolvedDevicePin,\n} from './types';\n\n/** Rails every circuit understands without declaring them. */\nexport const DEFAULT_RAILS: Readonly<Record<string, boolean>> = Object.freeze({\n GND: false,\n VCC: true,\n VDD: true,\n});\n\n/** Options for {@link NetworkTopologyAnalyzer}. */\nexport interface TopologyOptions {\n /** Extra or overriding rails; merged over {@link DEFAULT_RAILS}. */\n readonly rails?: Readonly<Record<string, boolean>>;\n}\n\ninterface ResolvedPinEndpoint {\n readonly kind: 'pin';\n readonly nodeId: number;\n readonly pin: ResolvedDevicePin;\n}\n\ninterface ResolvedRailEndpoint {\n readonly kind: 'rail';\n readonly nodeId: number;\n readonly name: string;\n readonly level: boolean;\n}\n\ntype ResolvedEndpoint = ResolvedPinEndpoint | ResolvedRailEndpoint;\n\ninterface ComponentPins {\n readonly pins: CompiledPinConnection[];\n readonly rails: CompiledRail[];\n readonly endpoints: string[];\n}\n\n/**\n * Analyses the pin-to-pin connections of a circuit.\n *\n * 1. every connection edge joins two nodes (pins and rails);\n * 2. a union-find pass collapses them into electrical nets (connected components);\n * 3. each net gets an id in first-appearance order and is split into drivers,\n * loads and sinks;\n * 4. electrical conflicts (a driver against a rail, two rails of opposite\n * level) become diagnostics instead of silently wrong IR.\n *\n * Several drivers on one net are legal and solved as a wired-OR, which is what\n * a bidirectional pin fighting a switch looks like on a bench.\n */\nexport class NetworkTopologyAnalyzer {\n private readonly rails: ReadonlyMap<string, boolean>;\n\n constructor(options: TopologyOptions = {}) {\n this.rails = new Map([\n ...Object.entries(DEFAULT_RAILS),\n ...Object.entries(options.rails ?? {}),\n ]);\n }\n\n /**\n * @throws {UnifiedIRCompilerError} when a connection is malformed, names an\n * unknown device, or names a pin the device does not declare.\n */\n analyze(connections: readonly Connection[], pins: GlobalPinMap): CompiledNetlist {\n if (!Array.isArray(connections)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.connections must be an array',\n );\n }\n\n const set = new DisjointSet();\n const pinNodes = new Map<number, CompiledPinConnection>();\n const railNodes = new Map<number, CompiledRail>();\n const railNodeIds = new Map<string, number>();\n const connectionOrder: number[] = [];\n\n for (const [index, connection] of connections.entries()) {\n if (connection === null || typeof connection !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-connection',\n `Connection[${index}] must be an object with \"from\" and \"to\"`,\n );\n }\n const from = this.resolveEndpoint(connection.from, pins, railNodeIds, index);\n const to = this.resolveEndpoint(connection.to, pins, railNodeIds, index);\n set.union(from.nodeId, to.nodeId);\n connectionOrder.push(from.nodeId);\n if (from.kind === 'pin') pinNodes.set(from.pin.globalPinId, toConnection(from.pin));\n else railNodes.set(from.nodeId, Object.freeze({ name: from.name, level: from.level }));\n if (to.kind === 'pin') pinNodes.set(to.pin.globalPinId, toConnection(to.pin));\n else railNodes.set(to.nodeId, Object.freeze({ name: to.name, level: to.level }));\n }\n\n // Component identity is the union-find root; the first connection that\n // touches a component decides its net id, which keeps ids stable.\n const components = new Map<number, ComponentPins>();\n const componentOf = (nodeId: number): ComponentPins => {\n const root = set.find(nodeId);\n let component = components.get(root);\n if (component === undefined) {\n component = { pins: [], rails: [], endpoints: [] };\n components.set(root, component);\n }\n return component;\n };\n\n for (const [pinId, connection] of pinNodes) componentOf(pinId).pins.push(connection);\n for (const [nodeId, rail] of railNodes) {\n const component = componentOf(nodeId);\n component.rails.push(rail);\n component.endpoints.push(rail.name);\n }\n\n const orderedRoots: number[] = [];\n const seen = new Set<number>();\n for (const nodeId of connectionOrder) {\n const root = set.find(nodeId);\n if (seen.has(root)) continue;\n seen.add(root);\n orderedRoots.push(root);\n }\n\n const diagnostics: CompilationDiagnostic[] = [];\n const nets: CompiledNet[] = [];\n for (const root of orderedRoots) {\n const component = components.get(root);\n if (component === undefined) continue;\n component.pins.sort((left, right) => left.globalPinId - right.globalPinId);\n component.rails.sort((left, right) => left.name.localeCompare(right.name));\n const endpoints = [...component.endpoints, ...component.pins.map((pin) => pin.endpoint)];\n\n if (component.pins.length === 0) {\n // Rail-to-rail wiring only: report a short, never emit a net.\n const levels = new Set(component.rails.map((rail) => rail.level));\n if (levels.size > 1) {\n diagnostics.push(\n diagnostic(\n 'rail-conflict',\n 'error',\n `Rails ${component.rails.map((rail) => rail.name).join(' and ')} are wired together with opposite levels`,\n undefined,\n endpoints,\n ),\n );\n }\n continue;\n }\n\n const netId = nets.length;\n const net = this.classify(netId, component.pins, component.rails, diagnostics);\n nets.push(net);\n }\n\n return Object.freeze({ nets: Object.freeze(nets), diagnostics: Object.freeze(diagnostics) });\n }\n\n private classify(\n netId: number,\n pins: readonly CompiledPinConnection[],\n rails: readonly CompiledRail[],\n diagnostics: CompilationDiagnostic[],\n ): CompiledNet {\n const drivers = pins.filter((pin) => pin.role === 'driver');\n const loads = pins.filter((pin) => pin.role === 'load');\n const sinks = pins.filter((pin) => pin.senses);\n const endpoints = [...rails.map((rail) => rail.name), ...pins.map((pin) => pin.endpoint)];\n const levels = new Set(rails.map((rail) => rail.level));\n\n if (rails.length > 1 && levels.size > 1) {\n diagnostics.push(\n diagnostic(\n 'rail-conflict',\n 'error',\n `Net ${netId} ties rails ${rails.map((rail) => rail.name).join(' and ')} with opposite levels`,\n netId,\n endpoints,\n ),\n );\n }\n if (drivers.length > 0 && rails.length > 0) {\n diagnostics.push(\n diagnostic(\n 'power-short',\n 'error',\n `Net ${netId} shorts rail ${rails[0]?.name ?? '?'} against driver ${drivers[0]?.endpoint ?? '?'}`,\n netId,\n endpoints,\n ),\n );\n }\n if (drivers.length === 0 && rails.length === 0) {\n diagnostics.push(\n diagnostic(\n 'floating-net',\n 'warning',\n `Net ${netId} has no driver and no rail; its loads read a constant low`,\n netId,\n endpoints,\n ),\n );\n }\n\n const source = drivers.length > 0 ? 'driver' : rails.length > 0 ? 'rail' : 'floating';\n const level = rails[0]?.level ?? false;\n\n return Object.freeze({\n netId,\n pins: Object.freeze([...pins]),\n rails: Object.freeze([...rails]),\n drivers: Object.freeze(drivers),\n loads: Object.freeze(loads),\n sinks: Object.freeze(sinks),\n source,\n level,\n });\n }\n\n private resolveEndpoint(\n raw: unknown,\n pins: GlobalPinMap,\n railNodeIds: Map<string, number>,\n index: number,\n ): ResolvedEndpoint {\n if (typeof raw !== 'string' || raw.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-connection',\n `Connection[${index}] endpoint must be a non-empty \"device.pin\" string or a rail name`,\n );\n }\n const railLevel = this.rails.get(raw);\n if (railLevel !== undefined) {\n let nodeId = railNodeIds.get(raw);\n if (nodeId === undefined) {\n nodeId = pins.totalPins + railNodeIds.size;\n railNodeIds.set(raw, nodeId);\n }\n return { kind: 'rail', nodeId, name: raw, level: railLevel };\n }\n\n const dot = raw.indexOf('.');\n if (dot <= 0 || dot === raw.length - 1) {\n throw new UnifiedIRCompilerError(\n 'invalid-connection',\n `Connection endpoint \"${raw}\" must be \"device.pin\" or a known rail (${[...this.rails.keys()].join(', ')})`,\n );\n }\n const deviceId = raw.slice(0, dot);\n const pinName = raw.slice(dot + 1);\n const allocation = pins.devices.get(deviceId);\n if (allocation === undefined) {\n throw new UnifiedIRCompilerError(\n 'unknown-device',\n `Connection endpoint \"${raw}\" references unknown device \"${deviceId}\". Available: [${[...pins.devices.keys()].join(', ')}]`,\n { deviceId },\n );\n }\n const pin = allocation.resolved.get(pinName);\n if (pin === undefined) {\n const available = [...allocation.resolved.keys()].map((name) => `${deviceId}.${name}`);\n throw new UnifiedIRCompilerError(\n 'pin-not-found',\n `Pin '${raw}' not found. Available: [${available.join(', ')}]`,\n { deviceId, pinName },\n );\n }\n return { kind: 'pin', nodeId: pin.globalPinId, pin };\n }\n}\n\n/**\n * Throws the first error diagnostic of a netlist, or returns it unchanged.\n *\n * @throws {UnifiedIRCompilerError} carrying every diagnostic for inspection.\n */\nexport function assertNoElectricalErrors(netlist: CompiledNetlist): CompiledNetlist {\n const errors = netlist.diagnostics.filter((entry) => entry.severity === 'error');\n const first = errors[0];\n if (first === undefined) return netlist;\n throw new UnifiedIRCompilerError(mapErrorCode(first.code), first.message, {\n ...(first.netId === undefined ? {} : { netId: first.netId }),\n diagnostics: netlist.diagnostics,\n });\n}\n\nfunction mapErrorCode(code: CompilationDiagnostic['code']): 'power-short' | 'rail-conflict' {\n return code === 'rail-conflict' ? 'rail-conflict' : 'power-short';\n}\n\nfunction diagnostic(\n code: CompilationDiagnostic['code'],\n severity: CompilationDiagnostic['severity'],\n message: string,\n netId: number | undefined,\n endpoints: readonly string[],\n): CompilationDiagnostic {\n return Object.freeze({\n code,\n severity,\n message,\n netId,\n endpoints: Object.freeze([...endpoints]),\n });\n}\n\nfunction toConnection(pin: ResolvedDevicePin): CompiledPinConnection {\n return Object.freeze({\n endpoint: `${pin.deviceId}.${pin.name}`,\n deviceId: pin.deviceId,\n pinName: pin.name,\n globalPinId: pin.globalPinId,\n role: pin.role,\n senses: pin.senses,\n });\n}\n\n/** Union-find over pin ids and rail node ids. */\nclass DisjointSet {\n private readonly parent = new Map<number, number>();\n private readonly rank = new Map<number, number>();\n\n find(id: number): number {\n const parent = this.parent.get(id);\n if (parent === undefined) {\n this.parent.set(id, id);\n this.rank.set(id, 0);\n return id;\n }\n if (parent === id) return id;\n const root = this.find(parent);\n this.parent.set(id, root);\n return root;\n }\n\n union(left: number, right: number): void {\n const leftRoot = this.find(left);\n const rightRoot = this.find(right);\n if (leftRoot === rightRoot) return;\n const leftRank = this.rank.get(leftRoot) ?? 0;\n const rightRank = this.rank.get(rightRoot) ?? 0;\n if (leftRank < rightRank) {\n this.parent.set(leftRoot, rightRoot);\n return;\n }\n this.parent.set(rightRoot, leftRoot);\n if (leftRank === rightRank) this.rank.set(leftRoot, leftRank + 1);\n }\n}\n","import { createIRModule, validateIR } from '@mica-js/ir';\nimport type { IRModule, IRValidationOptions } from '@mica-js/ir';\nimport { createModuleValidation } from '../validation';\nimport { GlobalResourceAllocator } from './allocator';\nimport { DeviceIRGenerator } from './device-gen';\nimport { DEFAULT_ENTRY_POINT_NAMES, MainLoopGenerator, type MainLoopNames } from './mainloop-gen';\nimport { ElectricalSolverGenerator } from './solver-gen';\nimport {\n NetworkTopologyAnalyzer,\n assertNoElectricalErrors,\n type TopologyOptions,\n} from './topology';\nimport {\n UnifiedIRCompilerError,\n type CircuitCompilationInput,\n type CircuitCompilationOptions,\n type CompiledCircuit,\n type Connection,\n type DeviceConfig,\n} from './types';\n\n/**\n * Compiles several devices and their wiring into one unified IR module (U01).\n *\n * Device models are caller-supplied: every entry of `devices` carries the pins,\n * states and behaviors (or `kernel`) its type needs.\n *\n * ```ts\n * const circuit = compileCircuit({\n * devices: [\n * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },\n * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },\n * ],\n * connections: [\n * { from: 'drive1.channel0', to: 'sink1.anode' },\n * { from: 'sink1.cathode', to: 'GND' },\n * ],\n * });\n *\n * const jit = createIRJIT(circuit.module, { validation: circuit.validation });\n * jit.execute(circuit.entryPoints.refs.initialize, []);\n * jit.execute(circuit.entryPoints.refs.tick, []); // drive1 + nets + sink1\n * ```\n *\n * The pipeline is: validate the input, allocate the global pin and state\n * spaces, analyse the electrical topology, generate one function per device\n * phase, generate one solver per net, generate the main loop, then validate the\n * resulting module with `validateIR`.\n *\n * @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown\n * pins, electrical conflicts, or when the generated module fails validation.\n */\nexport function compileCircuit(\n input: CircuitCompilationInput,\n options: CircuitCompilationOptions = {},\n): CompiledCircuit {\n const { devices, connections } = validateInput(input);\n const resolvedOptions = validateOptions(options);\n const names = resolveEntryNames(resolvedOptions);\n\n const module = createIRModule();\n const allocation = new GlobalResourceAllocator(module).allocate(devices);\n\n const topologyOptions: TopologyOptions = {\n ...(resolvedOptions.rails === undefined ? {} : { rails: resolvedOptions.rails }),\n };\n const netlist = new NetworkTopologyAnalyzer(topologyOptions).analyze(\n connections,\n allocation.pins,\n );\n assertNoElectricalErrors(netlist);\n\n const generator = new DeviceIRGenerator({\n module,\n memory: allocation.memory,\n pins: allocation.pins,\n states: allocation.states,\n });\n const generated = devices.map((device) => generator.generate(device));\n\n const solvers = new ElectricalSolverGenerator({\n module,\n memory: allocation.memory,\n }).generate(netlist);\n\n assertNoNameCollisions(\n devices,\n solvers.map((solver) => solver.name),\n names,\n );\n\n const loop = new MainLoopGenerator(module).generate(\n generated.map((device) => device.entry),\n solvers,\n netlist,\n names,\n );\n\n const validation = createModuleValidation(\n module,\n devices.flatMap((device) => device.description.updateResources ?? []),\n );\n if (resolvedOptions.validate !== false) validateModule(module, validation);\n\n const deviceMap = new Map(generated.map((device) => [device.metadata.deviceId, device.metadata]));\n\n return Object.freeze({\n module,\n entryPoints: Object.freeze({\n tick: loop.names.tick,\n initialize: loop.names.initialize,\n batch: loop.names.batch,\n refs: Object.freeze({\n tick: loop.tick,\n initialize: loop.initialize,\n batch: loop.batch,\n }),\n }),\n pinMap: allocation.pins.pins,\n deviceMap,\n netlist,\n pins: allocation.pins,\n states: allocation.states,\n memory: allocation.memory,\n validation,\n executionOrder: loop.order,\n functions: Object.freeze(module.functions.map((fn) => fn.name)),\n });\n}\n\nfunction validateInput(input: unknown): {\n readonly devices: readonly DeviceConfig[];\n readonly connections: readonly Connection[];\n} {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput must be an object with devices and connections',\n );\n }\n const { devices, connections } = input as Partial<CircuitCompilationInput>;\n if (!Array.isArray(devices) || devices.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.devices must be a non-empty array',\n );\n }\n if (!Array.isArray(connections)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.connections must be an array',\n );\n }\n return { devices, connections };\n}\n\nfunction validateOptions(options: unknown): CircuitCompilationOptions {\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw new UnifiedIRCompilerError('invalid-input', 'Compile options must be an object');\n }\n const resolved = options as CircuitCompilationOptions;\n if (resolved.validate !== undefined && typeof resolved.validate !== 'boolean') {\n throw new UnifiedIRCompilerError('invalid-input', 'options.validate must be a boolean');\n }\n if (resolved.rails !== undefined) {\n if (\n resolved.rails === null ||\n typeof resolved.rails !== 'object' ||\n Array.isArray(resolved.rails)\n ) {\n throw new UnifiedIRCompilerError('invalid-input', 'options.rails must be a plain object');\n }\n for (const [name, level] of Object.entries(resolved.rails)) {\n if (name.length === 0 || typeof level !== 'boolean') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `options.rails[\"${name}\"] must be a boolean`,\n );\n }\n }\n }\n return resolved;\n}\n\nfunction resolveEntryNames(options: CircuitCompilationOptions): MainLoopNames {\n const names: MainLoopNames = {\n tick: options.entryPointNames?.tick ?? DEFAULT_ENTRY_POINT_NAMES.tick,\n initialize: options.entryPointNames?.initialize ?? DEFAULT_ENTRY_POINT_NAMES.initialize,\n batch: options.entryPointNames?.batch ?? DEFAULT_ENTRY_POINT_NAMES.batch,\n };\n for (const [role, name] of Object.entries(names)) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Entry point names.${role} must be a non-empty string`,\n );\n }\n }\n if (new Set(Object.values(names)).size !== 3) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Entry point names must be distinct: ${JSON.stringify(names)}`,\n );\n }\n return Object.freeze(names);\n}\n\nfunction assertNoNameCollisions(\n devices: readonly DeviceConfig[],\n solverNames: readonly string[],\n names: MainLoopNames,\n): void {\n const reserved = new Set<string>([names.tick, names.initialize, names.batch, ...solverNames]);\n for (const device of devices) {\n for (const phase of ['initialize', 'tick', 'update'] as const) {\n const generated = `${device.id}_${phase}`;\n if (reserved.has(generated)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" generates \"${generated}\", which collides with another generated function; rename the device or the entry point`,\n { deviceId: device.id },\n );\n }\n }\n }\n}\n\nfunction validateModule(module: IRModule, validation: IRValidationOptions): void {\n const result = validateIR(module, validation);\n if (result.ok) return;\n const details = result.diagnostics\n .map((entry) => `- [${entry.code}] ${entry.message} at ${entry.location.path}`)\n .join('\\n');\n throw new UnifiedIRCompilerError(\n 'invalid-ir',\n `Generated IR failed validateIR (${result.diagnostics.length} diagnostic(s)):\\n${details}`,\n );\n}\n\nexport * from './types';\nexport { GlobalResourceAllocator, createPinMemory, stateOffsetOf } from './allocator';\nexport type { ResourceAllocation } from './allocator';\nexport { DEFAULT_RAILS, NetworkTopologyAnalyzer, assertNoElectricalErrors } from './topology';\nexport type { TopologyOptions } from './topology';\nexport { DeviceIRGenerator } from './device-gen';\nexport type { DeviceGenerationContext, DeviceLoopEntry, GeneratedDevice } from './device-gen';\nexport { ElectricalSolverGenerator } from './solver-gen';\nexport type { NetSolverRuntime, SolverGenerationContext } from './solver-gen';\nexport { DEFAULT_ENTRY_POINT_NAMES, MainLoopGenerator } from './mainloop-gen';\nexport type { MainLoopNames, MainLoopOutput } from './mainloop-gen';\n","import type { IRJITTuning } from '@mica-js/ir';\nimport type { CircuitCompilationInput } from '../compiler';\n\n/**\n * Types of the unified circuit runtime (U02).\n *\n * `Circuit` is the host-facing facade over one compiled unified IR module: it\n * owns the engine instance, exposes typed per-device accessors and keeps the\n * tick counter. Everything here is transport-neutral; no type mentions the\n * device host or the schematic editor.\n */\n\n/** Execution engine a `Circuit` runs on. */\nexport type CircuitEngine = 'jit' | 'reference';\n\n/** Electrical-solve options forwarded to `compileCircuit`. */\nexport interface CircuitElectricalOptions {\n /** Named fixed-level rails; merged over `GND`/`VCC`/`VDD`. */\n readonly rails?: Readonly<Record<string, boolean>>;\n}\n\n/**\n * Options for `Circuit.create`.\n *\n * @example\n * const circuit = await Circuit.create(input, { engine: 'reference' });\n */\nexport interface CircuitRuntimeOptions {\n /** Execution engine. Defaults to `'jit'`; `'reference'` runs the interpreter. */\n readonly engine?: CircuitEngine;\n /** JIT tuning. The runtime always supplies the module's own validation grant. */\n readonly jit?: IRJITTuning;\n /**\n * Run `validateIR` over the generated module during compilation.\n * Defaults to `true`; pass `false` only for measured warm paths.\n */\n readonly validateIR?: boolean;\n /** Electrical-solve options. */\n readonly electrical?: CircuitElectricalOptions;\n /** Instance id reported to the engine. Defaults to `'unified-circuit'`. */\n readonly instanceId?: string;\n}\n\n/** Error codes raised by `CircuitError`. */\nexport type CircuitErrorCode =\n | 'invalid-options'\n | 'invalid-count'\n | 'pin-not-found'\n | 'pin-not-writable'\n | 'state-not-found'\n | 'invalid-state-value'\n | 'unresolved-device'\n | 'disposed';\n\nexport interface CircuitErrorOptions {\n readonly deviceId?: string;\n readonly pinName?: string;\n readonly stateName?: string;\n readonly cause?: unknown;\n}\n\n/**\n * Error raised while driving a `Circuit`.\n *\n * The code is stable and machine-checkable, and the message always names the\n * offending device/pin/state plus the values that would have been accepted.\n */\nexport class CircuitError extends Error {\n override readonly name = 'CircuitError';\n readonly code: CircuitErrorCode;\n readonly deviceId: string | undefined;\n readonly pinName: string | undefined;\n readonly stateName: string | undefined;\n\n constructor(code: CircuitErrorCode, message: string, options: CircuitErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.code = code;\n this.deviceId = options.deviceId;\n this.pinName = options.pinName;\n this.stateName = options.stateName;\n }\n}\n\n/**\n * What every device accessor offers, whatever its type.\n *\n * `readPin` returns the level the *device* drives onto one of its pins (its\n * output latch), while `Circuit.getPin('device.pin')` returns the level the pin\n * *observes* after the electrical solve. Writing a pin only makes sense for\n * driver pins, so `writePin` rejects load and passive pins.\n */\nexport interface DeviceAccessor {\n /** Circuit-unique device id. */\n readonly deviceId: string;\n /** Device type, e.g. `'push-pull-driver'`. */\n readonly type: string;\n /** Declared pin names, in declaration order. */\n readonly pinNames: readonly string[];\n /** Declared internal state names, in declaration order. */\n readonly stateNames: readonly string[];\n /** Reads the level the device drives onto `pinName`. */\n readPin(pinName: string): boolean;\n /** Writes the level the device drives onto `pinName`. */\n writePin(pinName: string, value: boolean): void;\n /** Reads one declared internal state. */\n getState(name: string): unknown;\n /** Writes one declared internal state. */\n setState(name: string, value: unknown): void;\n}\n\n/** Every accessor of one circuit, keyed by device id. */\nexport type DeviceAccessors = Readonly<Record<string, DeviceAccessor>>;\n\n/**\n * Accessor map derived from a literal compilation input.\n *\n * `Circuit.create` infers the device ids of a `const` input, so\n * `circuit.devices.<id>` is typed without a cast. A device package that wants a\n * richer surface builds it through `DeviceDescription.accessor` and casts at\n * the call site.\n */\nexport type DeviceAccessorsOf<I extends CircuitCompilationInput> = {\n readonly [D in I['devices'][number] as D['id']]: DeviceAccessor;\n};\n","import type { FloatBits, IRInterpreter, RuntimeScalar } from '@mica-js/ir';\nimport type {\n CompiledCircuit,\n DeviceMetadata,\n DeviceStateSlot,\n ResolvedDevicePin,\n} from '../compiler';\nimport { CircuitError, type DeviceAccessor, type DeviceAccessors } from './types';\n\n/** Everything the accessor builders read from one live circuit. */\nexport interface DeviceAccessorContext {\n readonly compiled: CompiledCircuit;\n readonly jit: IRInterpreter;\n /** Invoked before every read or write; throws once the circuit is disposed. */\n readonly assertActive: () => void;\n /** Advances the circuit by one tick; used by custom accessors. */\n readonly step: () => void;\n /** Advances the circuit by `count` ticks; used by custom accessors. */\n readonly runBatch: (count: number) => void;\n}\n\n/**\n * Builds one accessor per compiled device.\n *\n * A description that declares `accessor` owns its surface; every other device\n * keeps the generic state/pin accessor. The returned record is frozen and keyed\n * by device id.\n */\nexport function buildDeviceAccessors(context: DeviceAccessorContext): DeviceAccessors {\n const entries: [string, DeviceAccessor][] = [];\n for (const device of context.compiled.deviceMap.values()) {\n const base = createBaseAccessor(context, device);\n if (device.accessor !== undefined) {\n // A custom kernel owns its accessor: the factory closes over the layout\n // its IR factory allocated in this module.\n entries.push([\n device.deviceId,\n device.accessor({\n deviceId: device.deviceId,\n storage: context.jit.storage,\n assertActive: context.assertActive,\n step: context.step,\n runBatch: context.runBatch,\n }) as unknown as DeviceAccessor,\n ]);\n } else {\n entries.push([device.deviceId, base]);\n }\n }\n // `Object.fromEntries` defines own data properties, so ids such as\n // `__proto__` stay ordinary keys instead of reaching the prototype chain.\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction createBaseAccessor(\n context: DeviceAccessorContext,\n device: DeviceMetadata,\n): DeviceAccessor {\n const { jit } = context;\n const storage = jit.storage;\n const memory = context.compiled.memory;\n const resolved = context.compiled.pins.devices.get(device.deviceId)?.resolved;\n\n const accessor: DeviceAccessor = {\n deviceId: device.deviceId,\n type: device.type,\n pinNames: Object.freeze([...device.pins.keys()]),\n stateNames: Object.freeze([...device.states.keys()]),\n readPin(pinName: string): boolean {\n context.assertActive();\n const pin = pinOf(device, resolved, pinName);\n return storage.loadArray(memory.output, pin.globalPinId) === true;\n },\n writePin(pinName: string, value: boolean): void {\n context.assertActive();\n const pin = pinOf(device, resolved, pinName);\n if (pin.role !== 'driver') {\n throw new CircuitError(\n 'pin-not-writable',\n `Pin \"${device.deviceId}.${pinName}\" has role \"${pin.role}\"; only driver pins can be written. Use Circuit.setPin to override a sensed level`,\n { deviceId: device.deviceId, pinName },\n );\n }\n assertBoolean(device.deviceId, pinName, value);\n storage.storeArray(memory.output, pin.globalPinId, value);\n },\n getState(name: string): unknown {\n context.assertActive();\n const slot = stateOf(device, name);\n return storage.loadArray(slot.array, slot.index);\n },\n setState(name: string, value: unknown): void {\n context.assertActive();\n const slot = stateOf(device, name);\n const accepted = coerceStateValue(device, slot, value);\n try {\n storage.storeArray(slot.array, slot.index, accepted);\n } catch (cause) {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${name}\" (${slot.type}) rejected ${String(value)}`,\n { deviceId: device.deviceId, stateName: name, cause },\n );\n }\n },\n };\n return Object.freeze(accessor);\n}\n\n/** Resolves one pin of `device`, or throws with every pin the device declares. */\nfunction pinOf(\n device: DeviceMetadata,\n resolved: ReadonlyMap<string, ResolvedDevicePin> | undefined,\n pinName: string,\n): ResolvedDevicePin {\n const pin = resolved?.get(pinName);\n if (pin === undefined) {\n throw new CircuitError(\n 'pin-not-found',\n `Device \"${device.deviceId}\" (${device.type}) has no pin \"${pinName}\". Available: ${formatNames(device.pins.keys())}`,\n { deviceId: device.deviceId, pinName },\n );\n }\n return pin;\n}\n\n/** Resolves one state slot of `device`, or throws with every state it declares. */\nfunction stateOf(device: DeviceMetadata, name: string): DeviceStateSlot {\n const slot = device.states.get(name);\n if (slot === undefined) {\n throw new CircuitError(\n 'state-not-found',\n `Device \"${device.deviceId}\" (${device.type}) has no state \"${name}\". Available: ${formatNames(device.states.keys())}`,\n { deviceId: device.deviceId, stateName: name },\n );\n }\n return slot;\n}\n\nfunction assertBoolean(\n deviceId: string,\n pinName: string,\n value: unknown,\n): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new CircuitError(\n 'invalid-state-value',\n `Pin \"${deviceId}.${pinName}\" needs a boolean level, received ${typeof value}`,\n { deviceId, pinName },\n );\n }\n}\n\n/**\n * Validates a host-written state value against the declared scalar type.\n * Range checks stay in storage, which owns the encoding.\n */\nfunction coerceStateValue(\n device: DeviceMetadata,\n slot: DeviceStateSlot,\n value: unknown,\n): RuntimeScalar {\n if (slot.type === 'bool') {\n if (typeof value !== 'boolean') {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is bool and needs true or false, received ${String(value)}`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n return value;\n }\n if (slot.type === 'f32' || slot.type === 'f64') {\n if (typeof value === 'number' || isFloatBits(value)) return value;\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is ${slot.type} and needs a number or FloatBits`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is ${slot.type} and needs an integer, received ${String(value)}`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n return value;\n}\n\nfunction isFloatBits(value: unknown): value is FloatBits {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as { readonly type?: unknown; readonly bits?: unknown };\n return (\n (candidate.type === 'f32' || candidate.type === 'f64') && typeof candidate.bits === 'string'\n );\n}\n\nfunction formatNames(names: Iterable<string>): string {\n const list = [...names];\n return list.length === 0 ? '(none)' : `[${list.join(', ')}]`;\n}\n","import { createIRInterpreter, createIRJIT } from '@mica-js/ir';\nimport type {\n ArrayRef,\n BytesRef,\n IRInterpreter,\n IRJITTuning,\n RuntimeScalar,\n StateRef,\n} from '@mica-js/ir';\nimport { compileCircuit } from '../compiler';\nimport type {\n CircuitCompilationInput,\n CircuitCompilationOptions,\n CompiledCircuit,\n} from '../compiler';\nimport { PIN_MODE } from '../pin-space';\nimport { buildDeviceAccessors } from './accessors';\nimport {\n CircuitError,\n type CircuitEngine,\n type CircuitRuntimeOptions,\n type DeviceAccessorsOf,\n} from './types';\n\n/** Every generated entry takes no arguments, so one frozen array is reused. */\nconst NO_ARGS: readonly RuntimeScalar[] = Object.freeze([]);\n\n/** `unified_tick_batch` takes a u32 tick count. */\nconst MAX_BATCH_TICKS = 0xffff_ffff;\n\n/** Virtual time is a JS number, so it wraps before losing integer precision. */\nconst MAX_VIRTUAL_TIME = Number.MAX_SAFE_INTEGER;\n\nconst DEFAULT_INSTANCE_ID = 'unified-circuit';\n\n/**\n * Mutable execution context. `IRExecutionContext` is readonly for callers; the\n * runtime owns this object and updates `virtualTime` in place so that `step()`\n * allocates nothing on the hot path.\n */\ninterface RuntimeContext {\n instanceId: string;\n virtualTime: number;\n}\n\n/** One pin of the global address space, resolved at construction time. */\ninterface PinRuntime {\n readonly globalPinId: number;\n readonly role: 'driver' | 'load';\n /** Whether the device reads the solved level of this pin. */\n readonly senses: boolean;\n}\n\n/** Declared initial value of one memory resource, replayed by `reset()`. */\ntype ResetSeed =\n | { readonly kind: 'array'; readonly ref: ArrayRef; readonly values: readonly RuntimeScalar[] }\n | { readonly kind: 'state'; readonly ref: StateRef; readonly value: RuntimeScalar }\n | {\n readonly kind: 'bytes';\n readonly ref: BytesRef<false>;\n readonly values: readonly RuntimeScalar[];\n }\n | {\n readonly kind: 'readonly-bytes';\n readonly ref: BytesRef<true>;\n readonly values: Uint8Array;\n };\n\ninterface ResolvedRuntimeOptions {\n readonly engine: CircuitEngine;\n readonly jit: IRJITTuning | undefined;\n readonly validateIR: boolean;\n readonly rails: Readonly<Record<string, boolean>> | undefined;\n readonly instanceId: string;\n}\n\n/**\n * Host-facing runtime of one compiled unified circuit (U02).\n *\n * ```ts\n * const circuit = await Circuit.create({\n * devices: [\n * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },\n * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },\n * ],\n * connections: [\n * { from: 'drive1.PA0', to: 'sink1.anode' },\n * { from: 'sink1.cathode', to: 'GND' },\n * ],\n * });\n *\n * circuit.runBatch(1_000_000); // one engine call\n * expect(circuit.tickCount).toBe(1_000_000n);\n *\n * circuit.reset();\n * circuit.setPin('drive1.PA0', true); // host drives the pin\n * circuit.step();\n * expect(circuit.devices.sink1.getState('lamp')).toBe(true);\n * ```\n *\n * `Circuit` owns the engine instance and the tick counter; the compiled module\n * keeps every device, net and the main loop in one `@mica-js/ir` module, so a\n * batch is one interpreter/JIT call for the whole circuit.\n */\nexport class Circuit<I extends CircuitCompilationInput = CircuitCompilationInput> {\n /** Typed per-device accessors, keyed by device id. */\n readonly devices: DeviceAccessorsOf<I>;\n\n readonly #compiled: CompiledCircuit;\n readonly #jit: IRInterpreter;\n readonly #context: RuntimeContext;\n readonly #pins: ReadonlyMap<string, PinRuntime>;\n readonly #pinNames: readonly string[];\n readonly #seeds: readonly ResetSeed[];\n #tickCount = 0n;\n #virtualTime = 0;\n #disposed = false;\n\n private constructor(\n compiled: CompiledCircuit,\n jit: IRInterpreter,\n instanceId: string,\n accessors: DeviceAccessorsOf<I>,\n pins: ReadonlyMap<string, PinRuntime>,\n seeds: readonly ResetSeed[],\n ) {\n this.#compiled = compiled;\n this.#jit = jit;\n this.#context = { instanceId, virtualTime: 0 };\n this.devices = accessors;\n this.#pins = pins;\n this.#pinNames = Object.freeze([...pins.keys()]);\n this.#seeds = seeds;\n }\n\n /**\n * Compiles `input`, builds the engine instance and runs the generated\n * `initialize` entry once.\n *\n * The input is inferred as a `const` type, so a literal device list keeps its\n * ids and `circuit.devices.<id>` is typed without a cast.\n *\n * @throws {UnifiedIRCompilerError} when the circuit cannot be compiled.\n * @throws {CircuitError} for invalid options.\n */\n static async create<const I extends CircuitCompilationInput>(\n input: I,\n options: CircuitRuntimeOptions = {},\n ): Promise<Circuit<I>> {\n const resolved = resolveOptions(options);\n const compiled = compileCircuit(input, compileOptionsOf(resolved));\n const jit = createEngine(compiled, resolved);\n // The accessor factories run inside `buildDeviceAccessors`, which happens\n // before `circuit` is assigned. They only close over this holder; the\n // callbacks are invoked after construction.\n const host: { circuit: Circuit<I> | undefined } = { circuit: undefined };\n const circuit = new Circuit<I>(\n compiled,\n jit,\n resolved.instanceId,\n buildDeviceAccessors({\n compiled,\n jit,\n assertActive: () => {\n circuit.#assertActive();\n },\n step: () => {\n host.circuit?.step();\n },\n runBatch: (count) => {\n host.circuit?.runBatch(count);\n },\n }) as DeviceAccessorsOf<I>,\n pinRuntimeOf(compiled),\n resetSeedsOf(compiled),\n );\n host.circuit = circuit;\n // `initialize` runs once at creation; `reset()` replays the same sequence\n // after restoring every memory to its declared initial value.\n jit.execute(compiled.entryPoints.refs.initialize, NO_ARGS, circuit.#context);\n return circuit;\n }\n\n /**\n * Runs `count` ticks inside one generated loop — the throughput path.\n *\n * The whole batch is one engine call; `tickCount` grows by `count` once the\n * call returns, so a failed batch never advances the clock.\n *\n * @throws {CircuitError} with code `invalid-count` unless `count` is a u32.\n */\n runBatch(count: number): void {\n this.#assertActive();\n if (\n typeof count !== 'number' ||\n !Number.isSafeInteger(count) ||\n count < 0 ||\n count > MAX_BATCH_TICKS\n ) {\n throw new CircuitError(\n 'invalid-count',\n `runBatch(count) needs an integer in [0, ${MAX_BATCH_TICKS}], received ${String(count)}`,\n );\n }\n if (count === 0) return;\n this.#context.virtualTime = this.#virtualTime;\n this.#jit.execute(this.#compiled.entryPoints.refs.batch, [count], this.#context);\n this.#advance(count);\n }\n\n /**\n * Advances exactly one tick — the debugging path.\n *\n * Every call is one engine entry, so prefer `runBatch` for throughput.\n */\n step(): void {\n this.#assertActive();\n this.#context.virtualTime = this.#virtualTime;\n this.#jit.execute(this.#compiled.entryPoints.refs.tick, NO_ARGS, this.#context);\n this.#advance(1);\n }\n\n /**\n * Restores every memory to its declared initial value, re-runs `initialize`\n * and resets `tickCount` to `0n`.\n *\n * Device state written by earlier ticks is discarded, so the circuit behaves\n * exactly like a freshly created one.\n */\n reset(): void {\n this.#assertActive();\n for (const seed of this.#seeds) {\n if (seed.kind === 'state') {\n this.#jit.storage.storeState(seed.ref, seed.value);\n continue;\n }\n if (seed.kind === 'bytes') {\n for (let index = 0; index < seed.values.length; index += 1) {\n this.#jit.storage.storeBytes(\n 'u8',\n 'little',\n seed.ref,\n index,\n seed.values[index] as RuntimeScalar,\n );\n }\n continue;\n }\n if (seed.kind === 'readonly-bytes') {\n try {\n this.#jit.storage.updateBytesFromBytes(seed.ref, 0, seed.values);\n } catch {\n // Read-only memories are constants unless their device explicitly\n // grants host update access (for example MCU firmware patching).\n }\n continue;\n }\n for (let index = 0; index < seed.values.length; index += 1) {\n this.#jit.storage.storeArray(seed.ref, index, seed.values[index] as RuntimeScalar);\n }\n }\n this.#tickCount = 0n;\n this.#virtualTime = 0;\n this.#context.virtualTime = 0;\n this.#jit.execute(this.#compiled.entryPoints.refs.initialize, NO_ARGS, this.#context);\n }\n\n /**\n * Reads the level one pin observes.\n *\n * A sensing pin (input, passive or bidirectional) reports the solved net\n * level; a pure driver pin reports the level it actually drives, which is\n * `false` unless it is configured push-pull.\n *\n * @throws {CircuitError} with code `pin-not-found`.\n */\n getPin(pinName: string): boolean {\n this.#assertActive();\n const pin = this.#pinRuntime(pinName);\n const storage = this.#jit.storage;\n if (pin.senses) {\n return storage.loadArray(this.#compiled.memory.input, pin.globalPinId) === true;\n }\n const mode = Number(storage.loadArray(this.#compiled.memory.mode, pin.globalPinId));\n return (\n mode === PIN_MODE.pushPull &&\n storage.loadArray(this.#compiled.memory.output, pin.globalPinId) === true\n );\n }\n\n /**\n * Forces the level of one pin from the host.\n *\n * A driver pin gets its output latch written, so the level survives the next\n * electrical solve. A sensing pin gets the solved-value slot overridden, which\n * lasts until the next tick recomputes its net.\n *\n * @throws {CircuitError} with code `pin-not-found`.\n */\n setPin(pinName: string, value: boolean): void {\n this.#assertActive();\n const pin = this.#pinRuntime(pinName);\n if (typeof value !== 'boolean') {\n throw new CircuitError(\n 'invalid-state-value',\n `Pin \"${pinName}\" needs a boolean level, received ${typeof value}`,\n { pinName },\n );\n }\n const target =\n pin.role === 'driver' ? this.#compiled.memory.output : this.#compiled.memory.input;\n this.#jit.storage.storeArray(target, pin.globalPinId, value);\n }\n\n /** Number of ticks completed since creation or the last `reset()`. */\n get tickCount(): bigint {\n this.#assertActive();\n return this.#tickCount;\n }\n\n /** Virtual tick time completed since creation or the last `reset()`. */\n get virtualTime(): number {\n this.#assertActive();\n return this.#virtualTime;\n }\n\n /** Underlying engine instance, e.g. for diagnostics or custom entries. */\n get jit(): IRInterpreter {\n this.#assertActive();\n return this.#jit;\n }\n\n /** Whether `dispose()` already ran. */\n get disposed(): boolean {\n return this.#disposed;\n }\n\n /**\n * Releases the runtime. Idempotent; every later call throws a `CircuitError`\n * with code `disposed`, including stale device accessors.\n */\n dispose(): void {\n this.#disposed = true;\n this.#tickCount = 0n;\n this.#virtualTime = 0;\n }\n\n /** @internal Shared guard of the circuit and all of its accessors. */\n #assertActive(): void {\n if (this.#disposed) {\n throw new CircuitError(\n 'disposed',\n 'Circuit has been disposed; create a new circuit to keep simulating',\n );\n }\n }\n\n #advance(count: number): void {\n this.#tickCount += BigInt(count);\n const next = this.#virtualTime + count;\n this.#virtualTime = next > MAX_VIRTUAL_TIME ? 0 : next;\n }\n\n #pinRuntime(pinName: string): PinRuntime {\n const pin = this.#pins.get(pinName);\n if (pin === undefined) {\n throw new CircuitError(\n 'pin-not-found',\n `Pin \"${pinName}\" not found. Available: ${this.#pinNames.length === 0 ? '(none)' : `[${this.#pinNames.join(', ')}]`}`,\n { pinName },\n );\n }\n return pin;\n }\n}\n\n/** Resolves every pin of the global address space into its runtime view. */\nfunction pinRuntimeOf(compiled: CompiledCircuit): ReadonlyMap<string, PinRuntime> {\n const pins = new Map<string, PinRuntime>();\n for (const [deviceId, allocation] of compiled.pins.devices) {\n for (const [pinName, pin] of allocation.resolved) {\n pins.set(\n `${deviceId}.${pinName}`,\n Object.freeze({\n globalPinId: pin.globalPinId,\n role: pin.role,\n senses: pin.senses,\n }),\n );\n }\n }\n return pins;\n}\n\n/**\n * Captures the declared initial value of every scalar memory, which is what\n * `reset()` restores before the generated `initialize` runs again.\n */\nfunction resetSeedsOf(compiled: CompiledCircuit): readonly ResetSeed[] {\n const seeds: ResetSeed[] = [];\n for (const memory of compiled.module.memories) {\n if (memory.kind === 'array') {\n seeds.push({\n kind: 'array',\n ref: memory.ref as ArrayRef,\n values: memory.initial as readonly RuntimeScalar[],\n });\n } else if (memory.kind === 'state') {\n seeds.push({\n kind: 'state',\n ref: memory.ref as StateRef,\n value: memory.initial[0] as RuntimeScalar,\n });\n } else if (memory.kind === 'bytes') {\n if (memory.writable) {\n seeds.push({\n kind: 'bytes',\n ref: memory.ref as BytesRef<false>,\n values: memory.initial as readonly RuntimeScalar[],\n });\n } else {\n seeds.push({\n kind: 'readonly-bytes',\n ref: memory.ref as BytesRef<true>,\n values: Uint8Array.from(memory.initial as readonly number[]),\n });\n }\n }\n }\n return Object.freeze(seeds);\n}\n\nfunction createEngine(compiled: CompiledCircuit, options: ResolvedRuntimeOptions): IRInterpreter {\n const base = {\n validation: compiled.validation,\n // One batch can execute hundreds of millions of instructions; the default\n // step budget is tuned for single entries, not for a loop in the IR.\n maxSteps: Number.MAX_SAFE_INTEGER,\n };\n if (options.engine === 'reference') {\n return createIRInterpreter(compiled.module, base);\n }\n return createIRJIT(compiled.module, {\n ...base,\n jit: { tierUpThreshold: 0, ...options.jit },\n });\n}\n\nfunction compileOptionsOf(options: ResolvedRuntimeOptions): CircuitCompilationOptions {\n return {\n validate: options.validateIR,\n ...(options.rails === undefined ? {} : { rails: options.rails }),\n };\n}\n\nfunction resolveOptions(options: unknown): ResolvedRuntimeOptions {\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw new CircuitError('invalid-options', 'Circuit options must be a plain object');\n }\n const candidate = options as CircuitRuntimeOptions;\n\n const engine = candidate.engine ?? 'jit';\n if (engine !== 'jit' && engine !== 'reference') {\n throw new CircuitError(\n 'invalid-options',\n `engine=${String(engine)} must be \"jit\" or \"reference\"`,\n );\n }\n\n if (candidate.validateIR !== undefined && typeof candidate.validateIR !== 'boolean') {\n throw new CircuitError('invalid-options', 'validateIR must be a boolean');\n }\n\n if (candidate.instanceId !== undefined && candidate.instanceId.length === 0) {\n throw new CircuitError('invalid-options', 'instanceId must be a non-empty string');\n }\n\n if (candidate.jit !== undefined) {\n if (\n candidate.jit === null ||\n typeof candidate.jit !== 'object' ||\n Array.isArray(candidate.jit)\n ) {\n throw new CircuitError('invalid-options', 'jit must be a JIT tuning object');\n }\n }\n\n let rails: Readonly<Record<string, boolean>> | undefined;\n if (candidate.electrical !== undefined) {\n const electrical = candidate.electrical;\n if (electrical === null || typeof electrical !== 'object' || Array.isArray(electrical)) {\n throw new CircuitError('invalid-options', 'electrical must be a plain object');\n }\n rails = electrical.rails;\n }\n\n return Object.freeze({\n engine,\n jit: candidate.jit,\n validateIR: candidate.validateIR ?? true,\n rails,\n instanceId: candidate.instanceId ?? DEFAULT_INSTANCE_ID,\n });\n}\n","import type { PayloadType } from '@mica-js/core/canvas';\nimport { deriveSchematicTopology, parseDeviceReference, symbolRole } from '@mica-js/core/schematic';\nimport type {\n DeviceReference,\n DeviceSymbolProvider,\n SchematicDocument,\n} from '@mica-js/core/schematic';\nimport { DEFAULT_RAILS } from '../compiler';\nimport type {\n CircuitCompilationInput,\n Connection,\n DeviceConfig,\n DeviceDescription,\n} from '../compiler';\nimport { Circuit } from './circuit';\nimport { CircuitError, type CircuitRuntimeOptions, type DeviceAccessor } from './types';\n\n/**\n * One endpoint a caller-supplied device declares to the simulation host.\n *\n * The simulator never guesses ports from a device type: the package that\n * resolves the reference states which payloads the device accepts and which it\n * publishes, in the same place it supplies the IR description.\n */\nexport interface SchematicDeviceTopic {\n readonly port: string;\n readonly direction: 'input' | 'output';\n readonly type: PayloadType;\n readonly title?: string;\n}\n\n/** Runtime behaviour of one schematic device package. */\nexport interface SchematicDeviceBinding {\n /** Device type, e.g. `'counter-ir'`. */\n readonly type: string;\n /** IR description: pins, states and behaviours. */\n readonly description: DeviceDescription;\n /** Instance configuration reserved for device kernels. */\n readonly config?: Readonly<Record<string, unknown>>;\n /** Endpoints the simulation host exposes; absent means the device has none. */\n readonly topics?: readonly SchematicDeviceTopic[];\n /** Bridges one input topic payload onto the compiled device accessor. */\n deliver?(accessor: DeviceAccessor, port: string, payload: unknown): void;\n /** Reads one output topic from the compiled device accessor. */\n read?(accessor: DeviceAccessor, port: string): unknown;\n}\n\n/** Options for {@link createCircuitFromSchematic}. */\nexport interface SchematicCircuitOptions extends CircuitRuntimeOptions {\n /**\n * Symbol geometry provider — pass the same provider that authored the\n * schematic. Without it the derived topology contains no pins.\n */\n readonly devices?: DeviceSymbolProvider;\n /** Resolves a schematic device reference to its runtime description. */\n readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n /** Coordinate tolerance used when matching pins to wires. */\n readonly tolerance?: number;\n}\n\n/**\n * Compiles a schematic sheet into a circuit.\n *\n * Nets come from `deriveSchematicTopology`, so wires, junctions, labels and\n * power symbols keep their usual meaning: a net that names a rail connects\n * every member to that rail, and any other net joins its pins pairwise (the\n * compiler merges transitively).\n *\n * ```ts\n * const circuit = await createCircuitFromSchematic(schematic, {\n * devices: symbolProvider,\n * resolveDevice: (reference) => bindings.get(reference.deviceId),\n * });\n * ```\n *\n * @throws {CircuitError} with code `unresolved-device` when a component symbol\n * has no binding; `SchematicError` for malformed sheets.\n */\nexport async function createCircuitFromSchematic(\n schematic: SchematicDocument,\n options: SchematicCircuitOptions,\n): Promise<Circuit> {\n return (await createSchematicCircuit(schematic, options)).circuit;\n}\n\n/** One component symbol of a compiled schematic. */\nexport interface SchematicCircuitBinding {\n /** Symbol id as written in the schematic. */\n readonly symbolId: string;\n /** Compiler-safe device id assigned to the symbol. */\n readonly deviceId: string;\n /** Parsed `\"<packageId>:<deviceId>\"` reference. */\n readonly reference: DeviceReference;\n /** Device type from the resolved runtime binding. */\n readonly type: string;\n}\n\n/** A compiled schematic circuit plus the symbol-to-device mapping it produced. */\nexport interface SchematicCircuitResult {\n readonly circuit: Circuit;\n /** Component symbols in schematic order; non-component symbols are absent. */\n readonly bindings: readonly SchematicCircuitBinding[];\n}\n\n/**\n * Compiles a schematic and reports which circuit device each symbol became.\n *\n * {@link createCircuitFromSchematic} returns only the circuit; hosts that route\n * schematic endpoints to circuit accessors need the mapping as well.\n */\nexport async function createSchematicCircuit(\n schematic: SchematicDocument,\n options: SchematicCircuitOptions,\n): Promise<SchematicCircuitResult> {\n if (\n schematic === null ||\n typeof schematic !== 'object' ||\n schematic.sheet === null ||\n typeof schematic.sheet !== 'object' ||\n !Array.isArray(schematic.sheet.symbols) ||\n !Array.isArray(schematic.sheet.wires) ||\n !Array.isArray(schematic.sheet.junctions)\n ) {\n throw new CircuitError(\n 'invalid-options',\n 'createSchematicCircuit needs a schematic with sheet.symbols, sheet.wires and sheet.junctions',\n );\n }\n if (options === null || typeof options !== 'object') {\n throw new CircuitError('invalid-options', 'createSchematicCircuit needs options');\n }\n const { resolveDevice, devices, tolerance, ...runtime } = options;\n if (typeof resolveDevice !== 'function') {\n throw new CircuitError('invalid-options', 'resolveDevice must be a function');\n }\n\n const usedIds = new Set<string>();\n const deviceIdBySymbol = new Map<string, string>();\n const deviceConfigs: DeviceConfig[] = [];\n const bindings: SchematicCircuitBinding[] = [];\n let componentCount = 0;\n\n for (const symbol of schematic.sheet.symbols) {\n if (symbolRole(symbol.device) !== 'component') continue;\n componentCount += 1;\n const reference = parseDeviceReference(symbol.device);\n const binding = reference === undefined ? undefined : resolveDevice(reference);\n if (binding === undefined) {\n throw new CircuitError(\n 'unresolved-device',\n `Symbol \"${symbol.id}\" (${symbol.device}) has no runtime device binding; resolve it in resolveDevice`,\n { deviceId: symbol.id },\n );\n }\n const deviceId = uniqueDeviceId(symbol.designator ?? symbol.id, usedIds);\n usedIds.add(deviceId);\n deviceIdBySymbol.set(symbol.id, deviceId);\n deviceConfigs.push({\n id: deviceId,\n type: binding.type,\n description: binding.description,\n ...(binding.config === undefined ? {} : { config: binding.config }),\n });\n if (reference !== undefined) {\n bindings.push({\n symbolId: symbol.id,\n deviceId,\n reference,\n type: binding.type,\n });\n }\n }\n\n const topology = deriveSchematicTopology(schematic, {\n ...(devices === undefined ? {} : { devices }),\n ...(tolerance === undefined ? {} : { tolerance }),\n });\n if (componentCount > 0 && topology.pins.length === 0) {\n throw new CircuitError(\n 'invalid-options',\n 'The derived topology has no pins; pass the DeviceSymbolProvider that authored the schematic so pins can be located',\n );\n }\n\n const railNames = new Set([\n ...Object.keys(DEFAULT_RAILS),\n ...Object.keys(options.electrical?.rails ?? {}),\n ]);\n const connections: Connection[] = [];\n\n for (const net of topology.nets) {\n const endpoints: string[] = [];\n let rail: string | undefined;\n for (const member of net.members) {\n if (member.kind === 'pin') {\n const deviceId = deviceIdBySymbol.get(member.symbolId);\n if (deviceId === undefined) {\n throw new CircuitError(\n 'unresolved-device',\n `Net \"${net.name ?? 'anonymous'}\" references pin \"${member.pinId}\" of symbol \"${member.symbolId}\", which has no runtime device`,\n { deviceId: member.symbolId },\n );\n }\n endpoints.push(`${deviceId}.${member.pinId}`);\n continue;\n }\n if (member.kind === 'power' || member.kind === 'ground') {\n rail = net.name ?? rail;\n }\n }\n if (endpoints.length === 0) continue;\n // A named net that matches a rail ties its pins to that rail; everything\n // else is joined to the first pin, which the compiler merges transitively.\n const railName = rail ?? (net.name !== null && railNames.has(net.name) ? net.name : undefined);\n if (railName !== undefined) {\n for (const endpoint of endpoints) connections.push({ from: endpoint, to: railName });\n continue;\n }\n const first = endpoints[0] as string;\n for (const endpoint of endpoints.slice(1)) connections.push({ from: first, to: endpoint });\n }\n\n const input: CircuitCompilationInput = {\n devices: Object.freeze(deviceConfigs),\n connections: Object.freeze(connections),\n };\n const circuit = await Circuit.create(input, runtime);\n return Object.freeze({ circuit, bindings: Object.freeze(bindings) });\n}\n\n/**\n * Turns a designator or symbol id into a compiler-safe device id.\n *\n * Device ids prefix generated IR function names, so they must be identifiers.\n */\nfunction uniqueDeviceId(preferred: string, used: ReadonlySet<string>): string {\n const base = sanitizeDeviceId(preferred);\n if (!used.has(base)) return base;\n for (let suffix = 2; ; suffix += 1) {\n const candidate = `${base}_${suffix}`;\n if (!used.has(candidate)) return candidate;\n }\n}\n\nfunction sanitizeDeviceId(value: string): string {\n const cleaned = value.replace(/[^A-Za-z0-9_]/g, '_');\n if (cleaned.length === 0) return 'device';\n return /^[A-Za-z_]/.test(cleaned) ? cleaned : `d_${cleaned}`;\n}\n","import type { SchematicDocument } from '@mica-js/core/schematic';\nimport type { CanvasBindingTarget } from '@mica-js/core/canvas';\nimport { toDisposable } from '@mica-js/core/lifecycle';\nimport type { Circuit } from '../unified-ir/runtime';\nimport type { DeviceSimulationHost, DeviceSimTickReport, DeviceTopic } from './types';\n\n/** Picoseconds per circuit step used when mapping `Circuit.virtualTime` to simulation time. */\nconst DEFAULT_STEP_PS = 10_000;\n\nexport interface CircuitDeviceSimulationHostOptions {\n /** Circuit the caller already created. */\n readonly circuit: Circuit;\n /** Whether `dispose()` also disposes the circuit. Defaults to `true`. */\n readonly ownsCircuit?: boolean;\n /** Schematic the circuit was built from, reported through `getSchematic`. */\n readonly schematic?: SchematicDocument;\n /** Endpoints the running devices expose. */\n readonly topics?: readonly DeviceTopic[];\n /** Picoseconds per circuit step. Defaults to 10 ns. */\n readonly stepPs?: number;\n /** Routes one widget payload into the caller's device layer. */\n readonly deliver: (symbol: string, port: string, payload: unknown) => void;\n}\n\n/**\n * Adapts one already-loaded unified-IR circuit to the RFC 0018 device host.\n *\n * This is the same-thread adapter for an owner that keeps `Circuit` accessors for itself (a\n * diagnostics bench, for example). Application/canvas integration uses\n * `createDeviceSimulationHostFromSandbox` from `@mica-js/simulator/sandbox` and never holds a circuit.\n */\nexport function createCircuitDeviceSimulationHost({\n circuit,\n ownsCircuit = true,\n schematic,\n topics = [],\n stepPs = DEFAULT_STEP_PS,\n deliver,\n}: CircuitDeviceSimulationHostOptions): DeviceSimulationHost {\n const simTime = (): number => circuit.virtualTime * stepPs;\n\n return {\n async loadSchematic() {\n // The caller built the circuit before constructing this adapter.\n },\n async reset() {\n circuit.reset();\n },\n async tick(dt: number): Promise<DeviceSimTickReport> {\n if (!Number.isSafeInteger(dt) || dt <= 0) {\n throw new TypeError(\n `DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`,\n );\n }\n circuit.runBatch(1);\n return { simTime: simTime(), executed: 1 };\n },\n async deliver(target: CanvasBindingTarget, payload: unknown) {\n deliver(target.symbol, target.port, payload);\n },\n onDidPublish: () =>\n toDisposable(() => {\n // The owner drives publishing through its own device layer.\n }),\n async getTopics() {\n return topics;\n },\n async getSimTime() {\n return simTime();\n },\n async getSchematic() {\n return schematic;\n },\n async dispose() {\n if (ownsCircuit) circuit.dispose();\n },\n };\n}\n","import type { DeviceReference, DeviceSymbolProvider } from '@mica-js/core/schematic';\nimport { parseSchematic } from '@mica-js/core/schematic';\nimport type { SchematicDocument } from '@mica-js/core/schematic';\nimport type { CanvasBindingTarget, PayloadType } from '@mica-js/core/canvas';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport { createSchematicCircuit } from '../unified-ir/runtime';\nimport type { Circuit, SchematicDeviceBinding, SchematicDeviceTopic } from '../unified-ir/runtime';\nimport type { DeviceAccessor } from '../unified-ir/runtime/types';\nimport type {\n DeviceSimulationHost,\n DeviceSimTickReport,\n DeviceTopic,\n SimulationPublish,\n} from './types';\n\n/** Reads the bytes of one schematic URI; the caller resolves relative references. */\nexport interface SchematicDeviceSimulationHostOptions {\n readonly read: (uri: string) => Promise<Uint8Array>;\n /**\n * Symbol geometry of the schematics this host loads. Pass the same provider the schematic was\n * authored with; without it the derived topology contains no pins. A factory is called when a\n * schematic loads, so a caller can read its device library first.\n */\n readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);\n /**\n * Resolves one schematic device reference to its runtime description and endpoints.\n *\n * The host ships no device models: the package that owns the devices decides which references\n * exist, what they look like and which topics they expose.\n */\n readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n}\n\ninterface LoadedDevice {\n readonly symbol: string;\n readonly designator: string;\n readonly binding: SchematicDeviceBinding;\n readonly accessor: DeviceAccessor;\n}\n\ninterface LoadedRuntime {\n readonly circuit: Circuit;\n readonly schematic: SchematicDocument;\n readonly devices: readonly LoadedDevice[];\n readonly topics: readonly DeviceTopic[];\n readonly inputs: ReadonlyMap<string, InputBinding>;\n}\n\ninterface InputBinding {\n readonly device: LoadedDevice;\n readonly topic: SchematicDeviceTopic;\n}\n\ninterface PendingDelivery {\n readonly device: LoadedDevice;\n readonly port: string;\n readonly payload: unknown;\n}\n\nconst INSTANCE_ID = 'device-simulation-host';\n\nfunction targetKey(deviceId: string, port: string): string {\n return `${deviceId}\\u0000${port}`;\n}\n\n/**\n * Value equality of two topic payloads.\n *\n * A canvas topic is a `level` unless it carries text or bytes (RFC 0017), so re-sending the value a\n * device already published only costs a widget repaint. Byte payloads compare by content because a\n * device may hand out a fresh buffer per step.\n */\nfunction samePayload(previous: unknown, next: unknown): boolean {\n if (Object.is(previous, next)) return true;\n if (previous instanceof Uint8Array && next instanceof Uint8Array) {\n if (previous.length !== next.length) return false;\n for (let index = 0; index < previous.length; index += 1) {\n if (previous[index] !== next[index]) return false;\n }\n return true;\n }\n if (typeof previous !== 'object' || previous === null) return false;\n if (typeof next !== 'object' || next === null) return false;\n const a = previous as { readonly x?: unknown; readonly y?: unknown; readonly z?: unknown };\n const b = next as { readonly x?: unknown; readonly y?: unknown; readonly z?: unknown };\n return a.x === b.x && a.y === b.y && a.z === b.z;\n}\n\nfunction isVec2d(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) return false;\n const point = value as { readonly x?: unknown; readonly y?: unknown };\n return typeof point.x === 'number' && typeof point.y === 'number';\n}\n\nfunction payloadMatches(type: PayloadType, payload: unknown): boolean {\n switch (type) {\n case 'boolean':\n return typeof payload === 'boolean';\n case 'number':\n return typeof payload === 'number';\n case 'string':\n return typeof payload === 'string';\n case 'bytes':\n case 'bytes<rgb565>':\n case 'bytes<segments>':\n return payload instanceof Uint8Array;\n case 'vec2d':\n return isVec2d(payload);\n case 'vec3d':\n return isVec2d(payload) && typeof (payload as { readonly z?: unknown }).z === 'number';\n }\n}\n\nfunction decodeSchematic(bytes: Uint8Array): SchematicDocument {\n return parseSchematic(new TextDecoder().decode(bytes));\n}\n\nfunction buildRuntime(\n circuit: Circuit,\n schematic: SchematicDocument,\n bindings: Awaited<ReturnType<typeof createSchematicCircuit>>['bindings'],\n resolveDevice: SchematicDeviceSimulationHostOptions['resolveDevice'],\n): LoadedRuntime {\n const symbols = new Map(schematic.sheet.symbols.map((symbol) => [symbol.id, symbol]));\n const devices: LoadedDevice[] = [];\n const topics: DeviceTopic[] = [];\n const inputs = new Map<string, InputBinding>();\n\n for (const binding of bindings) {\n const deviceBinding = resolveDevice(binding.reference);\n const accessor = circuit.devices[binding.deviceId];\n if (deviceBinding === undefined || accessor === undefined) continue;\n const symbol = symbols.get(binding.symbolId);\n const designator = symbol?.designator ?? binding.symbolId;\n const device: LoadedDevice = {\n symbol: binding.symbolId,\n designator,\n binding: deviceBinding,\n accessor,\n };\n devices.push(device);\n for (const topic of deviceBinding.topics ?? []) {\n topics.push({\n symbol: binding.symbolId,\n designator,\n port: topic.port,\n direction: topic.direction,\n type: topic.type,\n ...(topic.title === undefined ? {} : { title: topic.title }),\n });\n if (topic.direction === 'input')\n inputs.set(targetKey(binding.symbolId, topic.port), { device, topic });\n }\n }\n\n return {\n circuit,\n schematic,\n devices,\n topics: Object.freeze(topics),\n inputs,\n };\n}\n\n/**\n * Same-thread `DeviceSimulationHost` over a schematic compiled by the unified-IR runtime.\n *\n * The host owns the circuit: `loadSchematic` reads, parses and compiles it, `tick` advances one\n * circuit step and publishes the output topics that changed, and `deliver` queues widget payloads\n * for the next step. Device models and their endpoints come from `resolveDevice`, so the host stays\n * generic. Nothing here touches the DOM, so the sandbox guest and a Node test use the same\n * implementation.\n */\nexport function createSchematicDeviceSimulationHost(\n options: SchematicDeviceSimulationHostOptions,\n): DeviceSimulationHost {\n if (typeof options?.resolveDevice !== 'function') {\n throw new TypeError('createSchematicDeviceSimulationHost needs a resolveDevice function');\n }\n const { read, devices: symbols, resolveDevice } = options;\n const publishes = new Emitter<SimulationPublish>();\n const pending: PendingDelivery[] = [];\n /** Last payload published per endpoint, so an unchanged level topic stays silent. */\n const published = new Map<string, unknown>();\n let runtime: LoadedRuntime | undefined;\n let simTimePs = 0;\n let disposed = false;\n\n const publishOutputs = (active: LoadedRuntime): void => {\n if (!publishes.hasListeners) return;\n for (const device of active.devices) {\n for (const topic of device.binding.topics ?? []) {\n if (topic.direction !== 'output' || device.binding.read === undefined) continue;\n const key = targetKey(device.symbol, topic.port);\n const payload = device.binding.read(device.accessor, topic.port);\n // Only a change is news to a level port; repeating it would make every widget repaint on\n // every step the circuit does not touch.\n if (published.has(key) && samePayload(published.get(key), payload)) continue;\n published.set(key, payload);\n const publish: SimulationPublish = {\n target: { symbol: device.symbol, port: topic.port },\n payload,\n simTime: simTimePs,\n };\n publishes.fire(publish);\n }\n }\n };\n\n const clearRuntime = (): void => {\n runtime?.circuit.dispose();\n runtime = undefined;\n pending.length = 0;\n published.clear();\n simTimePs = 0;\n };\n\n return {\n async loadSchematic(uri: string | undefined): Promise<void> {\n if (disposed) return;\n if (uri === undefined) {\n clearRuntime();\n return;\n }\n const bytes = await read(uri);\n const schematic = decodeSchematic(bytes);\n const symbolProvider = typeof symbols === 'function' ? symbols() : symbols;\n const compiled = await createSchematicCircuit(schematic, {\n ...(symbolProvider === undefined ? {} : { devices: symbolProvider }),\n resolveDevice,\n instanceId: INSTANCE_ID,\n });\n const next = buildRuntime(compiled.circuit, schematic, compiled.bindings, resolveDevice);\n runtime?.circuit.dispose();\n pending.length = 0;\n // A fresh runtime starts from its initial state, so the first step after it publishes again.\n published.clear();\n simTimePs = 0;\n runtime = next;\n },\n\n async reset(): Promise<void> {\n if (disposed) return;\n pending.length = 0;\n published.clear();\n simTimePs = 0;\n runtime?.circuit.reset();\n },\n\n async tick(dt: number): Promise<DeviceSimTickReport> {\n if (!Number.isSafeInteger(dt) || dt <= 0) {\n throw new TypeError(\n `DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`,\n );\n }\n if (disposed) {\n return { simTime: simTimePs, executed: 0 };\n }\n const active = runtime;\n if (active === undefined) {\n simTimePs += dt;\n return { simTime: simTimePs, executed: 0 };\n }\n const queued = pending.splice(0, pending.length);\n for (const delivery of queued) {\n if (delivery.device.binding.deliver === undefined) {\n throw new TypeError(\n `${delivery.device.binding.type} has no writable topic ${JSON.stringify(delivery.port)}`,\n );\n }\n delivery.device.binding.deliver(delivery.device.accessor, delivery.port, delivery.payload);\n }\n active.circuit.runBatch(1);\n simTimePs += dt;\n publishOutputs(active);\n return { simTime: simTimePs, executed: 1 };\n },\n\n async deliver(target: CanvasBindingTarget, payload: unknown): Promise<void> {\n if (disposed) return;\n const active = runtime;\n if (active === undefined) {\n throw new Error('DeviceSimulationHost has no loaded schematic');\n }\n const binding = active.inputs.get(targetKey(target.symbol, target.port));\n if (binding === undefined) {\n throw new Error(`Unknown device input ${target.symbol}.${target.port}`);\n }\n if (!payloadMatches(binding.topic.type, payload)) {\n throw new TypeError(\n `${target.symbol}.${target.port} expects a ${binding.topic.type} payload`,\n );\n }\n const device = binding.device;\n if (device.binding.deliver === undefined) {\n throw new Error(\n `${device.binding.type} has no writable topic ${JSON.stringify(target.port)}`,\n );\n }\n pending.push({ device, port: target.port, payload });\n },\n\n onDidPublish: publishes.event,\n\n async getTopics(): Promise<readonly DeviceTopic[]> {\n return runtime?.topics ?? [];\n },\n\n async getSimTime(): Promise<number> {\n return simTimePs;\n },\n\n async getSchematic(): Promise<SchematicDocument | undefined> {\n return runtime?.schematic;\n },\n\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n publishes.dispose();\n clearRuntime();\n },\n };\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport { loggerService } from '@mica-js/core/logging';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { DeviceReference, DeviceSymbolProvider } from '@mica-js/core/schematic';\nimport type { SchematicDeviceBinding } from '../unified-ir/runtime';\nimport { deviceSimulationHostFileSystemService, deviceSimulationHostGuestService } from './rpc';\nimport type { DeviceSimulationHostRpc } from './rpc';\nimport { createSchematicDeviceSimulationHost } from './runtime';\n\n/**\n * Device wiring a worker script hands to {@link startDeviceSimulationHostGuest}.\n *\n * The simulator ships no device models, so every option defaults to \"knows no references\": a\n * package that owns devices bundles its own worker script and supplies these.\n */\nexport interface DeviceSimulationHostGuestOptions {\n /** Symbol geometry of the schematics this guest loads, or a factory called per load. */\n readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);\n /** Resolves a schematic device reference; when omitted every reference stays unresolved. */\n readonly resolveDevice?: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n /**\n * Awaited before the first schematic load, so a device library can be read through the host file\n * system before anything compiles. Runs at most once.\n */\n readonly prepare?: () => Promise<void>;\n /**\n * Extra ports the worker received in the first ordinary message. The RPC port comes first, so these are\n * `event.ports` from index 1 onward, in the order the caller transferred them. The first one is\n * the direct topic channel (RFC 0018): the widget guest holds the other end and talks to this\n * guest without the host relaying.\n */\n readonly ports?: readonly MessagePort[];\n}\n\n/** Running guest: where the typed services live and which ports the worker was handed. */\nexport interface DeviceSimulationHostGuest {\n /**\n * Endpoint the typed device simulation services are registered on. A worker script that owns\n * further capabilities registers them here instead of opening a second sandbox channel.\n */\n readonly rpc: RpcEndpoint;\n /** Extra startup ports, in the order the worker received them. */\n readonly ports: readonly MessagePort[];\n /** Releases the circuit and closes the endpoint. */\n dispose(): Promise<void>;\n}\n\n/**\n * Registers RFC 0018's device simulation services on a sandbox RPC port.\n *\n * A worker script obtains the port from `event.ports[0]` and calls this function; nothing else is\n * needed, because the guest is a plain module the `@mica-js/sandbox/vite` plugin bundles into a\n * self-contained script. The guest registers `deviceSimulationHostGuestService` and reads schematics\n * through `deviceSimulationHostFileSystemService`, so schematic bytes never enter the guest's own\n * message handling and every payload is a typed RPC DTO.\n */\nexport function startDeviceSimulationHostGuest(\n port: MessagePort,\n options: DeviceSimulationHostGuestOptions = {},\n): DeviceSimulationHostGuest {\n const { devices, resolveDevice, prepare, ports = [] } = options;\n const rpc = createRpc(port);\n const logger = rpc.getProxy(loggerService);\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'guest-started',\n data: [{ extraPortCount: ports.length }],\n })\n .catch(() => undefined);\n const files = rpc.getProxy(deviceSimulationHostFileSystemService);\n const host = createSchematicDeviceSimulationHost({\n async read(uri: string): Promise<Uint8Array> {\n const bytes = await files.read(uri);\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError(`DeviceSimulationHost file system returned ${typeof bytes} for ${uri}`);\n }\n return bytes;\n },\n ...(devices === undefined ? {} : { devices }),\n resolveDevice: resolveDevice ?? (() => undefined),\n });\n\n let prepared: Promise<void> | undefined;\n const ensurePrepared = async (): Promise<void> => {\n if (prepare === undefined) return;\n prepared ??= prepare();\n try {\n await prepared;\n } catch (error) {\n // A failed preparation must not poison later loads: forget it so the next call retries.\n prepared = undefined;\n throw error;\n }\n };\n\n const service: DeviceSimulationHostRpc = {\n async loadSchematic(uri: string | undefined): Promise<void> {\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'load-schematic-start',\n data: [uri],\n })\n .catch(() => undefined);\n try {\n if (uri !== undefined) await ensurePrepared();\n await host.loadSchematic(uri);\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'load-schematic-end',\n data: [uri],\n })\n .catch(() => undefined);\n } catch (error) {\n void logger\n .write({\n level: 'error',\n scope: 'device-simulation',\n message: 'load-schematic-failed',\n data: [uri, String(error)],\n })\n .catch(() => undefined);\n throw error;\n }\n },\n async reset(): Promise<void> {\n await ensurePrepared();\n return host.reset();\n },\n tick: (dt: number) => host.tick(dt),\n deliver: (target, payload, simTime) => host.deliver(target, payload, simTime),\n onDidPublish: (listener) => {\n const subscription = host.onDidPublish(listener);\n return () => subscription.dispose();\n },\n getTopics: () => host.getTopics(),\n getSimTime: () => host.getSimTime(),\n getSchematic: () => host.getSchematic(),\n dispose: () => host.dispose(),\n };\n\n const registration = rpc.register(deviceSimulationHostGuestService, service);\n\n // The direct topic channel registers the same contract on the extra port, so the widget guest can\n // deliver and subscribe without the host in between. It only calls `deliver` and `onDidPublish`;\n // schematic, topics and the clock stay the host's business.\n const topicPort = ports[0];\n const topicRpc = topicPort === undefined ? undefined : createRpc(topicPort);\n const topicRegistration = topicRpc?.register(deviceSimulationHostGuestService, service);\n\n let disposed = false;\n return {\n rpc,\n ports,\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n topicRegistration?.dispose();\n topicRpc?.dispose();\n registration.dispose();\n await host.dispose();\n rpc.dispose();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAcA,SAAgB,uBACd,QACA,kBAAuC,CAAC,GACnB;CACrB,MAAM,wBAAQ,IAAI,IAAY;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