RuntimeOptions
Стабильный · с 0.1.0
Семантика
Заголовок раздела «Семантика inspector»
Bag опций, передаваемый в createRuntime. Все поля необязательные; без аргументов создаётся рантайм со всеми дефолтами.
import type { RuntimeOptions } from '@triggery/core';
Определение
Заголовок раздела «Определение»type RuntimeOptions = {
middleware?: readonly Middleware[];
maxCascadeDepth?: number;
inspectorBufferSize?: number;
inspector?: boolean | { dev?: boolean; prod?: boolean };
};| Поле | Тип | По умолчанию | Описание |
|---|---|---|---|
middleware | readonly Middleware[] | [] | Цепочка, применяемая к каждому триггеру в этом рантайме. Порядок важен для onFire / onSkip / onActionStart / onActionEnd / onError / onCascade. |
maxCascadeDepth | number | 3 | Максимальная глубина цепочек action → fireEvent → …. Запуски выше этой границы пропускаются с 'overflow'. |
inspectorBufferSize | number | 50 | Размер кольцевого буфера инспектора. Игнорируется, когда инспектор выключен. |
inspector | boolean | { dev?: boolean; prod?: boolean } | DEV true, PROD false (авто) | Переключатель инспектора по средам. См. ниже. |
Семантика inspector
Заголовок раздела «Семантика inspector»| Значение | Эффект |
|---|---|
undefined (по умолчанию) | Авто — включён при process.env.NODE_ENV !== 'production', иначе выключен. |
true | Всегда включён, вне зависимости от среды. |
false | Всегда выключен — горячий путь не аллоцирует снепшот вообще (~30–40% дополнительной пропускной способности). |
{ dev?, prod? } | Переопределение по средам. Неустановленные поля падают на авто-дефолт. |
Когда выключен, обратные вызовы runtime.subscribe не вызываются, runtime.getInspectorBuffer() возвращает [], а trigger.inspect() — undefined. Devtools — @triggery/devtools-redux, @triggery/devtools-bridge, хук useInspectHistory для React — зависят от включённого инспектора.
Примеры
Заголовок раздела «Примеры»Большинству приложений хватает дефолтов
Заголовок раздела «Большинству приложений хватает дефолтов»import { createRuntime function createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';
const runtime const runtime: Runtime = createRuntime function createRuntime(options?: RuntimeOptions): Runtime (); // inspector auto, cascade=3, buffer=50, no middlewareУменьшить глубину каскада
Заголовок раздела «Уменьшить глубину каскада»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 });
// Now `action → fireEvent → trigger` is allowed but `action → fireEvent → trigger → action → fireEvent → …` is not.Увеличить буфер инспектора
Заголовок раздела «Увеличить буфер инспектора»import { createRuntime function createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';
const runtime const runtime: Runtime = createRuntime function createRuntime(options?: RuntimeOptions): Runtime ({ inspectorBufferSize inspectorBufferSize?: number | undefinedInspector ring buffer size (default: 50). Ignored when the inspector is disabled. : 500 });
// Helpful for long-running e2e tests that need to see runs from many minutes ago.Переопределение инспектора по средам
Заголовок раздела «Переопределение инспектора по средам»import { createRuntime function createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';
// On in dev, also on in prod (e.g. for an opt-in beta where you want telemetry).
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 : true } });Режим бенчмарка горячего пути
Заголовок раздела «Режим бенчмарка горячего пути»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 });
// `getInspectorBuffer()` returns a shared frozen `[]`; `subscribe` is a noop.Цепочка миддлвэров
Заголовок раздела «Цепочка миддлвэров»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 tracing const tracing: 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 : 'tracing',
onFire onFire?(ctx: FireContext): void | {
cancel: true;
reason: string;
}
({ eventName eventName: string }) { console var console: Console .debug Console.debug(...data: any[]): voidThe **`console.debug()`** static method outputs a message to the console at the 'debug' log level.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) ('[fire]', eventName eventName: string ); },
onActionEnd onActionEnd?(ctx: ActionContext & {
durationMs: number;
result?: unknown;
}): void
({ actionName actionName: string , durationMs durationMs: number }) {
console var console: Console .debug Console.debug(...data: any[]): voidThe **`console.debug()`** static method outputs a message to the console at the 'debug' log level.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) (`[action] ${actionName actionName: string } ${durationMs durationMs: number .toFixed Number.toFixed(fractionDigits?: number): stringReturns a string representing a number in fixed-point notation. (2)}ms`);
},
};
const audit const audit: 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 : 'audit',
onError onError?(ctx: ActionContext & {
error: unknown;
}): void
({ triggerId triggerId: string , actionName actionName: string , error error: unknown }) {
console var console: Console .error Console.error(...data: any[]): voidThe **`console.error()`** static method outputs a message to the console at the 'error' log level.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) (`[${triggerId triggerId: string }] ${actionName actionName: string } failed`, error error: unknown );
},
};
const runtime const runtime: Runtime = createRuntime function createRuntime(options?: RuntimeOptions): Runtime ({ middleware middleware?: readonly Middleware[] | undefinedGlobal middleware applied to every trigger in this runtime. : [tracing const tracing: Middleware , audit const audit: Middleware ] });Замечания
Заголовок раздела «Замечания»См. также
Заголовок раздела «См. также» createRuntime Конструктор, который принимает этот тип.
Middleware Форма хуков каждого middleware в цепочке.
createInspector Реализация кольцевого буфера.
Каскады и ограничения Почему max-depth по умолчанию равен 3.