libpetri 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/token.ts","../src/core/place.ts","../src/core/arc.ts","../src/core/in.ts","../src/core/transition-action.ts","../src/core/transition-context.ts","../src/core/token-input.ts","../src/core/token-output.ts","../src/core/transition.ts","../src/core/petri-net.ts","../src/runtime/marking.ts","../src/runtime/compiled-net.ts","../src/event/net-event.ts","../src/event/event-store.ts","../src/runtime/out-violation-error.ts","../src/runtime/executor-support.ts","../src/runtime/bitmap-net-executor.ts"],"sourcesContent":["/**\n * An immutable token carrying a typed value through the Petri net.\n *\n * Tokens flow from place to place as transitions fire, carrying typed\n * payloads that represent the state of a computation or workflow.\n */\nexport interface Token<T> {\n readonly value: T;\n /** Epoch milliseconds when the token was created. */\n readonly createdAt: number;\n}\n\n/** Cached singleton unit token. */\nconst UNIT_TOKEN: Token<null> = Object.freeze({\n value: null,\n createdAt: 0,\n});\n\n/** Creates a token with the given value and current timestamp. */\nexport function tokenOf<T>(value: T): Token<T> {\n return { value, createdAt: Date.now() };\n}\n\n/**\n * Returns a unit token (marker with no meaningful value).\n * Used for pure control flow where presence matters but data doesn't.\n * Returns a cached singleton whose `value` is `null`.\n */\nexport function unitToken(): Token<null> {\n return UNIT_TOKEN;\n}\n\n/** Creates a token with a specific timestamp (for testing/replay). */\nexport function tokenAt<T>(value: T, createdAt: number): Token<T> {\n return { value, createdAt };\n}\n\n/** Checks if this is the singleton unit token. */\nexport function isUnit(token: Token<unknown>): boolean {\n return token === UNIT_TOKEN;\n}\n","/**\n * A typed place in the Petri Net that holds tokens of a specific type.\n *\n * Places are the \"state containers\" of a Petri net. They hold tokens that\n * represent data or resources flowing through the net.\n *\n * Places use name-based equality (matching Java record semantics).\n * Internally use `Map<string, ...>` keyed by `place.name` for O(1) lookups.\n */\nexport interface Place<T> {\n readonly name: string;\n /** Phantom field to carry the type parameter. Never set at runtime. */\n readonly _phantom?: T;\n}\n\n/**\n * An environment place that accepts external token injection.\n * Wraps a regular Place and marks it for external event injection.\n */\nexport interface EnvironmentPlace<T> {\n readonly place: Place<T>;\n}\n\n/** Creates a typed place. */\nexport function place<T>(name: string): Place<T> {\n return { name };\n}\n\n/** Creates an environment place (external event injection point). */\nexport function environmentPlace<T>(name: string): EnvironmentPlace<T> {\n return { place: place<T>(name) };\n}\n","import type { Place } from './place.js';\n\n/**\n * Arc types connecting places to transitions in the Petri net.\n *\n * | Arc Type | Requires Token? | Consumes? | Effect |\n * |-----------|-----------------|-----------|--------------------------|\n * | Input | Yes | Yes | Token consumed on fire |\n * | Output | No | No | Token produced on complete|\n * | Inhibitor | No (blocks) | No | Disables transition |\n * | Read | Yes | No | Token remains |\n * | Reset | No | Yes (all) | All tokens removed |\n */\nexport type Arc = ArcInput | ArcOutput | ArcInhibitor | ArcRead | ArcReset;\n\nexport interface ArcInput<T = any> {\n readonly type: 'input';\n readonly place: Place<T>;\n readonly guard?: (value: T) => boolean;\n}\n\nexport interface ArcOutput<T = any> {\n readonly type: 'output';\n readonly place: Place<T>;\n}\n\nexport interface ArcInhibitor<T = any> {\n readonly type: 'inhibitor';\n readonly place: Place<T>;\n}\n\nexport interface ArcRead<T = any> {\n readonly type: 'read';\n readonly place: Place<T>;\n}\n\nexport interface ArcReset<T = any> {\n readonly type: 'reset';\n readonly place: Place<T>;\n}\n\n// ==================== Factory Functions ====================\n\n/** Input arc: consumes token from place when transition fires. */\nexport function inputArc<T>(place: Place<T>, guard?: (value: T) => boolean): ArcInput<T> {\n return guard !== undefined ? { type: 'input', place, guard } : { type: 'input', place };\n}\n\n/** Output arc: produces token to place when transition fires. */\nexport function outputArc<T>(place: Place<T>): ArcOutput<T> {\n return { type: 'output', place };\n}\n\n/** Inhibitor arc: blocks transition if place has tokens. */\nexport function inhibitorArc<T>(place: Place<T>): ArcInhibitor<T> {\n return { type: 'inhibitor', place };\n}\n\n/** Read arc: requires token without consuming. */\nexport function readArc<T>(place: Place<T>): ArcRead<T> {\n return { type: 'read', place };\n}\n\n/** Reset arc: removes all tokens from place when firing. */\nexport function resetArc<T>(place: Place<T>): ArcReset<T> {\n return { type: 'reset', place };\n}\n\n/** Returns the place this arc connects to. */\nexport function arcPlace(arc: Arc): Place<any> {\n return arc.place;\n}\n\n/** Checks if an input arc has a guard predicate. */\nexport function hasGuard(arc: ArcInput): boolean {\n return arc.guard !== undefined;\n}\n\n/** Checks if a token value matches an input arc's guard. */\nexport function matchesGuard<T>(arc: ArcInput<T>, value: T): boolean {\n if (arc.guard === undefined) return true;\n return arc.guard(value);\n}\n","import type { Place } from './place.js';\n\n/**\n * Input specification with cardinality and optional guard predicate.\n * CPN-compliant: cardinality determines how many tokens to consume,\n * guard filters which tokens are eligible.\n *\n * Inputs are always AND-joined (all must be satisfied to enable transition).\n * XOR on inputs is modeled via multiple transitions (conflict).\n */\nexport type In = InOne | InExactly | InAll | InAtLeast;\n\nexport interface InOne<T = any> {\n readonly type: 'one';\n readonly place: Place<T>;\n readonly guard?: (value: T) => boolean;\n}\n\nexport interface InExactly<T = any> {\n readonly type: 'exactly';\n readonly place: Place<T>;\n readonly count: number;\n readonly guard?: (value: T) => boolean;\n}\n\nexport interface InAll<T = any> {\n readonly type: 'all';\n readonly place: Place<T>;\n readonly guard?: (value: T) => boolean;\n}\n\nexport interface InAtLeast<T = any> {\n readonly type: 'at-least';\n readonly place: Place<T>;\n readonly minimum: number;\n readonly guard?: (value: T) => boolean;\n}\n\n// ==================== Factory Functions ====================\n\n/** Consume exactly 1 token (standard CPN semantics). Optional guard filters eligible tokens. */\nexport function one<T>(place: Place<T>, guard?: (value: T) => boolean): InOne<T> {\n return guard !== undefined ? { type: 'one', place, guard } : { type: 'one', place };\n}\n\n/** Consume exactly N tokens (batching). Optional guard filters eligible tokens. */\nexport function exactly<T>(count: number, place: Place<T>, guard?: (value: T) => boolean): InExactly<T> {\n if (count < 1) {\n throw new Error(`count must be >= 1, got: ${count}`);\n }\n return guard !== undefined ? { type: 'exactly', place, count, guard } : { type: 'exactly', place, count };\n}\n\n/** Consume all available tokens (must be 1+). Optional guard filters eligible tokens. */\nexport function all<T>(place: Place<T>, guard?: (value: T) => boolean): InAll<T> {\n return guard !== undefined ? { type: 'all', place, guard } : { type: 'all', place };\n}\n\n/** Wait for N+ tokens, consume all when enabled. Optional guard filters eligible tokens. */\nexport function atLeast<T>(minimum: number, place: Place<T>, guard?: (value: T) => boolean): InAtLeast<T> {\n if (minimum < 1) {\n throw new Error(`minimum must be >= 1, got: ${minimum}`);\n }\n return guard !== undefined\n ? { type: 'at-least', place, minimum, guard }\n : { type: 'at-least', place, minimum };\n}\n\n// ==================== Helper Functions ====================\n\n/** Returns the minimum number of tokens required to enable. */\nexport function requiredCount(spec: In): number {\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return 1;\n case 'at-least': return spec.minimum;\n }\n}\n\n/**\n * Returns the actual number of tokens to consume given the available count.\n * - One: always consumes 1\n * - Exactly: always consumes exactly count\n * - All: consumes all available\n * - AtLeast: consumes all available (when enabled, i.e., >= minimum)\n */\nexport function consumptionCount(spec: In, available: number): number {\n if (available < requiredCount(spec)) {\n throw new Error(\n `Cannot consume from '${spec.place.name}': available=${available}, required=${requiredCount(spec)}`\n );\n }\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return available;\n case 'at-least': return available;\n }\n}\n","import type { Place } from './place.js';\nimport type { TransitionContext } from './transition-context.js';\n\n/**\n * The action executed when a transition fires.\n * Receives a TransitionContext providing filtered I/O and structure access.\n */\nexport type TransitionAction = (ctx: TransitionContext) => Promise<void>;\n\n// ==================== Built-in Actions ====================\n\n/** Identity action: produces no outputs. */\nexport function passthrough(): TransitionAction {\n return async () => {};\n}\n\n/**\n * Transform action: applies function to context, copies result to ALL output places.\n *\n * @example\n * ```ts\n * const action = transform(ctx => ctx.input(inputPlace).toUpperCase());\n * // Result is copied to every declared output place\n * ```\n */\nexport function transform(fn: (ctx: TransitionContext) => unknown): TransitionAction {\n return async (ctx) => {\n const result = fn(ctx);\n for (const outputPlace of ctx.outputPlaces()) {\n ctx.output(outputPlace, result);\n }\n };\n}\n\n/**\n * Fork action: copies single input token to all outputs.\n * Requires exactly one input place (derived from structure).\n */\nexport function fork(): TransitionAction {\n return transform((ctx) => {\n const inputPlaces = ctx.inputPlaces();\n if (inputPlaces.size !== 1) {\n throw new Error(`Fork requires exactly 1 input place, found ${inputPlaces.size}`);\n }\n const inputPlace = inputPlaces.values().next().value as Place<any>;\n return ctx.input(inputPlace);\n });\n}\n\n/**\n * Transform with explicit input place.\n */\nexport function transformFrom<I>(inputPlace: Place<I>, fn: (value: I) => unknown): TransitionAction {\n return transform((ctx) => fn(ctx.input(inputPlace)));\n}\n\n/**\n * Async transform: applies async function, copies result to all outputs.\n */\nexport function transformAsync(fn: (ctx: TransitionContext) => Promise<unknown>): TransitionAction {\n return async (ctx) => {\n const result = await fn(ctx);\n for (const outputPlace of ctx.outputPlaces()) {\n ctx.output(outputPlace, result);\n }\n };\n}\n\n/** Produce action: produces a single token with the given value to the specified place. */\nexport function produce<T>(place: Place<T>, value: T): TransitionAction {\n return async (ctx) => {\n ctx.output(place, value);\n };\n}\n\n/**\n * Wraps an action with timeout handling.\n * If the action completes within the timeout, normal completion.\n * If the timeout expires, the timeoutValue is produced to the timeoutPlace.\n *\n * @example\n * ```ts\n * const action = withTimeout(\n * async (ctx) => { ctx.output(resultPlace, await fetchData()); },\n * 5000,\n * timeoutPlace,\n * 'timed-out',\n * );\n * ```\n */\nexport function withTimeout<T>(\n action: TransitionAction,\n timeoutMs: number,\n timeoutPlace: Place<T>,\n timeoutValue: T,\n): TransitionAction {\n return (ctx) => {\n return new Promise<void>((resolve, reject) => {\n let completed = false;\n const timer = setTimeout(() => {\n if (!completed) {\n completed = true;\n ctx.output(timeoutPlace, timeoutValue);\n resolve();\n }\n }, timeoutMs);\n action(ctx).then(\n () => {\n if (!completed) {\n completed = true;\n clearTimeout(timer);\n resolve();\n }\n },\n (err) => {\n if (!completed) {\n completed = true;\n clearTimeout(timer);\n reject(err);\n }\n },\n );\n });\n };\n}\n","import type { Place } from './place.js';\nimport type { Token } from './token.js';\nimport type { TokenInput } from './token-input.js';\nimport { TokenOutput } from './token-output.js';\n\n/** Callback for emitting log messages from transition actions. */\nexport type LogFn = (level: string, message: string, error?: Error) => void;\n\n/**\n * Context provided to transition actions.\n *\n * Provides filtered access based on structure:\n * - Input places (consumed tokens)\n * - Read places (context tokens, not consumed)\n * - Output places (where to produce tokens)\n *\n * Enforces the structure contract — actions can only access places\n * declared in the transition's structure.\n */\nexport class TransitionContext {\n private readonly rawInput: TokenInput;\n private readonly _rawOutput: TokenOutput;\n private readonly allowedInputs: Set<string>;\n private readonly allowedReads: Set<string>;\n private readonly allowedOutputs: Set<string>;\n private readonly _inputPlaces: ReadonlySet<Place<any>>;\n private readonly _readPlaces: ReadonlySet<Place<any>>;\n private readonly _outputPlaces: ReadonlySet<Place<any>>;\n private readonly _transitionName: string;\n private readonly executionCtx: Map<string, unknown>;\n private readonly _logFn?: LogFn;\n\n constructor(\n transitionName: string,\n rawInput: TokenInput,\n rawOutput: TokenOutput,\n inputPlaces: ReadonlySet<Place<any>>,\n readPlaces: ReadonlySet<Place<any>>,\n outputPlaces: ReadonlySet<Place<any>>,\n executionContext?: Map<string, unknown>,\n logFn?: LogFn,\n ) {\n this._transitionName = transitionName;\n this.rawInput = rawInput;\n this._rawOutput = rawOutput;\n this._inputPlaces = inputPlaces;\n this._readPlaces = readPlaces;\n this._outputPlaces = outputPlaces;\n const ai = new Set<string>();\n for (const p of inputPlaces) ai.add(p.name);\n this.allowedInputs = ai;\n const ar = new Set<string>();\n for (const p of readPlaces) ar.add(p.name);\n this.allowedReads = ar;\n const ao = new Set<string>();\n for (const p of outputPlaces) ao.add(p.name);\n this.allowedOutputs = ao;\n this.executionCtx = executionContext ?? new Map();\n this._logFn = logFn;\n }\n\n // ==================== Input Access (consumed) ====================\n\n /** Get single consumed input value. Throws if place not declared or multiple tokens. */\n input<T>(place: Place<T>): T {\n this.requireInput(place);\n const values = this.rawInput.values(place);\n if (values.length !== 1) {\n throw new Error(\n `Place '${place.name}' consumed ${values.length} tokens, use inputs() for batched access`\n );\n }\n return values[0]!;\n }\n\n /** Get all consumed input values for a place. */\n inputs<T>(place: Place<T>): readonly T[] {\n this.requireInput(place);\n return this.rawInput.values(place);\n }\n\n /** Get consumed input token with metadata. */\n inputToken<T>(place: Place<T>): Token<T> {\n this.requireInput(place);\n return this.rawInput.get(place);\n }\n\n /** Returns declared input places (consumed). */\n inputPlaces(): ReadonlySet<Place<any>> {\n return this._inputPlaces;\n }\n\n private requireInput(place: Place<any>): void {\n if (!this.allowedInputs.has(place.name)) {\n throw new Error(\n `Place '${place.name}' not in declared inputs: [${[...this.allowedInputs].join(', ')}]`\n );\n }\n }\n\n // ==================== Read Access (not consumed) ====================\n\n /** Get read-only context value. Throws if place not declared as read. */\n read<T>(place: Place<T>): T {\n this.requireRead(place);\n return this.rawInput.value(place);\n }\n\n /** Get all read-only context values for a place. */\n reads<T>(place: Place<T>): readonly T[] {\n this.requireRead(place);\n return this.rawInput.values(place);\n }\n\n /** Returns declared read places (context, not consumed). */\n readPlaces(): ReadonlySet<Place<any>> {\n return this._readPlaces;\n }\n\n private requireRead(place: Place<any>): void {\n if (!this.allowedReads.has(place.name)) {\n throw new Error(\n `Place '${place.name}' not in declared reads: [${[...this.allowedReads].join(', ')}]`\n );\n }\n }\n\n // ==================== Output Access ====================\n\n /** Add output value. Throws if place not declared as output. */\n output<T>(place: Place<T>, value: T): this {\n this.requireOutput(place);\n this._rawOutput.add(place, value);\n return this;\n }\n\n /** Add output token with metadata. */\n outputToken<T>(place: Place<T>, token: Token<T>): this {\n this.requireOutput(place);\n this._rawOutput.addToken(place, token);\n return this;\n }\n\n /** Returns declared output places. */\n outputPlaces(): ReadonlySet<Place<any>> {\n return this._outputPlaces;\n }\n\n private requireOutput(place: Place<any>): void {\n if (!this.allowedOutputs.has(place.name)) {\n throw new Error(\n `Place '${place.name}' not in declared outputs: [${[...this.allowedOutputs].join(', ')}]`\n );\n }\n }\n\n // ==================== Structure Info ====================\n\n /** Returns the transition name. */\n transitionName(): string {\n return this._transitionName;\n }\n\n // ==================== Execution Context ====================\n\n /** Retrieves an execution context object by key. */\n executionContext<T>(key: string): T | undefined {\n return this.executionCtx.get(key) as T | undefined;\n }\n\n /** Checks if an execution context object of the given key is present. */\n hasExecutionContext(key: string): boolean {\n return this.executionCtx.has(key);\n }\n\n // ==================== Logging ====================\n\n /** Emits a structured log message into the event store. */\n log(level: string, message: string, error?: Error): void {\n this._logFn?.(level, message, error);\n }\n\n // ==================== Internal ====================\n\n /** @internal Used by BitmapNetExecutor to collect outputs after action completion. */\n rawOutput(): TokenOutput {\n return this._rawOutput;\n }\n}\n","import type { Place } from './place.js';\nimport type { Token } from './token.js';\n\n/**\n * Consumed input tokens bound to their source places.\n *\n * Passed to TransitionAction as the `input` parameter, providing\n * type-safe read access to tokens consumed from input places.\n */\nexport class TokenInput {\n private readonly tokens = new Map<string, Token<any>[]>();\n\n /** Add a token (used by executor when firing transition). */\n add<T>(place: Place<T>, token: Token<T>): this {\n const existing = this.tokens.get(place.name);\n if (existing) {\n existing.push(token);\n } else {\n this.tokens.set(place.name, [token]);\n }\n return this;\n }\n\n /** Get all tokens for a place. */\n getAll<T>(place: Place<T>): readonly Token<T>[] {\n return (this.tokens.get(place.name) ?? []) as Token<T>[];\n }\n\n /** Get the first token for a place. Throws if no tokens. */\n get<T>(place: Place<T>): Token<T> {\n const list = this.tokens.get(place.name);\n if (!list || list.length === 0) {\n throw new Error(`No token for place: ${place.name}`);\n }\n return list[0] as Token<T>;\n }\n\n /** Get the first token's value for a place. Throws if no tokens. */\n value<T>(place: Place<T>): T {\n return this.get(place).value;\n }\n\n /** Get all token values for a place. */\n values<T>(place: Place<T>): readonly T[] {\n return this.getAll(place).map(t => t.value);\n }\n\n /** Get token count for a place. */\n count(place: Place<any>): number {\n return this.getAll(place).length;\n }\n\n /** Check if any tokens exist for a place. */\n has(place: Place<any>): boolean {\n return this.count(place) > 0;\n }\n}\n","import type { Place } from './place.js';\nimport type { Token } from './token.js';\nimport { tokenOf } from './token.js';\n\n/**\n * An output entry: place + token pair.\n */\nexport interface OutputEntry {\n readonly place: Place<any>;\n readonly token: Token<any>;\n}\n\n/**\n * Collects output tokens produced by a transition action.\n */\nexport class TokenOutput {\n private readonly _entries: OutputEntry[] = [];\n\n /** Add a value to an output place (creates token with current timestamp). */\n add<T>(place: Place<T>, value: T): this {\n this._entries.push({ place, token: tokenOf(value) });\n return this;\n }\n\n /** Add a pre-existing token to an output place. */\n addToken<T>(place: Place<T>, token: Token<T>): this {\n this._entries.push({ place, token });\n return this;\n }\n\n /** Returns all collected outputs. */\n entries(): readonly OutputEntry[] {\n return this._entries;\n }\n\n /** Check if any outputs were produced. */\n isEmpty(): boolean {\n return this._entries.length === 0;\n }\n\n /** Returns the set of place names that received tokens. */\n placesWithTokens(): Set<string> {\n const result = new Set<string>();\n for (const entry of this._entries) {\n result.add(entry.place.name);\n }\n return result;\n }\n}\n","import type { Place } from './place.js';\nimport type { ArcInhibitor, ArcRead, ArcReset } from './arc.js';\nimport type { In } from './in.js';\nimport type { Out, OutTimeout } from './out.js';\nimport type { Timing } from './timing.js';\nimport type { TransitionAction } from './transition-action.js';\nimport { passthrough } from './transition-action.js';\nimport { immediate } from './timing.js';\nimport { allPlaces } from './out.js';\n\n/** @internal Symbol key restricting construction to the builder. */\nconst TRANSITION_KEY = Symbol('Transition.internal');\n\n/**\n * A transition in the Time Petri Net that transforms tokens.\n *\n * Transitions use identity-based equality (===) — each instance is unique\n * regardless of name. The name is purely a label for display/debugging/export.\n */\nexport class Transition {\n readonly name: string;\n readonly inputSpecs: readonly In[];\n readonly outputSpec: Out | null;\n readonly inhibitors: readonly ArcInhibitor[];\n readonly reads: readonly ArcRead[];\n readonly resets: readonly ArcReset[];\n readonly timing: Timing;\n readonly actionTimeout: OutTimeout | null;\n readonly action: TransitionAction;\n readonly priority: number;\n\n private readonly _inputPlaces: ReadonlySet<Place<any>>;\n private readonly _readPlaces: ReadonlySet<Place<any>>;\n private readonly _outputPlaces: ReadonlySet<Place<any>>;\n\n /** @internal Use {@link Transition.builder} to create instances. */\n constructor(\n key: symbol,\n name: string,\n inputSpecs: readonly In[],\n outputSpec: Out | null,\n inhibitors: readonly ArcInhibitor[],\n reads: readonly ArcRead[],\n resets: readonly ArcReset[],\n timing: Timing,\n action: TransitionAction,\n priority: number,\n ) {\n if (key !== TRANSITION_KEY) throw new Error('Use Transition.builder() to create instances');\n this.name = name;\n this.inputSpecs = inputSpecs;\n this.outputSpec = outputSpec;\n this.inhibitors = inhibitors;\n this.reads = reads;\n this.resets = resets;\n this.timing = timing;\n this.actionTimeout = findTimeout(outputSpec);\n this.action = action;\n this.priority = priority;\n\n // Precompute place sets\n const inputPlaces = new Set<Place<any>>();\n for (const spec of inputSpecs) {\n inputPlaces.add(spec.place);\n }\n this._inputPlaces = inputPlaces;\n\n const readPlaces = new Set<Place<any>>();\n for (const r of reads) {\n readPlaces.add(r.place);\n }\n this._readPlaces = readPlaces;\n\n const outputPlaces = new Set<Place<any>>();\n if (outputSpec !== null) {\n for (const p of allPlaces(outputSpec)) {\n outputPlaces.add(p);\n }\n }\n this._outputPlaces = outputPlaces;\n }\n\n /** Returns set of input places — consumed tokens. */\n inputPlaces(): ReadonlySet<Place<any>> {\n return this._inputPlaces;\n }\n\n /** Returns set of read places — context tokens, not consumed. */\n readPlaces(): ReadonlySet<Place<any>> {\n return this._readPlaces;\n }\n\n /** Returns set of output places — where tokens are produced. */\n outputPlaces(): ReadonlySet<Place<any>> {\n return this._outputPlaces;\n }\n\n /** Returns true if this transition has an action timeout. */\n hasActionTimeout(): boolean {\n return this.actionTimeout !== null;\n }\n\n toString(): string {\n return `Transition[${this.name}]`;\n }\n\n static builder(name: string): TransitionBuilder {\n return new TransitionBuilder(name);\n }\n}\n\nexport class TransitionBuilder {\n private readonly _name: string;\n private readonly _inputSpecs: In[] = [];\n private _outputSpec: Out | null = null;\n private readonly _inhibitors: ArcInhibitor[] = [];\n private readonly _reads: ArcRead[] = [];\n private readonly _resets: ArcReset[] = [];\n private _timing: Timing = immediate();\n private _action: TransitionAction = passthrough();\n private _priority = 0;\n\n constructor(name: string) {\n this._name = name;\n }\n\n /** Add input specifications with cardinality. */\n inputs(...specs: In[]): this {\n this._inputSpecs.push(...specs);\n return this;\n }\n\n /** Set the output specification (composite AND/XOR structure). */\n outputs(spec: Out): this {\n this._outputSpec = spec;\n return this;\n }\n\n /** Add inhibitor arc. */\n inhibitor(place: Place<any>): this {\n this._inhibitors.push({ type: 'inhibitor', place });\n return this;\n }\n\n /** Add inhibitor arcs. */\n inhibitors(...places: Place<any>[]): this {\n for (const p of places) {\n this._inhibitors.push({ type: 'inhibitor', place: p });\n }\n return this;\n }\n\n /** Add read arc. */\n read(place: Place<any>): this {\n this._reads.push({ type: 'read', place });\n return this;\n }\n\n /** Add read arcs. */\n reads(...places: Place<any>[]): this {\n for (const p of places) {\n this._reads.push({ type: 'read', place: p });\n }\n return this;\n }\n\n /** Add reset arc. */\n reset(place: Place<any>): this {\n this._resets.push({ type: 'reset', place });\n return this;\n }\n\n /** Add reset arcs. */\n resets(...places: Place<any>[]): this {\n for (const p of places) {\n this._resets.push({ type: 'reset', place: p });\n }\n return this;\n }\n\n /** Set timing specification. */\n timing(timing: Timing): this {\n this._timing = timing;\n return this;\n }\n\n /** Set the transition action. */\n action(action: TransitionAction): this {\n this._action = action;\n return this;\n }\n\n /** Set the priority (higher fires first). */\n priority(priority: number): this {\n this._priority = priority;\n return this;\n }\n\n build(): Transition {\n // Validate ForwardInput references\n if (this._outputSpec !== null) {\n const inputPlaceNames = new Set(this._inputSpecs.map(s => s.place.name));\n for (const fi of findForwardInputs(this._outputSpec)) {\n if (!inputPlaceNames.has(fi.from.name)) {\n throw new Error(\n `Transition '${this._name}': ForwardInput references non-input place '${fi.from.name}'`\n );\n }\n }\n }\n\n return new Transition(\n TRANSITION_KEY,\n this._name,\n [...this._inputSpecs],\n this._outputSpec,\n [...this._inhibitors],\n [...this._reads],\n [...this._resets],\n this._timing,\n this._action,\n this._priority,\n );\n }\n}\n\n/** Recursively searches the output spec for a Timeout node. */\nfunction findTimeout(out: Out | null): OutTimeout | null {\n if (out === null) return null;\n switch (out.type) {\n case 'timeout': return out;\n case 'and':\n case 'xor':\n for (const child of out.children) {\n const found = findTimeout(child);\n if (found !== null) return found;\n }\n return null;\n case 'place':\n case 'forward-input':\n return null;\n }\n}\n\n/** Recursively finds all ForwardInput nodes in the output spec. */\nfunction findForwardInputs(out: Out): Array<{ from: Place<any>; to: Place<any> }> {\n switch (out.type) {\n case 'forward-input':\n return [{ from: out.from, to: out.to }];\n case 'and':\n case 'xor':\n return out.children.flatMap(findForwardInputs);\n case 'timeout':\n return findForwardInputs(out.child);\n case 'place':\n return [];\n }\n}\n","import type { Place } from './place.js';\nimport type { TransitionAction } from './transition-action.js';\nimport { passthrough } from './transition-action.js';\nimport { Transition } from './transition.js';\n\n/** @internal Symbol key restricting construction to the builder and bindActions. */\nconst PETRI_NET_KEY = Symbol('PetriNet.internal');\n\n/**\n * Immutable definition of a Time Petri Net structure.\n *\n * A PetriNet is a reusable definition that can be executed multiple times\n * with different initial markings. Places are auto-collected from transitions.\n */\nexport class PetriNet {\n readonly name: string;\n readonly places: ReadonlySet<Place<any>>;\n readonly transitions: ReadonlySet<Transition>;\n\n /** @internal Use {@link PetriNet.builder} to create instances. */\n constructor(\n key: symbol,\n name: string,\n places: ReadonlySet<Place<any>>,\n transitions: ReadonlySet<Transition>,\n ) {\n if (key !== PETRI_NET_KEY) throw new Error('Use PetriNet.builder() to create instances');\n this.name = name;\n this.places = places;\n this.transitions = transitions;\n }\n\n /**\n * Creates a new PetriNet with actions bound to transitions by name.\n * Unbound transitions keep passthrough action.\n */\n bindActions(actionBindings: Map<string, TransitionAction> | Record<string, TransitionAction>): PetriNet {\n const bindings = actionBindings instanceof Map\n ? actionBindings\n : new Map(Object.entries(actionBindings));\n\n return this.bindActionsWithResolver(\n (name) => bindings.get(name) ?? passthrough(),\n );\n }\n\n /**\n * Creates a new PetriNet with actions bound via a resolver function.\n */\n bindActionsWithResolver(actionResolver: (name: string) => TransitionAction): PetriNet {\n const boundTransitions = new Set<Transition>();\n for (const t of this.transitions) {\n const action = actionResolver(t.name);\n if (action !== null && action !== t.action) {\n boundTransitions.add(rebuildWithAction(t, action));\n } else {\n boundTransitions.add(t);\n }\n }\n return new PetriNet(PETRI_NET_KEY, this.name, this.places, boundTransitions);\n }\n\n static builder(name: string): PetriNetBuilder {\n return new PetriNetBuilder(name);\n }\n}\n\nexport class PetriNetBuilder {\n private readonly _name: string;\n private readonly _places = new Set<Place<any>>();\n private readonly _transitions = new Set<Transition>();\n\n constructor(name: string) {\n this._name = name;\n }\n\n /** Add an explicit place. */\n place(place: Place<any>): this {\n this._places.add(place);\n return this;\n }\n\n /** Add explicit places. */\n places(...places: Place<any>[]): this {\n for (const p of places) this._places.add(p);\n return this;\n }\n\n /** Add a transition (auto-collects places from arcs). */\n transition(transition: Transition): this {\n this._transitions.add(transition);\n for (const spec of transition.inputSpecs) {\n this._places.add(spec.place);\n }\n for (const p of transition.outputPlaces()) {\n this._places.add(p);\n }\n for (const inh of transition.inhibitors) {\n this._places.add(inh.place);\n }\n for (const r of transition.reads) {\n this._places.add(r.place);\n }\n for (const r of transition.resets) {\n this._places.add(r.place);\n }\n return this;\n }\n\n /** Add transitions (auto-collects places from arcs). */\n transitions(...transitions: Transition[]): this {\n for (const t of transitions) this.transition(t);\n return this;\n }\n\n build(): PetriNet {\n return new PetriNet(PETRI_NET_KEY, this._name, this._places, this._transitions);\n }\n}\n\n/** Creates a new transition with a different action while preserving all arc specs. */\nfunction rebuildWithAction(t: Transition, action: TransitionAction): Transition {\n const builder = Transition.builder(t.name)\n .timing(t.timing)\n .priority(t.priority)\n .action(action);\n\n if (t.inputSpecs.length > 0) {\n builder.inputs(...t.inputSpecs);\n }\n if (t.outputSpec !== null) {\n builder.outputs(t.outputSpec);\n }\n\n for (const inh of t.inhibitors) {\n builder.inhibitor(inh.place);\n }\n for (const r of t.reads) {\n builder.read(r.place);\n }\n for (const r of t.resets) {\n builder.reset(r.place);\n }\n\n return builder.build();\n}\n","/**\n * @module marking\n *\n * Mutable token state (marking) of a running Petri net.\n *\n * Tokens per place are stored in FIFO arrays (push to end, shift from front).\n * Not thread-safe — all mutation occurs from the single-threaded orchestrator.\n *\n * For typical nets (≤10 tokens per place), Array.shift() is faster than a deque\n * due to cache locality. Only optimize if profiling shows a bottleneck.\n */\nimport type { Place } from '../core/place.js';\nimport type { Token } from '../core/token.js';\n\nconst EMPTY_TOKENS: readonly Token<any>[] = Object.freeze([]);\n\n/** Anything that carries a place reference and an optional guard predicate. */\nexport interface GuardSpec<T = any> {\n readonly place: Place<T>;\n readonly guard?: (value: T) => boolean;\n}\n\n/**\n * Mutable marking (token state) of a Petri Net during execution.\n *\n * Tokens in each place are maintained in FIFO order (array: push to end, shift from front).\n * Not thread-safe — all access must be from the orchestrator.\n */\nexport class Marking {\n /** Place name -> FIFO queue of tokens. */\n private readonly tokens = new Map<string, Token<any>[]>();\n /** Place name -> Place reference (for inspection). */\n private readonly placeRefs = new Map<string, Place<any>>();\n\n static empty(): Marking {\n return new Marking();\n }\n\n static from(initial: Map<Place<any>, Token<any>[]>): Marking {\n const m = new Marking();\n for (const [place, tokens] of initial) {\n m.placeRefs.set(place.name, place);\n m.tokens.set(place.name, [...tokens]);\n }\n return m;\n }\n\n // ======================== Token Addition ========================\n\n addToken<T>(place: Place<T>, token: Token<T>): void {\n this.placeRefs.set(place.name, place);\n const queue = this.tokens.get(place.name);\n if (queue) {\n queue.push(token);\n } else {\n this.tokens.set(place.name, [token]);\n }\n }\n\n // ======================== Token Removal ========================\n\n /** Removes and returns the oldest token. Returns null if empty. */\n removeFirst<T>(place: Place<T>): Token<T> | null {\n const queue = this.tokens.get(place.name);\n if (!queue || queue.length === 0) return null;\n return queue.shift() as Token<T>;\n }\n\n /** Removes and returns all tokens from a place. */\n removeAll<T>(place: Place<T>): Token<T>[] {\n const queue = this.tokens.get(place.name);\n if (!queue || queue.length === 0) return [];\n const result = [...queue] as Token<T>[];\n queue.length = 0;\n return result;\n }\n\n /**\n * Removes and returns the first token whose value satisfies the guard predicate.\n *\n * Performs a linear scan of the place's FIFO queue. If no guard is provided,\n * behaves like `removeFirst()`. If a guard is provided, skips non-matching\n * tokens and splices the first match out of the queue (O(n) worst case).\n */\n removeFirstMatching(spec: GuardSpec): Token<any> | null {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return null;\n if (!spec.guard) {\n return queue.shift()!;\n }\n for (let i = 0; i < queue.length; i++) {\n const token = queue[i]!;\n if (spec.guard(token.value)) {\n queue.splice(i, 1);\n return token;\n }\n }\n return null;\n }\n\n // ======================== Token Inspection ========================\n\n /** Check if any token matches a guard predicate. */\n hasMatchingToken(spec: GuardSpec): boolean {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return false;\n if (!spec.guard) return true;\n return queue.some(t => spec.guard!(t.value));\n }\n\n /**\n * Counts tokens in a place whose values satisfy the guard predicate.\n *\n * If no guard is provided, returns the total token count (O(1)).\n * With a guard, performs a linear scan over all tokens (O(n)).\n * Used by the executor for enablement checks on guarded `all`/`at-least` inputs.\n */\n countMatching(spec: GuardSpec): number {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return 0;\n if (!spec.guard) return queue.length;\n let count = 0;\n for (const t of queue) {\n if (spec.guard(t.value)) count++;\n }\n return count;\n }\n\n /**\n * Returns tokens in a place. **Returns a live reference** to the internal\n * array — callers must not mutate it. Copy with `[...peekTokens(p)]` if\n * mutation or snapshot semantics are needed.\n */\n peekTokens<T>(place: Place<T>): readonly Token<T>[] {\n return (this.tokens.get(place.name) ?? EMPTY_TOKENS) as readonly Token<T>[];\n }\n\n /** Returns the oldest token without removing it. */\n peekFirst<T>(place: Place<T>): Token<T> | null {\n const queue = this.tokens.get(place.name);\n return queue && queue.length > 0 ? queue[0] as Token<T> : null;\n }\n\n /** Checks if a place has any tokens. */\n hasTokens(place: Place<any>): boolean {\n const queue = this.tokens.get(place.name);\n return queue !== undefined && queue.length > 0;\n }\n\n /** Returns the number of tokens in a place. */\n tokenCount(place: Place<any>): number {\n const queue = this.tokens.get(place.name);\n return queue ? queue.length : 0;\n }\n\n // ======================== Debugging ========================\n\n toString(): string {\n const parts: string[] = [];\n for (const [name, queue] of this.tokens) {\n if (queue.length > 0) {\n parts.push(`${name}: ${queue.length}`);\n }\n }\n return `Marking{${parts.join(', ')}}`;\n }\n}\n","/**\n * @module compiled-net\n *\n * Integer-indexed, precomputed representation of a PetriNet for bitmap-based execution.\n *\n * **Precomputation strategy**: At compile time, all places and transitions are assigned\n * stable integer IDs. Input/inhibitor arcs are converted to Uint32Array bitmasks (one per\n * transition), enabling O(W) enablement checks via bitwise AND where W = ceil(numPlaces/32).\n *\n * **Why bitmaps**: JS bitwise operators work natively on 32-bit integers. Using Uint32Array\n * with 32-bit words (WORD_SHIFT=5) avoids BigInt overhead while keeping enablement checks\n * branch-free and cache-friendly. For a typical 50-place net, W=2 words per mask.\n *\n * **Reverse index**: A place-to-transitions mapping enables the dirty set pattern —\n * when a place's marking changes, only affected transitions are re-evaluated.\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place } from '../core/place.js';\nimport type { Transition } from '../core/transition.js';\nimport { requiredCount } from '../core/in.js';\nimport { allPlaces } from '../core/out.js';\n\n/** 32-bit words for JS bitwise ops. */\nexport const WORD_SHIFT = 5;\nexport const BIT_MASK = 31;\n\nexport interface CardinalityCheck {\n readonly placeIds: readonly number[];\n readonly requiredCounts: readonly number[];\n}\n\n/**\n * Integer-indexed, precomputed representation of a PetriNet for bitmap-based execution.\n *\n * Uses Uint32Array masks with 32-bit words (JS bitwise ops work on 32-bit ints natively).\n */\nexport class CompiledNet {\n readonly net: PetriNet;\n readonly placeCount: number;\n readonly transitionCount: number;\n readonly wordCount: number;\n\n // ID mappings\n private readonly _placesById: Place<any>[];\n private readonly _transitionsById: Transition[];\n private readonly _placeIndex: Map<string, number>;\n private readonly _transitionIndex: Map<Transition, number>;\n\n // Precomputed masks per transition\n private readonly _needsMask: Uint32Array[];\n private readonly _inhibitorMask: Uint32Array[];\n\n // Reverse index: place -> affected transition IDs\n private readonly _placeToTransitions: number[][];\n\n // Consumption place IDs per transition (input + reset places)\n private readonly _consumptionPlaceIds: number[][];\n\n // Cardinality and guard flags\n private readonly _cardinalityChecks: (CardinalityCheck | null)[];\n private readonly _hasGuards: boolean[];\n\n private constructor(net: PetriNet) {\n this.net = net;\n\n // Collect all places\n const allPlacesSet = new Map<string, Place<any>>();\n for (const t of net.transitions) {\n for (const spec of t.inputSpecs) allPlacesSet.set(spec.place.name, spec.place);\n for (const r of t.reads) allPlacesSet.set(r.place.name, r.place);\n for (const inh of t.inhibitors) allPlacesSet.set(inh.place.name, inh.place);\n for (const rst of t.resets) allPlacesSet.set(rst.place.name, rst.place);\n if (t.outputSpec !== null) {\n for (const p of allPlaces(t.outputSpec)) allPlacesSet.set(p.name, p);\n }\n }\n for (const p of net.places) allPlacesSet.set(p.name, p);\n\n this.placeCount = allPlacesSet.size;\n this.wordCount = (this.placeCount + BIT_MASK) >>> WORD_SHIFT;\n\n // Assign place IDs\n this._placesById = [...allPlacesSet.values()];\n this._placeIndex = new Map();\n for (let i = 0; i < this._placesById.length; i++) {\n this._placeIndex.set(this._placesById[i]!.name, i);\n }\n\n // Assign transition IDs\n this._transitionsById = [...net.transitions];\n this.transitionCount = this._transitionsById.length;\n this._transitionIndex = new Map();\n for (let i = 0; i < this._transitionsById.length; i++) {\n this._transitionIndex.set(this._transitionsById[i]!, i);\n }\n\n // Precompute masks\n this._needsMask = new Array(this.transitionCount);\n this._inhibitorMask = new Array(this.transitionCount);\n this._consumptionPlaceIds = new Array(this.transitionCount);\n this._cardinalityChecks = new Array(this.transitionCount).fill(null);\n this._hasGuards = new Array(this.transitionCount).fill(false);\n\n const placeToTransitionsList: number[][] = new Array(this.placeCount);\n for (let i = 0; i < this.placeCount; i++) {\n placeToTransitionsList[i] = [];\n }\n\n for (let tid = 0; tid < this.transitionCount; tid++) {\n const t = this._transitionsById[tid]!;\n const needs = new Uint32Array(this.wordCount);\n const inhibitors = new Uint32Array(this.wordCount);\n\n let needsCardinality = false;\n\n // Input specs\n for (const inSpec of t.inputSpecs) {\n const pid = this._placeIndex.get(inSpec.place.name)!;\n setBit(needs, pid);\n placeToTransitionsList[pid]!.push(tid);\n\n if (inSpec.type !== 'one') {\n needsCardinality = true;\n }\n if (inSpec.guard) {\n this._hasGuards[tid] = true;\n }\n }\n\n // Build cardinality check if needed\n if (needsCardinality) {\n const pids: number[] = [];\n const reqs: number[] = [];\n for (const inSpec of t.inputSpecs) {\n pids.push(this._placeIndex.get(inSpec.place.name)!);\n reqs.push(requiredCount(inSpec));\n }\n this._cardinalityChecks[tid] = { placeIds: pids, requiredCounts: reqs };\n }\n\n // Read arcs\n for (const arc of t.reads) {\n const pid = this._placeIndex.get(arc.place.name)!;\n setBit(needs, pid);\n placeToTransitionsList[pid]!.push(tid);\n }\n\n // Inhibitor arcs\n for (const arc of t.inhibitors) {\n const pid = this._placeIndex.get(arc.place.name)!;\n setBit(inhibitors, pid);\n placeToTransitionsList[pid]!.push(tid);\n }\n\n // Reset arcs (add to affected transitions)\n for (const arc of t.resets) {\n const pid = this._placeIndex.get(arc.place.name)!;\n placeToTransitionsList[pid]!.push(tid);\n }\n\n // Consumption place IDs (input + reset, deduplicated)\n const consumptionSet = new Set<number>();\n for (const spec of t.inputSpecs) consumptionSet.add(this._placeIndex.get(spec.place.name)!);\n for (const arc of t.resets) consumptionSet.add(this._placeIndex.get(arc.place.name)!);\n this._consumptionPlaceIds[tid] = [...consumptionSet];\n\n this._needsMask[tid] = needs;\n this._inhibitorMask[tid] = inhibitors;\n }\n\n // Build reverse index: deduplicate transition IDs per place\n this._placeToTransitions = new Array(this.placeCount);\n for (let pid = 0; pid < this.placeCount; pid++) {\n this._placeToTransitions[pid] = [...new Set(placeToTransitionsList[pid]!)];\n }\n }\n\n static compile(net: PetriNet): CompiledNet {\n return new CompiledNet(net);\n }\n\n // ==================== Accessors ====================\n\n place(pid: number): Place<any> { return this._placesById[pid]!; }\n transition(tid: number): Transition { return this._transitionsById[tid]!; }\n\n placeId(place: Place<any>): number {\n const id = this._placeIndex.get(place.name);\n if (id === undefined) throw new Error(`Unknown place: ${place.name}`);\n return id;\n }\n\n transitionId(t: Transition): number {\n const id = this._transitionIndex.get(t);\n if (id === undefined) throw new Error(`Unknown transition: ${t.name}`);\n return id;\n }\n\n affectedTransitions(pid: number): readonly number[] {\n return this._placeToTransitions[pid]!;\n }\n\n consumptionPlaceIds(tid: number): readonly number[] {\n return this._consumptionPlaceIds[tid]!;\n }\n\n cardinalityCheck(tid: number): CardinalityCheck | null {\n return this._cardinalityChecks[tid]!;\n }\n\n hasGuards(tid: number): boolean {\n return this._hasGuards[tid]!;\n }\n\n // ==================== Enablement Check ====================\n\n /**\n * Two-phase bitmap enablement check for a transition:\n * 1. **Presence check**: verifies all required places (inputs + reads) have tokens\n * via `containsAll(snapshot, needsMask)`.\n * 2. **Inhibitor check**: verifies no inhibitor places have tokens\n * via `!intersects(snapshot, inhibitorMask)`.\n *\n * This is a necessary but not sufficient condition — cardinality and guard checks\n * are performed separately by the executor for transitions that pass this fast path.\n */\n canEnableBitmap(tid: number, markingSnapshot: Uint32Array): boolean {\n // All needed places present?\n if (!containsAll(markingSnapshot, this._needsMask[tid]!)) return false;\n // No inhibitors active?\n if (intersects(markingSnapshot, this._inhibitorMask[tid]!)) return false;\n return true;\n }\n}\n\n// ==================== Bitmap Helpers ====================\n\nexport function setBit(arr: Uint32Array, bit: number): void {\n arr[bit >>> WORD_SHIFT]! |= (1 << (bit & BIT_MASK));\n}\n\nexport function clearBit(arr: Uint32Array, bit: number): void {\n arr[bit >>> WORD_SHIFT]! &= ~(1 << (bit & BIT_MASK));\n}\n\nexport function testBit(arr: Uint32Array, bit: number): boolean {\n return (arr[bit >>> WORD_SHIFT]! & (1 << (bit & BIT_MASK))) !== 0;\n}\n\n/** Checks if all bits in mask are set in snapshot. */\nexport function containsAll(snapshot: Uint32Array, mask: Uint32Array): boolean {\n for (let i = 0; i < mask.length; i++) {\n const m = mask[i]!;\n if (m === 0) continue;\n const s = i < snapshot.length ? snapshot[i]! : 0;\n if ((s & m) !== m) return false;\n }\n return true;\n}\n\n/** Checks if any bit in mask is set in snapshot. */\nexport function intersects(snapshot: Uint32Array, mask: Uint32Array): boolean {\n for (let i = 0; i < mask.length; i++) {\n const m = mask[i]!;\n if (m === 0) continue;\n if (i < snapshot.length && (snapshot[i]! & m) !== 0) return true;\n }\n return false;\n}\n\n","import type { Token } from '../core/token.js';\n\n/**\n * Events emitted during Petri Net execution.\n * Discriminated union capturing all observable state changes.\n */\nexport type NetEvent =\n | ExecutionStarted\n | ExecutionCompleted\n | TransitionEnabled\n | TransitionClockRestarted\n | TransitionStarted\n | TransitionCompleted\n | TransitionFailed\n | TransitionTimedOut\n | ActionTimedOut\n | TokenAdded\n | TokenRemoved\n | LogMessage\n | MarkingSnapshot;\n\n// ======================== Execution Lifecycle ========================\n\nexport interface ExecutionStarted {\n readonly type: 'execution-started';\n readonly timestamp: number;\n readonly netName: string;\n readonly executionId: string;\n}\n\nexport interface ExecutionCompleted {\n readonly type: 'execution-completed';\n readonly timestamp: number;\n readonly netName: string;\n readonly executionId: string;\n readonly totalDurationMs: number;\n}\n\n// ======================== Transition Lifecycle ========================\n\nexport interface TransitionEnabled {\n readonly type: 'transition-enabled';\n readonly timestamp: number;\n readonly transitionName: string;\n}\n\nexport interface TransitionClockRestarted {\n readonly type: 'transition-clock-restarted';\n readonly timestamp: number;\n readonly transitionName: string;\n}\n\nexport interface TransitionStarted {\n readonly type: 'transition-started';\n readonly timestamp: number;\n readonly transitionName: string;\n readonly consumedTokens: readonly Token<unknown>[];\n}\n\nexport interface TransitionCompleted {\n readonly type: 'transition-completed';\n readonly timestamp: number;\n readonly transitionName: string;\n readonly producedTokens: readonly Token<unknown>[];\n readonly durationMs: number;\n}\n\nexport interface TransitionFailed {\n readonly type: 'transition-failed';\n readonly timestamp: number;\n readonly transitionName: string;\n readonly errorMessage: string;\n readonly exceptionType: string;\n /** Original stack trace, if available. */\n readonly stack?: string;\n}\n\n/**\n * Emitted when a transition exceeds its deadline (upper time bound) without firing.\n * Classical TPN semantics: transition is forcibly disabled by the executor in\n * `updateDirtyTransitions()` when elapsed time exceeds `latest(timing)`.\n */\nexport interface TransitionTimedOut {\n readonly type: 'transition-timed-out';\n readonly timestamp: number;\n readonly transitionName: string;\n /** The deadline that was exceeded, in milliseconds from enablement. */\n readonly deadlineMs: number;\n /** Actual time elapsed since enablement, in milliseconds. */\n readonly actualDurationMs: number;\n}\n\nexport interface ActionTimedOut {\n readonly type: 'action-timed-out';\n readonly timestamp: number;\n readonly transitionName: string;\n readonly timeoutMs: number;\n}\n\n// ======================== Token Movement ========================\n\nexport interface TokenAdded {\n readonly type: 'token-added';\n readonly timestamp: number;\n readonly placeName: string;\n readonly token: Token<unknown>;\n}\n\nexport interface TokenRemoved {\n readonly type: 'token-removed';\n readonly timestamp: number;\n readonly placeName: string;\n readonly token: Token<unknown>;\n}\n\n// ======================== Log Capture ========================\n\nexport interface LogMessage {\n readonly type: 'log-message';\n readonly timestamp: number;\n readonly transitionName: string;\n readonly logger: string;\n readonly level: string;\n readonly message: string;\n readonly error: string | null;\n readonly errorMessage: string | null;\n}\n\n// ======================== Checkpointing ========================\n\n/**\n * Snapshot of the full marking (token state) at a point in time.\n * Emitted at two points during execution:\n * 1. After initialization (before the main loop) — captures the initial marking\n * 2. Before the execution-completed event — captures the final marking\n */\nexport interface MarkingSnapshot {\n readonly type: 'marking-snapshot';\n readonly timestamp: number;\n /** Place name -> tokens in that place at snapshot time. Only non-empty places are included. */\n readonly marking: ReadonlyMap<string, readonly Token<unknown>[]>;\n}\n\n// ======================== Helper Functions ========================\n\n/** Extracts transition name from events that have one. Returns null otherwise. */\nexport function eventTransitionName(event: NetEvent): string | null {\n switch (event.type) {\n case 'transition-enabled':\n case 'transition-clock-restarted':\n case 'transition-started':\n case 'transition-completed':\n case 'transition-failed':\n case 'transition-timed-out':\n case 'action-timed-out':\n case 'log-message':\n return event.transitionName;\n default:\n return null;\n }\n}\n\n/** Checks if the event is a failure type. */\nexport function isFailureEvent(event: NetEvent): boolean {\n return event.type === 'transition-failed'\n || event.type === 'transition-timed-out'\n || event.type === 'action-timed-out';\n}\n","import type { NetEvent } from './net-event.js';\nimport { eventTransitionName, isFailureEvent } from './net-event.js';\n\n/**\n * Storage for events emitted during Petri net execution.\n */\nexport interface EventStore {\n /** Appends an event to the store. */\n append(event: NetEvent): void;\n\n /** Returns all events in chronological order. */\n events(): readonly NetEvent[];\n\n /** Whether this store is enabled (false = skip event creation). */\n isEnabled(): boolean;\n\n /** Number of events captured. */\n size(): number;\n\n /** Whether no events have been captured. */\n isEmpty(): boolean;\n}\n\n// ==================== Query Helpers ====================\n\n/** Returns events matching a predicate. */\nexport function filterEvents(store: EventStore, predicate: (e: NetEvent) => boolean): NetEvent[] {\n return store.events().filter(predicate);\n}\n\n/** Returns events of a specific type. */\nexport function eventsOfType<T extends NetEvent['type']>(\n store: EventStore,\n type: T,\n): Extract<NetEvent, { type: T }>[] {\n return store.events().filter(e => e.type === type) as Extract<NetEvent, { type: T }>[];\n}\n\n/** Returns all events for a specific transition. */\nexport function transitionEvents(store: EventStore, transitionName: string): NetEvent[] {\n return store.events().filter(e => eventTransitionName(e) === transitionName);\n}\n\n/** Returns all failure events. */\nexport function failures(store: EventStore): NetEvent[] {\n return store.events().filter(isFailureEvent);\n}\n\n// ==================== InMemoryEventStore ====================\n\nexport class InMemoryEventStore implements EventStore {\n private readonly _events: NetEvent[] = [];\n\n append(event: NetEvent): void {\n this._events.push(event);\n }\n\n events(): readonly NetEvent[] {\n return this._events;\n }\n\n isEnabled(): boolean {\n return true;\n }\n\n size(): number {\n return this._events.length;\n }\n\n isEmpty(): boolean {\n return this._events.length === 0;\n }\n\n /** Clears all stored events. */\n clear(): void {\n this._events.length = 0;\n }\n}\n\n// ==================== NoopEventStore ====================\n\nconst EMPTY: readonly NetEvent[] = Object.freeze([]);\n\nclass NoopEventStoreImpl implements EventStore {\n append(_event: NetEvent): void {\n // No-op\n }\n\n events(): readonly NetEvent[] {\n return EMPTY;\n }\n\n isEnabled(): boolean {\n return false;\n }\n\n size(): number {\n return 0;\n }\n\n isEmpty(): boolean {\n return true;\n }\n}\n\nconst NOOP_INSTANCE = new NoopEventStoreImpl();\n\n/** Returns a no-op event store that discards all events. */\nexport function noopEventStore(): EventStore {\n return NOOP_INSTANCE;\n}\n\n/** Creates a new in-memory event store. */\nexport function inMemoryEventStore(): InMemoryEventStore {\n return new InMemoryEventStore();\n}\n","/**\n * Error thrown when a transition's output doesn't satisfy its declared Out spec.\n */\nexport class OutViolationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OutViolationError';\n }\n}\n","/**\n * @module executor-support\n *\n * Output validation and timeout production for the Petri net executor.\n *\n * **Output validation algorithm**: Recursively walks the declared Out spec tree,\n * checking that the action's produced tokens match the structure:\n * - Place/ForwardInput: place must be in the produced set\n * - AND: all children must be satisfied (conjunction)\n * - XOR: exactly 1 child must be satisfied (throws OutViolationError for 0 or 2+)\n * - Timeout: delegates to child spec\n *\n * Returns the set of \"claimed\" place names on success, or null if unsatisfied.\n *\n * **Timeout production**: When an action exceeds its timeout, produces default\n * tokens to the timeout branch's output places, enabling the net to continue.\n */\nimport type { Out } from '../core/out.js';\nimport type { TransitionContext } from '../core/transition-context.js';\nimport { OutViolationError } from './out-violation-error.js';\n\n/**\n * Recursively validates that a transition's output satisfies its declared Out spec.\n *\n * @returns the set of claimed place names, or null if not satisfied\n * @throws OutViolationError if a structural violation is detected (e.g. XOR with 0 or 2+ branches)\n */\nexport function validateOutSpec(\n tName: string,\n spec: Out,\n producedPlaceNames: Set<string>,\n): Set<string> | null {\n switch (spec.type) {\n case 'place':\n return producedPlaceNames.has(spec.place.name)\n ? new Set([spec.place.name])\n : null;\n\n case 'forward-input':\n return producedPlaceNames.has(spec.to.name)\n ? new Set([spec.to.name])\n : null;\n\n case 'and': {\n const claimed = new Set<string>();\n for (const child of spec.children) {\n const result = validateOutSpec(tName, child, producedPlaceNames);\n if (result === null) return null;\n for (const p of result) claimed.add(p);\n }\n return claimed;\n }\n\n case 'xor': {\n const satisfied: Set<string>[] = [];\n for (const child of spec.children) {\n const result = validateOutSpec(tName, child, producedPlaceNames);\n if (result !== null) satisfied.push(result);\n }\n if (satisfied.length === 0) {\n throw new OutViolationError(\n `'${tName}': XOR violation - no branch produced (exactly 1 required)`\n );\n }\n if (satisfied.length > 1) {\n throw new OutViolationError(\n `'${tName}': XOR violation - multiple branches produced`\n );\n }\n return satisfied[0]!;\n }\n\n case 'timeout':\n return validateOutSpec(tName, spec.child, producedPlaceNames);\n }\n}\n\n/**\n * Produces default tokens to the timeout branch's output places when an action\n * exceeds its timeout. Walks the Out spec tree recursively:\n *\n * - **Place**: produces `null` (the timeout sentinel value).\n * - **ForwardInput**: forwards the consumed input token to the output place.\n * - **AND**: recurses into all children (all branches get tokens).\n * - **XOR**: disallowed — timeout cannot choose a branch non-deterministically.\n * - **Timeout**: disallowed — nested timeouts would create ambiguous recovery paths.\n */\nexport function produceTimeoutOutput(context: TransitionContext, timeoutChild: Out): void {\n switch (timeoutChild.type) {\n case 'place':\n context.output(timeoutChild.place, null);\n break;\n case 'forward-input': {\n const value = context.input(timeoutChild.from);\n context.output(timeoutChild.to, value);\n break;\n }\n case 'and':\n for (const child of timeoutChild.children) {\n produceTimeoutOutput(context, child);\n }\n break;\n case 'xor':\n throw new Error('XOR not allowed in timeout child');\n case 'timeout':\n throw new Error('Nested Timeout not allowed');\n }\n}\n","/**\n * @module bitmap-net-executor\n *\n * Async bitmap-based executor for Typed Coloured Time Petri Nets.\n *\n * **Execution loop phases** (per cycle):\n * 1. Process completed transitions — collect outputs, validate against Out specs\n * 2. Process external events — inject tokens from EnvironmentPlaces\n * 3. Update dirty transitions — re-evaluate enablement for transitions whose\n * input/inhibitor/read places changed (bitmap-based dirty set tracking)\n * 4. Fire ready transitions — sorted by priority (desc) then FIFO enablement time\n * 5. Await work — sleep until an action completes, a timer fires, or an external event arrives\n *\n * **Concurrency model**: Single-threaded JS event loop. No locks or CAS needed.\n * Multiple transitions execute concurrently via Promises (actions return Promise<void>).\n * Only the orchestrator mutates marking state — actions communicate via TokenOutput.\n *\n * **Bitmap strategy**: Places are tracked as bits in Uint32Array words. Enablement\n * checks use bitwise AND/OR for O(W) where W = ceil(numPlaces/32). A dirty set\n * bitmap tracks which transitions need re-evaluation, avoiding O(T) scans per cycle.\n *\n * @see CompiledNet for the precomputed bitmap masks and reverse indices\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place, EnvironmentPlace } from '../core/place.js';\nimport type { Token } from '../core/token.js';\nimport type { Transition } from '../core/transition.js';\nimport type { EventStore } from '../event/event-store.js';\nimport type { NetEvent } from '../event/net-event.js';\nimport type { PetriNetExecutor } from './petri-net-executor.js';\nimport { tokenOf } from '../core/token.js';\nimport { TokenInput } from '../core/token-input.js';\nimport { TokenOutput } from '../core/token-output.js';\nimport { TransitionContext } from '../core/transition-context.js';\nimport { noopEventStore } from '../event/event-store.js';\nimport { CompiledNet, WORD_SHIFT, BIT_MASK, setBit, clearBit } from './compiled-net.js';\nimport { Marking } from './marking.js';\nimport { validateOutSpec, produceTimeoutOutput } from './executor-support.js';\nimport { OutViolationError } from './out-violation-error.js';\nimport { earliest as timingEarliest, latest as timingLatest, hasDeadline as timingHasDeadline } from '../core/timing.js';\n\n/** Tolerance for JS timer jitter (setTimeout resolution ~1-4ms). */\nconst DEADLINE_TOLERANCE_MS = 1;\n\ninterface InFlightTransition {\n promise: Promise<void>;\n context: TransitionContext;\n consumed: Token<any>[];\n startMs: number;\n resolve: () => void;\n error?: unknown;\n}\n\ninterface ExternalEvent<T = any> {\n place: Place<T>;\n token: Token<T>;\n resolve: (value: boolean) => void;\n reject: (err: Error) => void;\n}\n\nexport interface BitmapNetExecutorOptions {\n eventStore?: EventStore;\n environmentPlaces?: Set<EnvironmentPlace<any>>;\n longRunning?: boolean;\n /** Provides execution context data for each transition firing. */\n executionContextProvider?: (transitionName: string, consumed: Token<any>[]) => Map<string, unknown>;\n}\n\n/**\n * Async bitmap-based executor for Coloured Time Petri Nets.\n *\n * Single-threaded JS model: no CAS needed, direct array writes.\n * Actions return Promise<void> — multiple in-flight actions are naturally concurrent.\n *\n * @remarks\n * **Deadline enforcement**: Transitions with finite deadlines (`deadline`, `window`, `exact`)\n * are checked in `enforceDeadlines()`, called from the main loop only when `hasAnyDeadlines`\n * is true (precomputed at construction). If a transition has been enabled longer than\n * `latest(timing)`, it is forcibly disabled and a `TransitionTimedOut` event is emitted.\n * The `awaitWork()` timer also schedules wake-ups for approaching deadlines, not just\n * earliest firing times.\n *\n * **Constructor precomputation**: `hasAnyDeadlines`, `allImmediate`/`allSamePriority`,\n * and `eventStoreEnabled` are computed once to avoid per-cycle overhead. Safe because\n * `isEnabled()` is constant and timing/priority are immutable on Transition.\n */\nexport class BitmapNetExecutor implements PetriNetExecutor {\n private readonly compiled: CompiledNet;\n private readonly marking: Marking;\n private readonly eventStore: EventStore;\n private readonly environmentPlaces: Set<string>;\n private readonly longRunning: boolean;\n private readonly executionContextProvider?: (transitionName: string, consumed: Token<any>[]) => Map<string, unknown>;\n private readonly startMs: number;\n private readonly hasAnyDeadlines: boolean;\n private readonly allImmediate: boolean;\n private readonly allSamePriority: boolean;\n private readonly eventStoreEnabled: boolean;\n\n // Bitmaps (Uint32Array, direct writes)\n private readonly markedPlaces: Uint32Array;\n private readonly dirtySet: Uint32Array;\n private readonly markingSnapBuffer: Uint32Array;\n private readonly dirtySnapBuffer: Uint32Array;\n private readonly firingSnapBuffer: Uint32Array;\n\n // Orchestrator state\n private readonly enabledAtMs: Float64Array;\n private readonly inFlightFlags: Uint8Array;\n private readonly enabledFlags: Uint8Array;\n /** Precomputed: 1 if transition has a finite deadline, 0 otherwise. */\n private readonly hasDeadlineFlags: Uint8Array;\n private enabledTransitionCount = 0;\n\n // In-flight tracking\n private readonly inFlight = new Map<Transition, InFlightTransition>();\n private readonly inFlightPromises: Promise<void>[] = [];\n private readonly awaitPromises: Promise<void>[] = [];\n\n // Queues\n private readonly completionQueue: Transition[] = [];\n private readonly externalQueue: ExternalEvent[] = [];\n\n // Wake-up mechanism\n private wakeUpResolve: (() => void) | null = null;\n\n // Pre-allocated buffer for fireReadyTransitions() to avoid per-cycle allocation\n private readonly readyBuffer: { tid: number; priority: number; enabledAtMs: number }[] = [];\n\n // Pending reset places for clock-restart detection\n private readonly pendingResetPlaces = new Set<string>();\n private readonly transitionInputPlaceNames: Map<Transition, Set<string>>;\n\n private running = false;\n private closed = false;\n\n constructor(\n net: PetriNet,\n initialTokens: Map<Place<any>, Token<any>[]>,\n options: BitmapNetExecutorOptions = {},\n ) {\n this.compiled = CompiledNet.compile(net);\n this.marking = Marking.from(initialTokens);\n this.eventStore = options.eventStore ?? noopEventStore();\n this.environmentPlaces = new Set(\n [...(options.environmentPlaces ?? [])].map(ep => ep.place.name)\n );\n this.longRunning = options.longRunning ?? false;\n this.executionContextProvider = options.executionContextProvider;\n this.startMs = performance.now();\n\n const wordCount = this.compiled.wordCount;\n this.markedPlaces = new Uint32Array(wordCount);\n this.markingSnapBuffer = new Uint32Array(wordCount);\n this.firingSnapBuffer = new Uint32Array(wordCount);\n const dirtyWords = (this.compiled.transitionCount + BIT_MASK) >>> WORD_SHIFT;\n this.dirtySet = new Uint32Array(dirtyWords);\n this.dirtySnapBuffer = new Uint32Array(dirtyWords);\n\n this.enabledAtMs = new Float64Array(this.compiled.transitionCount);\n this.enabledAtMs.fill(-Infinity);\n this.inFlightFlags = new Uint8Array(this.compiled.transitionCount);\n this.enabledFlags = new Uint8Array(this.compiled.transitionCount);\n this.hasDeadlineFlags = new Uint8Array(this.compiled.transitionCount);\n let anyDeadlines = false;\n let allImm = true;\n let samePrio = true;\n const firstPriority = this.compiled.transitionCount > 0\n ? this.compiled.transition(0).priority : 0;\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n const t = this.compiled.transition(tid);\n if (timingHasDeadline(t.timing)) {\n this.hasDeadlineFlags[tid] = 1;\n anyDeadlines = true;\n }\n if (t.timing.type !== 'immediate') allImm = false;\n if (t.priority !== firstPriority) samePrio = false;\n }\n this.hasAnyDeadlines = anyDeadlines;\n this.allImmediate = allImm;\n this.allSamePriority = samePrio;\n this.eventStoreEnabled = this.eventStore.isEnabled();\n\n // Precompute input place names per transition\n this.transitionInputPlaceNames = new Map();\n for (const t of net.transitions) {\n const names = new Set<string>();\n for (const spec of t.inputSpecs) names.add(spec.place.name);\n this.transitionInputPlaceNames.set(t, names);\n }\n }\n\n // ======================== Execution ========================\n\n async run(timeoutMs?: number): Promise<Marking> {\n if (timeoutMs !== undefined) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('Execution timed out')), timeoutMs);\n });\n try {\n return await Promise.race([this.executeLoop(), timeoutPromise]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n return this.executeLoop();\n }\n\n private async executeLoop(): Promise<Marking> {\n this.running = true;\n this.emitEvent({\n type: 'execution-started',\n timestamp: Date.now(),\n netName: this.compiled.net.name,\n executionId: this.executionId(),\n });\n\n this.initializeMarkedBitmap();\n this.markAllDirty();\n\n this.emitEvent({\n type: 'marking-snapshot',\n timestamp: Date.now(),\n marking: this.snapshotMarking(),\n });\n\n while (this.running && !this.closed) {\n this.processCompletedTransitions();\n this.processExternalEvents();\n this.updateDirtyTransitions();\n // Deadline enforcement: separate pass over ALL enabled transitions (not just dirty\n // ones), since deadlines tick independently of place changes. Uses fresh\n // performance.now() for timing accuracy. Gated by hasAnyDeadlines (O(0) skip for\n // pure immediate nets).\n if (this.hasAnyDeadlines) this.enforceDeadlines(performance.now());\n\n if (this.shouldTerminate()) break;\n\n this.fireReadyTransitions();\n // Skip awaitWork() when firing produced dirty bits (e.g., token consumption\n // disabled a conflicting transition). Bounded: without microtask yield no new\n // completions arrive, so the loop converges in at most one extra pass.\n if (this.hasDirtyBits()) continue;\n await this.awaitWork();\n }\n\n this.running = false;\n this.drainPendingExternalEvents();\n\n this.emitEvent({\n type: 'marking-snapshot',\n timestamp: Date.now(),\n marking: this.snapshotMarking(),\n });\n\n this.emitEvent({\n type: 'execution-completed',\n timestamp: Date.now(),\n netName: this.compiled.net.name,\n executionId: this.executionId(),\n totalDurationMs: performance.now() - this.startMs,\n });\n\n return this.marking;\n }\n\n // ======================== Environment Place API ========================\n\n async inject<T>(envPlace: EnvironmentPlace<T>, token: Token<T>): Promise<boolean> {\n if (!this.environmentPlaces.has(envPlace.place.name)) {\n throw new Error(`Place ${envPlace.place.name} is not registered as an environment place`);\n }\n if (this.closed) return false;\n\n return new Promise<boolean>((resolve, reject) => {\n this.externalQueue.push({\n place: envPlace.place,\n token,\n resolve,\n reject,\n });\n this.wakeUp();\n });\n }\n\n /** Convenience: inject a raw value (creates token with current timestamp). */\n async injectValue<T>(envPlace: EnvironmentPlace<T>, value: T): Promise<boolean> {\n return this.inject(envPlace, tokenOf(value));\n }\n\n // ======================== Initialize ========================\n\n private initializeMarkedBitmap(): void {\n for (let pid = 0; pid < this.compiled.placeCount; pid++) {\n const place = this.compiled.place(pid);\n if (this.marking.hasTokens(place)) {\n setBit(this.markedPlaces, pid);\n }\n }\n }\n\n private markAllDirty(): void {\n const tc = this.compiled.transitionCount;\n const dirtyWords = this.dirtySet.length;\n for (let w = 0; w < dirtyWords - 1; w++) {\n this.dirtySet[w] = 0xFFFFFFFF;\n }\n if (dirtyWords > 0) {\n const lastWordBits = tc & BIT_MASK;\n this.dirtySet[dirtyWords - 1] = lastWordBits === 0 ? 0xFFFFFFFF : (1 << lastWordBits) - 1;\n }\n }\n\n private shouldTerminate(): boolean {\n if (this.longRunning) return this.closed;\n return this.enabledTransitionCount === 0\n && this.inFlight.size === 0\n && this.completionQueue.length === 0;\n }\n\n // ======================== Dirty Set Transitions ========================\n\n private updateDirtyTransitions(): void {\n const nowMs = performance.now();\n\n // Snapshot the marking bitmap into pre-allocated buffer.\n // We need a consistent snapshot because enablement checks read multiple words,\n // and concurrent completions/injections could modify markedPlaces mid-scan.\n const markingSnap = this.markingSnapBuffer;\n markingSnap.set(this.markedPlaces);\n\n // Snapshot-and-clear the dirty set in one pass. New dirty bits set during\n // re-evaluation (e.g., by cascading enablement) are captured in the next cycle.\n const dirtyWords = this.dirtySet.length;\n const dirtySnap = this.dirtySnapBuffer;\n for (let w = 0; w < dirtyWords; w++) {\n dirtySnap[w] = this.dirtySet[w]!;\n this.dirtySet[w] = 0;\n }\n\n // Iterate over set bits using the numberOfTrailingZeros trick.\n for (let w = 0; w < dirtyWords; w++) {\n let word = dirtySnap[w]!;\n while (word !== 0) {\n // Extract lowest set bit index: `word & -word` isolates the lowest set bit,\n // `Math.clz32()` counts leading zeros (0-31), XOR 31 converts to trailing zeros.\n const bit = Math.clz32(word & -word) ^ 31;\n const tid = (w << WORD_SHIFT) | bit;\n word &= word - 1; // clear lowest set bit (Kernighan's trick)\n\n if (tid >= this.compiled.transitionCount) break;\n if (this.inFlightFlags[tid]) continue;\n\n const wasEnabled = this.enabledFlags[tid] !== 0;\n const canNow = this.canEnable(tid, markingSnap);\n\n if (canNow && !wasEnabled) {\n this.enabledFlags[tid] = 1;\n this.enabledTransitionCount++;\n this.enabledAtMs[tid] = nowMs;\n this.emitEvent({\n type: 'transition-enabled',\n timestamp: Date.now(),\n transitionName: this.compiled.transition(tid).name,\n });\n } else if (!canNow && wasEnabled) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n } else if (canNow && wasEnabled && this.hasInputFromResetPlace(this.compiled.transition(tid))) {\n this.enabledAtMs[tid] = nowMs;\n this.emitEvent({\n type: 'transition-clock-restarted',\n timestamp: Date.now(),\n transitionName: this.compiled.transition(tid).name,\n });\n }\n }\n }\n\n this.pendingResetPlaces.clear();\n }\n\n /**\n * Checks all enabled transitions with finite deadlines. If a transition has been\n * enabled longer than `latest(timing)`, it is forcibly disabled and a\n * `TransitionTimedOut` event is emitted. Classical TPN semantics require transitions\n * to either fire within their window or become disabled.\n *\n * A 1ms tolerance is applied to account for timer jitter and microtask scheduling\n * delays. Without this, exact-timed transitions (where earliest == latest) would\n * almost always be disabled before they can fire.\n */\n private enforceDeadlines(nowMs: number): void {\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.hasDeadlineFlags[tid]) continue; // O(1) skip for non-deadline transitions\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n const t = this.compiled.transition(tid);\n\n const elapsed = nowMs - this.enabledAtMs[tid]!;\n const latestMs = timingLatest(t.timing);\n if (elapsed > latestMs + DEADLINE_TOLERANCE_MS) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.emitEvent({\n type: 'transition-timed-out',\n timestamp: Date.now(),\n transitionName: t.name,\n deadlineMs: latestMs,\n actualDurationMs: elapsed,\n });\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n private canEnable(tid: number, markingSnap: Uint32Array): boolean {\n if (!this.compiled.canEnableBitmap(tid, markingSnap)) return false;\n\n // Cardinality check\n const cardCheck = this.compiled.cardinalityCheck(tid);\n if (cardCheck !== null) {\n for (let i = 0; i < cardCheck.placeIds.length; i++) {\n const pid = cardCheck.placeIds[i]!;\n const required = cardCheck.requiredCounts[i]!;\n const place = this.compiled.place(pid);\n if (this.marking.tokenCount(place) < required) return false;\n }\n }\n\n // Guard check: verify matching tokens exist for each guarded input\n if (this.compiled.hasGuards(tid)) {\n const t = this.compiled.transition(tid);\n for (const spec of t.inputSpecs) {\n if (!spec.guard) continue;\n const requiredCount = spec.type === 'one' ? 1\n : spec.type === 'exactly' ? spec.count\n : spec.type === 'at-least' ? spec.minimum\n : 1; // 'all' requires at least 1 matching\n if (this.marking.countMatching(spec) < requiredCount) return false;\n }\n }\n\n return true;\n }\n\n private hasInputFromResetPlace(t: Transition): boolean {\n if (this.pendingResetPlaces.size === 0) return false;\n const inputNames = this.transitionInputPlaceNames.get(t);\n if (!inputNames) return false;\n for (const name of this.pendingResetPlaces) {\n if (inputNames.has(name)) return true;\n }\n return false;\n }\n\n // ======================== Firing ========================\n\n private fireReadyTransitions(): void {\n if (this.allImmediate && this.allSamePriority) {\n this.fireReadyImmediate();\n return;\n }\n this.fireReadyGeneral();\n }\n\n /**\n * Fast path for nets where all transitions are immediate and same priority.\n * Skips timing checks, sorting, and snapshot buffer — just scan and fire.\n *\n * Uses live `markedPlaces` instead of a snapshot. Safe because\n * `updateBitmapAfterConsumption()` synchronously updates the bitmap before the next\n * iteration. For equal-priority immediate transitions, tid scan order satisfies\n * FIFO-by-enablement-time (all enabled in the same cycle).\n */\n private fireReadyImmediate(): void {\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n if (this.canEnable(tid, this.markedPlaces)) {\n this.fireTransition(tid);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n private fireReadyGeneral(): void {\n const nowMs = performance.now();\n\n // Collect ready transitions into pre-allocated buffer to reduce GC pressure\n const ready = this.readyBuffer;\n ready.length = 0;\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n const t = this.compiled.transition(tid);\n const enabledMs = this.enabledAtMs[tid]!;\n const elapsedMs = nowMs - enabledMs;\n const earliestMs = timingEarliest(t.timing);\n if (earliestMs <= elapsedMs) {\n ready.push({ tid, priority: t.priority, enabledAtMs: enabledMs });\n }\n }\n if (ready.length === 0) return;\n\n // Sort: higher priority first, then earlier enablement (FIFO).\n // This defines the deterministic scheduling contract for conflict resolution.\n // We re-sort each cycle rather than maintaining a sorted invariant because\n // enablement times change on clock-restarts (reset arcs), which would require\n // expensive re-insertion. Sorting ≤T entries per cycle is fast enough.\n ready.sort((a, b) => {\n const prioCmp = b.priority - a.priority;\n if (prioCmp !== 0) return prioCmp;\n return a.enabledAtMs - b.enabledAtMs;\n });\n\n // Take a fresh snapshot for re-checking (reuse pre-allocated buffer)\n const freshSnap = this.firingSnapBuffer;\n freshSnap.set(this.markedPlaces);\n for (const entry of ready) {\n const { tid } = entry;\n if (this.enabledFlags[tid] && this.canEnable(tid, freshSnap)) {\n this.fireTransition(tid);\n // Update snapshot after consuming tokens\n freshSnap.set(this.markedPlaces);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n private fireTransition(tid: number): void {\n const t = this.compiled.transition(tid);\n const inputs = new TokenInput();\n const consumed: Token<any>[] = [];\n\n // Consume tokens based on input specs with cardinality and guard.\n // Note: for guarded 'all'/'at-least' inputs, countMatching() is called here AND in\n // canEnable() — a known O(2n) tradeoff. Token queues are typically ≤10 items, so\n // the simplicity of re-scanning outweighs caching complexity.\n for (const inSpec of t.inputSpecs) {\n let toConsume: number;\n switch (inSpec.type) {\n case 'one': toConsume = 1; break;\n case 'exactly': toConsume = inSpec.count; break;\n case 'all':\n toConsume = inSpec.guard\n ? this.marking.countMatching(inSpec)\n : this.marking.tokenCount(inSpec.place);\n break;\n case 'at-least':\n toConsume = inSpec.guard\n ? this.marking.countMatching(inSpec)\n : this.marking.tokenCount(inSpec.place);\n break;\n }\n\n for (let i = 0; i < toConsume; i++) {\n const token = inSpec.guard\n ? this.marking.removeFirstMatching(inSpec)\n : this.marking.removeFirst(inSpec.place);\n if (token === null) break;\n consumed.push(token);\n inputs.add(inSpec.place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: inSpec.place.name,\n token,\n });\n }\n }\n\n // Read arcs (peek, don't consume)\n for (const arc of t.reads) {\n const token = this.marking.peekFirst(arc.place);\n if (token !== null) {\n inputs.add(arc.place, token);\n }\n }\n\n // Reset arcs\n for (const arc of t.resets) {\n const removed = this.marking.removeAll(arc.place);\n this.pendingResetPlaces.add(arc.place.name);\n for (const token of removed) {\n consumed.push(token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: arc.place.name,\n token,\n });\n }\n }\n\n // Update bitmap for consumed/reset places\n this.updateBitmapAfterConsumption(tid);\n\n this.emitEvent({\n type: 'transition-started',\n timestamp: Date.now(),\n transitionName: t.name,\n consumedTokens: consumed,\n });\n\n const execCtx = this.executionContextProvider?.(t.name, consumed);\n const logFn = (level: string, message: string, error?: Error) => {\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName: t.name,\n logger: t.name,\n level,\n message,\n error: error?.name ?? null,\n errorMessage: error?.message ?? null,\n });\n };\n const context = new TransitionContext(\n t.name, inputs, new TokenOutput(),\n t.inputPlaces(), t.readPlaces(), t.outputPlaces(),\n execCtx,\n logFn,\n );\n\n // Create action promise with optional timeout\n let actionPromise = t.action(context);\n\n if (t.hasActionTimeout()) {\n const timeoutSpec = t.actionTimeout;\n if (timeoutSpec === null) throw new Error(`Expected actionTimeout on ${t.name}`);\n const timeoutMs = timeoutSpec.afterMs;\n actionPromise = Promise.race([\n actionPromise,\n new Promise<void>((_, reject) =>\n setTimeout(() => reject(new TimeoutSentinel()), timeoutMs)\n ),\n ]).catch((err) => {\n if (err instanceof TimeoutSentinel) {\n produceTimeoutOutput(context, timeoutSpec.child);\n this.emitEvent({\n type: 'action-timed-out',\n timestamp: Date.now(),\n transitionName: t.name,\n timeoutMs,\n });\n return;\n }\n throw err;\n });\n }\n\n // On completion, push to completionQueue\n let resolveInFlight!: () => void;\n const completionPromise = new Promise<void>(r => { resolveInFlight = r; });\n\n const flight: InFlightTransition = {\n promise: completionPromise,\n context,\n consumed,\n startMs: performance.now(),\n resolve: resolveInFlight,\n };\n\n actionPromise.then(\n () => {\n this.completionQueue.push(t);\n this.wakeUp();\n resolveInFlight();\n },\n (err) => {\n flight.error = err;\n this.completionQueue.push(t);\n this.wakeUp();\n resolveInFlight();\n },\n );\n\n this.inFlight.set(t, flight);\n this.inFlightFlags[tid] = 1;\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n\n private updateBitmapAfterConsumption(tid: number): void {\n const pids = this.compiled.consumptionPlaceIds(tid);\n for (const pid of pids) {\n const place = this.compiled.place(pid);\n if (!this.marking.hasTokens(place)) {\n clearBit(this.markedPlaces, pid);\n }\n this.markDirty(pid);\n }\n }\n\n // ======================== Completion Processing ========================\n\n private processCompletedTransitions(): void {\n if (this.completionQueue.length === 0) return;\n // In-place iteration is safe: processing is synchronous and .push() only\n // happens from microtasks which cannot interleave within this loop.\n const len = this.completionQueue.length;\n for (let i = 0; i < len; i++) {\n const t = this.completionQueue[i]!;\n const flight = this.inFlight.get(t);\n if (!flight) continue;\n this.inFlight.delete(t);\n\n const tid = this.compiled.transitionId(t);\n this.inFlightFlags[tid] = 0;\n\n if (flight.error) {\n const err = flight.error instanceof Error\n ? flight.error\n : new Error(String(flight.error));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n continue;\n }\n\n try {\n const outputs = flight.context.rawOutput();\n\n // Validate output against spec\n if (t.outputSpec !== null) {\n const produced = outputs.placesWithTokens();\n const result = validateOutSpec(t.name, t.outputSpec, produced);\n if (result === null) {\n throw new OutViolationError(\n `'${t.name}': output does not satisfy declared spec`\n );\n }\n }\n\n // Single pass: add tokens to marking, update bitmap, and emit events\n const produced: Token<any>[] = [];\n for (const entry of outputs.entries()) {\n this.marking.addToken(entry.place, entry.token);\n produced.push(entry.token);\n const pid = this.compiled.placeId(entry.place);\n setBit(this.markedPlaces, pid);\n this.markDirty(pid);\n this.emitEvent({\n type: 'token-added',\n timestamp: Date.now(),\n placeName: entry.place.name,\n token: entry.token,\n });\n }\n this.markTransitionDirty(tid);\n\n this.emitEvent({\n type: 'transition-completed',\n timestamp: Date.now(),\n transitionName: t.name,\n producedTokens: produced,\n durationMs: performance.now() - flight.startMs,\n });\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n }\n }\n this.completionQueue.length = 0;\n }\n\n // ======================== External Events ========================\n\n private processExternalEvents(): void {\n if (this.externalQueue.length === 0) return;\n // In-place iteration is safe: processing is synchronous and .push() only\n // happens from microtasks which cannot interleave within this loop.\n const len = this.externalQueue.length;\n for (let i = 0; i < len; i++) {\n const event = this.externalQueue[i]!;\n try {\n this.marking.addToken(event.place, event.token);\n const pid = this.compiled.placeId(event.place);\n setBit(this.markedPlaces, pid);\n this.markDirty(pid);\n\n this.emitEvent({\n type: 'token-added',\n timestamp: Date.now(),\n placeName: event.place.name,\n token: event.token,\n });\n event.resolve(true);\n } catch (e) {\n event.reject(e instanceof Error ? e : new Error(String(e)));\n }\n }\n this.externalQueue.length = 0;\n }\n\n private drainPendingExternalEvents(): void {\n while (this.externalQueue.length > 0) {\n this.externalQueue.shift()!.resolve(false);\n }\n }\n\n // ======================== Await Work ========================\n\n /**\n * Suspends the executor until work is available. Composes up to 3 promise sources\n * into a single Promise.race: (1) any in-flight action completing, (2) external\n * event injection via wakeUp(), (3) timer for the next delayed transition's earliest\n * firing time. This avoids busy-waiting while remaining responsive to all event types.\n *\n * **Microtask flush**: Before building Promise.race, yields via `await Promise.resolve()`\n * to drain the microtask queue. Sync actions complete via `.then()` microtask; this\n * yield lets those fire, avoiding ~5 allocations when work is already available.\n * After the yield, re-checks queues and `this.closed` for close-during-yield safety.\n */\n private async awaitWork(): Promise<void> {\n if (this.completionQueue.length > 0 || this.externalQueue.length > 0) return;\n\n // Flush microtask queue: sync actions complete via .then() which schedules a\n // microtask. A single await here lets those fire before we build a full\n // Promise.race (~5 allocations). For async workloads this adds ~0.05us.\n await Promise.resolve();\n if (this.completionQueue.length > 0 || this.externalQueue.length > 0 || this.closed) return;\n\n const promises = this.awaitPromises;\n promises.length = 0;\n\n // 1. Any in-flight action completing (reuse array to avoid 2 intermediate allocations)\n if (this.inFlight.size > 0) {\n const arr = this.inFlightPromises;\n arr.length = 0;\n for (const f of this.inFlight.values()) arr.push(f.promise);\n promises.push(Promise.race(arr));\n }\n\n // 2. External event wake-up\n promises.push(new Promise<void>(resolve => { this.wakeUpResolve = resolve; }));\n\n // 3. Timer for next delayed transition\n const timerMs = this.millisUntilNextTimedTransition();\n if (timerMs > 0 && timerMs < Infinity) {\n promises.push(new Promise<void>(r => setTimeout(r, timerMs)));\n }\n\n if (promises.length > 0) {\n await Promise.race(promises);\n }\n this.wakeUpResolve = null;\n }\n\n private millisUntilNextTimedTransition(): number {\n const nowMs = performance.now();\n let minWaitMs = Infinity;\n\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.enabledFlags[tid]) continue;\n const t = this.compiled.transition(tid);\n const enabledMs = this.enabledAtMs[tid]!;\n const elapsedMs = nowMs - enabledMs;\n\n // Time until earliest firing\n const earliestMs = timingEarliest(t.timing);\n const remainingEarliest = earliestMs - elapsedMs;\n if (remainingEarliest <= 0) return 0;\n minWaitMs = Math.min(minWaitMs, remainingEarliest);\n\n // Time until deadline expiry (must wake up to enforce deadline)\n if (timingHasDeadline(t.timing)) {\n const latestMs = timingLatest(t.timing);\n const remainingDeadline = latestMs - elapsedMs;\n if (remainingDeadline <= 0) return 0;\n minWaitMs = Math.min(minWaitMs, remainingDeadline);\n }\n }\n return minWaitMs;\n }\n\n private wakeUp(): void {\n this.wakeUpResolve?.();\n }\n\n // ======================== Dirty Set Helpers ========================\n\n /** Returns true if any transition needs re-evaluation. O(W) where W = ceil(transitions/32). */\n private hasDirtyBits(): boolean {\n for (let w = 0; w < this.dirtySet.length; w++) {\n if (this.dirtySet[w] !== 0) return true;\n }\n return false;\n }\n\n private markDirty(pid: number): void {\n const tids = this.compiled.affectedTransitions(pid);\n for (const tid of tids) {\n this.markTransitionDirty(tid);\n }\n }\n\n private markTransitionDirty(tid: number): void {\n this.dirtySet[tid >>> WORD_SHIFT]! |= (1 << (tid & BIT_MASK));\n }\n\n // ======================== State Inspection ========================\n\n getMarking(): Marking { return this.marking; }\n\n /** Builds a snapshot of the current marking for event emission. */\n private snapshotMarking(): ReadonlyMap<string, readonly Token<any>[]> {\n const snap = new Map<string, readonly Token<any>[]>();\n for (let pid = 0; pid < this.compiled.placeCount; pid++) {\n const p = this.compiled.place(pid);\n const tokens = this.marking.peekTokens(p);\n if (tokens.length > 0) {\n snap.set(p.name, [...tokens]);\n }\n }\n return snap;\n }\n\n isQuiescent(): boolean {\n return this.enabledTransitionCount === 0 && this.inFlight.size === 0;\n }\n\n executionId(): string {\n return this.startMs.toString(16);\n }\n\n close(): void {\n this.running = false;\n this.closed = true;\n this.wakeUp();\n }\n\n // ======================== Event Emission ========================\n\n private emitEvent(event: NetEvent): void {\n if (this.eventStoreEnabled) {\n this.eventStore.append(event);\n }\n }\n}\n\n/** Internal sentinel for timeout detection. */\nclass TimeoutSentinel extends Error {\n constructor() { super('action timeout'); this.name = 'TimeoutSentinel'; }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAaA,IAAM,aAA0B,OAAO,OAAO;AAAA,EAC5C,OAAO;AAAA,EACP,WAAW;AACb,CAAC;AAGM,SAAS,QAAW,OAAoB;AAC7C,SAAO,EAAE,OAAO,WAAW,KAAK,IAAI,EAAE;AACxC;AAOO,SAAS,YAAyB;AACvC,SAAO;AACT;AAGO,SAAS,QAAW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,SAAK,UAAU;AACf,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AAAA;AAAA,EAIQ,UAAU,OAAuB;AACvC,QAAI,KAAK,mBAAmB;AAC1B,WAAK,WAAW,OAAO,KAAK;AAAA,IAC9B;AAAA,EACF;AACF;AAGA,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAClC,cAAc;AAAE,UAAM,gBAAgB;AAAG,SAAK,OAAO;AAAA,EAAmB;AAC1E;","names":["place","place","place","timeoutPlace","place","place","place","place","place","place","place","place","requiredCount","produced"]}