Skip to content
GitHubXDiscord

createRuntime

Stable · since 0.1.0

createRuntime returns an isolated Runtime — the container that holds triggers, conditions and actions for a tree of components. Most apps create one runtime in main.tsx and pass it down via <TriggerRuntimeProvider>. Skip the call entirely and Triggery uses a lazily created default runtime via getDefaultRuntime.

import { createRuntime } from '@triggery/core';
function createRuntime(options?: RuntimeOptions): Runtime;
FieldTypeDefaultDescription
inspectorboolean | { dev?: boolean; prod?: boolean }DEV true, PROD falseEnable / disable the per-run inspector.
inspectorBufferSizenumber50Inspector ring-buffer size. Ignored when the inspector is disabled.
middlewarereadonly Middleware[][]Middleware chain.
maxCascadeDepthnumber3Maximum cascade depth — action → fireEvent → …. Runs above this are skipped with 'overflow'.

See RuntimeOptions for the full shape.

A Runtime object. The methods most apps touch:

MethodDescription
runtime.fire(event, payload)Dispatch an event through the scheduler. Returns void.
runtime.fireSync(event, payload)Dispatch synchronously (bypass scheduler). For tests and bench.
runtime.subscribe(listener)Listen for every recorded run. Returns a RegistrationToken.
runtime.getInspectorBuffer()Most-recent N inspector snapshots.
runtime.getTrigger(id)Look up a registered trigger.
runtime.graph()JSON-friendly snapshot of the registry — used by triggery graph CLI.
runtime.dispose()Abort all in-flight runs and drop all registrations.

register* methods (registerTrigger, registerCondition, registerAction) are also part of the surface, but bindings handle them for you.

import { createRuntime } from '@triggery/core';
import { TriggerRuntimeProvider } from '@triggery/react';
import type { ComponentType } from 'react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

const runtime = createRuntime();

declare const App: ComponentType;
createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <TriggerRuntimeProvider runtime={runtime}>
      <App />
    </TriggerRuntimeProvider>
  </StrictMode>,
);
import { createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';
import { afterEachfunction afterEach<ExtraContext = object>(fn: AfterEachListener<ExtraContext>, timeout?: number): void
Registers a callback function to be executed after each test within the current suite has completed. This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using afterEach to delete temporary files created during a test afterEach(async () => { await fileSystem.deleteTempFiles(); }); ```
, beforeEachfunction beforeEach<ExtraContext = object>(fn: BeforeEachListener<ExtraContext>, timeout?: number): void
Registers a callback function to be executed before each test within the current suite. This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using beforeEach to reset a database state beforeEach(async () => { await database.reset(); }); ```
} from 'vitest';
let runtimelet runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime(); beforeEachbeforeEach<object>(fn: BeforeEachListener<object>, timeout?: number): void
Registers a callback function to be executed before each test within the current suite. This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using beforeEach to reset a database state beforeEach(async () => { await database.reset(); }); ```
(() => {
runtimelet runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime({ inspectorBufferSizeinspectorBufferSize?: number | undefined
Inspector ring buffer size (default: 50). Ignored when the inspector is disabled.
: 100 });
}); afterEachafterEach<object>(fn: AfterEachListener<object>, timeout?: number): void
Registers a callback function to be executed after each test within the current suite has completed. This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using afterEach to delete temporary files created during a test afterEach(async () => { await fileSystem.deleteTempFiles(); }); ```
(() => {
runtimelet runtime: Runtime.disposefunction dispose(): void
Tear down the runtime completely.
();
});
import { createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';

const runtimeconst runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime({
  maxCascadeDepthmaxCascadeDepth?: number | undefined
Maximum cascade depth (action → fireEvent → ...). Default: 3.
: 1, // refuse any indirect chain — action→event→trigger is enough
});
import { createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime, type Middleware
type Middleware = {
    readonly name: string;
    onFire?(ctx: FireContext): void | {
        cancel: true;
        reason: string;
    };
    onBeforeMatch?(ctx: MatchContext): void;
    onSkip?(ctx: SkipContext): void;
    onActionStart?(ctx: ActionContext): void;
    onActionEnd?(ctx: ActionContext & {
        durationMs: number;
        result?: unknown;
    }): void;
    onError?(ctx: ActionContext & {
        error: unknown;
    }): void;
    onCascade?(ctx: CascadeContext): void;
}
} from '@triggery/core';
const loggerconst logger: Middleware: Middleware
type Middleware = {
    readonly name: string;
    onFire?(ctx: FireContext): void | {
        cancel: true;
        reason: string;
    };
    onBeforeMatch?(ctx: MatchContext): void;
    onSkip?(ctx: SkipContext): void;
    onActionStart?(ctx: ActionContext): void;
    onActionEnd?(ctx: ActionContext & {
        durationMs: number;
        result?: unknown;
    }): void;
    onError?(ctx: ActionContext & {
        error: unknown;
    }): void;
    onCascade?(ctx: CascadeContext): void;
}
= {
namename: string: 'logger', onActionEnd
onActionEnd?(ctx: ActionContext & {
    durationMs: number;
    result?: unknown;
}): void
({ triggerIdtriggerId: string, actionNameactionName: string, durationMsdurationMs: number }) {
consolevar console: Console.logConsole.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
(`[${triggerIdtriggerId: string}] ${actionNameactionName: string} ${durationMsdurationMs: number.toFixedNumber.toFixed(fractionDigits?: number): string
Returns a string representing a number in fixed-point notation.
@paramfractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
(2)}ms`);
}, }; const runtimeconst runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime({ middlewaremiddleware?: readonly Middleware[] | undefined
Global middleware applied to every trigger in this runtime.
: [loggerconst logger: Middleware] });
import { createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';

const runtimeconst runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime({ inspectorinspector?: InspectorOption | undefined
Enable / disable the per-run inspector. See {@link InspectorOption } .
: false });

Or per-environment:

import { createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';

const runtimeconst runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime({
  inspectorinspector?: InspectorOption | undefined
Enable / disable the per-run inspector. See {@link InspectorOption } .
: { devdev?: boolean | undefined: true, prodprod?: boolean | undefined: false },
});