createRuntime
Стабильный · с 0.1.0
createRuntime возвращает изолированный Runtime — контейнер, в котором живут триггеры, условия и действия для дерева компонентов. Большинство приложений создают один рантайм в main.tsx и пробрасывают его через <TriggerRuntimeProvider>. Если пропустить вызов полностью, Triggery использует лениво создаваемый рантайм по умолчанию через getDefaultRuntime.
import { createRuntime } from '@triggery/core';
Сигнатура
Заголовок раздела «Сигнатура»function createRuntime(options?: RuntimeOptions): Runtime;| Параметр | Тип | По умолчанию | Описание |
|---|---|---|---|
inspector | boolean | { dev?: boolean; prod?: boolean } | DEV true, PROD false | Включить / выключить per-run инспектор. |
inspectorBufferSize | number | 50 | Размер кольцевого буфера инспектора. Игнорируется, если инспектор отключён. |
middleware | readonly Middleware[] | [] | Цепочка миддлвэров. |
maxCascadeDepth | number | 3 | Максимальная глубина каскада — action → fireEvent → …. Запуски глубже пропускаются со статусом 'overflow'. |
Полную форму смотри в RuntimeOptions.
Возвращает
Заголовок раздела «Возвращает»Объект Runtime. Методы, которыми пользуется большинство приложений:
| Метод | Описание |
|---|---|
runtime.fire(event, payload) | Диспатчит событие через планировщик. Возвращает void. |
runtime.fireSync(event, payload) | Диспатчит синхронно (минуя планировщик). Для тестов и бенчмарков. |
runtime.subscribe(listener) | Слушать каждый записанный запуск. Возвращает RegistrationToken. |
runtime.getInspectorBuffer() | Последние N снепшотов инспектора. |
runtime.getTrigger(id) | Найти зарегистрированный триггер. |
runtime.graph() | JSON-friendly снепшот реестра — используется CLI triggery graph. |
runtime.dispose() | Прервать все запуски в полёте и сбросить все регистрации. |
Методы register* (registerTrigger, registerCondition, registerAction) тоже часть поверхности, но их за тебя вызывают биндинги.
Примеры
Заголовок раздела «Примеры»По умолчанию — один рантайм в корне
Заголовок раздела «По умолчанию — один рантайм в корне»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 { createRuntime function createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';
import { afterEach function afterEach<ExtraContext = object>(fn: AfterEachListener<ExtraContext>, timeout?: number): voidRegisters 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. , beforeEach function beforeEach<ExtraContext = object>(fn: BeforeEachListener<ExtraContext>, timeout?: number): voidRegisters 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. } from 'vitest';
let runtime let runtime: Runtime = createRuntime function createRuntime(options?: RuntimeOptions): Runtime ();
beforeEach beforeEach<object>(fn: BeforeEachListener<object>, timeout?: number): voidRegisters 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. (() => {
runtime let runtime: Runtime = createRuntime function createRuntime(options?: RuntimeOptions): Runtime ({ inspectorBufferSize inspectorBufferSize?: number | undefinedInspector ring buffer size (default: 50). Ignored when the inspector is disabled. : 100 });
});
afterEach afterEach<object>(fn: AfterEachListener<object>, timeout?: number): voidRegisters 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. (() => {
runtime let runtime: Runtime .dispose function dispose(): voidTear down the runtime completely. ();
});Жёсткий лимит каскада
Заголовок раздела «Жёсткий лимит каскада»import { createRuntime function createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';
const runtime const runtime: Runtime = createRuntime function createRuntime(options?: RuntimeOptions): Runtime ({
maxCascadeDepth maxCascadeDepth?: number | undefinedMaximum cascade depth (action → fireEvent → ...). Default: 3. : 1, // refuse any indirect chain — action→event→trigger is enough
});С миддлвэрами
Заголовок раздела «С миддлвэрами»import { createRuntime function 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 logger const 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;
}
= {
name name: string : 'logger',
onActionEnd onActionEnd?(ctx: ActionContext & {
durationMs: number;
result?: unknown;
}): void
({ triggerId triggerId: string , actionName actionName: string , durationMs durationMs: number }) {
console var console: Console .log Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) (`[${triggerId triggerId: string }] ${actionName actionName: string } ${durationMs durationMs: number .toFixed Number.toFixed(fractionDigits?: number): stringReturns a string representing a number in fixed-point notation. (2)}ms`);
},
};
const runtime const runtime: Runtime = createRuntime function createRuntime(options?: RuntimeOptions): Runtime ({ middleware middleware?: readonly Middleware[] | undefinedGlobal middleware applied to every trigger in this runtime. : [logger const logger: Middleware ] });Инспектор явно выключен
Заголовок раздела «Инспектор явно выключен»import { createRuntime function createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';
const runtime const runtime: Runtime = createRuntime function createRuntime(options?: RuntimeOptions): Runtime ({ inspector inspector?: InspectorOption | undefinedEnable / disable the per-run inspector. See
{@link
InspectorOption
}
. : false });Или по окружениям:
import { createRuntime function createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';
const runtime const runtime: Runtime = createRuntime function createRuntime(options?: RuntimeOptions): Runtime ({
inspector inspector?: InspectorOption | undefinedEnable / disable the per-run inspector. See
{@link
InspectorOption
}
. : { dev dev?: boolean | undefined : true, prod prod?: boolean | undefined : false },
});Замечания
Заголовок раздела «Замечания»См. также
Заголовок раздела «См. также» getDefaultRuntime Доступ (и ленивое создание) к глобальному синглтону.
setDefaultRuntime Заменить синглтон — полезно в тестах.
Тип Runtime Полная поверхность методов.
Руководство по рантайму Нарративный разбор скоупов, изоляции, жизненного цикла.