createInspector
Стабильный · с 0.1.0
Создаёт инспектор на кольцевом буфере, которым рантайм пользуется для записи снепшотов. Рантайм вызывает его за тебя, когда ты передаёшь inspectorBufferSize в createRuntime; напрямую createInspector нужен только при сборке кастомной инфраструктуры рантайма (например, моста devtools, которому нужен прямой доступ к record / subscribe).
Реализация не аллоцирует на горячем пути: O(1) record, фиксированный массив слотов, индекс с обёртыванием. getBuffer() материализует массив (newest-first) по требованию.
import { createInspector } from '@triggery/core';
Сигнатура
Заголовок раздела «Сигнатура»function createInspector(bufferSize: number): InspectorImpl;Параметры
Заголовок раздела «Параметры»| Параметр | Тип | Описание |
|---|---|---|
bufferSize | number | Сколько снепшотов хранить. Зажимается минимум до 1. |
Возвращает
Заголовок раздела «Возвращает»Объект InspectorImpl:
| Метод | Сигнатура | Описание |
|---|---|---|
record(snapshot) | (s: TriggerInspectSnapshot) => void | Запушить снепшот. Обёртывается по буферу. Уведомляет подписчиков. |
getBuffer() | () => readonly TriggerInspectSnapshot[] | Массив (newest-first) последних N записей. |
getLastForTrigger(id) | (triggerId: string) => Snapshot | undefined | Самый свежий снепшот по id триггера. |
subscribe(fn) | (fn) => () => void | Слушатель, вызываемый на каждый record. Возвращает unsubscribe. |
clear() | () => void | Очистить буфер и карту по триггерам. |
Примеры
Заголовок раздела «Примеры»Сборка кастомного моста devtools
Заголовок раздела «Сборка кастомного моста devtools»import { createInspector function createInspector(bufferSize: number): InspectorImplRing-buffer inspector. `record` is O(1) — writes into a fixed-size slot array
with a wrap-around index, no `unshift`/`shift` allocations. `getBuffer`
materializes a newest-first array on demand (rare relative to fires). , type TriggerInspectSnapshot type TriggerInspectSnapshot = {
readonly triggerId: string;
readonly runId: string;
readonly eventName: string;
readonly status: "fired" | "skipped" | "errored" | "aborted";
readonly reason?: string;
readonly durationMs: number;
readonly executedActions: readonly string[];
readonly snapshotKeys: readonly string[];
}
} from '@triggery/core';
const inspector const inspector: InspectorImpl = createInspector function createInspector(bufferSize: number): InspectorImplRing-buffer inspector. `record` is O(1) — writes into a fixed-size slot array
with a wrap-around index, no `unshift`/`shift` allocations. `getBuffer`
materializes a newest-first array on demand (rare relative to fires). (200);
inspector const inspector: InspectorImpl .subscribe function subscribe(listener: (snapshot: TriggerInspectSnapshot) => void): () => void ((snapshot snapshot: TriggerInspectSnapshot : TriggerInspectSnapshot type TriggerInspectSnapshot = {
readonly triggerId: string;
readonly runId: string;
readonly eventName: string;
readonly status: "fired" | "skipped" | "errored" | "aborted";
readonly reason?: string;
readonly durationMs: number;
readonly executedActions: readonly string[];
readonly snapshotKeys: readonly string[];
}
) => {
globalThis module globalThis .postMessage function postMessage(message: any, targetOrigin: string, transfer?: Transferable[]): void (+1 overload)The **`window.postMessage()`** method safely enables cross-origin communication between Window objects; _e.g.,_ between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/postMessage) (
{ source source: string : 'triggery-bridge', snapshot snapshot: TriggerInspectSnapshot },
'*',
);
});
// Feed it manually — the example assumes you wired up your own dispatch
// recording. The runtime created via `createRuntime` calls `record` for you.
inspector const inspector: InspectorImpl .record function record(snapshot: TriggerInspectSnapshot): void ({
triggerId triggerId: string : 'demo',
runId runId: string : '1',
eventName eventName: string : 'ping',
status status: "fired" | "skipped" | "errored" | "aborted" : 'fired',
durationMs durationMs: number : 0.2,
executedActions executedActions: readonly string[] : ['log'],
snapshotKeys snapshotKeys: readonly string[] : [],
});Подключение к latest-per-trigger
Заголовок раздела «Подключение к latest-per-trigger»import { createInspector function createInspector(bufferSize: number): InspectorImplRing-buffer inspector. `record` is O(1) — writes into a fixed-size slot array
with a wrap-around index, no `unshift`/`shift` allocations. `getBuffer`
materializes a newest-first array on demand (rare relative to fires). } from '@triggery/core';
const inspector const inspector: InspectorImpl = createInspector function createInspector(bufferSize: number): InspectorImplRing-buffer inspector. `record` is O(1) — writes into a fixed-size slot array
with a wrap-around index, no `unshift`/`shift` allocations. `getBuffer`
materializes a newest-first array on demand (rare relative to fires). (50);
const latest const latest: TriggerInspectSnapshot | undefined = inspector const inspector: InspectorImpl .getLastForTrigger function getLastForTrigger(triggerId: string): TriggerInspectSnapshot | undefined ('chat:new-message');
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) (latest const latest: TriggerInspectSnapshot | undefined ?.status status: "fired" | "skipped" | "errored" | "aborted" | undefined );Подписка и отписка
Заголовок раздела «Подписка и отписка»import { createInspector function createInspector(bufferSize: number): InspectorImplRing-buffer inspector. `record` is O(1) — writes into a fixed-size slot array
with a wrap-around index, no `unshift`/`shift` allocations. `getBuffer`
materializes a newest-first array on demand (rare relative to fires). } from '@triggery/core';
const inspector const inspector: InspectorImpl = createInspector function createInspector(bufferSize: number): InspectorImplRing-buffer inspector. `record` is O(1) — writes into a fixed-size slot array
with a wrap-around index, no `unshift`/`shift` allocations. `getBuffer`
materializes a newest-first array on demand (rare relative to fires). (50);
const unsubscribe const unsubscribe: () => void = inspector const inspector: InspectorImpl .subscribe function subscribe(listener: (snapshot: TriggerInspectSnapshot) => void): () => void (snapshot snapshot: TriggerInspectSnapshot => {
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) (snapshot snapshot: TriggerInspectSnapshot .triggerId triggerId: string , snapshot snapshot: TriggerInspectSnapshot .status status: "fired" | "skipped" | "errored" | "aborted" );
});
// Later, when the panel unmounts:
unsubscribe const unsubscribe: () => void ();Замечания
Заголовок раздела «Замечания»См. также
Заголовок раздела «См. также» createRuntime Передай `inspectorBufferSize`, чтобы настроить стандартный инспектор.
useInspectHistory React-хук поверх буфера инспектора.
TriggerInspectSnapshot Форма снепшота.
Руководство по инспектору Что отслеживает инспектор и как это рендерить.