@shadow-js/devtools 0.0.0-stage → 1.0.0
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.
- package/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +576 -2
- package/dist/dev/agent.d.ts +239 -0
- package/dist/dev/agent.js +626 -0
- package/dist/dev/agent.js.map +1 -0
- package/dist/dev/backend.d.ts +53 -0
- package/dist/dev/backend.js +53 -0
- package/dist/dev/backend.js.map +1 -0
- package/dist/dev/hook.d.ts +83 -0
- package/dist/dev/hook.js +136 -0
- package/dist/dev/hook.js.map +1 -0
- package/dist/dev/index.d.ts +17 -0
- package/dist/dev/index.js +17 -0
- package/dist/dev/inspection.d.ts +226 -0
- package/dist/dev/inspection.js +263 -0
- package/dist/dev/inspection.js.map +1 -0
- package/dist/dev/inspector.d.ts +331 -0
- package/dist/dev/inspector.js +429 -0
- package/dist/dev/inspector.js.map +1 -0
- package/dist/dev/model.d.ts +418 -0
- package/dist/dev/model.js +559 -0
- package/dist/dev/model.js.map +1 -0
- package/dist/dev/mount.d.ts +207 -0
- package/dist/dev/mount.js +256 -0
- package/dist/dev/mount.js.map +1 -0
- package/dist/dev/overlay.d.ts +102 -0
- package/dist/dev/overlay.js +176 -0
- package/dist/dev/overlay.js.map +1 -0
- package/dist/dev/preview.d.ts +74 -0
- package/dist/dev/preview.js +122 -0
- package/dist/dev/preview.js.map +1 -0
- package/dist/dev/protocol.d.ts +288 -0
- package/dist/dev/protocol.js +109 -0
- package/dist/dev/protocol.js.map +1 -0
- package/dist/dev/ring.d.ts +50 -0
- package/dist/dev/ring.js +94 -0
- package/dist/dev/ring.js.map +1 -0
- package/dist/dev/transport.d.ts +347 -0
- package/dist/dev/transport.js +394 -0
- package/dist/dev/transport.js.map +1 -0
- package/dist/dev/ui/details.js +294 -0
- package/dist/dev/ui/details.js.map +1 -0
- package/dist/dev/ui/inspection-state.d.ts +43 -0
- package/dist/dev/ui/inspection-state.js +62 -0
- package/dist/dev/ui/inspection-state.js.map +1 -0
- package/dist/dev/ui/issues.js +85 -0
- package/dist/dev/ui/issues.js.map +1 -0
- package/dist/dev/ui/panel.d.ts +55 -0
- package/dist/dev/ui/panel.js +160 -0
- package/dist/dev/ui/panel.js.map +1 -0
- package/dist/dev/ui/rows.d.ts +44 -0
- package/dist/dev/ui/rows.js +132 -0
- package/dist/dev/ui/rows.js.map +1 -0
- package/dist/dev/ui/state-tab.js +88 -0
- package/dist/dev/ui/state-tab.js.map +1 -0
- package/dist/dev/ui/state.d.ts +192 -0
- package/dist/dev/ui/state.js +147 -0
- package/dist/dev/ui/state.js.map +1 -0
- package/dist/dev/ui/styles.d.ts +31 -0
- package/dist/dev/ui/styles.js +113 -0
- package/dist/dev/ui/styles.js.map +1 -0
- package/dist/dev/ui/timeline.js +135 -0
- package/dist/dev/ui/timeline.js.map +1 -0
- package/dist/dev/ui/tree.js +186 -0
- package/dist/dev/ui/tree.js.map +1 -0
- package/dist/prod/agent.js +2 -0
- package/dist/prod/agent.js.map +1 -0
- package/dist/prod/backend.js +2 -0
- package/dist/prod/backend.js.map +1 -0
- package/dist/prod/hook.js +2 -0
- package/dist/prod/hook.js.map +1 -0
- package/dist/prod/index.js +1 -0
- package/dist/prod/inspection.js +2 -0
- package/dist/prod/inspection.js.map +1 -0
- package/dist/prod/inspector.js +2 -0
- package/dist/prod/inspector.js.map +1 -0
- package/dist/prod/model.js +2 -0
- package/dist/prod/model.js.map +1 -0
- package/dist/prod/mount.js +2 -0
- package/dist/prod/mount.js.map +1 -0
- package/dist/prod/overlay.js +11 -0
- package/dist/prod/overlay.js.map +1 -0
- package/dist/prod/preview.js +2 -0
- package/dist/prod/preview.js.map +1 -0
- package/dist/prod/protocol.js +2 -0
- package/dist/prod/protocol.js.map +1 -0
- package/dist/prod/ring.js +2 -0
- package/dist/prod/ring.js.map +1 -0
- package/dist/prod/transport.js +2 -0
- package/dist/prod/transport.js.map +1 -0
- package/dist/prod/ui/details.js +2 -0
- package/dist/prod/ui/details.js.map +1 -0
- package/dist/prod/ui/inspection-state.js +2 -0
- package/dist/prod/ui/inspection-state.js.map +1 -0
- package/dist/prod/ui/issues.js +2 -0
- package/dist/prod/ui/issues.js.map +1 -0
- package/dist/prod/ui/panel.js +2 -0
- package/dist/prod/ui/panel.js.map +1 -0
- package/dist/prod/ui/rows.js +2 -0
- package/dist/prod/ui/rows.js.map +1 -0
- package/dist/prod/ui/state-tab.js +2 -0
- package/dist/prod/ui/state-tab.js.map +1 -0
- package/dist/prod/ui/state.js +2 -0
- package/dist/prod/ui/state.js.map +1 -0
- package/dist/prod/ui/styles.js +82 -0
- package/dist/prod/ui/styles.js.map +1 -0
- package/dist/prod/ui/timeline.js +2 -0
- package/dist/prod/ui/timeline.js.map +1 -0
- package/dist/prod/ui/tree.js +2 -0
- package/dist/prod/ui/tree.js.map +1 -0
- package/package.json +69 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent.js","names":[],"sources":["../../src/agent.ts"],"sourcesContent":["import { readInspections } from \"./inspection\";\nimport { type GraphSnapshot, snapshotOf } from \"./inspector\";\nimport { InspectorModel, type ModelLimits, type ModelState, type NodeRecord } from \"./model\";\nimport { errorMessage, parseEditableText, preview, toEditableText } from \"./preview\";\nimport {\n type DevtoolsHook,\n EVENT,\n type HookSink,\n NO_ID,\n type StoreHandle,\n type WireEvent,\n} from \"./protocol\";\nimport { RingBuffer } from \"./ring\";\n\n/**\n * Options of {@link createAgent}. Every field is optional.\n *\n * @since 1.0.0\n */\nexport interface AgentOptions {\n /** Capacities of the model's buffers. The values left out take the defaults of `DEFAULT_LIMITS`. */\n limits?: Partial<ModelLimits>;\n /**\n * Raw events kept for the events log. The newest are kept; older ones are overwritten and counted\n * in `dropped`.\n *\n * @default 10000\n */\n events?: number;\n /**\n * Most events waiting for subscribers. When this many are pending they are delivered at once,\n * instead of at the end of the current microtask.\n *\n * @default 10000\n */\n maxPending?: number;\n /**\n * Maximum length of a value preview, in characters.\n *\n * @default 80\n */\n previewLength?: number;\n /**\n * The clock, in milliseconds. Defaults to `performance.now` (or `Date.now` where it is missing).\n */\n now?: () => number;\n /**\n * Writes a signal node for the value editor. Pass `writeSignal` from `@shadow-js/core/extend`.\n * Without it signals are shown but not editable: a write is refused with \"Editing is not enabled.\".\n */\n writeSignal?: (node: never, value: never) => unknown;\n}\n\n/**\n * Counters of what the agent saw. They keep growing while the agent runs; {@link Agent.clear} does not\n * reset them.\n *\n * @since 1.0.0\n */\nexport interface AgentStats {\n /** Events the agent was offered while it was not paused. */\n received: number;\n /** Events turned into wire events. */\n recorded: number;\n /**\n * Events the agent skipped on purpose: objects created inside {@link Agent.quiet} (the tools' own\n * UI), dispose and unmount events for objects it never named, malformed store handles, and event\n * kinds from a newer runtime.\n */\n ignored: number;\n /**\n * Writes, runs and mounts about objects the agent never saw created (reported before it attached,\n * when the hook's replay buffer had been released).\n */\n unknown: number;\n}\n\n/**\n * A command a panel sends to the agent, answered by {@link Agent.handle}. All fields are plain data,\n * so a command can cross a message channel:\n *\n * - `snapshot`: the model's state.\n * - `value` and `write`: read a signal as editable text, or write it.\n * - `store` and `store-set`: read a store as editable text, or write one path of it.\n * - `highlight`: the agent acknowledges it; the page draws the highlight (see `createLocalBackend`).\n * - `pause`, `resume`, `clear`: control recording. `stats`: the counters.\n * - `inspect`: every inspection source registered with `registerInspection`, read now.\n *\n * @since 1.0.0\n */\nexport type AgentRequest =\n | { type: \"snapshot\" }\n | { type: \"value\"; id: number }\n | { type: \"write\"; id: number; text: string }\n | { type: \"store\"; id: number }\n | { type: \"store-set\"; id: number; path: Array<string | number>; text: string }\n | { type: \"highlight\"; id: number | null }\n | { type: \"pause\" }\n | { type: \"resume\" }\n | { type: \"clear\" }\n | { type: \"stats\" }\n | { type: \"inspect\" };\n\n/**\n * The answer to an {@link AgentRequest}: the result, or an error message to show the user.\n *\n * @since 1.0.0\n */\nexport type AgentResponse = { ok: true; result: unknown } | { ok: false; error: string };\n\n/**\n * The value of a node, as text, for the value editor.\n *\n * @since 1.0.0\n */\nexport interface ValueResult {\n /** The node that was asked for. */\n id: number;\n /** `signal` for a signal, `store` for a store. */\n kind: \"signal\" | \"store\";\n /** The value as editable text (see {@link toEditableText}). */\n text: string;\n /** True when the panel may write it: a store always, a signal only when `writeSignal` is set. */\n editable: boolean;\n}\n\n/**\n * The agent. It receives the runtime's own objects from the hook, turns them into id-based\n * {@link WireEvent}s and folds them into an {@link InspectorModel}. Recording is O(1) per event and\n * every buffer is bounded: the raw event ring, the model's run, write and flush rings, the disposed-node\n * graveyard and the live node count.\n *\n * A development tool: the hook it attaches to is installed only in development builds (see\n * `installHook`).\n *\n * @since 1.0.0\n */\nexport interface Agent extends HookSink {\n /** The model the events are folded into. */\n readonly model: InspectorModel;\n /** The newest raw events, as many as the `events` option holds (default 10000). */\n readonly events: RingBuffer<WireEvent>;\n /** Counters of what the agent saw. */\n readonly stats: Readonly<AgentStats>;\n /** True while the agent drops the events the runtime reports (see {@link Agent.pause}). */\n readonly paused: boolean;\n /**\n * Attaches the agent to `hook`, so that the hook delivers its events to the agent. Pass the hook\n * from `installHook` or `getHook`.\n *\n * @param hook The hook to listen to.\n * @returns A function that detaches the agent from the hook.\n */\n attach(hook: DevtoolsHook): () => void;\n /**\n * Calls `listener` with batches of new events: once per microtask, or sooner when `maxPending`\n * events are waiting. Only events recorded after the call are delivered.\n *\n * @param listener Receives each batch, oldest first.\n * @returns A function that unsubscribes the listener.\n */\n subscribe(listener: (events: readonly WireEvent[]) => void): () => void;\n /** Delivers the pending events to the subscribers now, instead of at the end of the microtask. */\n flush(): void;\n /**\n * Runs `fn` while the agent ignores everything the runtime creates, and everything created under\n * those nodes. Use it to mount the tools' own UI, so that the tools never inspect themselves. An error\n * thrown by `fn` propagates.\n *\n * @param fn The work to run.\n * @returns What `fn` returns.\n */\n quiet<T>(fn: () => T): T;\n /** Stops recording: events the runtime reports are dropped until {@link Agent.resume}. */\n pause(): void;\n /** Resumes recording after {@link Agent.pause}. */\n resume(): void;\n /**\n * Forgets everything recorded so far: the model's nodes and records, the event ring, and the\n * references to live nodes. Nodes created later are tracked; live ones are not, and later events about\n * them count as unknown. {@link AgentStats} are not reset.\n */\n clear(): void;\n /** The graph snapshot of the model (see `snapshotOf`). Each call builds a new object. */\n snapshot(): GraphSnapshot;\n /** The model state, for sending to a remote panel. */\n state(): ModelState;\n /**\n * Answers a panel command. Never throws: a failure, such as an error from writing user state, comes\n * back as `ok: false`, and so does an unknown command.\n *\n * @param request The command.\n * @returns The answer.\n */\n handle(request: AgentRequest): AgentResponse;\n /**\n * The connected DOM nodes that the component `id` rendered, for highlighting. Empty when the\n * component is unknown or its nodes left the page. The agent holds the nodes weakly.\n *\n * @param id The component's node id.\n * @returns The nodes.\n */\n nodesOf(id: number): Node[];\n /**\n * Detaches from every hook it was attached to, and drops the listeners and the references to live\n * signals, components and stores. The model and the event ring keep what they recorded.\n */\n dispose(): void;\n}\n\n/**\n * Store handles by node id, held weakly: the handle lives as long as the store it reads, because the\n * runtime keeps it reachable from the store's root (see `createDeepStore` in `@shadow-js/core`).\n */\ntype Registry = Map<number, WeakRef<StoreHandle>>;\n\nfunction now(): number {\n return typeof performance !== \"undefined\" ? performance.now() : Date.now();\n}\n\nfunction isObject(value: unknown): value is object {\n return (typeof value === \"object\" && value !== null) || typeof value === \"function\";\n}\n\nfunction toNumber(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction describeSide(value: unknown): string {\n if (typeof value === \"string\") return value.length > 200 ? `${value.slice(0, 199)}…` : value;\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n if (value instanceof Element) {\n const html = value.outerHTML;\n return html.length > 200 ? `${html.slice(0, 199)}…` : html;\n }\n return `#${value.nodeName}`;\n }\n return preview(value, 200);\n}\n\n/**\n * Creates an agent that records the runtime's events. Attach it to a hook with `agent.attach(hook)`.\n * A development tool: the events come only from development builds, where the hook is installed.\n *\n * @param options Buffer sizes, clock and the signal writer. Every field is optional.\n * @returns The agent.\n * @example\n * import { createAgent, installHook } from \"@shadow-js/devtools\";\n * import { writeSignal } from \"@shadow-js/core/extend\";\n *\n * const hook = installHook();\n * const agent = createAgent({ writeSignal });\n * if (hook !== undefined) agent.attach(hook);\n * agent.snapshot().counts.nodes;\n * @since 1.0.0\n */\nexport function createAgent(options: AgentOptions = {}): Agent {\n const clock = options.now ?? now;\n const previewLength = options.previewLength ?? 80;\n const maxPending = options.maxPending ?? 10_000;\n const model = new InspectorModel(options.limits);\n const events = new RingBuffer<WireEvent>(options.events ?? 10_000);\n const stats: AgentStats = { received: 0, recorded: 0, ignored: 0, unknown: 0 };\n\n // Objects are named by id through weak maps: the agent never keeps the runtime's nodes alive.\n const ids = new WeakMap<object, number>();\n const ignored = new WeakSet<object>();\n const signals = new Map<number, WeakRef<object>>();\n const components = new Map<number, WeakRef<Node>[]>();\n const stores: Registry = new Map();\n let nextId = 1;\n let seq = 0;\n let paused = false;\n let quietDepth = 0;\n /** The hook the agent listens to: its registry of inspection sources answers `inspect`. */\n let inspectionHook: DevtoolsHook | undefined;\n let pending: WireEvent[] = [];\n let scheduled = false;\n /** A flush that started but has not recorded any run yet: empty flushes are not worth a record. */\n let queuedFlush: { render: number; user: number; t: number } | null = null;\n let flushOpen = false;\n const listeners = new Set<(events: readonly WireEvent[]) => void>();\n const detachers = new Set<() => void>();\n // Signals, stores and resources have no dispose event of their own when nothing owns them (or their\n // owner never disposes): the finalizer retires their node once the runtime has collected them. It is\n // registered once per object, so a resource that reports many states is not registered many times.\n const finalizer: FinalizationRegistry<number> | undefined =\n typeof FinalizationRegistry === \"function\"\n ? new FinalizationRegistry<number>((id) => {\n signals.delete(id);\n stores.delete(id);\n if (model.nodes.has(id)) emit({ k: \"owner-\", seq: 0, t: 0, id });\n })\n : undefined;\n\n model.onBury = (record: NodeRecord) => {\n signals.delete(record.id);\n components.delete(record.id);\n stores.delete(record.id);\n };\n\n const deliver = (): void => {\n scheduled = false;\n if (pending.length === 0) return;\n const batch = pending;\n pending = [];\n for (const listener of listeners) listener(batch);\n };\n\n /** Stamps, records and fans out one event. */\n function emit(event: WireEvent, at?: number): void {\n seq += 1;\n event.seq = seq;\n event.t = at ?? clock();\n stats.recorded += 1;\n events.push(event);\n model.apply(event);\n if (listeners.size === 0) return;\n pending.push(event);\n if (pending.length >= maxPending) {\n deliver();\n } else if (!scheduled) {\n scheduled = true;\n queueMicrotask(deliver);\n }\n }\n\n /** Emits the held-back flush start before the first event that belongs to it. */\n const openFlush = (): void => {\n if (queuedFlush === null) return;\n const held = queuedFlush;\n queuedFlush = null;\n flushOpen = true;\n emit({ k: \"flush+\", seq: 0, t: 0, render: held.render, user: held.user }, held.t);\n };\n\n const lookup = (value: unknown): number => {\n if (!isObject(value)) return NO_ID;\n return ids.get(value) ?? NO_ID;\n };\n\n const register = (value: object): number => {\n const existing = ids.get(value);\n if (existing !== undefined) return existing;\n const id = nextId;\n nextId += 1;\n ids.set(value, id);\n return id;\n };\n\n /**\n * Like `register`, for a leaf node (signal, store, resource): the finalizer retires it once the runtime\n * has collected the object. Owners and computations are not registered: an owner can be unreachable\n * while its signals are still in use, and retiring it would bury them too.\n */\n const registerLeaf = (value: object): number => {\n const existing = ids.get(value);\n if (existing !== undefined) return existing;\n const id = register(value);\n finalizer?.register(value, id);\n return id;\n };\n\n /** True (and remembered) when the object belongs to the tools' own UI. */\n const isIgnored = (value: unknown, parent: unknown): boolean => {\n if (!isObject(value)) return false;\n if (quietDepth > 0 || (isObject(parent) && ignored.has(parent))) {\n ignored.add(value);\n return true;\n }\n return ignored.has(value);\n };\n\n const mapIds = (values: unknown): number[] => {\n const out: number[] = [];\n if (!Array.isArray(values)) return out;\n for (let i = 0; i < values.length; i += 1) {\n const id = lookup(values[i]);\n if (id !== NO_ID) out.push(id);\n }\n return out;\n };\n\n const nodesIn = (value: unknown): WeakRef<Node>[] => {\n const out: WeakRef<Node>[] = [];\n if (typeof Node === \"undefined\") return out;\n const push = (candidate: unknown): void => {\n if (candidate instanceof DocumentFragment) {\n for (const child of Array.from(candidate.childNodes)) out.push(new WeakRef(child));\n } else if (candidate instanceof Node) {\n out.push(new WeakRef(candidate));\n }\n };\n if (Array.isArray(value)) for (const entry of value) push(entry);\n else push(value);\n return out;\n };\n\n function receive(kind: number, a: unknown, b: unknown, c: unknown, d: unknown, e: unknown): void {\n if (paused) return;\n stats.received += 1;\n switch (kind) {\n case EVENT.OWNER_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const name = typeof d === \"string\" ? d : undefined;\n emit({\n k: \"owner+\",\n seq: 0,\n t: 0,\n id: register(a),\n parent: lookup(b),\n label: typeof c === \"string\" ? c : \"owner\",\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.OWNER_DISPOSED: {\n const id = lookup(a);\n if (id === NO_ID) {\n stats.ignored += 1;\n return;\n }\n emit({ k: \"owner-\", seq: 0, t: 0, id });\n return;\n }\n case EVENT.SIGNAL_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const id = registerLeaf(a);\n signals.set(id, new WeakRef(a));\n const name = typeof c === \"string\" ? c : undefined;\n emit({\n k: \"signal+\",\n seq: 0,\n t: 0,\n id,\n owner: lookup(b),\n preview: preview(d, previewLength),\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.SIGNAL_WRITTEN: {\n const id = lookup(a);\n if (id === NO_ID) {\n if (isObject(a) && ignored.has(a)) stats.ignored += 1;\n else stats.unknown += 1;\n return;\n }\n emit({\n k: \"write\",\n seq: 0,\n t: 0,\n id,\n preview: preview(b, previewLength),\n writer: lookup(c),\n observers: mapIds(d),\n });\n return;\n }\n case EVENT.COMPUTATION_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const name = typeof d === \"string\" ? d : undefined;\n emit({\n k: \"comp+\",\n seq: 0,\n t: 0,\n id: register(a),\n owner: lookup(b),\n kind: c === \"memo\" ? \"memo\" : \"effect\",\n render: e === true,\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.COMPUTATION_RUN: {\n const id = lookup(a);\n if (id === NO_ID) {\n if (isObject(a) && ignored.has(a)) stats.ignored += 1;\n else stats.unknown += 1;\n return;\n }\n openFlush();\n emit({\n k: \"run\",\n seq: 0,\n t: 0,\n id,\n start: toNumber(b),\n duration: toNumber(c),\n changed: d === true,\n sources: mapIds(e),\n });\n return;\n }\n case EVENT.COMPUTATION_DISPOSED: {\n const id = lookup(a);\n if (id === NO_ID) {\n stats.ignored += 1;\n return;\n }\n emit({ k: \"comp-\", seq: 0, t: 0, id });\n return;\n }\n case EVENT.COMPONENT_MOUNTED: {\n const id = lookup(a);\n if (id === NO_ID) {\n if (isObject(a) && ignored.has(a)) stats.ignored += 1;\n else stats.unknown += 1;\n return;\n }\n const refs = nodesIn(c);\n if (refs.length > 0) components.set(id, refs);\n emit({ k: \"mount\", seq: 0, t: 0, id, name: typeof b === \"string\" ? b : \"Component\" });\n // A node beyond maxNodes is never buried, so its entry would never be removed: forget it.\n if (!model.nodes.has(id)) components.delete(id);\n return;\n }\n case EVENT.COMPONENT_UNMOUNTED: {\n const id = lookup(a);\n if (id === NO_ID) {\n stats.ignored += 1;\n return;\n }\n components.delete(id);\n emit({ k: \"unmount\", seq: 0, t: 0, id });\n return;\n }\n case EVENT.RESOURCE_STATE: {\n if (!isObject(a) || isIgnored(a, d)) {\n stats.ignored += 1;\n return;\n }\n const name = typeof c === \"string\" ? c : undefined;\n emit({\n k: \"resource\",\n seq: 0,\n t: 0,\n id: registerLeaf(a),\n owner: lookup(d),\n state: typeof b === \"string\" ? b : String(b),\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.ERROR: {\n const code = typeof c === \"string\" ? c : undefined;\n emit({\n k: \"error\",\n seq: 0,\n t: 0,\n id: lookup(a),\n message: errorMessage(b),\n ...(code === undefined ? {} : { code }),\n });\n return;\n }\n case EVENT.HYDRATION_MISMATCH:\n emit({\n k: \"hydration\",\n seq: 0,\n t: 0,\n message: typeof a === \"string\" ? a : errorMessage(a),\n expected: describeSide(b),\n actual: describeSide(c),\n });\n return;\n case EVENT.FLUSH_START:\n queuedFlush = { render: toNumber(a), user: toNumber(b), t: clock() };\n return;\n case EVENT.FLUSH_END:\n queuedFlush = null;\n if (flushOpen) {\n flushOpen = false;\n emit({ k: \"flush-\", seq: 0, t: 0, runs: toNumber(a) });\n }\n return;\n case EVENT.STORE_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const handle = readStoreHandle(a);\n if (handle === null) {\n stats.ignored += 1;\n return;\n }\n const id = registerLeaf(a);\n stores.set(id, new WeakRef(handle));\n emit({ k: \"store+\", seq: 0, t: 0, id, owner: lookup(b), name: handle.name });\n // A store beyond maxNodes is never buried: nothing else would forget its handle.\n if (!model.nodes.has(id)) stores.delete(id);\n return;\n }\n default:\n // An event kind from a newer runtime: ignore it.\n stats.ignored += 1;\n }\n }\n\n const readStoreHandle = (value: object): StoreHandle | null => {\n const name: unknown = Reflect.get(value, \"name\");\n const snapshot: unknown = Reflect.get(value, \"snapshot\");\n const set: unknown = Reflect.get(value, \"set\");\n if (typeof name !== \"string\" || typeof snapshot !== \"function\" || typeof set !== \"function\") {\n return null;\n }\n return value as StoreHandle;\n };\n\n const signalValue = (id: number): { found: true; value: unknown } | { found: false } => {\n const node = signals.get(id)?.deref();\n if (node === undefined) return { found: false };\n return { found: true, value: Reflect.get(node, \"value\") };\n };\n\n const fail = (error: string): AgentResponse => ({ ok: false, error });\n\n function handle(request: AgentRequest): AgentResponse {\n try {\n switch (request.type) {\n case \"snapshot\":\n return { ok: true, result: model.exportState() };\n case \"stats\":\n return { ok: true, result: { ...stats, events: events.size, dropped: events.dropped } };\n case \"value\": {\n const read = signalValue(request.id);\n if (!read.found) return fail(\"The signal is gone.\");\n const result: ValueResult = {\n id: request.id,\n kind: \"signal\",\n text: toEditableText(read.value),\n editable: options.writeSignal !== undefined,\n };\n return { ok: true, result };\n }\n case \"write\": {\n const node = signals.get(request.id)?.deref();\n if (node === undefined) return fail(\"The signal is gone.\");\n if (options.writeSignal === undefined) return fail(\"Editing is not enabled.\");\n const parsed = parseEditableText(request.text);\n if (!parsed.ok) return fail(parsed.error);\n const write = options.writeSignal as (node: object, value: unknown) => unknown;\n write(node, parsed.value);\n return { ok: true, result: null };\n }\n case \"store\": {\n const store = stores.get(request.id)?.deref();\n if (store === undefined) return fail(\"The store is gone.\");\n const result: ValueResult = {\n id: request.id,\n kind: \"store\",\n text: toEditableText(store.snapshot()),\n editable: true,\n };\n return { ok: true, result };\n }\n case \"store-set\": {\n const store = stores.get(request.id)?.deref();\n if (store === undefined) return fail(\"The store is gone.\");\n const parsed = parseEditableText(request.text);\n if (!parsed.ok) return fail(parsed.error);\n store.set(request.path, parsed.value);\n return { ok: true, result: null };\n }\n case \"pause\":\n paused = true;\n return { ok: true, result: null };\n case \"resume\":\n paused = false;\n return { ok: true, result: null };\n case \"clear\":\n clear();\n return { ok: true, result: null };\n case \"highlight\":\n // Drawing needs the page; the page side draws it (see createLocalBackend).\n return { ok: true, result: null };\n case \"inspect\":\n return {\n ok: true,\n result: { sources: readInspections(inspectionHook?.inspections?.() ?? []) },\n };\n default:\n return fail(\"Unknown command.\");\n }\n } catch (error) {\n // Writing user state can throw (a validation in the app): report it to the panel.\n return fail(errorMessage(error));\n }\n }\n\n function clear(): void {\n model.importState({\n lastSeq: model.lastSeq,\n overflow: 0,\n unknown: 0,\n nodes: [],\n graveyard: [],\n runs: [],\n writes: [],\n flushes: [],\n errors: [],\n hydration: [],\n });\n events.clear();\n pending = [];\n queuedFlush = null;\n flushOpen = false;\n signals.clear();\n components.clear();\n stores.clear();\n }\n\n const agent: Agent = {\n model,\n events,\n stats,\n get paused(): boolean {\n return paused;\n },\n receive,\n attach(hook): () => void {\n inspectionHook = hook;\n const detach = hook.attach(agent);\n detachers.add(detach);\n return () => {\n detachers.delete(detach);\n detach();\n };\n },\n subscribe(listener): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n flush: deliver,\n quiet<T>(fn: () => T): T {\n quietDepth += 1;\n try {\n return fn();\n } finally {\n quietDepth -= 1;\n }\n },\n pause(): void {\n paused = true;\n },\n resume(): void {\n paused = false;\n },\n clear,\n snapshot: () => snapshotOf(model),\n state: () => model.exportState(),\n handle,\n nodesOf(id): Node[] {\n const out: Node[] = [];\n const own = components.get(id);\n if (own !== undefined) {\n for (const ref of own) {\n const node = ref.deref();\n if (node?.isConnected === true) out.push(node);\n }\n }\n return out;\n },\n dispose(): void {\n for (const detach of detachers) detach();\n detachers.clear();\n inspectionHook = undefined;\n listeners.clear();\n pending = [];\n signals.clear();\n components.clear();\n stores.clear();\n model.onBury = undefined;\n },\n };\n return agent;\n}\n"],"mappings":";;;;;;;AAwNA,SAAS,MAAc;CACrB,OAAO,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAC3E;AAEA,SAAS,SAAS,OAAiC;CACjD,OAAQ,OAAO,UAAU,YAAY,UAAU,QAAS,OAAO,UAAU;AAC3E;AAEA,SAAS,SAAS,OAAwB;CACxC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAS,aAAa,OAAwB;CAC5C,IAAI,OAAO,UAAU,UAAU,OAAO,MAAM,SAAS,MAAM,GAAG,MAAM,MAAM,GAAG,GAAG,EAAE,KAAK;CACvF,IAAI,OAAO,SAAS,eAAe,iBAAiB,MAAM;EACxD,IAAI,iBAAiB,SAAS;GAC5B,MAAM,OAAO,MAAM;GACnB,OAAO,KAAK,SAAS,MAAM,GAAG,KAAK,MAAM,GAAG,GAAG,EAAE,KAAK;EACxD;EACA,OAAO,IAAI,MAAM;CACnB;CACA,OAAO,QAAQ,OAAO,GAAG;AAC3B;;;;;;;;;;;;;;;;;AAkBA,SAAgB,YAAY,UAAwB,CAAC,G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AAM,IAAI,KAAK,IAAI;GAC/C;GAEF,OAAO;EACT;EACA,UAAgB;GACd,KAAK,MAAM,UAAU,WAAW,OAAO;GACvC,UAAU,MAAM;GAChB,iBAAiB,KAAA;GACjB,UAAU,MAAM;GAChB,UAAU,CAAC;GACX,QAAQ,MAAM;GACd,WAAW,MAAM;GACjB,OAAO,MAAM;GACb,MAAM,SAAS,KAAA;EACjB;CACF;CACA,OAAO;AACT"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { InspectorModel } from "./model.js";
|
|
2
|
+
import { Agent, AgentRequest, AgentResponse } from "./agent.js";
|
|
3
|
+
//#region src/backend.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* What a panel talks to: a model that stays up to date, and requests. The panel never knows
|
|
6
|
+
* whether the agent is in the same page ({@link createLocalBackend}) or behind a transport
|
|
7
|
+
* (`connectRemote`), so the same UI serves the floating overlay and a browser-extension panel.
|
|
8
|
+
*
|
|
9
|
+
* @since 1.0.0
|
|
10
|
+
*/
|
|
11
|
+
export interface Backend {
|
|
12
|
+
/** The inspector model, kept current. Read it; do not apply events to it yourself. */
|
|
13
|
+
readonly model: InspectorModel;
|
|
14
|
+
/** Resolves once the first complete state is available. */
|
|
15
|
+
readonly ready: Promise<void>;
|
|
16
|
+
/** Calls `listener` after the model changed (batched). Returns the unsubscribe function. */
|
|
17
|
+
subscribe(listener: () => void): () => void;
|
|
18
|
+
/** Sends a command to the agent. Resolves with its answer; rejects only when the backend is disposed. */
|
|
19
|
+
request(request: AgentRequest): Promise<AgentResponse>;
|
|
20
|
+
/** Stops listening. */
|
|
21
|
+
dispose(): void;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Page-side behavior that a backend cannot do through the agent alone.
|
|
25
|
+
*
|
|
26
|
+
* @since 1.0.0
|
|
27
|
+
*/
|
|
28
|
+
export interface PageHooks {
|
|
29
|
+
/**
|
|
30
|
+
* Highlights a component on the page. `null` clears the highlight. Without this hook a highlight
|
|
31
|
+
* request is acknowledged and nothing is drawn.
|
|
32
|
+
*/
|
|
33
|
+
highlight?(id: number | null): void;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A backend for an agent in the same page: the model is the agent's own model, and the requests go to
|
|
37
|
+
* the agent. A development tool: the page-side panel (`mountDevtools`) uses it in development builds.
|
|
38
|
+
*
|
|
39
|
+
* @param agent The agent.
|
|
40
|
+
* @param page Page-side behavior such as the highlight overlay.
|
|
41
|
+
* @returns The backend.
|
|
42
|
+
* @example
|
|
43
|
+
* import { createAgent, createLocalBackend } from "@shadow-js/devtools";
|
|
44
|
+
*
|
|
45
|
+
* const agent = createAgent();
|
|
46
|
+
* const backend = createLocalBackend(agent, {
|
|
47
|
+
* highlight: (id) => console.info("highlight", id),
|
|
48
|
+
* });
|
|
49
|
+
* @since 1.0.0
|
|
50
|
+
*/
|
|
51
|
+
export declare function createLocalBackend(agent: Agent, page?: PageHooks): Backend;
|
|
52
|
+
//#endregion
|
|
53
|
+
//# sourceMappingURL=backend.d.ts.map
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
//#region src/backend.ts
|
|
2
|
+
/**
|
|
3
|
+
* A backend for an agent in the same page: the model is the agent's own model, and the requests go to
|
|
4
|
+
* the agent. A development tool: the page-side panel (`mountDevtools`) uses it in development builds.
|
|
5
|
+
*
|
|
6
|
+
* @param agent The agent.
|
|
7
|
+
* @param page Page-side behavior such as the highlight overlay.
|
|
8
|
+
* @returns The backend.
|
|
9
|
+
* @example
|
|
10
|
+
* import { createAgent, createLocalBackend } from "@shadow-js/devtools";
|
|
11
|
+
*
|
|
12
|
+
* const agent = createAgent();
|
|
13
|
+
* const backend = createLocalBackend(agent, {
|
|
14
|
+
* highlight: (id) => console.info("highlight", id),
|
|
15
|
+
* });
|
|
16
|
+
* @since 1.0.0
|
|
17
|
+
*/
|
|
18
|
+
function createLocalBackend(agent, page = {}) {
|
|
19
|
+
const unsubscribers = /* @__PURE__ */ new Set();
|
|
20
|
+
let disposed = false;
|
|
21
|
+
return {
|
|
22
|
+
model: agent.model,
|
|
23
|
+
ready: Promise.resolve(),
|
|
24
|
+
subscribe(listener) {
|
|
25
|
+
const off = agent.subscribe(() => listener());
|
|
26
|
+
unsubscribers.add(off);
|
|
27
|
+
return () => {
|
|
28
|
+
unsubscribers.delete(off);
|
|
29
|
+
off();
|
|
30
|
+
};
|
|
31
|
+
},
|
|
32
|
+
request(request) {
|
|
33
|
+
if (disposed) return Promise.reject(/* @__PURE__ */ new Error("The devtools backend was disposed."));
|
|
34
|
+
if (request.type === "highlight") {
|
|
35
|
+
page.highlight?.(request.id);
|
|
36
|
+
return Promise.resolve({
|
|
37
|
+
ok: true,
|
|
38
|
+
result: null
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
return Promise.resolve(agent.handle(request));
|
|
42
|
+
},
|
|
43
|
+
dispose() {
|
|
44
|
+
disposed = true;
|
|
45
|
+
for (const off of unsubscribers) off();
|
|
46
|
+
unsubscribers.clear();
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
export { createLocalBackend };
|
|
52
|
+
|
|
53
|
+
//# sourceMappingURL=backend.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backend.js","names":[],"sources":["../../src/backend.ts"],"sourcesContent":["import type { Agent, AgentRequest, AgentResponse } from \"./agent\";\nimport type { InspectorModel } from \"./model\";\n\n/**\n * What a panel talks to: a model that stays up to date, and requests. The panel never knows\n * whether the agent is in the same page ({@link createLocalBackend}) or behind a transport\n * (`connectRemote`), so the same UI serves the floating overlay and a browser-extension panel.\n *\n * @since 1.0.0\n */\nexport interface Backend {\n /** The inspector model, kept current. Read it; do not apply events to it yourself. */\n readonly model: InspectorModel;\n /** Resolves once the first complete state is available. */\n readonly ready: Promise<void>;\n /** Calls `listener` after the model changed (batched). Returns the unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Sends a command to the agent. Resolves with its answer; rejects only when the backend is disposed. */\n request(request: AgentRequest): Promise<AgentResponse>;\n /** Stops listening. */\n dispose(): void;\n}\n\n/**\n * Page-side behavior that a backend cannot do through the agent alone.\n *\n * @since 1.0.0\n */\nexport interface PageHooks {\n /**\n * Highlights a component on the page. `null` clears the highlight. Without this hook a highlight\n * request is acknowledged and nothing is drawn.\n */\n highlight?(id: number | null): void;\n}\n\n/**\n * A backend for an agent in the same page: the model is the agent's own model, and the requests go to\n * the agent. A development tool: the page-side panel (`mountDevtools`) uses it in development builds.\n *\n * @param agent The agent.\n * @param page Page-side behavior such as the highlight overlay.\n * @returns The backend.\n * @example\n * import { createAgent, createLocalBackend } from \"@shadow-js/devtools\";\n *\n * const agent = createAgent();\n * const backend = createLocalBackend(agent, {\n * highlight: (id) => console.info(\"highlight\", id),\n * });\n * @since 1.0.0\n */\nexport function createLocalBackend(agent: Agent, page: PageHooks = {}): Backend {\n const unsubscribers = new Set<() => void>();\n let disposed = false;\n return {\n model: agent.model,\n ready: Promise.resolve(),\n subscribe(listener): () => void {\n const off = agent.subscribe(() => listener());\n unsubscribers.add(off);\n return () => {\n unsubscribers.delete(off);\n off();\n };\n },\n request(request): Promise<AgentResponse> {\n if (disposed) return Promise.reject(new Error(\"The devtools backend was disposed.\"));\n if (request.type === \"highlight\") {\n page.highlight?.(request.id);\n return Promise.resolve({ ok: true, result: null });\n }\n return Promise.resolve(agent.handle(request));\n },\n dispose(): void {\n disposed = true;\n for (const off of unsubscribers) off();\n unsubscribers.clear();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoDA,SAAgB,mBAAmB,OAAc,OAAkB,CAAC,GAAY;CAC9E,MAAM,gCAAgB,IAAI,IAAgB;CAC1C,IAAI,WAAW;CACf,OAAO;EACL,OAAO,MAAM;EACb,OAAO,QAAQ,QAAQ;EACvB,UAAU,UAAsB;GAC9B,MAAM,MAAM,MAAM,gBAAgB,SAAS,CAAC;GAC5C,cAAc,IAAI,GAAG;GACrB,aAAa;IACX,cAAc,OAAO,GAAG;IACxB,IAAI;GACN;EACF;EACA,QAAQ,SAAiC;GACvC,IAAI,UAAU,OAAO,QAAQ,uBAAO,IAAI,MAAM,oCAAoC,CAAC;GACnF,IAAI,QAAQ,SAAS,aAAa;IAChC,KAAK,YAAY,QAAQ,EAAE;IAC3B,OAAO,QAAQ,QAAQ;KAAE,IAAI;KAAM,QAAQ;IAAK,CAAC;GACnD;GACA,OAAO,QAAQ,QAAQ,MAAM,OAAO,OAAO,CAAC;EAC9C;EACA,UAAgB;GACd,WAAW;GACX,KAAK,MAAM,OAAO,eAAe,IAAI;GACrC,cAAc,MAAM;EACtB;CACF;AACF"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { DevtoolsHook } from "./protocol.js";
|
|
2
|
+
//#region src/hook.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Options of {@link installHook}. Every field is optional.
|
|
5
|
+
*
|
|
6
|
+
* @since 1.0.0
|
|
7
|
+
*/
|
|
8
|
+
export interface InstallHookOptions {
|
|
9
|
+
/**
|
|
10
|
+
* The object to install the hook on.
|
|
11
|
+
*
|
|
12
|
+
* @default globalThis
|
|
13
|
+
*/
|
|
14
|
+
target?: object;
|
|
15
|
+
/**
|
|
16
|
+
* How many events to keep for a sink that attaches later. The first events reported are kept and
|
|
17
|
+
* later ones are dropped. The buffer is released when the first sink attaches, so a hook that nobody
|
|
18
|
+
* listens to cannot grow without bound.
|
|
19
|
+
*
|
|
20
|
+
* @default 5000
|
|
21
|
+
*/
|
|
22
|
+
buffer?: number;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The hook that {@link installHook} installs: a {@link DevtoolsHook} with the counters of its sinks.
|
|
26
|
+
*
|
|
27
|
+
* @since 1.0.0
|
|
28
|
+
*/
|
|
29
|
+
export interface InstalledHook extends DevtoolsHook {
|
|
30
|
+
/** Number of times a sink threw while receiving an event. The hook swallows each error so the app keeps running. */
|
|
31
|
+
readonly faults: number;
|
|
32
|
+
/** The last error a sink threw, or `undefined` when none did. */
|
|
33
|
+
readonly lastFault: unknown;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Installs the dev hook on `globalThis.__SHADOWJS_DEVTOOLS_HOOK__` (or on `options.target`), once, and
|
|
37
|
+
* returns it. A development tool: in production builds (`__DEV__` false) it installs nothing and returns
|
|
38
|
+
* `undefined`. The runtime looks the global up on each event, so call this before the application code
|
|
39
|
+
* runs: events reported earlier are lost, and those reported before a sink attaches are buffered.
|
|
40
|
+
*
|
|
41
|
+
* When a hook with the same protocol version is already installed, it is returned. When the global holds
|
|
42
|
+
* a hook of another version (or anything that is not a hook), nothing is installed and `undefined` is
|
|
43
|
+
* returned.
|
|
44
|
+
*
|
|
45
|
+
* @param options Target object and replay buffer size. Every field is optional.
|
|
46
|
+
* @returns The installed hook, or `undefined`.
|
|
47
|
+
* @example
|
|
48
|
+
* import { createAgent, installHook } from "@shadow-js/devtools";
|
|
49
|
+
*
|
|
50
|
+
* const hook = installHook();
|
|
51
|
+
* const agent = createAgent();
|
|
52
|
+
* if (hook !== undefined) agent.attach(hook);
|
|
53
|
+
* @since 1.0.0
|
|
54
|
+
*/
|
|
55
|
+
export declare function installHook(options?: InstallHookOptions): InstalledHook | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* The hook that {@link installHook} installed, or `undefined` when none is installed or its protocol
|
|
58
|
+
* version differs. A development tool: production builds never install a hook.
|
|
59
|
+
*
|
|
60
|
+
* @param target Object to look at (default `globalThis`).
|
|
61
|
+
* @returns The installed hook, or `undefined`.
|
|
62
|
+
* @example
|
|
63
|
+
* import { getHook } from "@shadow-js/devtools";
|
|
64
|
+
*
|
|
65
|
+
* const sinks = getHook()?.sinks ?? 0;
|
|
66
|
+
* @since 1.0.0
|
|
67
|
+
*/
|
|
68
|
+
export declare function getHook(target?: object): InstalledHook | undefined;
|
|
69
|
+
/**
|
|
70
|
+
* Removes the installed hook, so that a later {@link installHook} installs a new one. For tests and for
|
|
71
|
+
* hot reloading the tools; a development tool, and a no-op in production builds. Sinks stay attached to
|
|
72
|
+
* the old hook object.
|
|
73
|
+
*
|
|
74
|
+
* @param target Object to remove it from (default `globalThis`).
|
|
75
|
+
* @example
|
|
76
|
+
* import { uninstallHook } from "@shadow-js/devtools";
|
|
77
|
+
*
|
|
78
|
+
* uninstallHook();
|
|
79
|
+
* @since 1.0.0
|
|
80
|
+
*/
|
|
81
|
+
export declare function uninstallHook(target?: object): void;
|
|
82
|
+
//#endregion
|
|
83
|
+
//# sourceMappingURL=hook.d.ts.map
|
package/dist/dev/hook.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { HOOK_KEY } from "./protocol.js";
|
|
2
|
+
//#region src/hook.ts
|
|
3
|
+
function lookup(target) {
|
|
4
|
+
return Reflect.get(target, HOOK_KEY);
|
|
5
|
+
}
|
|
6
|
+
function isHook(value) {
|
|
7
|
+
return typeof value === "object" && value !== null && typeof Reflect.get(value, "report") === "function" && typeof Reflect.get(value, "attach") === "function" && typeof Reflect.get(value, "version") === "number";
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Installs the dev hook on `globalThis.__SHADOWJS_DEVTOOLS_HOOK__` (or on `options.target`), once, and
|
|
11
|
+
* returns it. A development tool: in production builds (`__DEV__` false) it installs nothing and returns
|
|
12
|
+
* `undefined`. The runtime looks the global up on each event, so call this before the application code
|
|
13
|
+
* runs: events reported earlier are lost, and those reported before a sink attaches are buffered.
|
|
14
|
+
*
|
|
15
|
+
* When a hook with the same protocol version is already installed, it is returned. When the global holds
|
|
16
|
+
* a hook of another version (or anything that is not a hook), nothing is installed and `undefined` is
|
|
17
|
+
* returned.
|
|
18
|
+
*
|
|
19
|
+
* @param options Target object and replay buffer size. Every field is optional.
|
|
20
|
+
* @returns The installed hook, or `undefined`.
|
|
21
|
+
* @example
|
|
22
|
+
* import { createAgent, installHook } from "@shadow-js/devtools";
|
|
23
|
+
*
|
|
24
|
+
* const hook = installHook();
|
|
25
|
+
* const agent = createAgent();
|
|
26
|
+
* if (hook !== undefined) agent.attach(hook);
|
|
27
|
+
* @since 1.0.0
|
|
28
|
+
*/
|
|
29
|
+
function installHook(options = {}) {
|
|
30
|
+
const target = options.target ?? globalThis;
|
|
31
|
+
const existing = lookup(target);
|
|
32
|
+
if (existing !== void 0) return isHook(existing) && existing.version === 1 ? existing : void 0;
|
|
33
|
+
const limit = options.buffer ?? 5e3;
|
|
34
|
+
const sinks = [];
|
|
35
|
+
const registry = /* @__PURE__ */ new Map();
|
|
36
|
+
let buffer = [];
|
|
37
|
+
let faults = 0;
|
|
38
|
+
let lastFault;
|
|
39
|
+
const deliver = (sink, kind, a, b, c, d, e) => {
|
|
40
|
+
try {
|
|
41
|
+
sink.receive(kind, a, b, c, d, e);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
faults += 1;
|
|
44
|
+
lastFault = error;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const hook = {
|
|
48
|
+
version: 1,
|
|
49
|
+
get sinks() {
|
|
50
|
+
return sinks.length;
|
|
51
|
+
},
|
|
52
|
+
get faults() {
|
|
53
|
+
return faults;
|
|
54
|
+
},
|
|
55
|
+
get lastFault() {
|
|
56
|
+
return lastFault;
|
|
57
|
+
},
|
|
58
|
+
report(kind, a, b, c, d, e) {
|
|
59
|
+
if (sinks.length === 0) {
|
|
60
|
+
if (buffer !== null && buffer.length < limit) buffer.push([
|
|
61
|
+
kind,
|
|
62
|
+
a,
|
|
63
|
+
b,
|
|
64
|
+
c,
|
|
65
|
+
d,
|
|
66
|
+
e
|
|
67
|
+
]);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
for (let i = 0; i < sinks.length; i += 1) {
|
|
71
|
+
const sink = sinks[i];
|
|
72
|
+
if (sink !== void 0) deliver(sink, kind, a, b, c, d, e);
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
inspect(name, source) {
|
|
76
|
+
if (!registry.has(name) && registry.size >= 16) return false;
|
|
77
|
+
registry.set(name, source);
|
|
78
|
+
return true;
|
|
79
|
+
},
|
|
80
|
+
inspections() {
|
|
81
|
+
return [...registry].map(([name, source]) => ({
|
|
82
|
+
name,
|
|
83
|
+
source
|
|
84
|
+
}));
|
|
85
|
+
},
|
|
86
|
+
attach(sink) {
|
|
87
|
+
sinks.push(sink);
|
|
88
|
+
if (buffer !== null) {
|
|
89
|
+
const replay = buffer;
|
|
90
|
+
buffer = null;
|
|
91
|
+
for (const entry of replay) deliver(sink, entry[0], entry[1], entry[2], entry[3], entry[4], entry[5]);
|
|
92
|
+
}
|
|
93
|
+
return () => {
|
|
94
|
+
const index = sinks.indexOf(sink);
|
|
95
|
+
if (index !== -1) sinks.splice(index, 1);
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
Reflect.set(target, HOOK_KEY, hook);
|
|
100
|
+
return hook;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The hook that {@link installHook} installed, or `undefined` when none is installed or its protocol
|
|
104
|
+
* version differs. A development tool: production builds never install a hook.
|
|
105
|
+
*
|
|
106
|
+
* @param target Object to look at (default `globalThis`).
|
|
107
|
+
* @returns The installed hook, or `undefined`.
|
|
108
|
+
* @example
|
|
109
|
+
* import { getHook } from "@shadow-js/devtools";
|
|
110
|
+
*
|
|
111
|
+
* const sinks = getHook()?.sinks ?? 0;
|
|
112
|
+
* @since 1.0.0
|
|
113
|
+
*/
|
|
114
|
+
function getHook(target = globalThis) {
|
|
115
|
+
const existing = lookup(target);
|
|
116
|
+
return isHook(existing) && existing.version === 1 ? existing : void 0;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Removes the installed hook, so that a later {@link installHook} installs a new one. For tests and for
|
|
120
|
+
* hot reloading the tools; a development tool, and a no-op in production builds. Sinks stay attached to
|
|
121
|
+
* the old hook object.
|
|
122
|
+
*
|
|
123
|
+
* @param target Object to remove it from (default `globalThis`).
|
|
124
|
+
* @example
|
|
125
|
+
* import { uninstallHook } from "@shadow-js/devtools";
|
|
126
|
+
*
|
|
127
|
+
* uninstallHook();
|
|
128
|
+
* @since 1.0.0
|
|
129
|
+
*/
|
|
130
|
+
function uninstallHook(target = globalThis) {
|
|
131
|
+
Reflect.deleteProperty(target, HOOK_KEY);
|
|
132
|
+
}
|
|
133
|
+
//#endregion
|
|
134
|
+
export { getHook, installHook, uninstallHook };
|
|
135
|
+
|
|
136
|
+
//# sourceMappingURL=hook.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hook.js","names":[],"sources":["../../src/hook.ts"],"sourcesContent":["import type { InspectionEntry, InspectionSource } from \"./inspection\";\nimport {\n type DevtoolsHook,\n HOOK_KEY,\n type HookSink,\n MAX_INSPECTIONS,\n PROTOCOL_VERSION,\n} from \"./protocol\";\n\n/**\n * Options of {@link installHook}. Every field is optional.\n *\n * @since 1.0.0\n */\nexport interface InstallHookOptions {\n /**\n * The object to install the hook on.\n *\n * @default globalThis\n */\n target?: object;\n /**\n * How many events to keep for a sink that attaches later. The first events reported are kept and\n * later ones are dropped. The buffer is released when the first sink attaches, so a hook that nobody\n * listens to cannot grow without bound.\n *\n * @default 5000\n */\n buffer?: number;\n}\n\n/**\n * The hook that {@link installHook} installs: a {@link DevtoolsHook} with the counters of its sinks.\n *\n * @since 1.0.0\n */\nexport interface InstalledHook extends DevtoolsHook {\n /** Number of times a sink threw while receiving an event. The hook swallows each error so the app keeps running. */\n readonly faults: number;\n /** The last error a sink threw, or `undefined` when none did. */\n readonly lastFault: unknown;\n}\n\ntype Buffered = readonly [number, unknown, unknown, unknown, unknown, unknown];\n\nfunction lookup(target: object): unknown {\n return Reflect.get(target, HOOK_KEY);\n}\n\nfunction isHook(value: unknown): value is InstalledHook {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof Reflect.get(value, \"report\") === \"function\" &&\n typeof Reflect.get(value, \"attach\") === \"function\" &&\n typeof Reflect.get(value, \"version\") === \"number\"\n );\n}\n\n/**\n * Installs the dev hook on `globalThis.__SHADOWJS_DEVTOOLS_HOOK__` (or on `options.target`), once, and\n * returns it. A development tool: in production builds (`__DEV__` false) it installs nothing and returns\n * `undefined`. The runtime looks the global up on each event, so call this before the application code\n * runs: events reported earlier are lost, and those reported before a sink attaches are buffered.\n *\n * When a hook with the same protocol version is already installed, it is returned. When the global holds\n * a hook of another version (or anything that is not a hook), nothing is installed and `undefined` is\n * returned.\n *\n * @param options Target object and replay buffer size. Every field is optional.\n * @returns The installed hook, or `undefined`.\n * @example\n * import { createAgent, installHook } from \"@shadow-js/devtools\";\n *\n * const hook = installHook();\n * const agent = createAgent();\n * if (hook !== undefined) agent.attach(hook);\n * @since 1.0.0\n */\nexport function installHook(options: InstallHookOptions = {}): InstalledHook | undefined {\n if (!__DEV__) return undefined;\n const target = options.target ?? globalThis;\n const existing = lookup(target);\n if (existing !== undefined) {\n return isHook(existing) && existing.version === PROTOCOL_VERSION ? existing : undefined;\n }\n const limit = options.buffer ?? 5000;\n const sinks: HookSink[] = [];\n const registry = new Map<string, InspectionSource>();\n let buffer: Buffered[] | null = [];\n let faults = 0;\n let lastFault: unknown;\n\n const deliver = (\n sink: HookSink,\n kind: number,\n a: unknown,\n b: unknown,\n c: unknown,\n d: unknown,\n e: unknown,\n ): void => {\n try {\n sink.receive(kind, a, b, c, d, e);\n } catch (error) {\n // A broken tool must never break the application: count the fault and keep the error.\n faults += 1;\n lastFault = error;\n }\n };\n\n const hook: InstalledHook = {\n version: PROTOCOL_VERSION,\n get sinks(): number {\n return sinks.length;\n },\n get faults(): number {\n return faults;\n },\n get lastFault(): unknown {\n return lastFault;\n },\n report(kind, a, b, c, d, e): void {\n if (sinks.length === 0) {\n if (buffer !== null && buffer.length < limit) buffer.push([kind, a, b, c, d, e]);\n return;\n }\n for (let i = 0; i < sinks.length; i += 1) {\n const sink = sinks[i];\n if (sink !== undefined) deliver(sink, kind, a, b, c, d, e);\n }\n },\n inspect(name, source): boolean {\n if (!registry.has(name) && registry.size >= MAX_INSPECTIONS) return false;\n registry.set(name, source);\n return true;\n },\n inspections(): readonly InspectionEntry[] {\n return [...registry].map(([name, source]) => ({ name, source }));\n },\n attach(sink): () => void {\n sinks.push(sink);\n if (buffer !== null) {\n const replay = buffer;\n buffer = null;\n for (const entry of replay)\n deliver(sink, entry[0], entry[1], entry[2], entry[3], entry[4], entry[5]);\n }\n return () => {\n const index = sinks.indexOf(sink);\n if (index !== -1) sinks.splice(index, 1);\n };\n },\n };\n Reflect.set(target, HOOK_KEY, hook);\n return hook;\n}\n\n/**\n * The hook that {@link installHook} installed, or `undefined` when none is installed or its protocol\n * version differs. A development tool: production builds never install a hook.\n *\n * @param target Object to look at (default `globalThis`).\n * @returns The installed hook, or `undefined`.\n * @example\n * import { getHook } from \"@shadow-js/devtools\";\n *\n * const sinks = getHook()?.sinks ?? 0;\n * @since 1.0.0\n */\nexport function getHook(target: object = globalThis): InstalledHook | undefined {\n const existing = lookup(target);\n return isHook(existing) && existing.version === PROTOCOL_VERSION ? existing : undefined;\n}\n\n/**\n * Removes the installed hook, so that a later {@link installHook} installs a new one. For tests and for\n * hot reloading the tools; a development tool, and a no-op in production builds. Sinks stay attached to\n * the old hook object.\n *\n * @param target Object to remove it from (default `globalThis`).\n * @example\n * import { uninstallHook } from \"@shadow-js/devtools\";\n *\n * uninstallHook();\n * @since 1.0.0\n */\nexport function uninstallHook(target: object = globalThis): void {\n Reflect.deleteProperty(target, HOOK_KEY);\n}\n"],"mappings":";;AA6CA,SAAS,OAAO,QAAyB;CACvC,OAAO,QAAQ,IAAI,QAAQ,QAAQ;AACrC;AAEA,SAAS,OAAO,OAAwC;CACtD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAO,QAAQ,IAAI,OAAO,QAAQ,MAAM,cACxC,OAAO,QAAQ,IAAI,OAAO,QAAQ,MAAM,cACxC,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM;AAE7C;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,YAAY,UAA8B,C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EACjE;EACA,OAAO,MAAkB;GACvB,MAAM,KAAK,IAAI;GACf,IAAI,WAAW,MAAM;IACnB,MAAM,SAAS;IACf,SAAS;IACT,KAAK,MAAM,SAAS,QAClB,QAAQ,MAAM,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,EAAE;GAC5E;GACA,aAAa;IACX,MAAM,QAAQ,MAAM,QAAQ,IAAI;IAChC,IAAI,UAAU,IAAI,MAAM,OAAO,OAAO,CAAC;GACzC;EACF;CACF;CACA,QAAQ,IAAI,QAAQ,UAAU,IAAI;CAClC,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,QAAQ,SAAiB,YAAuC;CAC9E,MAAM,WAAW,OAAO,MAAM;CAC9B,OAAO,OAAO,QAAQ,KAAK,SAAS,YAAA,IAA+B,WAAW,KAAA;AAChF;;;;;;;;;;;;;AAcA,SAAgB,cAAc,SAAiB,YAAkB;CAC/D,QAAQ,eAAe,QAAQ,QAAQ;AACzC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { InspectionEntry, InspectionRow, InspectionSnapshot, InspectionSource, QueryInfoLike, QueryLike, RouterLike, parseInspectResult, queryInspection, readInspections, registerInspection, routerInspection, sanitizeRows } from "./inspection.js";
|
|
2
|
+
import { DevtoolsHook, EVENT, EventKind, HOOK_KEY, HookSink, MAX_INSPECTIONS, MAX_INSPECTION_ROWS, NO_ID, PROTOCOL_VERSION, StoreHandle, WireEvent, WireKind } from "./protocol.js";
|
|
3
|
+
import { RingBuffer } from "./ring.js";
|
|
4
|
+
import { Cause, DEFAULT_LIMITS, ErrorRecord, FlushRecord, HydrationRecord, InspectorModel, ModelLimits, ModelState, NodeRecord, NodeType, RunRecord, WriteRecord, foldEvents } from "./model.js";
|
|
5
|
+
import { ComponentStat, ExplainStep, Explanation, FlameFlush, FlameSpan, GraphSnapshot, SnapshotCounts, SnapshotNode, TreeNode, componentStats, explainRun, flameTimeline, nodeLabel, ownerTree, snapshotOf } from "./inspector.js";
|
|
6
|
+
import { Agent, AgentOptions, AgentRequest, AgentResponse, AgentStats, ValueResult, createAgent } from "./agent.js";
|
|
7
|
+
import { Backend, PageHooks, createLocalBackend } from "./backend.js";
|
|
8
|
+
import { InstallHookOptions, InstalledHook, getHook, installHook, uninstallHook } from "./hook.js";
|
|
9
|
+
import { AgentMessage, BroadcastChannelLike, CHANNEL, MessagePortLike, PanelMessage, RemoteOptions, ServeOptions, Transport, WindowTransportOptions, connectRemote, createBroadcastChannelTransport, createMemoryTransportPair, createPortTransport, createWindowTransport, isAgentMessage, isPanelMessage, serveAgent } from "./transport.js";
|
|
10
|
+
import { PanelState, TABS, TabId, createPanelState } from "./ui/state.js";
|
|
11
|
+
import { DevtoolsHandle, MountOptions, matchesShortcut, mountDevtools, parseShortcut } from "./mount.js";
|
|
12
|
+
import { Box, Overlay, OverlayOptions, boxOf, createOverlay } from "./overlay.js";
|
|
13
|
+
import { errorMessage, parseEditableText, preview, toEditableText } from "./preview.js";
|
|
14
|
+
import { InspectionState, createInspectionState } from "./ui/inspection-state.js";
|
|
15
|
+
import { Panel, PanelProps } from "./ui/panel.js";
|
|
16
|
+
import { LAUNCHER_CSS, PANEL_CSS } from "./ui/styles.js";
|
|
17
|
+
export { type Agent, type AgentMessage, type AgentOptions, type AgentRequest, type AgentResponse, type AgentStats, type Backend, type Box, type BroadcastChannelLike, CHANNEL, type Cause, type ComponentStat, DEFAULT_LIMITS, type DevtoolsHandle, type DevtoolsHook, EVENT, type ErrorRecord, type EventKind, type ExplainStep, type Explanation, type FlameFlush, type FlameSpan, type FlushRecord, type GraphSnapshot, HOOK_KEY, type HookSink, type HydrationRecord, type InspectionEntry, type InspectionRow, type InspectionSnapshot, type InspectionSource, type InspectionState, InspectorModel, type InstallHookOptions, type InstalledHook, LAUNCHER_CSS, MAX_INSPECTIONS, MAX_INSPECTION_ROWS, type MessagePortLike, type ModelLimits, type ModelState, type MountOptions, NO_ID, type NodeRecord, type NodeType, type Overlay, type OverlayOptions, PANEL_CSS, PROTOCOL_VERSION, type PageHooks, Panel, type PanelMessage, type PanelProps, type PanelState, type QueryInfoLike, type QueryLike, type RemoteOptions, RingBuffer, type RouterLike, type RunRecord, type ServeOptions, type SnapshotCounts, type SnapshotNode, type StoreHandle, TABS, type TabId, type Transport, type TreeNode, type ValueResult, type WindowTransportOptions, type WireEvent, type WireKind, type WriteRecord, boxOf, componentStats, connectRemote, createAgent, createBroadcastChannelTransport, createInspectionState, createLocalBackend, createMemoryTransportPair, createOverlay, createPanelState, createPortTransport, createWindowTransport, errorMessage, explainRun, flameTimeline, foldEvents, getHook, installHook, isAgentMessage, isPanelMessage, matchesShortcut, mountDevtools, nodeLabel, ownerTree, parseEditableText, parseInspectResult, parseShortcut, preview, queryInspection, readInspections, registerInspection, routerInspection, sanitizeRows, serveAgent, snapshotOf, toEditableText, uninstallHook };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { EVENT, HOOK_KEY, MAX_INSPECTIONS, MAX_INSPECTION_ROWS, NO_ID, PROTOCOL_VERSION } from "./protocol.js";
|
|
2
|
+
import { getHook, installHook, uninstallHook } from "./hook.js";
|
|
3
|
+
import { errorMessage, parseEditableText, preview, toEditableText } from "./preview.js";
|
|
4
|
+
import { parseInspectResult, queryInspection, readInspections, registerInspection, routerInspection, sanitizeRows } from "./inspection.js";
|
|
5
|
+
import { componentStats, explainRun, flameTimeline, nodeLabel, ownerTree, snapshotOf } from "./inspector.js";
|
|
6
|
+
import { RingBuffer } from "./ring.js";
|
|
7
|
+
import { DEFAULT_LIMITS, InspectorModel, foldEvents } from "./model.js";
|
|
8
|
+
import { createAgent } from "./agent.js";
|
|
9
|
+
import { createLocalBackend } from "./backend.js";
|
|
10
|
+
import { boxOf, createOverlay } from "./overlay.js";
|
|
11
|
+
import { CHANNEL, connectRemote, createBroadcastChannelTransport, createMemoryTransportPair, createPortTransport, createWindowTransport, isAgentMessage, isPanelMessage, serveAgent } from "./transport.js";
|
|
12
|
+
import { TABS, createPanelState } from "./ui/state.js";
|
|
13
|
+
import { Panel } from "./ui/panel.js";
|
|
14
|
+
import { LAUNCHER_CSS, PANEL_CSS } from "./ui/styles.js";
|
|
15
|
+
import { matchesShortcut, mountDevtools, parseShortcut } from "./mount.js";
|
|
16
|
+
import { createInspectionState } from "./ui/inspection-state.js";
|
|
17
|
+
export { CHANNEL, DEFAULT_LIMITS, EVENT, HOOK_KEY, InspectorModel, LAUNCHER_CSS, MAX_INSPECTIONS, MAX_INSPECTION_ROWS, NO_ID, PANEL_CSS, PROTOCOL_VERSION, Panel, RingBuffer, TABS, boxOf, componentStats, connectRemote, createAgent, createBroadcastChannelTransport, createInspectionState, createLocalBackend, createMemoryTransportPair, createOverlay, createPanelState, createPortTransport, createWindowTransport, errorMessage, explainRun, flameTimeline, foldEvents, getHook, installHook, isAgentMessage, isPanelMessage, matchesShortcut, mountDevtools, nodeLabel, ownerTree, parseEditableText, parseInspectResult, parseShortcut, preview, queryInspection, readInspections, registerInspection, routerInspection, sanitizeRows, serveAgent, snapshotOf, toEditableText, uninstallHook };
|