@expressive/inspect 0.6.2 → 0.6.4

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/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  ---
12
12
 
13
- Query the live instance graph of an [Expressive MVC](https://github.com/gabeklein/expressive-mvc) app from a test, a browser driver (Playwright, puppeteer, CDP), or the browser console. No UI, and no network beyond an opt-in dev-server relay or server handler - a base layer for agents, devtools, and test helpers.
13
+ Query the live instance graph of an [Expressive MVC](https://github.com/gabeklein/expressive) app from a test, a browser driver (Playwright, puppeteer, CDP), or the browser console. No UI, and no network beyond an opt-in dev-server relay or server handler - a base layer for agents, devtools, and test helpers.
14
14
 
15
15
  ```bash
16
16
  npm install --save-dev @expressive/inspect
@@ -61,7 +61,7 @@ export default defineConfig({ plugins: [inspect()] });
61
61
  ```bash
62
62
  curl localhost:5173/__inspect # connected pages, iframes included
63
63
  curl localhost:5173/__inspect/<id> -d '["get", "Composer.draft"]'
64
- curl localhost:5173/__inspect/<id> -d '["act", ["call", "Composer.submit", "hi"]]' # { value, frames, settled, pending }
64
+ curl localhost:5173/__inspect/<id> -d '["act", ["call", "Composer.submit", "hi"]]' # { value, frames, settled, pending, missing }
65
65
  ```
66
66
 
67
67
  Local callers only; browser and proxied (tunnel) requests are refused.
@@ -110,4 +110,4 @@ Instances a host never committed - a render thrown away, a StrictMode twin - sta
110
110
 
111
111
  Property names survive minification; class names do not. Each class gets a stable `typeId` and a construction `site`. Name them with `label(Type, 'Composer')`, `static displayName`, or `resolve({ T3: 'Composer' })`, or keep names at build time (`keepNames`, `keep_classnames`).
112
112
 
113
- Full reference: [skills/inspect.md](https://github.com/gabeklein/expressive-mvc/blob/main/skills/inspect.md).
113
+ Full reference: [skills/expressive-inspect](https://github.com/gabeklein/expressive/blob/main/packages/inspect/skills/expressive-inspect/SKILL.md), shipped in the package.
@@ -26,7 +26,6 @@ function unreached(timeout, pending, missing, frames, hint = "") {
26
26
 
27
27
  //#endregion
28
28
  //#region src/bracket.ts
29
- /** Resolve `address.key` to the instance `address` names - label, id, or owner path - so frames match it alone. */
30
29
  /** Resolve `address.key` to the instance `address` names - label, id, or owner path - as the `id.key` its frames carry. */
31
30
  async function locate(remote, target) {
32
31
  const dot = target.lastIndexOf(".");
@@ -96,4 +95,4 @@ async function bracket(remote, step, wait, { until = [], timeout = SETTLE_TIMEOU
96
95
 
97
96
  //#endregion
98
97
  export { unsettled as i, tick as n, unreached as r, bracket as t };
99
- //# sourceMappingURL=bracket-D3xwitlE.js.map
98
+ //# sourceMappingURL=bracket-iTnJYPw-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bracket-iTnJYPw-.js","names":[],"sources":["../src/settle.ts","../src/bracket.ts"],"sourcesContent":["import type { Frame, Options } from './journal';\n\nexport const SETTLE_TIMEOUT = 1000;\n\nexport interface Act {\n /**\n * What to wait for before settling: `Type.key` / `id.key` addresses that must each see a frame after the\n * step's synchronous writes, or `{ [address]: value }` pairs that must each hold that value.\n */\n until?: string | string[] | Record<string, unknown>;\n /** Longest to wait, in ms; default 1000. */\n timeout?: number;\n /** Recording filters for this window, instead of the journal's - `{ paths: [], types: [], keys: [] }` records everything. */\n record?: Omit<Options, 'level'>;\n}\n\nexport const tick = () => new Promise((resolve) => setTimeout(resolve, 0));\n\n/** Wait a macrotask at a time until one passes with no new frame. Resolves `false` if `timeout` passes first. */\nexport async function settle(seq: () => number | Promise<number>, wait: () => unknown = tick, timeout = SETTLE_TIMEOUT) {\n const end = Date.now() + timeout;\n\n for (let last = await seq(); ; ) {\n await wait();\n\n const next = await seq();\n\n if (next === last) return true;\n if (Date.now() >= end) return false;\n\n last = next;\n }\n}\n\nexport function unsettled(timeout = SETTLE_TIMEOUT) {\n console.warn(\n `Still active after ${timeout}ms - frames may be incomplete. Narrow the recording ({ record: { types, paths, keys } }) to exclude background work, or pass { timeout }.`\n );\n}\n\n/** `until` not met within `timeout` - carries the frames recorded so far and what never arrived. */\nexport function unreached(timeout: number, pending: string[], missing: string[], frames: Frame[], hint = '') {\n const list = pending.map((address) => (missing.includes(address) ? `${address} (names no instance)` : address));\n return Object.assign(new Error(`Not reached within ${timeout}ms: ${list.join(', ')}.${hint}`), { frames, pending });\n}\n","import type { Frame, Options, Query } from './journal';\nimport { SETTLE_TIMEOUT, settle, type Act } from './settle';\n\nexport interface Remote {\n record(options?: Options): Required<Options> | Promise<Required<Options>>;\n seq(): number | Promise<number>;\n frames(query: Query): Frame[] | Promise<Frame[]>;\n get(address: string): unknown;\n}\n\n/** Resolve `address.key` to the instance `address` names - label, id, or owner path - as the `id.key` its frames carry. */\nasync function locate(remote: Remote, target: string) {\n const dot = target.lastIndexOf('.');\n\n if (target[dot + 1] == '_')\n throw new Error(`until ${target}: _ keys are unmanaged and emit no events - wait on a value instead.`);\n const found = (await remote.get(target.slice(0, dot))) as { $ref?: string } | undefined;\n\n if (!found?.$ref) throw new Error(`until ${target}: ${target.slice(0, dot)} names no Model.`);\n\n return `${found.$ref}.${target.slice(dot + 1)}`;\n}\n\n/**\n * Run `step` recording values, wait for `until`, settle, and return what it produced; the prior recording is restored.\n * `local` steps run here, so activity for `until` counts once their synchronous writes flush, not once they resolve.\n */\nexport async function bracket(\n remote: Remote,\n step: () => unknown,\n wait: () => unknown,\n { until = [], timeout = SETTLE_TIMEOUT, record }: Act = {},\n local?: boolean\n) {\n const before = await remote.record();\n const since = await remote.seq();\n const window = { ...before, ...record };\n const filtered = window.types.length + window.paths.length + window.keys.length > 0;\n const values = typeof until == 'string' || Array.isArray(until) ? undefined : until;\n const addresses = values ? [] : ([] as string[]).concat(until as string | string[]);\n const paths = filtered ? [...window.paths, ...addresses.filter((address) => address.indexOf('.') === address.lastIndexOf('.'))] : [];\n\n await remote.record({ ...record, level: 'values', ...(filtered && { paths }) });\n\n try {\n const running = step();\n let from: number | undefined;\n\n if (local) {\n await undefined;\n from = await remote.seq();\n }\n\n const value = await running;\n\n from ??= await remote.seq();\n const end = Date.now() + timeout;\n const pending = new Set(values ? Object.keys(values) : addresses);\n const targets = new Map<string, string>();\n\n for (const address of addresses) targets.set(address, await locate(remote, address));\n\n if (filtered && addresses.some((address) => address.indexOf('.') !== address.lastIndexOf('.')))\n await remote.record({ paths: [...paths, ...targets.values()] });\n\n while (pending.size) {\n if (values) {\n for (const address of pending)\n if (JSON.stringify(await remote.get(address)) === JSON.stringify(values[address])) pending.delete(address);\n } else\n for (const frame of await remote.frames({ since: from }))\n for (const event of frame.events)\n for (const address of pending) if (targets.get(address) === `${event.id}.${event.key}`) pending.delete(address);\n\n if (!pending.size || Date.now() >= end) break;\n\n await wait();\n }\n\n const settled = !pending.size && (await settle(remote.seq, wait, Math.max(0, end - Date.now())));\n const missing: string[] = [];\n\n if (values)\n for (const address of pending)\n if ((await remote.get(address.slice(0, address.lastIndexOf('.')))) === undefined) missing.push(address);\n\n return { value, frames: await remote.frames({ since }), settled, pending: [...pending], missing, timeout };\n } finally {\n await remote.record(before);\n }\n}\n"],"mappings":";AAEA,MAAa,iBAAiB;AAc9B,MAAa,aAAa,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;;AAG1E,eAAsB,OAAO,KAAqC,OAAsB,MAAM,UAAU,gBAAgB;CACtH,MAAM,MAAM,KAAK,KAAK,GAAG;AAEzB,MAAK,IAAI,OAAO,MAAM,KAAK,IAAM;AAC/B,QAAM,MAAM;EAEZ,MAAM,OAAO,MAAM,KAAK;AAExB,MAAI,SAAS,KAAM,QAAO;AAC1B,MAAI,KAAK,KAAK,IAAI,IAAK,QAAO;AAE9B,SAAO;;;AAIX,SAAgB,UAAU,UAAU,gBAAgB;AAClD,SAAQ,KACN,sBAAsB,QAAQ,2IAC/B;;;AAIH,SAAgB,UAAU,SAAiB,SAAmB,SAAmB,QAAiB,OAAO,IAAI;CAC3G,MAAM,OAAO,QAAQ,KAAK,YAAa,QAAQ,SAAS,QAAQ,GAAG,GAAG,QAAQ,wBAAwB,QAAS;AAC/G,QAAO,O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OAAW,SAAQ,KAAK,QAAQ;;AAE3G,SAAO;GAAE;GAAO,QAAQ,MAAM,OAAO,OAAO,EAAE,OAAO,CAAC;GAAE;GAAS,SAAS,CAAC,GAAG,QAAQ;GAAE;GAAS;GAAS;WAClG;AACR,QAAM,OAAO,OAAO,OAAO"}
package/dist/bridge.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Summary, E as Frame, O as Options, S as Select, k as Query, x as Act } from "./inspect-3AOGnw9P.js";
1
+ import { A as Summary, E as Frame, O as Options, S as Select, k as Query, x as Act } from "./inspect-SOZyvcTx.js";
2
2
  import inspect$1 from "./index.js";
3
3
 
4
4
  //#region src/devtools.d.ts
package/dist/bridge.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as unsettled, n as tick, r as unreached, t as bracket } from "./bracket-D3xwitlE.js";
1
+ import { i as unsettled, n as tick, r as unreached, t as bracket } from "./bracket-iTnJYPw-.js";
2
2
  import { t as dispatch } from "./dispatch-BmtaBKeH.js";
3
3
 
4
4
  //#region src/devtools.ts
package/dist/http.d.ts CHANGED
@@ -29,6 +29,11 @@ type Source = {
29
29
  };
30
30
  /** Serve an installed inspector over HTTP, to loopback callers only. */
31
31
  declare function handle(req: Request, source: Source): Promise<Response>;
32
+ /**
33
+ * Serve an installed inspector to a Node request - `node:http`, Express, Connect.
34
+ *
35
+ * Loopback callers only, by `req.socket.remoteAddress`. A JSON array a body parser left on `req.body` is used as is.
36
+ */
32
37
  declare function handle(req: NodeRequest, res: NodeResponse): Promise<void>;
33
38
  //#endregion
34
39
  export { handle };
package/dist/http.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./install.js";
2
- import { c as reply, i as headers, n as answer, o as local, r as body, s as parse, t as CALL_TIMEOUT } from "./protocol-BApRTxGk.js";
2
+ import { c as reply, i as headers, n as answer, o as local, r as body, s as parse, t as CALL_TIMEOUT } from "./protocol-DGf0aga5.js";
3
3
 
4
4
  //#region src/http.ts
5
5
  const USAGE = "GET describes this process; POST with [method, ...args] calls the inspector.";
package/dist/http.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"http.js","names":[],"sources":["../src/http.ts"],"sourcesContent":["import './install';\nimport { answer, body, CALL_TIMEOUT, headers, local, parse, reply, type Answer, type NodeRequest, type NodeResponse } from './protocol';\n\n/** Where the caller's address comes from: given outright, Bun's `server`, or Deno's `info`. */\ntype Source =\n | { ip: string | null | undefined }\n | { requestIP(req: Request): { address: string } | null }\n | { remoteAddr: { hostname: string } };\n\ntype Result = [status: number, data: unknown];\n\nconst USAGE = 'GET describes this process; POST with [method, ...args] calls the inspector.';\n\n/** Serve an installed inspector over HTTP, to loopback callers only. */\nexport function handle(req: Request, source: Source): Promise<Response>;\nexport function handle(req: NodeRequest, res: NodeResponse): Promise<void>;\nexport async function handle(req: Request | NodeRequest, second: Source | NodeResponse) {\n if (typeof (second as NodeResponse).end == 'function') {\n const node = req as NodeRequest;\n const text = () => body(node).then((text) => text || (Array.isArray(node.body) ? JSON.stringify(node.body) : ''));\n const [status, data] = await respond(node.method, node.socket?.remoteAddress, headers(node), text);\n\n return reply(second as NodeResponse, status, data);\n }\n\n const web = req as Request;\n const [status, data] = await respond(web.method, address(web, second as Source), web.headers, () => web.text());\n\n return Response.json(data, { status });\n}\n\nfunction address(req: Request, source: Source) {\n if ('ip' in source) return source.ip;\n if ('requestIP' in source) return source.requestIP(req)?.address;\n if ('remoteAddr' in source) return source.remoteAddr.hostname;\n}\n\nasync function respond(\n method: string | undefined,\n ip: string | null | undefined,\n headers: { has(name: string): boolean },\n text: () => Promise<string>\n): Promise<Result> {\n if (!globalThis.__EXPRESSIVE_INSPECT__) return [404, { error: 'Inspector not installed.' }];\n if (!local(ip, headers)) return [403, { error: 'Local callers only; browser and proxied requests are refused.' }];\n if (method === 'GET') return [200, identity()];\n if (method !== 'POST') return [405, { error: USAGE }];\n\n const call = parse(await text().catch(() => ''));\n\n if (!call) return [400, { error: 'Body must be a JSON array: [method, ...args].' }];\n\n let timer: Parameters<typeof clearTimeout>[0];\n const expire = new Promise<undefined>((resolve) => (timer = setTimeout(resolve, CALL_TIMEOUT)));\n const result: Answer | undefined = await Promise.race([answer(call), expire]);\n\n clearTimeout(timer);\n\n if (!result) return [504, { error: 'Call did not answer.' }];\n if (result.error) return [result.status ?? 500, { error: result.error }];\n\n return [200, result.value];\n}\n\nfunction identity() {\n const process = (globalThis as { process?: { pid?: number; title?: string; cwd?(): string } }).process;\n\n return {\n process: true,\n pid: process?.pid ?? null,\n cwd: process?.cwd?.() ?? null,\n started: Math.round(performance.timeOrigin),\n runtime: globalThis.navigator?.userAgent ?? null,\n title: process?.title ?? null\n };\n}\n"],"mappings":";;;;AAWA,MAAM,QAAQ;AAKd,eAAsB,OAAO,KAA4B,QAA+B;AACtF,KAAI,OAAQ,OAAwB,OAAO,YAAY;EACrD,MAAM,OAAO;EACb,MAAM,aAAa,KAAK,KAAK,CAAC,MAAM,SAAS,SAAS,MAAM,QAAQ,KAAK,KAAK,GAAG,KAAK,UAAU,KAAK,KAAK,GAAG,IAAI;EACjH,MAAM,CAAC,QAAQ,QAAQ,MAAM,QAAQ,KAAK,QAAQ,KAAK,QAAQ,eAAe,QAAQ,KAAK,EAAE,KAAK;AAElG,SAAO,MAAM,QAAwB,QAAQ,KAAK;;CAGpD,MAAM,MAAM;CACZ,MAAM,CAAC,QAAQ,QAAQ,MAAM,QAAQ,IAAI,QAAQ,QAAQ,KAAK,OAAiB,EAAE,IAAI,eAAe,IAAI,MAAM,CAAC;AAE/G,QAAO,SAAS,KAAK,MAAM,EAAE,QAAQ,CAAC;;AAGxC,SAAS,QAAQ,KAAc,QAAgB;AAC7C,KAAI,QAAQ,OAAQ,QAAO,OAAO;AAClC,KAAI,eAAe,OAAQ,QAAO,OAAO,UAAU,IAAI,EAAE;AACzD,KAAI,gBAAgB,OAAQ,QAAO,OAAO,WAAW;;AAGvD,eAAe,QACb,QACA,IACA,SACA,MACiB;AACjB,KAAI,CAAC,WAAW,uBAAwB,QAAO,CAAC,KAAK,EAAE,OAAO,4BAA4B,CAAC;AAC3F,KAAI,CAAC,MAAM,IAAI,QAAQ,CAAE,QAAO,CAAC,KAAK,EAAE,OAAO,iEAAiE,CAAC;AACjH,KAAI,WAAW,MAAO,QAAO,CAAC,KAAK,UAAU,CAAC;AAC9C,KAAI,WAAW,OAAQ,QAAO,CAAC,KAAK,EAAE,OAAO,OAAO,CAAC;CAErD,MAAM,OAAO,MAAM,MAAM,MAAM,CAAC,YAAY,GAAG,CAAC;AAEhD,KAAI,CAAC,KAAM,QAAO,CAAC,KAAK,EAAE,OAAO,iDAAiD,CAAC;CAEnF,IAAI;CACJ,MAAM,SAAS,IAAI,SAAoB,YAAa,QAAQ,WAAW,SAAS,aAAa,CAAE;CAC/F,MAAM,SAA6B,MAAM,QAAQ,KAAK,CAAC,OAAO,KAAK,EAAE,OAAO,CAAC;AAE7E,cAAa,MAAM;AAEnB,KAAI,CAAC,OAAQ,QAAO,CAAC,KAAK,EAAE,OAAO,wBAAwB,CAAC;AAC5D,KAAI,OAAO,MAAO,QAAO,CAAC,OAAO,UAAU,KAAK,EAAE,OAAO,OAAO,OAAO,CAAC;AAExE,QAAO,CAAC,KAAK,OAAO,MAAM;;AAG5B,SAAS,WAAW;CAClB,MAAM,UAAW,WAA8E;AAE/F,QAAO;EACL,SAAS;EACT,KAAK,SAAS,OAAO;EACrB,KAAK,SAAS,OAAO,IAAI;EACzB,SAAS,KAAK,MAAM,YAAY,WAAW;EAC3C,SAAS,WAAW,WAAW,aAAa;EAC5C,OAAO,SAAS,SAAS;EAC1B"}
1
+ {"version":3,"file":"http.js","names":[],"sources":["../src/http.ts"],"sourcesContent":["import './install';\nimport { answer, body, CALL_TIMEOUT, headers, local, parse, reply, type Answer, type NodeRequest, type NodeResponse } from './protocol';\n\n/** Where the caller's address comes from: given outright, Bun's `server`, or Deno's `info`. */\ntype Source =\n | { ip: string | null | undefined }\n | { requestIP(req: Request): { address: string } | null }\n | { remoteAddr: { hostname: string } };\n\ntype Result = [status: number, data: unknown];\n\nconst USAGE = 'GET describes this process; POST with [method, ...args] calls the inspector.';\n\n/** Serve an installed inspector over HTTP, to loopback callers only. */\nexport function handle(req: Request, source: Source): Promise<Response>;\n/**\n * Serve an installed inspector to a Node request - `node:http`, Express, Connect.\n *\n * Loopback callers only, by `req.socket.remoteAddress`. A JSON array a body parser left on `req.body` is used as is.\n */\nexport function handle(req: NodeRequest, res: NodeResponse): Promise<void>;\nexport async function handle(req: Request | NodeRequest, second: Source | NodeResponse) {\n if (typeof (second as NodeResponse).end == 'function') {\n const node = req as NodeRequest;\n const text = () => body(node).then((text) => text || (Array.isArray(node.body) ? JSON.stringify(node.body) : ''));\n const [status, data] = await respond(node.method, node.socket?.remoteAddress, headers(node), text);\n\n return reply(second as NodeResponse, status, data);\n }\n\n const web = req as Request;\n const [status, data] = await respond(web.method, address(web, second as Source), web.headers, () => web.text());\n\n return Response.json(data, { status });\n}\n\nfunction address(req: Request, source: Source) {\n if ('ip' in source) return source.ip;\n if ('requestIP' in source) return source.requestIP(req)?.address;\n if ('remoteAddr' in source) return source.remoteAddr.hostname;\n}\n\nasync function respond(\n method: string | undefined,\n ip: string | null | undefined,\n headers: { has(name: string): boolean },\n text: () => Promise<string>\n): Promise<Result> {\n if (!globalThis.__EXPRESSIVE_INSPECT__) return [404, { error: 'Inspector not installed.' }];\n if (!local(ip, headers)) return [403, { error: 'Local callers only; browser and proxied requests are refused.' }];\n if (method === 'GET') return [200, identity()];\n if (method !== 'POST') return [405, { error: USAGE }];\n\n const call = parse(await text().catch(() => ''));\n\n if (!call) return [400, { error: 'Body must be a JSON array: [method, ...args].' }];\n\n let timer: Parameters<typeof clearTimeout>[0];\n const expire = new Promise<undefined>((resolve) => (timer = setTimeout(resolve, CALL_TIMEOUT)));\n const result: Answer | undefined = await Promise.race([answer(call), expire]);\n\n clearTimeout(timer);\n\n if (!result) return [504, { error: 'Call did not answer.' }];\n if (result.error) return [result.status ?? 500, { error: result.error }];\n\n return [200, result.value];\n}\n\nfunction identity() {\n const process = (globalThis as { process?: { pid?: number; title?: string; cwd?(): string } }).process;\n\n return {\n process: true,\n pid: process?.pid ?? null,\n cwd: process?.cwd?.() ?? null,\n started: Math.round(performance.timeOrigin),\n runtime: globalThis.navigator?.userAgent ?? null,\n title: process?.title ?? null\n };\n}\n"],"mappings":";;;;AAWA,MAAM,QAAQ;AAUd,eAAsB,OAAO,KAA4B,QAA+B;AACtF,KAAI,OAAQ,OAAwB,OAAO,YAAY;EACrD,MAAM,OAAO;EACb,MAAM,aAAa,KAAK,KAAK,CAAC,MAAM,SAAS,SAAS,MAAM,QAAQ,KAAK,KAAK,GAAG,KAAK,UAAU,KAAK,KAAK,GAAG,IAAI;EACjH,MAAM,CAAC,QAAQ,QAAQ,MAAM,QAAQ,KAAK,QAAQ,KAAK,QAAQ,eAAe,QAAQ,KAAK,EAAE,KAAK;AAElG,SAAO,MAAM,QAAwB,QAAQ,KAAK;;CAGpD,MAAM,MAAM;CACZ,MAAM,CAAC,QAAQ,QAAQ,MAAM,QAAQ,IAAI,QAAQ,QAAQ,KAAK,OAAiB,EAAE,IAAI,eAAe,IAAI,MAAM,CAAC;AAE/G,QAAO,SAAS,KAAK,MAAM,EAAE,QAAQ,CAAC;;AAGxC,SAAS,QAAQ,KAAc,QAAgB;AAC7C,KAAI,QAAQ,OAAQ,QAAO,OAAO;AAClC,KAAI,eAAe,OAAQ,QAAO,OAAO,UAAU,IAAI,EAAE;AACzD,KAAI,gBAAgB,OAAQ,QAAO,OAAO,WAAW;;AAGvD,eAAe,QACb,QACA,IACA,SACA,MACiB;AACjB,KAAI,CAAC,WAAW,uBAAwB,QAAO,CAAC,KAAK,EAAE,OAAO,4BAA4B,CAAC;AAC3F,KAAI,CAAC,MAAM,IAAI,QAAQ,CAAE,QAAO,CAAC,KAAK,EAAE,OAAO,iEAAiE,CAAC;AACjH,KAAI,WAAW,MAAO,QAAO,CAAC,KAAK,UAAU,CAAC;AAC9C,KAAI,WAAW,OAAQ,QAAO,CAAC,KAAK,EAAE,OAAO,OAAO,CAAC;CAErD,MAAM,OAAO,MAAM,MAAM,MAAM,CAAC,YAAY,GAAG,CAAC;AAEhD,KAAI,CAAC,KAAM,QAAO,CAAC,KAAK,EAAE,OAAO,iDAAiD,CAAC;CAEnF,IAAI;CACJ,MAAM,SAAS,IAAI,SAAoB,YAAa,QAAQ,WAAW,SAAS,aAAa,CAAE;CAC/F,MAAM,SAA6B,MAAM,QAAQ,KAAK,CAAC,OAAO,KAAK,EAAE,OAAO,CAAC;AAE7E,cAAa,MAAM;AAEnB,KAAI,CAAC,OAAQ,QAAO,CAAC,KAAK,EAAE,OAAO,wBAAwB,CAAC;AAC5D,KAAI,OAAO,MAAO,QAAO,CAAC,OAAO,UAAU,KAAK,EAAE,OAAO,OAAO,OAAO,CAAC;AAExE,QAAO,CAAC,KAAK,OAAO,MAAM;;AAG5B,SAAS,WAAW;CAClB,MAAM,UAAW,WAA8E;AAE/F,QAAO;EACL,SAAS;EACT,KAAK,SAAS,OAAO;EACrB,KAAK,SAAS,OAAO,IAAI;EACzB,SAAS,KAAK,MAAM,YAAY,WAAW;EAC3C,SAAS,WAAW,WAAW,aAAa;EAC5C,OAAO,SAAS,SAAS;EAC1B"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Summary, C as parsePath, D as Level, E as Frame, O as Options, S as Select, T as Event, _ as tree, a as act, b as resolve, c as detach, d as health, f as instances, g as set, h as roots, i as Node, k as Query, l as find, m as orphans, n as Instance, o as attach, p as models, r as ModelInfo, s as call, t as Health, u as get, v as TypeInfo, w as serialize, x as Act, y as label } from "./inspect-3AOGnw9P.js";
1
+ import { A as Summary, C as parsePath, D as Level, E as Frame, O as Options, S as Select, T as Event, _ as tree, a as act, b as resolve, c as detach, d as health, f as instances, g as set, h as roots, i as Node, k as Query, l as find, m as orphans, n as Instance, o as attach, p as models, r as ModelInfo, s as call, t as Health, u as get, v as TypeInfo, w as serialize, x as Act, y as label } from "./inspect-SOZyvcTx.js";
2
2
 
3
3
  //#region src/index.d.ts
4
4
  declare const journal: {
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as label, a as clearCaught, b as serialize, c as get, d as models, f as orphans, g as journal$1, h as tree, i as call, l as health, m as set, n as act, o as detach, p as roots, r as attach, s as find, t as Instance, u as instances, v as resolve, y as parsePath } from "./inspect-D7_PFXdY.js";
1
+ import { _ as label, a as clearCaught, b as serialize, c as get, d as models, f as orphans, g as journal$1, h as tree, i as call, l as health, m as set, n as act, o as detach, p as roots, r as attach, s as find, t as Instance, u as instances, v as resolve, y as parsePath } from "./inspect-DhwL0EX2.js";
2
2
 
3
3
  //#region src/index.ts
4
4
  const journal = {
@@ -1,4 +1,4 @@
1
- import { i as unsettled, n as tick, r as unreached, t as bracket } from "./bracket-D3xwitlE.js";
1
+ import { i as unsettled, n as tick, r as unreached, t as bracket } from "./bracket-iTnJYPw-.js";
2
2
  import { Context, Model, unbind } from "@expressive/mvc";
3
3
  import { listener, observer } from "@expressive/mvc/observable";
4
4
  import { isElement } from "@expressive/mvc/jsx-runtime";
@@ -128,6 +128,7 @@ function labelOf(Type) {
128
128
  if (named) return named;
129
129
  return Type.name.length > 2 ? Type.name : row.typeId;
130
130
  }
131
+ /** Name a class for addresses and the journal - wins over `displayName`, `resolve()` names and the class name. */
131
132
  function label(Type, name) {
132
133
  labels.set(Type, name);
133
134
  }
@@ -567,6 +568,11 @@ var Instance = class Instance {
567
568
  });
568
569
  }
569
570
  };
571
+ /**
572
+ * Observe every instance of `Type` set up from now on; returns its detach.
573
+ *
574
+ * Default `Model`, so every class. Repeat calls for a class reuse the first. Instances set up before it stay unregistered.
575
+ */
570
576
  function attach(Type = Model) {
571
577
  if (!unwatch) watchCopies();
572
578
  if (!hooks.has(Type)) {
@@ -631,6 +637,7 @@ function attach(Type = Model) {
631
637
  hooks.delete(Type);
632
638
  };
633
639
  }
640
+ /** Stop observing every class and reset the registry, journal, labels and health counts. */
634
641
  function detach() {
635
642
  for (const stop of hooks.values()) stop();
636
643
  hooks.clear();
@@ -661,6 +668,7 @@ function find(target) {
661
668
  if (types.size > 1) throw new Error(`${target} matches ${types.size} classes (${[...types.values()].join(", ")}) - address by instance id or owner path, or label() one. models() lists their construction sites.`);
662
669
  return first && Instance.of(first);
663
670
  }
671
+ /** Every mainline instance - claimed, or too young to judge; orphans excluded. */
664
672
  function instances() {
665
673
  return [...mainline()].map(Instance.of);
666
674
  }
@@ -681,14 +689,17 @@ function health() {
681
689
  caught: { ...tally }
682
690
  };
683
691
  }
692
+ /** Mainline instances with no owner. */
684
693
  function roots() {
685
694
  const parents = ownership();
686
695
  return instances().filter((instance) => !parents.has(instance.state));
687
696
  }
697
+ /** One row per mainline instance, with its parent's id. */
688
698
  function models() {
689
699
  const parents = ownership();
690
700
  return [...mainline()].map((state) => describe(state, parents));
691
701
  }
702
+ /** Mainline instances nested by ownership. */
692
703
  function tree() {
693
704
  const parents = ownership();
694
705
  const nodes = /* @__PURE__ */ new Map();
@@ -716,11 +727,21 @@ async function act(work, options = {}) {
716
727
  if (!settled) unsettled(timeout);
717
728
  return frames;
718
729
  }
730
+ /**
731
+ * Stored value at an address - `Type.path` or `id.path` - serialized, with no accessor fired.
732
+ *
733
+ * No address returns `models()`. An address naming no instance returns `undefined`.
734
+ */
719
735
  function get(address, select) {
720
736
  if (!address) return models();
721
737
  const { target, path } = parsePath(address);
722
738
  return find(target)?.get(path, select);
723
739
  }
740
+ /**
741
+ * Assign at an address - a Model field, a `Map` key or an object property.
742
+ *
743
+ * Throws `No model at …` when the address resolves to nothing.
744
+ */
724
745
  function set(address, value) {
725
746
  const { target, path } = parsePath(address);
726
747
  const instance = find(target);
@@ -732,6 +753,11 @@ function set(address, value) {
732
753
  if (owner instanceof Map) owner.set(key, value);
733
754
  else owner[key] = value;
734
755
  }
756
+ /**
757
+ * Call a method by address; resolves to its result, serialized.
758
+ *
759
+ * Throws `No method at …` when the key is not a function.
760
+ */
735
761
  async function call(address, ...args) {
736
762
  const { target, path } = parsePath(address);
737
763
  const state = find(target)?.state;
@@ -820,4 +846,4 @@ function hold(holders, holder, value) {
820
846
 
821
847
  //#endregion
822
848
  export { label as _, clearCaught as a, serialize as b, get as c, models as d, orphans as f, journal as g, tree as h, call as i, health as l, set as m, act as n, detach as o, roots as p, attach as r, find as s, Instance as t, instances as u, resolve as v, parsePath as y };
823
- //# sourceMappingURL=inspect-D7_PFXdY.js.map
849
+ //# sourceMappingURL=inspect-DhwL0EX2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inspect-DhwL0EX2.js","names":[],"sources":["../src/serialize.ts","../src/types.ts","../src/journal.ts","../src/inspect.ts"],"sourcesContent":["import { Model } from '@expressive/mvc';\n\nconst MAX_STRING = 240;\nconst MAX_ARRAY = 24;\nconst MAX_KEYS = 40;\n\nexport type Address = { target: string; path?: string };\n\nexport function parsePath(raw: string): Address {\n const trimmed = raw.trim();\n const dot = trimmed.indexOf('.');\n if (dot <= 0) return { target: trimmed };\n return { target: trimmed.slice(0, dot), path: trimmed.slice(dot + 1) };\n}\n\n/** Raw stored entries of a Model - never reads through accessors. */\nexport function entries(state: Model): Map<string, unknown> {\n return new Map(state);\n}\n\n/** Walk `path` without triggering getters, factories, or suspense. */\nexport function walk(value: unknown, path?: string): unknown {\n if (!path) return value;\n let cur: unknown = value;\n for (const part of path.split('.')) {\n if (cur == null || typeof cur !== 'object') return undefined;\n if (cur instanceof Model)\n cur = part[0] == '_' ? Object.getOwnPropertyDescriptor(cur, part)?.get?.() : entries(cur).get(part);\n else if (cur instanceof Map) cur = cur.get(part);\n else cur = (cur as Record<string, unknown>)[part];\n }\n return cur;\n}\n\nexport function ref(state: Model) {\n return { $ref: String(state), $type: state.constructor.name };\n}\n\n/** `true` takes a value as `serialize` would; an object picks keys and descends, applying to each element of a list. */\nexport type Select = true | { [key: string]: Select };\n\n/** Only the selected keys, read in one synchronous pass - a consistent snapshot. Models keep their `$ref`. */\nexport function project(value: unknown, select: Select): unknown {\n if (select === true || value == null || typeof value !== 'object') return serialize(value);\n\n const items = value instanceof Model ? undefined : list(value);\n\n if (items) {\n const out = items.slice(0, MAX_ARRAY).map((row) => project(row, select));\n if (items.length > MAX_ARRAY) out.push(`…+${items.length - MAX_ARRAY}`);\n return out;\n }\n\n const out: Record<string, unknown> = value instanceof Model ? ref(value) : {};\n for (const key in select) out[key] = project(walk(value, key), select[key]);\n return out;\n}\n\n/** JSON-safe, size-capped view. Nested Models collapse to `$ref`. */\nexport function serialize(value: unknown, depth = 2): unknown {\n if (value instanceof Model) {\n const out: Record<string, unknown> = ref(value);\n for (const [key, child] of [...entries(value)].slice(0, MAX_KEYS))\n out[key] = write(child, depth - 1);\n return out;\n }\n return write(value, depth);\n}\n\nfunction write(value: unknown, depth: number): unknown {\n if (value == null || typeof value === 'boolean') return value;\n if (typeof value === 'number') return Number.isFinite(value) ? value : String(value);\n if (typeof value === 'string')\n return value.length > MAX_STRING ? `${value.slice(0, MAX_STRING - 1)}…` : value;\n if (typeof value === 'bigint') return `${value}n`;\n if (typeof value !== 'object') return undefined;\n if (value instanceof Model) return ref(value);\n if (value instanceof Date) return value.toISOString();\n if (value instanceof Error) return { name: value.name, message: value.message };\n if (typeof (value as PromiseLike<unknown>).then === 'function') return '(pending)';\n\n const items = list(value);\n\n if (items) {\n if (depth <= 0) return `[${items.length}]`;\n const out = items.slice(0, MAX_ARRAY).map((row) => write(row, depth - 1));\n if (items.length > MAX_ARRAY) out.push(`…+${items.length - MAX_ARRAY}`);\n return out;\n }\n\n const pairs = value instanceof Map\n ? [...value].map(([k, v]) => [String(k), v] as const)\n : Object.entries(value);\n\n if (depth <= 0) return `{${pairs.length}}`;\n\n const out: Record<string, unknown> = {};\n for (const [key, child] of pairs.slice(0, MAX_KEYS)) {\n if (key === 'is') continue;\n const next = write(child, depth - 1);\n if (next !== undefined) out[key] = next;\n }\n if (pairs.length > MAX_KEYS) out['…'] = pairs.length - MAX_KEYS;\n return out;\n}\n\nfunction list(value: object): unknown[] | undefined {\n if (Array.isArray(value)) return value;\n if (value instanceof Map) return undefined;\n if (typeof (value as Iterable<unknown>)[Symbol.iterator] === 'function')\n return [...(value as Iterable<unknown>)];\n return undefined;\n}\n","import { Model } from '@expressive/mvc';\n\nexport interface TypeInfo {\n /** Opaque, stable for the life of the process. */\n typeId: string;\n /** Resolved display name - see `label`. */\n type: string;\n /** Construction stack captured at first sight, for a source-map resolver. */\n site: string;\n}\n\nconst info = new Map<typeof Model, TypeInfo>();\nconst labels = new Map<typeof Model, string>();\nconst names = new Map<string, string>();\nlet count = 0;\n\nfunction register(Type: typeof Model): TypeInfo {\n let row = info.get(Type);\n if (!row) {\n const site = String(new Error().stack).split('\\n').slice(1, 16).join('\\n');\n info.set(Type, (row = { typeId: `T${++count}`, type: '', site }));\n }\n return row;\n}\n\nexport function seen(Type: typeof Model): TypeInfo {\n const row = register(Type);\n row.type = labelOf(Type);\n return { ...row };\n}\n\nexport function labelOf(Type: typeof Model): string {\n const row = register(Type);\n const explicit = labels.get(Type) ?? (Type as { displayName?: string }).displayName;\n if (explicit) return explicit;\n const named = names.get(row.typeId) ?? names.get(row.site);\n if (named) return named;\n return Type.name.length > 2 ? Type.name : row.typeId;\n}\n\n/** Name a class for addresses and the journal - wins over `displayName`, `resolve()` names and the class name. */\nexport function label(Type: typeof Model, name: string): void {\n labels.set(Type, name);\n}\n\n/** Supply resolved names keyed by `typeId` or `site`, e.g. from a source-map pass. */\nexport function resolve(table: Record<string, string>): void {\n for (const [key, name] of Object.entries(table)) names.set(key, name);\n}\n\nexport function forget(): void {\n info.clear();\n labels.clear();\n names.clear();\n count = 0;\n}\n","import { Model } from '@expressive/mvc';\n\nimport { parsePath, serialize } from './serialize';\nimport { labelOf, seen } from './types';\n\nexport type Level = 'off' | 'keys' | 'values';\n\nexport interface Options {\n level?: Level;\n /** Labels to record. */\n types?: string[];\n /** `Type.key` addresses to record - label, `typeId`, or instance id on the left, property on the right. */\n paths?: string[];\n /** Property names to record on any type. */\n keys?: string[];\n /** Also record method calls, except `render`. */\n calls?: boolean;\n}\n\nexport interface Event {\n id: string;\n type: string;\n key: string;\n kind: 'update' | 'event' | 'call' | 'destroy' | 'caught' | 'hot';\n value?: unknown;\n args?: unknown[];\n}\n\nexport interface Frame {\n seq: number;\n at: number;\n /** Frame whose flush scheduled the work that opened this one. */\n cause?: number;\n events: Event[];\n}\n\nexport interface Summary {\n id: string;\n type: string;\n /** Seq of the last frame touching this instance. */\n last: number;\n /** Updates and events per key, with the last recorded value at `values` level. */\n keys: Record<string, { count: number; value?: unknown }>;\n calls: Record<string, number>;\n /** `caught` reports. */\n caught: number;\n /** Hot patches applied to it. */\n hot: number;\n destroyed: boolean;\n}\n\nexport interface Query {\n since?: number;\n type?: string;\n id?: string;\n key?: string;\n cause?: number;\n}\n\nconst FRAME_CAP = 500;\n\nconst frames: Frame[] = [];\nconst config: Required<Options> = { level: 'off', types: [], paths: [], keys: [], calls: false };\nlet seq = 0;\nlet open: Frame | undefined;\nlet cause: number | undefined;\n\nexport const journal = {\n /**\n * Merge recording options; returns the effective settings.\n *\n * Filters OR together; none set records everything. `calls: true` alone lifts `level` from `off` to `keys`.\n */\n record(options: Options = {}): Required<Options> {\n Object.assign(config, options);\n if (!options.level && options.calls && config.level === 'off') config.level = 'keys';\n return { ...config, types: [...config.types], paths: [...config.paths], keys: [...config.keys] };\n },\n\n frames(query: Query = {}): Frame[] {\n const out: Frame[] = [];\n for (const frame of frames) {\n if (query.since !== undefined && frame.seq <= query.since) continue;\n if (query.cause !== undefined && frame.cause !== query.cause) continue;\n const events = frame.events.filter((e) => matches(e, query));\n if (events.length) out.push({ ...frame, events });\n }\n return out;\n },\n\n history(query: Query): Array<{ seq: number; at: number; event: Event }> {\n const out = [];\n for (const frame of journal.frames(query))\n for (const event of frame.events) out.push({ seq: frame.seq, at: frame.at, event });\n return out;\n },\n\n /** Frames reachable from `seq` through `cause` links, in order. */\n downstream(from: number): Frame[] {\n const roots = new Set([from]);\n return frames.filter((frame) => {\n if (frame.cause === undefined || !roots.has(frame.cause)) return false;\n roots.add(frame.seq);\n return true;\n });\n },\n\n /** Current sequence - pass as `since` to read only what follows. */\n seq(): number {\n return seq;\n },\n\n /** One event per line, for bulk export to a sidecar. */\n export(query: Query = {}): string {\n return journal\n .frames(query)\n .flatMap((frame) =>\n frame.events.map((event) =>\n JSON.stringify({ seq: frame.seq, at: frame.at, cause: frame.cause, ...event })\n )\n )\n .join('\\n');\n },\n\n /** Per-instance digest of recorded frames, most recently active first. */\n summary(query: Query = {}): Summary[] {\n const by = new Map<string, Summary>();\n\n for (const frame of journal.frames(query))\n for (const event of frame.events) {\n if (!event.id) continue;\n\n let entry = by.get(event.id);\n\n if (!entry) by.set(event.id, (entry = { id: event.id, type: event.type, last: 0, keys: {}, calls: {}, caught: 0, hot: 0, destroyed: false }));\n\n entry.last = frame.seq;\n\n if (event.kind === 'destroy') entry.destroyed = true;\n else if (event.kind === 'call') entry.calls[event.key] = (entry.calls[event.key] || 0) + 1;\n else if (event.kind === 'caught') entry.caught++;\n else if (event.kind === 'hot') entry.hot++;\n else {\n const key = (entry.keys[event.key] ||= { count: 0 });\n key.count++;\n if ('value' in event) key.value = event.value;\n }\n }\n\n return [...by.values()].sort((a, b) => b.last - a.last);\n },\n\n /**\n * Record a page-level hot update: `key` names it (`update`, `reload`), `value`\n * its detail. Recorded unfiltered while the journal is on.\n */\n hot(key: string, value?: unknown): void {\n if (config.level === 'off') return;\n\n const event: Event = { id: '', type: 'vite', key, kind: 'hot' };\n if (value !== undefined) event.value = value;\n push(event);\n },\n\n clear(): void {\n frames.length = 0;\n open = undefined;\n cause = undefined;\n seq = 0;\n },\n\n reset(): void {\n journal.clear();\n Object.assign(config, { level: 'off', types: [], paths: [], keys: [], calls: false });\n }\n};\n\nfunction matches(event: Event, query: Query) {\n return (\n (!query.type || event.type === query.type) &&\n (!query.id || event.id === query.id) &&\n (!query.key || event.key === query.key)\n );\n}\n\n/** Filters OR together; none set records everything. Without a key only type-level filters apply. */\nexport function wants(state: Model, key?: string): boolean {\n if (config.level === 'off') return false;\n\n const { types, paths, keys } = config;\n if (!types.length && !paths.length && !keys.length) return true;\n\n const Type = state.constructor as typeof Model;\n const label = labelOf(Type);\n if (types.includes(label)) return true;\n if (key !== undefined && keys.includes(key)) return true;\n\n const targets = [label, seen(Type).typeId, String(state)];\n for (const address of paths) {\n const { target, path } = parsePath(address);\n if (targets.includes(target) && (key === undefined || path === key)) return true;\n }\n return false;\n}\n\nexport function recordsCalls(): boolean {\n return config.calls && config.level !== 'off';\n}\n\n\nexport function note(state: Model, key: unknown, store: Map<string, unknown>): void {\n const name = String(key);\n if (!wants(state, name)) return;\n\n const event: Event = {\n id: String(state),\n type: labelOf(state.constructor as typeof Model),\n key: name,\n kind: typeof key === 'string' && store.has(key) ? 'update' : 'event'\n };\n\n if (config.level === 'values' && event.kind === 'update')\n event.value = serialize(store.get(name), 1);\n\n push(event);\n}\n\nexport function noteCall(state: Model, key: string, args: unknown[]): void {\n if (!recordsCalls() || !wants(state, key)) return;\n\n const event: Event = { id: String(state), type: labelOf(state.constructor as typeof Model), key, kind: 'call' };\n if (config.level === 'values') event.args = args.map((arg) => serialize(arg, 1));\n push(event);\n}\n\nexport function noteCaught(state: Model, error: unknown, kind: string, key?: string): { handled: boolean } | undefined {\n if (!wants(state, key)) return;\n const value = {\n case: kind,\n message: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n handled: true\n };\n push({ id: String(state), type: labelOf(state.constructor as typeof Model), key: key ?? '', kind: 'caught', value });\n return value;\n}\n\nexport function notePatch(state: Model): void {\n if (wants(state)) push({ id: String(state), type: labelOf(state.constructor as typeof Model), key: 'patch', kind: 'hot' });\n}\n\nexport function noteDestroy(state: Model): void {\n if (!wants(state)) return;\n push({ id: String(state), type: labelOf(state.constructor as typeof Model), key: '', kind: 'destroy' });\n}\n\nfunction push(event: Event) {\n if (!open) {\n const frame: Frame = { seq: ++seq, at: Date.now(), events: [] };\n if (cause !== undefined) frame.cause = cause;\n open = frame;\n frames.push(frame);\n if (frames.length > FRAME_CAP) frames.splice(0, frames.length - FRAME_CAP);\n queueMicrotask(() => {\n open = undefined;\n cause = frame.seq;\n queueMicrotask(() => {\n if (seq === frame.seq) cause = undefined;\n });\n });\n }\n open.events.push(event);\n}\n","import { Context, Model, unbind } from '@expressive/mvc';\nimport { listener, observer } from '@expressive/mvc/observable';\nimport { isElement } from '@expressive/mvc/jsx-runtime';\n\nimport { journal, note, noteCall, noteCaught, noteDestroy, notePatch, type Frame, type Query } from './journal';\nimport { entries, parsePath, project, serialize, walk, type Select } from './serialize';\nimport { bracket } from './bracket';\nimport { tick, unreached, unsettled, type Act } from './settle';\nimport { forget, seen, type TypeInfo } from './types';\n\nexport interface ModelInfo extends TypeInfo {\n id: string;\n parent?: string;\n /** Keys with a stored value. */\n keys: string[];\n /** Declared keys with no stored value yet - lazy, pending, or uncomputed. */\n absent: string[];\n}\n\nexport interface Node {\n id: string;\n type: string;\n children: Node[];\n}\n\ninterface Span {\n since: number;\n until?: number;\n claimed: boolean;\n settled: boolean;\n held?: boolean;\n}\n\ninterface Row {\n ref: { deref(): Model | undefined };\n held?: Model;\n}\n\nconst Reaper: typeof FinalizationRegistry =\n typeof FinalizationRegistry === 'function'\n ? FinalizationRegistry\n : (class {\n register() {}\n unregister() {}\n } as unknown as typeof FinalizationRegistry);\n\nconst weak = (state: Model): Row['ref'] =>\n typeof WeakRef === 'function' ? new WeakRef(state) : { deref: () => state };\n\nconst live = new Map<string, Row>();\nconst hooks = new Map<typeof Model, () => void>();\n\nconst COPIES = Symbol.for('@expressive/mvc');\n\nconst REFRESH = Symbol.for('@expressive/mvc.refresh');\nconst wrappers = new WeakMap<Model, Instance>();\nconst spans = new WeakMap<Model, Span>();\nconst reaper = new Reaper<string>(collected);\n\nlet version = 0;\nlet cached: { version: number; owners: Map<Model, Model>; holders: Map<Model, Model> } | undefined;\nlet lost = 0;\nlet tally = counts();\nlet copies = 1;\nlet unwatch: (() => void) | undefined;\n\nfunction counts(): Record<string, number> {\n return { dead: 0, unused: 0, getter: 0, setup: 0, effect: 0 };\n}\n\n/** The report `observe` last saw - the chain is synchronous, so `unhandled` checks it against its own. */\nlet last: { error: unknown; event?: { handled: boolean } } | undefined;\n\nfunction observe(this: Model, error: unknown, kind: string, key?: string) {\n tally[kind]++;\n last = { error, event: noteCaught(this, error, kind, key) };\n return error;\n}\n\nfunction unhandled(this: Model, error: unknown, kind: string, key?: string) {\n if (last?.error !== error) observe.call(this, error, kind, key);\n if (last!.event) last!.event.handled = false;\n last = undefined;\n return error;\n}\n\nexport function clearCaught(): void {\n tally = counts();\n}\n\n/** Count loaded copies of mvc from the list each one joins on first construction; warn once on a second. */\nfunction watchCopies() {\n const list = ((globalThis as { [COPIES]?: unknown[] })[COPIES] ||= []);\n const { push } = list;\n const check = () => {\n const was = copies;\n copies = new Set([Model, ...list]).size;\n if (copies > 1 && was === 1)\n console.warn(`${copies} copies of @expressive/mvc are loaded - inspect sees only the one it imports.`);\n };\n\n list.push = (...items) => {\n const length = push.apply(list, items);\n check();\n return length;\n };\n\n check();\n unwatch = () => {\n list.push = push;\n };\n}\n\n/** Registered instances still reachable, claimed or not. */\nfunction registered(): Model[] {\n return [...live.values()]\n .map((row) => row.held ?? row.ref.deref())\n .filter((state): state is Model => !!state);\n}\n\n/** Instances on the mainline: claimed, or too young to judge, or every one when no host renders. */\nfunction* mainline(): Generator<Model> {\n const parents = reach();\n for (const state of registered()) if (!orphaned(state, parents)) yield state;\n}\n\nfunction orphaned(state: Model, parents: Map<Model, Model>, seen = new Set<Model>()): boolean {\n const span = spans.get(state)!;\n if (span.claimed || !span.settled || !hosted()) return false;\n if (provided(state)) {\n claim(state);\n return false;\n }\n const owner = parents.get(state);\n if (!owner || seen.has(owner)) return true;\n seen.add(state);\n if (orphaned(owner, parents, seen)) return true;\n if (spans.get(owner)!.claimed) claim(state);\n return false;\n}\n\nfunction claim(state: Model) {\n const span = spans.get(state)!;\n if (span.claimed) return;\n span.claimed = true;\n const row = live.get(String(state));\n if (!row) return;\n row.held = state;\n reaper.unregister(state);\n version++;\n}\n\n/** An instance held in the root context. */\nfunction provided(state: Model): boolean {\n for (const set of Context.root.provide.values())\n if (set) for (const [member] of set) if (member === state) return true;\n return false;\n}\n\nfunction hosted(): boolean {\n try {\n isElement(null);\n return true;\n } catch {\n return false;\n }\n}\n\n/** A registered, unclaimed instance was garbage collected - it was abandoned. */\nexport function collected(id: string): void {\n if (!live.delete(id)) return;\n lost++;\n version++;\n}\n\n/** Navigable view of one instance - identity, ownership, reads, observation. One per state; outlives it. */\nexport class Instance {\n private constructor(readonly state: Model) {}\n\n static of(state: Model): Instance {\n let instance = wrappers.get(state);\n if (!instance) wrappers.set(state, (instance = new Instance(state)));\n return instance;\n }\n\n get id() {\n return String(this.state);\n }\n\n get type() {\n return seen(this.state.constructor as typeof Model).type;\n }\n\n get alive() {\n return live.has(this.id);\n }\n\n /** Reached by a host commit (`mount`), a claimed owner, or the root context. Always true without a host. */\n get claimed() {\n return !orphaned(this.state, reach());\n }\n\n /** Registration time (ms). */\n get since() {\n return spans.get(this.state)!.since;\n }\n\n /** Destruction time (ms), once destroyed. */\n get until() {\n return spans.get(this.state)!.until;\n }\n\n get parent(): Instance | undefined {\n const owner = ownership().get(this.state);\n return owner && Instance.of(owner);\n }\n\n get children(): Instance[] {\n const parents = ownership();\n return [...registered()]\n .filter((state) => parents.get(state) === this.state)\n .map(Instance.of);\n }\n\n /** First instance in this subtree, depth-first, matching `where` (a label or predicate). */\n find(where: string | ((instance: Instance) => boolean)): Instance | undefined {\n const test = typeof where === 'string' ? (h: Instance) => h.type === where : where;\n for (const child of this.children) {\n if (test(child)) return child;\n const deep = child.find(test);\n if (deep) return deep;\n }\n return undefined;\n }\n\n get(path?: string, select?: Select): unknown {\n const value = walk(this.state, path);\n return select ? project(value, select) : serialize(value);\n }\n\n model(): ModelInfo {\n return describe(this.state, ownership());\n }\n\n /** Run `work`, settle, and return the frames it produced. */\n act(work: (state: Model) => unknown, options?: Act): Promise<Frame[]> {\n return act(() => work(this.state), options);\n }\n\n /** Call `fn` on each update, and with `null` on destroy; `keys` narrows updates. Returns unsubscribe. */\n watch(fn: (key: string | null) => void, keys?: string[]): () => void {\n const updates = this.state.set((key) => {\n if (typeof key === 'string' && (!keys || keys.includes(key))) fn(key);\n });\n const destroy = this.state.get(null, () => fn(null));\n return () => {\n updates();\n destroy();\n };\n }\n\n frames(query: Query = {}): Frame[] {\n return journal.frames({ ...query, id: this.id });\n }\n}\n\n/**\n * Observe every instance of `Type` set up from now on; returns its detach.\n *\n * Default `Model`, so every class. Repeat calls for a class reuse the first. Instances set up before it stay unregistered.\n */\nexport function attach(Type: typeof Model = Model): () => void {\n if (!unwatch) watchCopies();\n\n if (!hooks.has(Type)) {\n const observed = new Map<typeof Model, () => void>();\n const stopCatch = Type.on({ catch: unhandled });\n const stopCall = Type.on({ type: trace, method: retrace });\n const stopSetup = Type.on({\n ready(this: Model) {\n const self = this.is;\n if (spans.get(self)!.held) claim(self);\n },\n setup(this: Model) {\n const self = this.is;\n const T = self.constructor as typeof Model;\n const id = String(self);\n const span: Span = { since: Date.now(), claimed: false, settled: false };\n if (!observed.has(T)) observed.set(T, T.on({ catch: observe }));\n seen(T);\n live.set(id, { ref: weak(self) });\n spans.set(self, span);\n reaper.register(self, id, self);\n setTimeout(() => {\n span.settled = true;\n }, 0);\n queueMicrotask(() => {\n span.held = !!observer(self)?.wait;\n });\n version++;\n const unpatch = listener(self, () => notePatch(self), REFRESH);\n const stop = self.set((key) => {\n const store = entries(self);\n if (typeof key === 'string' && typeof store.get(key) === 'object') version++;\n note(self, key, store);\n });\n return () => {\n stop();\n unpatch();\n live.delete(id);\n reaper.unregister(self);\n span.until = Date.now();\n version++;\n noteDestroy(self);\n };\n }\n });\n hooks.set(Type, () => {\n for (const stop of observed.values()) stop();\n stopCatch();\n stopCall();\n stopSetup();\n });\n }\n\n return () => {\n hooks.get(Type)?.();\n hooks.delete(Type);\n };\n}\n\n/** Stop observing every class and reset the registry, journal, labels and health counts. */\nexport function detach(): void {\n for (const stop of hooks.values()) stop();\n hooks.clear();\n live.clear();\n cached = undefined;\n lost = 0;\n tally = counts();\n copies = 1;\n unwatch?.();\n unwatch = undefined;\n journal.reset();\n forget();\n}\n\n/** Resolve an id or label to an instance - mainline first, then orphans. */\nexport function find(target: string): Instance | undefined {\n const byId = live.get(target);\n const held = byId && (byId.held ?? byId.ref.deref());\n if (held) return Instance.of(held);\n\n const types = new Map<typeof Model, string>();\n let first: Model | undefined;\n\n for (const pool of [mainline(), abandoned()])\n for (const state of pool) {\n const Type = state.constructor as typeof Model;\n const info = seen(Type);\n if (info.type !== target) continue;\n first ??= state;\n types.set(Type, info.typeId);\n }\n\n if (types.size > 1)\n throw new Error(\n `${target} matches ${types.size} classes (${[...types.values()].join(', ')}) - address by instance id or owner path, or label() one. models() lists their construction sites.`\n );\n\n return first && Instance.of(first);\n}\n\n/** Every mainline instance - claimed, or too young to judge; orphans excluded. */\nexport function instances(): Instance[] {\n return [...mainline()].map(Instance.of);\n}\n\n/** Registered and settled, but never claimed by a host commit, an owner, or root context. */\nexport function orphans(): Instance[] {\n return [...abandoned()].map(Instance.of);\n}\n\nfunction* abandoned(): Generator<Model> {\n const parents = reach();\n for (const state of registered()) if (orphaned(state, parents)) yield state;\n}\n\nexport interface Health {\n /** Live instances no host, owner, or root slot claimed. */\n orphans: number;\n /** Unclaimed instances the collector already reaped. */\n collected: number;\n /** Loaded copies of `@expressive/mvc` - more than 1 means inspect cannot see every Model. */\n copies: number;\n /** Reports by kind, including ones an app handler went on to handle; zeroed by `journal.clear()`. */\n caught: Record<string, number>;\n}\n\n/** Counts worth a look before trusting what inspect shows. */\nexport function health(): Health {\n return { orphans: orphans().length, collected: lost, copies, caught: { ...tally } };\n}\n\n/** Mainline instances with no owner. */\nexport function roots(): Instance[] {\n const parents = ownership();\n return instances().filter((instance) => !parents.has(instance.state));\n}\n\n/** One row per mainline instance, with its parent's id. */\nexport function models(): ModelInfo[] {\n const parents = ownership();\n return [...mainline()].map((state) => describe(state, parents));\n}\n\n/** Mainline instances nested by ownership. */\nexport function tree(): Node[] {\n const parents = ownership();\n const nodes = new Map<Model, Node>();\n const out: Node[] = [];\n\n for (const state of mainline())\n nodes.set(state, { id: String(state), type: seen(state.constructor as typeof Model).type, children: [] });\n\n for (const [state, node] of nodes) {\n const parent = parents.get(state);\n const owner = parent && nodes.get(parent);\n if (owner) owner.children.push(node);\n else out.push(node);\n }\n\n return out;\n}\n\n/** Run `work` recording values; returns the frames it produced once `until` holds and activity goes quiet. */\nexport async function act(work: () => unknown, options: Act = {}): Promise<Frame[]> {\n const { frames, settled, pending, missing, timeout } = await bracket({ ...journal, get }, work, tick, options, true);\n if (pending.length) throw unreached(timeout, pending, missing, frames);\n if (!settled) unsettled(timeout);\n return frames;\n}\n\n/**\n * Stored value at an address - `Type.path` or `id.path` - serialized, with no accessor fired.\n *\n * No address returns `models()`. An address naming no instance returns `undefined`.\n */\nexport function get(address?: string, select?: Select): unknown {\n if (!address) return models();\n const { target, path } = parsePath(address);\n return find(target)?.get(path, select);\n}\n\n/**\n * Assign at an address - a Model field, a `Map` key or an object property.\n *\n * Throws `No model at …` when the address resolves to nothing.\n */\nexport function set(address: string, value: unknown): void {\n const { target, path } = parsePath(address);\n const instance = find(target);\n if (!instance || !path) throw new Error(`No model at ${address}.`);\n\n const dot = path.lastIndexOf('.');\n const key = path.slice(dot + 1);\n const owner = dot < 0 ? instance.state : walk(instance.state, path.slice(0, dot));\n\n if (owner == null || typeof owner !== 'object') throw new Error(`No model at ${address}.`);\n\n if (owner instanceof Map) owner.set(key, value);\n else (owner as Record<string, unknown>)[key] = value;\n}\n\n/**\n * Call a method by address; resolves to its result, serialized.\n *\n * Throws `No method at …` when the key is not a function.\n */\nexport async function call(address: string, ...args: unknown[]): Promise<unknown> {\n const { target, path } = parsePath(address);\n const state = find(target)?.state;\n const method = state && path && (state as unknown as Record<string, unknown>)[path];\n\n if (typeof method !== 'function') throw new Error(`No method at ${address}.`);\n\n return serialize(await method.apply(state, args));\n}\n\nconst TRACED = new WeakSet<Function>();\n\n/** Wrap a class's own methods before they bind, so each call is recorded. */\nfunction trace(type: typeof Model) {\n const proto = type.prototype as unknown as Record<string, Function>;\n\n for (const [key, desc] of Object.entries(Object.getOwnPropertyDescriptors(proto)))\n if (key != 'constructor' && key != 'render' && typeof desc.value == 'function' && desc.configurable)\n proto[key] = traced(key, desc.value);\n}\n\n/**\n * Rebind a method replaced through `set()` to a traced copy, so `unbind` still yields a function honoring `this`.\n * A class bootstrapped before attach keeps its methods untraced - wrapped per instance, a hot patch would keep them.\n */\nfunction retrace(this: Model, key: string, fn: Function) {\n const source = unbind(fn);\n let proto = Object.getPrototypeOf(this);\n\n while (!Object.prototype.hasOwnProperty.call(proto, key)) proto = Object.getPrototypeOf(proto);\n\n if (key == 'render' || TRACED.has(source) || source === unbind(Object.getOwnPropertyDescriptor(proto, key)!.get!)) return;\n\n const self = this as unknown as Record<string, Function>;\n\n delete self[key];\n self[key] = traced(key, source);\n}\n\n/** A `super` call reaches the base wrapper too; only the one `this[key]` resolves to records. */\nfunction traced(key: string, fn: Function) {\n const wrapper = Object.defineProperties(\n function (this: Record<string, Function>, ...args: unknown[]) {\n if (unbind(this[key]) === wrapper) noteCall(this as unknown as Model, key, args);\n return fn.apply(this, args);\n },\n { name: { value: fn.name }, length: { value: fn.length } }\n );\n\n TRACED.add(wrapper);\n\n return wrapper;\n}\n\nfunction describe(state: Model, parents: Map<Model, Model>): ModelInfo {\n const stored = entries(state);\n const declared = Object.entries(Object.getOwnPropertyDescriptors(state))\n .filter(([, desc]) => typeof desc.get === 'function')\n .map(([key]) => key);\n const model: ModelInfo = {\n id: String(state),\n ...seen(state.constructor as typeof Model),\n keys: [...stored.keys()],\n absent: declared.filter((key) => !stored.has(key))\n };\n const parent = parents.get(state);\n if (parent) model.parent = String(parent);\n return model;\n}\n\n/** Each instance's owner, from mvc. */\nfunction ownership(): Map<Model, Model> {\n return graph().owners;\n}\n\n/** Owner, else the first instance holding it - what keeps an instance from being abandoned. */\nfunction reach(): Map<Model, Model> {\n return graph().holders;\n}\n\nfunction graph() {\n if (cached?.version !== version) {\n const owners = new Map<Model, Model>();\n const holders = new Map<Model, Model>();\n\n for (const state of registered()) {\n const owner = state.get(Model, false);\n if (owner) owners.set(state, owner);\n\n for (const [key, value] of entries(state)) {\n const field = Object.getOwnPropertyDescriptor(state, key)?.enumerable;\n if (field || !(value instanceof Model)) hold(holders, state, value);\n }\n }\n\n for (const [state, owner] of owners) holders.set(state, owner);\n\n cached = { version, owners, holders };\n }\n\n return cached;\n}\n\nfunction hold(holders: Map<Model, Model>, holder: Model, value: unknown) {\n if (value instanceof Model) {\n if (!holders.has(value) && value !== holder) holders.set(value, holder);\n } else if (value && typeof value === 'object' && Symbol.iterator in value) {\n const items = value instanceof Map ? value.values() : (value as Iterable<unknown>);\n for (const item of items) if (item instanceof Model) hold(holders, holder, item);\n }\n}\n"],"mappings":";;;;;;AAEA,MAAM,aAAa;AACnB,MAAM,YAAY;AAClB,MAAM,WAAW;AAIjB,SAAgB,UAAU,KAAsB;CAC9C,MAAM,UAAU,IAAI,MAAM;CAC1B,MAAM,MAAM,QAAQ,QAAQ,IAAI;AAChC,KAAI,OAAO,EAAG,QAAO,EAAE,QAAQ,SAAS;AACxC,QAAO;EAAE,QAAQ,QAAQ,MAAM,GAAG,IAAI;EAAE,MAAM,QAAQ,MAAM,MAAM,EAAE;EAAE;;;AAIxE,SAAgB,QAAQ,OAAoC;AAC1D,QAAO,IAAI,IAAI,MAAM;;;AAIvB,SAAgB,KAAK,OAAgB,MAAwB;AAC3D,KAAI,CAAC,KAAM,QAAO;CAClB,IAAI,MAAe;AACnB,MAAK,MAAM,QAAQ,KAAK,MAAM,IAAI,EAAE;AAClC,MAAI,OAAO,QAAQ,OAAO,QAAQ,SAAU,QAAO;AACnD,MAAI,eAAe,MACjB,OAAM,KAAK,MAAM,MAAM,O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AAEvC,OAAK,MAAM,SAAS,YAAY,EAAE;GAChC,MAAM,QAAQ,MAAM,IAAI,OAAO,MAAM;AACrC,OAAI,MAAO,QAAO,IAAI,OAAO,MAAM;AAEnC,QAAK,MAAM,CAAC,KAAK,UAAU,QAAQ,MAAM,CAEvC,KADc,OAAO,yBAAyB,OAAO,IAAI,EAAE,cAC9C,EAAE,iBAAiB,OAAQ,MAAK,SAAS,OAAO,MAAM;;AAIvE,OAAK,MAAM,CAAC,OAAO,UAAU,OAAQ,SAAQ,IAAI,OAAO,MAAM;AAE9D,WAAS;GAAE;GAAS;GAAQ;GAAS;;AAGvC,QAAO;;AAGT,SAAS,KAAK,SAA4B,QAAe,OAAgB;AACvE,KAAI,iBAAiB,OACnB;MAAI,CAAC,QAAQ,IAAI,MAAM,IAAI,UAAU,OAAQ,SAAQ,IAAI,OAAO,OAAO;YAC9D,SAAS,OAAO,UAAU,YAAY,OAAO,YAAY,OAAO;EACzE,MAAM,QAAQ,iBAAiB,MAAM,MAAM,QAAQ,GAAI;AACvD,OAAK,MAAM,QAAQ,MAAO,KAAI,gBAAgB,MAAO,MAAK,SAAS,QAAQ,KAAK"}
@@ -88,6 +88,7 @@ interface TypeInfo {
88
88
  /** Construction stack captured at first sight, for a source-map resolver. */
89
89
  site: string;
90
90
  }
91
+ /** Name a class for addresses and the journal - wins over `displayName`, `resolve()` names and the class name. */
91
92
  declare function label(Type: typeof Model, name: string): void;
92
93
  /** Supply resolved names keyed by `typeId` or `site`, e.g. from a source-map pass. */
93
94
  declare function resolve(table: Record<string, string>): void;
@@ -132,10 +133,17 @@ declare class Instance {
132
133
  watch(fn: (key: string | null) => void, keys?: string[]): () => void;
133
134
  frames(query?: Query): Frame[];
134
135
  }
136
+ /**
137
+ * Observe every instance of `Type` set up from now on; returns its detach.
138
+ *
139
+ * Default `Model`, so every class. Repeat calls for a class reuse the first. Instances set up before it stay unregistered.
140
+ */
135
141
  declare function attach(Type?: typeof Model): () => void;
142
+ /** Stop observing every class and reset the registry, journal, labels and health counts. */
136
143
  declare function detach(): void;
137
144
  /** Resolve an id or label to an instance - mainline first, then orphans. */
138
145
  declare function find(target: string): Instance | undefined;
146
+ /** Every mainline instance - claimed, or too young to judge; orphans excluded. */
139
147
  declare function instances(): Instance[];
140
148
  /** Registered and settled, but never claimed by a host commit, an owner, or root context. */
141
149
  declare function orphans(): Instance[];
@@ -151,14 +159,32 @@ interface Health {
151
159
  }
152
160
  /** Counts worth a look before trusting what inspect shows. */
153
161
  declare function health(): Health;
162
+ /** Mainline instances with no owner. */
154
163
  declare function roots(): Instance[];
164
+ /** One row per mainline instance, with its parent's id. */
155
165
  declare function models(): ModelInfo[];
166
+ /** Mainline instances nested by ownership. */
156
167
  declare function tree(): Node[];
157
168
  /** Run `work` recording values; returns the frames it produced once `until` holds and activity goes quiet. */
158
169
  declare function act(work: () => unknown, options?: Act): Promise<Frame[]>;
170
+ /**
171
+ * Stored value at an address - `Type.path` or `id.path` - serialized, with no accessor fired.
172
+ *
173
+ * No address returns `models()`. An address naming no instance returns `undefined`.
174
+ */
159
175
  declare function get(address?: string, select?: Select): unknown;
176
+ /**
177
+ * Assign at an address - a Model field, a `Map` key or an object property.
178
+ *
179
+ * Throws `No model at …` when the address resolves to nothing.
180
+ */
160
181
  declare function set(address: string, value: unknown): void;
182
+ /**
183
+ * Call a method by address; resolves to its result, serialized.
184
+ *
185
+ * Throws `No method at …` when the key is not a function.
186
+ */
161
187
  declare function call(address: string, ...args: unknown[]): Promise<unknown>;
162
188
  //#endregion
163
189
  export { Summary as A, parsePath as C, Level as D, Frame as E, Options as O, Select as S, Event as T, tree as _, act as a, resolve as b, detach as c, health as d, instances as f, set as g, roots as h, Node as i, Query as k, find as l, orphans as m, Instance as n, attach as o, models as p, ModelInfo as r, call as s, Health as t, get as u, TypeInfo as v, serialize as w, Act as x, label as y };
164
- //# sourceMappingURL=inspect-3AOGnw9P.d.ts.map
190
+ //# sourceMappingURL=inspect-SOZyvcTx.d.ts.map
package/dist/install.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as attach } from "./inspect-D7_PFXdY.js";
1
+ import { r as attach } from "./inspect-DhwL0EX2.js";
2
2
  import inspect, { journal } from "./index.js";
3
3
 
4
4
  //#region src/install.ts
@@ -1,4 +1,4 @@
1
- import { n as tick, t as bracket } from "./bracket-D3xwitlE.js";
1
+ import { n as tick, t as bracket } from "./bracket-iTnJYPw-.js";
2
2
  import { t as dispatch } from "./dispatch-BmtaBKeH.js";
3
3
 
4
4
  //#region src/protocol.ts
@@ -71,4 +71,4 @@ function reply(res, status, data) {
71
71
 
72
72
  //#endregion
73
73
  export { journalCall as a, reply as c, headers as i, answer as n, local as o, body as r, parse as s, CALL_TIMEOUT as t };
74
- //# sourceMappingURL=protocol-BApRTxGk.js.map
74
+ //# sourceMappingURL=protocol-DGf0aga5.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"protocol-BApRTxGk.js","names":[],"sources":["../src/protocol.ts"],"sourcesContent":["import { bracket } from './bracket';\nimport { dispatch, type Call } from './dispatch';\nimport type { Options, Query } from './journal';\nimport { tick, type Act } from './settle';\n\nexport const CALL_TIMEOUT = 10000;\n\nexport type Answer = { value?: unknown; error?: string; status?: number };\n\nexport interface NodeRequest extends AsyncIterable<unknown> {\n method?: string;\n headers: object;\n socket: { remoteAddress?: string };\n body?: unknown;\n}\n\nexport interface NodeResponse {\n headersSent?: boolean;\n statusCode: number;\n setHeader(name: string, value: string): unknown;\n end(data: string): unknown;\n}\n\nconst FOREIGN = ['origin', 'sec-fetch-site', 'forwarded', 'x-forwarded-for', 'x-real-ip', 'cf-connecting-ip'];\nconst LOOPBACK = /^((::ffff:)?127(\\.\\d{1,3}){3}|::1)$/;\nconst MISSING = Symbol.for('expressive-inspect.missing');\nconst FAILED = 'Call failed.';\n\nexport function local(ip: string | null | undefined, headers: { has(name: string): boolean }) {\n return !FOREIGN.some((header) => headers.has(header)) && LOOPBACK.test(ip ?? '');\n}\n\nexport function parse(text: string): Call | undefined {\n try {\n const input: unknown = JSON.parse(text);\n\n if (Array.isArray(input) && typeof input[0] == 'string') return [input[0].split('.'), input.slice(1)];\n } catch {}\n}\n\nexport const journalCall = (method: string, ...args: unknown[]) => dispatch([['journal', method], args]) as any;\n\nasync function act(step: unknown, options?: Act) {\n if (!Array.isArray(step) || typeof step[0] != 'string')\n throw new Error('act takes one call: [\"act\", [method, ...args], options?].');\n\n const remote = {\n record: (...options: Options[]) => journalCall('record', ...options),\n seq: () => journalCall('seq'),\n frames: (query: Query) => journalCall('frames', query),\n get: (address: string) => dispatch([['get'], [address]])\n };\n\n const { value, frames, settled, pending, missing } = await bracket(remote, () => dispatch([step[0].split('.'), step.slice(1)]), tick, options, true);\n\n return { value: value ?? null, frames, settled, pending, missing };\n}\n\nexport async function answer(call: Call): Promise<Answer> {\n try {\n const value = call[0].join('.') == 'act' ? await act(call[1][0], call[1][1] as Act) : await dispatch(call);\n\n return { value: JSON.parse(JSON.stringify(value) ?? 'null') };\n } catch (error) {\n if (!(error instanceof Error)) return { error: String(error) || FAILED };\n\n return { error: error.message || FAILED, status: MISSING in error ? 404 : undefined };\n }\n}\n\nexport function headers({ headers }: NodeRequest) {\n const fetched = typeof (headers as Headers).has == 'function';\n\n return { has: (name: string) => (fetched ? (headers as Headers).has(name) : name in headers) };\n}\n\nexport async function body(req: NodeRequest) {\n const decoder = new TextDecoder();\n let text = '';\n\n for await (const chunk of req) text += typeof chunk == 'string' ? chunk : decoder.decode(chunk as Uint8Array, { stream: true });\n\n return text + decoder.decode();\n}\n\nexport function reply(res: NodeResponse, status: number, data: unknown) {\n if (res.headersSent) return;\n\n res.statusCode = status;\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify(data ?? null));\n}\n"],"mappings":";;;;AAKA,MAAa,eAAe;AAkB5B,MAAM,UAAU;CAAC;CAAU;CAAkB;CAAa;CAAmB;CAAa;CAAmB;AAC7G,MAAM,WAAW;AACjB,MAAM,UAAU,OAAO,IAAI,6BAA6B;AACxD,MAAM,S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AAO;AACd,MAAI,EAAE,iBAAiB,OAAQ,QAAO,EAAE,OAAO,OAAO,MAAM,IAAI,QAAQ;AAExE,SAAO;GAAE,OAAO,MAAM,WAAW;GAAQ,QAAQ,WAAW,QAAQ,MAAM;GAAW;;;AAIzF,SAAgB,QAAQ,EAAE,WAAwB;CAChD,MAAM,UAAU,OAAQ,QAAoB,OAAO;AAEnD,QAAO,EAAE,MAAM,SAAkB,UAAW,QAAoB,IAAI,KAAK,GAAG,QAAQ,SAAU;;AAGhG,eAAsB,KAAK,KAAkB;CAC3C,MAAM,UAAU,IAAI,aAAa;CACjC,IAAI,OAAO;AAEX,YAAW,MAAM,SAAS,IAAK,SAAQ,OAAO,SAAS,WAAW,QAAQ,QAAQ,OAAO,OAAqB,EAAE,QAAQ,MAAM,CAAC;AAE/H,QAAO,OAAO,QAAQ,QAAQ;;AAGhC,SAAgB,MAAM,KAAmB,QAAgB,MAAe;AACtE,KAAI,IAAI,YAAa;AAErB,KAAI,aAAa;AACjB,KAAI,UAAU,gBAAgB,mBAAmB;AACjD,KAAI,IAAI,KAAK,UAAU,QAAQ,KAAK,CAAC"}
1
+ {"version":3,"file":"protocol-DGf0aga5.js","names":[],"sources":["../src/protocol.ts"],"sourcesContent":["import { bracket } from './bracket';\nimport { dispatch, type Call } from './dispatch';\nimport type { Options, Query } from './journal';\nimport { tick, type Act } from './settle';\n\nexport const CALL_TIMEOUT = 10000;\n\nexport type Answer = { value?: unknown; error?: string; status?: number };\n\nexport interface NodeRequest extends AsyncIterable<unknown> {\n method?: string;\n headers: object;\n socket: { remoteAddress?: string };\n body?: unknown;\n}\n\nexport interface NodeResponse {\n headersSent?: boolean;\n statusCode: number;\n setHeader(name: string, value: string): unknown;\n end(data: string): unknown;\n}\n\nconst FOREIGN = ['origin', 'sec-fetch-site', 'forwarded', 'x-forwarded-for', 'x-real-ip', 'cf-connecting-ip'];\nconst LOOPBACK = /^((::ffff:)?127(\\.\\d{1,3}){3}|::1)$/;\nconst MISSING = Symbol.for('expressive-inspect.missing');\nconst FAILED = 'Call failed.';\n\nexport function local(ip: string | null | undefined, headers: { has(name: string): boolean }) {\n return !FOREIGN.some((header) => headers.has(header)) && LOOPBACK.test(ip ?? '');\n}\n\nexport function parse(text: string): Call | undefined {\n try {\n const input: unknown = JSON.parse(text);\n\n if (Array.isArray(input) && typeof input[0] == 'string') return [input[0].split('.'), input.slice(1)];\n } catch {}\n}\n\nexport const journalCall = (method: string, ...args: unknown[]) => dispatch([['journal', method], args]) as any;\n\nasync function act(step: unknown, options?: Act) {\n if (!Array.isArray(step) || typeof step[0] != 'string')\n throw new Error('act takes one call: [\"act\", [method, ...args], options?].');\n\n const remote = {\n record: (...options: Options[]) => journalCall('record', ...options),\n seq: () => journalCall('seq'),\n frames: (query: Query) => journalCall('frames', query),\n get: (address: string) => dispatch([['get'], [address]])\n };\n\n const { value, frames, settled, pending, missing } = await bracket(remote, () => dispatch([step[0].split('.'), step.slice(1)]), tick, options, true);\n\n return { value: value ?? null, frames, settled, pending, missing };\n}\n\nexport async function answer(call: Call): Promise<Answer> {\n try {\n const value = call[0].join('.') == 'act' ? await act(call[1][0], call[1][1] as Act) : await dispatch(call);\n\n return { value: JSON.parse(JSON.stringify(value) ?? 'null') };\n } catch (error) {\n if (!(error instanceof Error)) return { error: String(error) || FAILED };\n\n return { error: error.message || FAILED, status: MISSING in error ? 404 : undefined };\n }\n}\n\nexport function headers({ headers }: NodeRequest) {\n const fetched = typeof (headers as Headers).has == 'function';\n\n return { has: (name: string) => (fetched ? (headers as Headers).has(name) : name in headers) };\n}\n\nexport async function body(req: NodeRequest) {\n const decoder = new TextDecoder();\n let text = '';\n\n for await (const chunk of req) text += typeof chunk == 'string' ? chunk : decoder.decode(chunk as Uint8Array, { stream: true });\n\n return text + decoder.decode();\n}\n\nexport function reply(res: NodeResponse, status: number, data: unknown) {\n if (res.headersSent) return;\n\n res.statusCode = status;\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify(data ?? null));\n}\n"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,IAAI,QAAQ,MAAM,IAAI,KAAK,GAAG,IAAI,KAAK,GAAG,GAAU,GAAG,MAAM,SAAS,KAAK;AAE1G,SAAO,EAAE,OAAO,KAAK,MAAM,KAAK,UAAU,MAAM,IAAI,OAAO,EAAE;UACtD,OAAO;AACd,MAAI,EAAE,iBAAiB,OAAQ,QAAO,EAAE,OAAO,OAAO,MAAM,IAAI,QAAQ;AAExE,SAAO;GAAE,OAAO,MAAM,WAAW;GAAQ,QAAQ,WAAW,QAAQ,MAAM;GAAW;;;AAIzF,SAAgB,QAAQ,EAAE,WAAwB;CAChD,MAAM,UAAU,OAAQ,QAAoB,OAAO;AAEnD,QAAO,EAAE,MAAM,SAAkB,UAAW,QAAoB,IAAI,KAAK,GAAG,QAAQ,SAAU;;AAGhG,eAAsB,KAAK,KAAkB;CAC3C,MAAM,UAAU,IAAI,aAAa;CACjC,IAAI,OAAO;AAEX,YAAW,MAAM,SAAS,IAAK,SAAQ,OAAO,SAAS,WAAW,QAAQ,QAAQ,OAAO,OAAqB,EAAE,QAAQ,MAAM,CAAC;AAE/H,QAAO,OAAO,QAAQ,QAAQ;;AAGhC,SAAgB,MAAM,KAAmB,QAAgB,MAAe;AACtE,KAAI,IAAI,YAAa;AAErB,KAAI,aAAa;AACjB,KAAI,UAAU,gBAAgB,mBAAmB;AACjD,KAAI,IAAI,KAAK,UAAU,QAAQ,KAAK,CAAC"}
@@ -1,4 +1,4 @@
1
- import { a as journalCall, n as answer } from "../protocol-BApRTxGk.js";
1
+ import { a as journalCall, n as answer } from "../protocol-DGf0aga5.js";
2
2
 
3
3
  //#region src/vite/client.ts
4
4
  const RELOAD = "@expressive/inspect.reload";
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import { c as reply, i as headers, o as local, r as body, s as parse, t as CALL_TIMEOUT } from "./protocol-BApRTxGk.js";
1
+ import { c as reply, i as headers, o as local, r as body, s as parse, t as CALL_TIMEOUT } from "./protocol-DGf0aga5.js";
2
2
 
3
3
  //#region src/vite/plugin.ts
4
4
  const VIRTUAL = "virtual:expressive-inspect";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressive/inspect",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
4
4
  "description": "In-process inspector for Expressive MVC - registry, ownership tree, path queries, and a frame journal for agents, tests, and devtools.",
5
5
  "keywords": [
6
6
  "expressive",
@@ -17,10 +17,11 @@
17
17
  },
18
18
  "repository": {
19
19
  "type": "git",
20
- "url": "git+https://github.com/gabeklein/expressive-mvc.git"
20
+ "url": "git+https://github.com/gabeklein/expressive.git"
21
21
  },
22
22
  "files": [
23
- "dist"
23
+ "dist",
24
+ "skills"
24
25
  ],
25
26
  "type": "module",
26
27
  "sideEffects": [
@@ -70,7 +71,7 @@
70
71
  "test": "bun run typecheck && bun run coverage"
71
72
  },
72
73
  "peerDependencies": {
73
- "@expressive/mvc": "^0.94.0",
74
+ "@expressive/mvc": "^0.94.3",
74
75
  "vite": ">=5"
75
76
  },
76
77
  "peerDependenciesMeta": {
@@ -0,0 +1,358 @@
1
+ ---
2
+ name: expressive-inspect
3
+ description: In-process inspector for Expressive MVC (@expressive/inspect) - registry of live instances, ownership tree, path reads, frame journal with causality, orphans and health. Use when debugging or testing Expressive state from an agent, browser tool, test or driver, or wiring the Vite or server relay.
4
+ ---
5
+
6
+ # Inspect
7
+
8
+ `@expressive/inspect` - in-process inspector over live instances: registry, ownership, path reads, a frame journal with causality. No UI; network only through the dev-server relay ([Vite](#vite)) or a handler your server mounts ([Server](#server)). Base layer for agents (via a browser tool or a driver's `evaluate`), devtools, and test helpers.
9
+
10
+ ## Install
11
+
12
+ ```ts
13
+ // first import of the app entry, before any Model is constructed
14
+ import '@expressive/inspect/install';
15
+ ```
16
+
17
+ Attaches to `Model` from the same `@expressive/mvc` instance and publishes `globalThis.__EXPRESSIVE_INSPECT__` (typed on `globalThis`). Instances constructed before the import are invisible. Install ships in the app bundle - a Playwright `addInitScript` or userscript imports a different `Model` and sees nothing. Gate it yourself: side-effect import for a harness, `attach()` behind a dev flag for a shipped build, `/http` for a server ([Server](#server)). A value already on `globalThis.__EXPRESSIVE_INSPECT__` of the form `{ record }` is read first, so a driver can arm recording before the page boots ([below](#failure-journal)).
18
+
19
+ Programmatic: `attach(Model)` returns detach; `attach(Sub)` scopes to a subclass.
20
+
21
+ Under Vite, the plugin installs it - see [Vite](#vite).
22
+
23
+ ## Two faces, one id
24
+
25
+ In process you get **instances**; across a serializing boundary (`evaluate`, `postMessage`, socket) you use **addresses**. Both key on the same id: `String(state)`, e.g. `Composer-x1s4`.
26
+
27
+ ## Instances (in process)
28
+
29
+ ```ts
30
+ import { find, roots, instances } from '@expressive/inspect';
31
+
32
+ const app = roots()[0]; // instances with no owner
33
+ const composer = find('Composer'); // by label, or find('Composer-x1s4') by id
34
+ composer.state // the raw instance - assign to it directly
35
+ composer.alive / since / until // registry span (ms); an Instance outlives its state
36
+ composer.parent / composer.children // ownership, memoized until the registry changes
37
+ app.find('Composer') // depth-first by label or predicate
38
+ composer.get('draft') // stored value, serialized
39
+ composer.model() // { id, typeId, type, site, parent?, keys, absent }
40
+ composer.watch((key) => ..., ['draft']) // key per update, null on destroy; unsubscribe returned
41
+ composer.frames({ since }) // this instance's journal
42
+ await composer.act((s) => s.submit('x')) // run, settle, return frames produced
43
+ await composer.act(work, { until: { 'Composer.status': 'sent' }, timeout: 3000, record: { paths: [] } })
44
+ ```
45
+
46
+ Ownership is mvc's (`get(Model)`): an instance constructed into a field, `has` pool, or `map`, or mounted by a host, is that owner's child; a `get(Type)` reference or an already-active instance assigned in is not. One `Instance` per instance - `find` returns the same object each time; a held reference keeps working after destruction, with `alive` false and `until` set.
47
+
48
+ `act` records values for its window whatever the journal level, and returns every frame produced, downstream ones included. It settles once a macrotask passes with no new recorded frame - so timer and promise chains finish - capped at `timeout` (default 1s), with a warning that frames may be incomplete.
49
+
50
+ - `until` - what to wait for first, for work that waits on I/O, where quiet arrives before the change does. Unmet within `timeout`, `act` throws - the error names what never arrived and carries `frames` and `pending`.
51
+ - `{ 'Chat.status': 'ready' }` - each address holds that value, compared as `get` returns it - past its caps (depth 2, 240-char strings) a value never matches, so compare a leaf. Precise everywhere: a loading write doesn't count, a value the step already awaited is met at once, and it reads current values, so the journal's filters don't apply. Prefer it.
52
+ - `'Chat.status'` or a list - each address sees a frame after the step's synchronous writes, so a loading flag it sets doesn't count. The address resolves once, after the step, to the instance `get` would read - label (first instance), id, or owner path (`Sidebar.control.value`). An address naming no instance throws right away. So does a `_` key - unmanaged, it emits no frames; use the value form. Under an app's recording filters, the addresses join the window's recording. On the bridge the step runs remotely, so activity counts from when it resolves - a step that awaits the change itself never counts; use the value form there.
53
+ - `record` - filters for this window instead of the journal's (`{ types: [], paths: [], keys: [] }` records everything); the journal's recording is restored after. Filtered-out events don't count as activity - narrow to exclude a poller or animation loop rather than raising the timeout.
54
+
55
+ ## Orphans
56
+
57
+ Under a host adapter, an activated instance is **claimed** once a host places it - it was held at activation and became ready - by a claimed owner or holder, or by being held in the root context. One settled but unclaimed - a render React threw away, a StrictMode twin, a `Model.new()` nobody placed - is an orphan; so are its children. Orphans stay out of `models()`, `tree()`, `instances()`, `roots()`; label lookups resolve mainline first. `orphans()` lists them; `health()` counts them plus unclaimed instances the collector already reaped. Without a host every instance is mainline.
58
+
59
+ ```ts
60
+ inspect.health().orphans // 54 - a suspended first render left a full tree behind
61
+ inspect.orphans().map((o) => o.type)
62
+ instance.claimed
63
+ ```
64
+
65
+ Unclaimed instances are held weakly - the inspector never pins an abandoned render in memory. `@expressive/react` destroys an abandoned render's instances once React releases the attempt, so in a production build an orphan that persists is a stray `Model.new()` or a host leak. React's development build can keep abandoned attempts reachable - expect orphans there. A rising `collected` with no `destroy` events is a leak the host cleaned up for you.
66
+
67
+ ## Health
68
+
69
+ Check before trusting what inspect shows:
70
+
71
+ ```ts
72
+ inspect.health() // { orphans, collected, copies, caught: { dead, unused, getter, setup, effect } } - also on the bridge and relay
73
+ ```
74
+
75
+ - `copies > 1` - more than one `@expressive/mvc` is loaded; inspect sees only instances from the copy it imports, and warns once. Usual cause: a bundler resolving mvc twice - dedupe or alias it. Counted only where inspect is loaded; a bundle that never imports it goes unseen.
76
+ - `caught` - reports by `kind`, handled or not (`Model.on()` - `expressive-mvc/state/state.md#modelon`). Inspect's `catch` joins each class as its first instance activates, ahead of app handlers registered before then, and passes each report on - behavior is unchanged. A handler registered on that class afterward runs first; one that handles or replaces a report hides the original. `journal.clear()` zeroes the counts - clear per test to assert on one test's reports.
77
+
78
+ ## Addresses (across a boundary)
79
+
80
+ `Type.path` or `Type-id.path`. `Type` is the label (first live instance); the path steps through child instances, `Map`s, arrays, objects.
81
+
82
+ ```ts
83
+ inspect.models() // flat list with parent ids
84
+ inspect.tree() // nested { id, type, children }
85
+ inspect.get('Composer.draft')
86
+ inspect.get('Sidebar', { status: true, control: { value: true }, rows: { id: true } })
87
+ inspect.set('Composer.draft', 'x')
88
+ await inspect.call('Composer.submit', 'x')
89
+ ```
90
+
91
+ Reads come from stored values, never accessors - no getter, factory, or suspense fires. An unmanaged `_` key reads only when addressed by name; whole-instance views omit it. `absent` lists declared keys with no stored value: lazy `set(factory)`, pending async, uncomputed getters. Nested instances serialize to `{ $ref, $type }` - follow one with `get(`${$ref}.key`)`; caps: strings 240 chars, arrays 24, keys 40, depth 2. Query, do not dump.
92
+
93
+ A selection reads several keys as one snapshot - one synchronous pass, so no write lands between them, unlike separate `get`s over the bridge or relay. `true` takes a value as `get` would; an object picks keys and descends through instances (keeping `$ref`), `Map`s and objects, applying to each element of a list (capped at 24). Relay: `["get", "Sidebar", { "status": true }]`.
94
+
95
+ ## Labels and minified builds
96
+
97
+ Minifiers keep property names and mangle class names - keys survive production, `constructor.name` does not. Each class gets an opaque `typeId` at first sight and a `site` (construction stack) for a resolver. Label resolution order:
98
+
99
+ 1. `label(Type, name)` or `static displayName`
100
+ 2. a table from `resolve({ [typeId | site]: name })`
101
+ 3. the class name, if longer than two characters
102
+ 4. `typeId`
103
+
104
+ For builds an agent or devtool will touch, keep class names: esbuild `keepNames`, terser `keep_classnames`. Property mangling is unsupported.
105
+
106
+ ## Journal
107
+
108
+ Off by default; nothing is retained until asked.
109
+
110
+ ```ts
111
+ journal.record({ level: 'keys' }) // keys only
112
+ journal.record({ level: 'values', calls: true }) // values and method calls
113
+ journal.record({ level: 'keys', types: ['Composer'] })
114
+ journal.record({ paths: ['Composer.draft', 'T3.openTabs', `${id}.value`], keys: ['status'] })
115
+ journal.frames({ since, type, id, key, cause })
116
+ journal.history({ id, key }) // flat [{ seq, at, event }]
117
+ journal.downstream(seq) // frames reachable through cause
118
+ journal.summary({ since }) // per instance, latest first: { id, type, last, keys: { [key]: { count, value } }, calls, caught, hot, destroyed }
119
+ journal.seq() // pass back as since
120
+ journal.export({ since }) // NDJSON, one event per line
121
+ journal.hot(key, value?) // page-level hot marker; the Vite client records these
122
+ journal.clear()
123
+ ```
124
+
125
+ Filters OR together; none set records everything. `paths` take a label, `typeId`, or instance id left of the dot and a property right - events key on the instance that changed, so `Chats.openTabs`, never the owner path `Pairing.chats.openTabs`. `keys` match that property on any type.
126
+
127
+ A frame is one synchronous batch of writes plus its flush, including writes effects make synchronously during it - the unit React commits. Work an effect defers to a later microtask opens a new frame with `cause` set to the scheduling frame; work deferred to a macrotask starts a new root. Events: `update` (stored key), `event` (custom dispatch), `call` (method, `render` excluded; not recorded for a class first constructed before attach), `destroy`, `caught` (a report, `value: { case, message, stack, handled }` at any level - `case` is its kind; `stack` is the throw site, the write site for `dead`; `handled` is false when the report got past every app handler; a replacement keeps the kind it replaced), `hot` (an HMR update, below). Retains 500 frames.
128
+
129
+ `hot` events separate state an edit reset from an app bug. On an instance, `key: 'patch'` - its class was hot-patched and the instance survived. Page-level ones carry `id: ''`, `type: 'vite'`: `update` (`value`: module paths) opens each hot update, so a `destroy` in the frames after it is the edit remounting - React Refresh; `reload` opens the journal of the page a full reload brought up, `value` the reason - `{ module, class, reason }` when a class could not be patched (`reason`: `'class changed shape'` or `'private members'`), `{ path, triggeredBy }` for Vite's own reloads.
130
+
131
+ Bulk analysis belongs outside the page: `export` to a sidecar and query there.
132
+
133
+ ## Testing a Model
134
+
135
+ `act` is the default assertion for Model specs - run a mutation, get back what changed:
136
+
137
+ ```ts
138
+ import { attach, find } from '@expressive/inspect';
139
+
140
+ attach();
141
+ const composer = Composer.new();
142
+ const frames = await find('Composer')!.act((s) => s.submit('hi'));
143
+ expect(frames[0].events.map((e) => e.key)).toEqual(['draft']);
144
+ ```
145
+
146
+ Host-agnostic packages depending only on `@expressive/mvc` get the same seat.
147
+
148
+ ## Bridge
149
+
150
+ `@expressive/inspect/bridge` drives the page's global from outside, through anything with `evaluate(fn, arg)` - Playwright `Page`, `Frame`, `Locator`, puppeteer `Page`/`Frame`, or `devtools()` ([below](#node-process-or-a-browser-with-a-debug-port)). No driver dependency. Each method is one round trip.
151
+
152
+ ```ts
153
+ import { inspect } from '@expressive/inspect/bridge';
154
+
155
+ const api = inspect(page); // or a frame - see below
156
+ expect(await api.get('Composer.draft')).toBe('');
157
+ const since = await api.journal.seq();
158
+ await page.click('#submit');
159
+ const frames = await api.journal.frames({ since, type: 'Composer' });
160
+
161
+ const produced = await api.act(() => page.click('#submit'), { until: { 'Composer.status': 'sent' } }); // same act and options
162
+ await api.journal.record({ level: 'keys', types: ['Composer'] }); // labels, not classes
163
+ ```
164
+
165
+ For an app in an iframe, pass that frame: `inspect(page.frame({ name }))`, or a locator such as `inspect(page.frameLocator('iframe[title="App"]').locator('body'))` - the helper accepts `Locator.evaluate`'s element-first arity. A missing global throws one line naming the install import - that is the install-order check.
166
+
167
+ Drive input through the UI; assert on the instance. Reserve DOM assertions for presentation the instance does not express.
168
+
169
+ ## Failure journal
170
+
171
+ Record from the first instance in any browser a driver controls - the app turns it on, so nothing is missed before a test attaches. The Vite plugin covers the dev server only; e2e against a built app (`vite preview`, a production build) needs the inspector in that build. Gate it on a flag the bundler folds, so a production build drops inspect entirely:
172
+
173
+ ```ts
174
+ // debug.ts - first import of the app entry; CI builds with `vite build --mode e2e`
175
+ import { inspect, journal } from '@expressive/inspect';
176
+
177
+ if (import.meta.env.MODE !== 'production') {
178
+ inspect.attach();
179
+ globalThis.__EXPRESSIVE_INSPECT__ = inspect; // what the bridge reaches
180
+ if (navigator.webdriver) journal.record({ level: 'values' });
181
+ }
182
+ ```
183
+
184
+ Attach it to failing tests. **Playwright** - a fixture covering every page in the test's context and their frames:
185
+
186
+ ```ts
187
+ import { test as base } from '@playwright/test';
188
+ import { inspect } from '@expressive/inspect/bridge';
189
+
190
+ export const test = base.extend({
191
+ page: async ({ page }, use, testInfo) => {
192
+ await use(page);
193
+ if (testInfo.status === testInfo.expectedStatus) return;
194
+ for (const [n, tab] of page.context().pages().entries())
195
+ for (const frame of tab.frames()) {
196
+ const api = inspect(frame);
197
+ const summary = await api.journal.summary().catch(() => []);
198
+ if (!summary.length) continue;
199
+ const name = `journal ${n} ${frame.url()}`;
200
+ const report = { summary, health: await api.health() };
201
+ await testInfo.attach(`${name} summary`, { body: JSON.stringify(report, null, 2), contentType: 'application/json' });
202
+ await testInfo.attach(name, { body: await api.journal.export(), contentType: 'application/x-ndjson' });
203
+ }
204
+ }
205
+ });
206
+ ```
207
+
208
+ In process, **any runner** (vitest, jest, bun, `node:test`, mocha) - wrap the test body:
209
+
210
+ ```ts
211
+ import { attach, journal } from '@expressive/inspect';
212
+
213
+ export const recorded = (test: () => unknown) => async () => {
214
+ attach();
215
+ journal.clear();
216
+ journal.record({ level: 'values' });
217
+ try {
218
+ await test();
219
+ } catch (error) {
220
+ console.log(JSON.stringify(journal.summary(), null, 2), `\n${journal.export()}`);
221
+ throw error;
222
+ }
223
+ };
224
+
225
+ it('submits', recorded(async () => { /* ... */ }));
226
+ ```
227
+
228
+ **vitest** - suite-wide from a setup file, no wrapping:
229
+
230
+ ```ts
231
+ beforeEach(({ onTestFailed }) => {
232
+ attach();
233
+ journal.clear();
234
+ journal.record({ level: 'values' });
235
+ onTestFailed(() => console.log(journal.export()));
236
+ });
237
+ ```
238
+
239
+ Across a page reload, `act` can't bracket the step - the journal lives in the page, and the reload starts a new one. Arm recording before boot instead, then read the whole boot back. **Playwright** (puppeteer: `evaluateOnNewDocument`):
240
+
241
+ ```ts
242
+ await page.addInitScript((record) => ((window as any).__EXPRESSIVE_INSPECT__ = { record }), { level: 'values' });
243
+ await page.reload();
244
+ const boot = await inspect(page).journal.frames({ since: 0 });
245
+ ```
246
+
247
+ The journal keeps the last 500 frames, so a failure carries what led up to it. `record()` merges settings - a later `record({ paths })` in the app narrows this recording, so skip it under `navigator.webdriver`.
248
+
249
+ ## Vite
250
+
251
+ `@expressive/inspect/vite` reaches the page a developer has open - any browser, no debug port - through the dev server.
252
+
253
+ ```ts
254
+ // vite.config.ts
255
+ import inspect from '@expressive/inspect/vite';
256
+
257
+ export default defineConfig({ plugins: [inspect()] });
258
+ ```
259
+
260
+ Dev server only. Injects `install` ahead of the app entry (a manual import becomes redundant, harmless) and relays over Vite's HMR socket. Pre-bundles `install` when inspect comes from `node_modules`, so a cold dep cache cannot split mvc into two copies.
261
+
262
+ ```bash
263
+ curl localhost:5173/__inspect # [{ id, url, title, top }] per document, iframes included
264
+ curl localhost:5173/__inspect/4rrsel -d '["get", "Counter.current"]'
265
+ curl localhost:5173/__inspect -d '["journal.frames", { "since": 3 }]' # the only connected page
266
+ ```
267
+
268
+ - Body `[method, ...args]`, method dotted from the console API (`get`, `set`, `call`, `models`, `tree`, `journal.record`, ...). Response is the JSON result.
269
+ - No id with several pages connected: 409 plus the page list - never guesses.
270
+ - Ids are per page load; a reload issues new ones, closed pages drop out.
271
+ - 404 unknown page or method, 500 the page threw (`{ error }`), 504 no answer within 10s.
272
+ - Local callers only: 403 for a request carrying `Origin`/`Sec-Fetch-Site` (a web page) or a proxy header (`Forwarded`, `X-Forwarded-For`, `X-Real-IP`, `CF-Connecting-IP`). Behind a tunnel, pages still connect; only `curl` on the dev machine reaches the relay. A proxy that strips these headers bypasses the guard - securing an exposed dev server is on its owner.
273
+ - Dev server in a container or VM: the host's request arrives from a gateway address and gets 403. Run the request inside it (`docker exec <container> curl localhost:5173/__inspect`), or forward the port over SSH (`ssh -L`) or a devcontainer - those arrive as loopback.
274
+ - No HTML (`appType: 'custom'`): `import 'virtual:expressive-inspect'` first in the entry.
275
+
276
+ The journal records `keys` from page load - a connected page carries history before anyone asks. A level the app sets wins. The Vite client adds the `hot` markers ([Journal](#journal)); a reload's reason survives the reload through `sessionStorage`.
277
+
278
+ `act` takes one call as its step, and the same options - answers `{ value, frames, settled, pending, missing }`. `settled: false` means the timeout passed first; `pending` lists `until` targets not reached, `missing` those that name no instance - an answer, not an error:
279
+
280
+ ```bash
281
+ curl … -d '["act", ["call", "Composer.submit", "hi"]]'
282
+ curl … -d '["act", ["call", "Composer.submit", "hi"], { "until": { "Composer.status": "sent" }, "timeout": 3000 }]'
283
+ ```
284
+
285
+ For what the developer does in the browser, read back with a cursor: `journal.seq`, then `journal.frames` with `since` once they're done - raise to `values` first if keys are not enough.
286
+
287
+ What to reach for, in order:
288
+
289
+ 1. **Observe** - `models`, `tree`, `get`, `journal.*`. Most questions end here.
290
+ 2. **Act through the instance** - `call("Type.method", ...)` runs the app's own logic; the way to reproduce what a user did.
291
+ 3. **Force a state** - `set("Type.key", value)` bypasses the instance's methods; for setting up a repro, sparingly.
292
+
293
+ The relay reaches only the inspector's own members - no `eval`, no property walks beyond them. Arbitrary JS belongs to a driver's `evaluate`, granted by whoever runs the harness.
294
+
295
+ ## Server
296
+
297
+ `@expressive/inspect/http` installs the inspector and exports `handle`, which serves it over HTTP from a backend's own server. `handle` takes each host's native handler arguments and reads the caller's address from them, so it mounts as a route - path-agnostic, nested routers included. Import it dynamically behind the dev flag so the package stays a devDependency - a static import crashes boot when dev dependencies are omitted.
298
+
299
+ ```ts
300
+ // top of the server entry - installs, so it precedes any Model
301
+ const inspect = dev && (await import('@expressive/inspect/http')).handle;
302
+
303
+ // Bun - (req, server)
304
+ Bun.serve({ routes: inspect ? { '/__inspect': inspect } : undefined, fetch: app });
305
+
306
+ // Node http, Express, Connect - (req, res)
307
+ if (inspect) app.use('/__inspect', inspect);
308
+ if (inspect && req.url?.split('?')[0] == '/__inspect') return inspect(req, res);
309
+
310
+ // Deno, TCP listeners - (req, info)
311
+ if (inspect && pathname == '/__inspect') return inspect(req, info);
312
+
313
+ // anything else with a Request and the socket address
314
+ if (inspect) return inspect(req, { ip });
315
+ ```
316
+
317
+ - The entry's static imports evaluate before its body, so instances they construct at module scope go unseen. Install first from the dev script instead - `bun --preload @expressive/inspect/install server.ts`, `node --import @expressive/inspect/install server.js` - and keep the `/http` import for `handle`.
318
+ - Hono: `inspect(c.req.raw, { ip: getConnInfo(c).remote.address })` - `getConnInfo` from `hono/bun`, `hono/deno` or `@hono/node-server/conninfo`.
319
+ - Fastify: `inspect(request.raw, reply.raw)`, with the route's JSON parser disabled.
320
+ - Node: a JSON array an earlier body parser read (`express.json()`) is used as is; mount before any other parser.
321
+ - An address that is missing or not loopback gets 403, as do the [Vite](#vite) relay's browser and proxy headers. Behind a tunnel (cloudflared) requests arrive from `127.0.0.1` but carry `CF-Connecting-IP`, so they are refused.
322
+ - Next route handlers and Workers expose no socket address - unsupported. Their only caller address is a header a client can forge.
323
+ - A static import works only with the package as a runtime dependency. A bundled server resolves dynamic imports at build time - the package must be installed when building.
324
+ - `GET` answers `{ process: true, pid, cwd, started, runtime, title }` - `started` epoch ms, `runtime` the user agent (`Bun/1.3.1`), null on Node 20. Tells backends apart, and from the Vite page list, when probing ports.
325
+ - `POST` takes the relay's body and answers: `[method, ...args]`, `act` included; 400 bad body, 404 unknown method, 500 `{ error }`, 504 no answer within 10s, 200 the value.
326
+ - Concurrent `act` calls share one journal window - run them one at a time.
327
+
328
+ ```bash
329
+ curl localhost:8787/__inspect -d '["tree"]'
330
+ ```
331
+
332
+ ## Node process, or a browser with a debug port
333
+
334
+ Install the same way (`import '@expressive/inspect/install'` first), then reach it through the debugger - no server in the app. `devtools()` connects to a Chrome DevTools Protocol endpoint as an `evaluate` target for the bridge:
335
+
336
+ ```bash
337
+ node --inspect app.js # or, already running: kill -USR1 <pid>
338
+ ```
339
+
340
+ ```ts
341
+ import { devtools, inspect } from '@expressive/inspect/bridge';
342
+
343
+ const target = await devtools(); // http://127.0.0.1:9229
344
+ const api = inspect(target);
345
+ await api.get('HostChat.status');
346
+ await api.act(() => api.call('HostChat.send', 'hi'), { until: { 'HostChat.status': 'sent' } });
347
+ target.close();
348
+ ```
349
+
350
+ - `devtools(endpoint, pick)` connects to the one `/json/list` target `pick` selects - a string matched against title and URL, or a predicate - or to a `ws://` debugger URL. Zero or several matches throw with the target list. A browser started with `--remote-debugging-port=9222`: `devtools('http://127.0.0.1:9222', 'localhost:5173')`.
351
+ - The debug port runs arbitrary code in the process - keep it on `127.0.0.1`.
352
+ - Node only among runtimes - Bun's `--inspect` speaks WebKit Inspector Protocol, not CDP.
353
+
354
+ ## Several instances of one type
355
+
356
+ `find('Row')` and `get('Row.x')` take the first live instance. Disambiguate by id (`models().filter((m) => m.type === 'Row')`, then `get(`${id}.x`)`), or address through the owner (`Table.rows`, not a bare `Row`).
357
+
358
+ A label two classes share - two modules each declaring `class Control` - throws rather than picking one; `models()` lists each class's `typeId` and construction site. Address by id or owner path, or give one a distinct `label()` / `static displayName`. Owner paths are the stable choice in tests: ids change every run. `instance.find()` searches its own subtree and keeps first-wins.
@@ -1 +0,0 @@
1
- {"version":3,"file":"bracket-D3xwitlE.js","names":[],"sources":["../src/settle.ts","../src/bracket.ts"],"sourcesContent":["import type { Frame, Options } from './journal';\n\nexport const SETTLE_TIMEOUT = 1000;\n\nexport interface Act {\n /**\n * What to wait for before settling: `Type.key` / `id.key` addresses that must each see a frame after the\n * step's synchronous writes, or `{ [address]: value }` pairs that must each hold that value.\n */\n until?: string | string[] | Record<string, unknown>;\n /** Longest to wait, in ms; default 1000. */\n timeout?: number;\n /** Recording filters for this window, instead of the journal's - `{ paths: [], types: [], keys: [] }` records everything. */\n record?: Omit<Options, 'level'>;\n}\n\nexport const tick = () => new Promise((resolve) => setTimeout(resolve, 0));\n\n/** Wait a macrotask at a time until one passes with no new frame. Resolves `false` if `timeout` passes first. */\nexport async function settle(seq: () => number | Promise<number>, wait: () => unknown = tick, timeout = SETTLE_TIMEOUT) {\n const end = Date.now() + timeout;\n\n for (let last = await seq(); ; ) {\n await wait();\n\n const next = await seq();\n\n if (next === last) return true;\n if (Date.now() >= end) return false;\n\n last = next;\n }\n}\n\nexport function unsettled(timeout = SETTLE_TIMEOUT) {\n console.warn(\n `Still active after ${timeout}ms - frames may be incomplete. Narrow the recording ({ record: { types, paths, keys } }) to exclude background work, or pass { timeout }.`\n );\n}\n\n/** `until` not met within `timeout` - carries the frames recorded so far and what never arrived. */\nexport function unreached(timeout: number, pending: string[], missing: string[], frames: Frame[], hint = '') {\n const list = pending.map((address) => (missing.includes(address) ? `${address} (names no instance)` : address));\n return Object.assign(new Error(`Not reached within ${timeout}ms: ${list.join(', ')}.${hint}`), { frames, pending });\n}\n","import type { Frame, Options, Query } from './journal';\nimport { SETTLE_TIMEOUT, settle, type Act } from './settle';\n\nexport interface Remote {\n record(options?: Options): Required<Options> | Promise<Required<Options>>;\n seq(): number | Promise<number>;\n frames(query: Query): Frame[] | Promise<Frame[]>;\n get(address: string): unknown;\n}\n\n/** Resolve `address.key` to the instance `address` names - label, id, or owner path - so frames match it alone. */\n/** Resolve `address.key` to the instance `address` names - label, id, or owner path - as the `id.key` its frames carry. */\nasync function locate(remote: Remote, target: string) {\n const dot = target.lastIndexOf('.');\n\n if (target[dot + 1] == '_')\n throw new Error(`until ${target}: _ keys are unmanaged and emit no events - wait on a value instead.`);\n const found = (await remote.get(target.slice(0, dot))) as { $ref?: string } | undefined;\n\n if (!found?.$ref) throw new Error(`until ${target}: ${target.slice(0, dot)} names no Model.`);\n\n return `${found.$ref}.${target.slice(dot + 1)}`;\n}\n\n/**\n * Run `step` recording values, wait for `until`, settle, and return what it produced; the prior recording is restored.\n * `local` steps run here, so activity for `until` counts once their synchronous writes flush, not once they resolve.\n */\nexport async function bracket(\n remote: Remote,\n step: () => unknown,\n wait: () => unknown,\n { until = [], timeout = SETTLE_TIMEOUT, record }: Act = {},\n local?: boolean\n) {\n const before = await remote.record();\n const since = await remote.seq();\n const window = { ...before, ...record };\n const filtered = window.types.length + window.paths.length + window.keys.length > 0;\n const values = typeof until == 'string' || Array.isArray(until) ? undefined : until;\n const addresses = values ? [] : ([] as string[]).concat(until as string | string[]);\n const paths = filtered ? [...window.paths, ...addresses.filter((address) => address.indexOf('.') === address.lastIndexOf('.'))] : [];\n\n await remote.record({ ...record, level: 'values', ...(filtered && { paths }) });\n\n try {\n const running = step();\n let from: number | undefined;\n\n if (local) {\n await undefined;\n from = await remote.seq();\n }\n\n const value = await running;\n\n from ??= await remote.seq();\n const end = Date.now() + timeout;\n const pending = new Set(values ? Object.keys(values) : addresses);\n const targets = new Map<string, string>();\n\n for (const address of addresses) targets.set(address, await locate(remote, address));\n\n if (filtered && addresses.some((address) => address.indexOf('.') !== address.lastIndexOf('.')))\n await remote.record({ paths: [...paths, ...targets.values()] });\n\n while (pending.size) {\n if (values) {\n for (const address of pending)\n if (JSON.stringify(await remote.get(address)) === JSON.stringify(values[address])) pending.delete(address);\n } else\n for (const frame of await remote.frames({ since: from }))\n for (const event of frame.events)\n for (const address of pending) if (targets.get(address) === `${event.id}.${event.key}`) pending.delete(address);\n\n if (!pending.size || Date.now() >= end) break;\n\n await wait();\n }\n\n const settled = !pending.size && (await settle(remote.seq, wait, Math.max(0, end - Date.now())));\n const missing: string[] = [];\n\n if (values)\n for (const address of pending)\n if ((await remote.get(address.slice(0, address.lastIndexOf('.')))) === undefined) missing.push(address);\n\n return { value, frames: await remote.frames({ since }), settled, pending: [...pending], missing, timeout };\n } finally {\n await remote.record(before);\n }\n}\n"],"mappings":";AAEA,MAAa,iBAAiB;AAc9B,MAAa,aAAa,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;;AAG1E,e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EAAE,OAAO,MAAM,CAAC,CACtD,MAAK,MAAM,SAAS,MAAM,OACxB,MAAK,MAAM,WAAW,QAAS,KAAI,QAAQ,IAAI,QAAQ,KAAK,GAAG,MAAM,GAAG,GAAG,MAAM,MAAO,SAAQ,OAAO,QAAQ;AAErH,OAAI,CAAC,QAAQ,QAAQ,KAAK,KAAK,IAAI,IAAK;AAExC,SAAM,MAAM;;EAGd,MAAM,UAAU,CAAC,QAAQ,QAAS,MAAM,OAAO,OAAO,KAAK,MAAM,KAAK,IAAI,GAAG,MAAM,KAAK,KAAK,CAAC,CAAC;EAC/F,MAAM,UAAoB,EAAE;AAE5B,MAAI,QACF;QAAK,MAAM,WAAW,QACpB,KAAK,MAAM,OAAO,IAAI,QAAQ,MAAM,GAAG,QAAQ,YAAY,IAAI,CAAC,CAAC,KAAM,OAAW,SAAQ,KAAK,QAAQ;;AAE3G,SAAO;GAAE;GAAO,QAAQ,MAAM,OAAO,OAAO,EAAE,OAAO,CAAC;GAAE;GAAS,SAAS,CAAC,GAAG,QAAQ;GAAE;GAAS;GAAS;WAClG;AACR,QAAM,OAAO,OAAO,OAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"inspect-D7_PFXdY.js","names":[],"sources":["../src/serialize.ts","../src/types.ts","../src/journal.ts","../src/inspect.ts"],"sourcesContent":["import { Model } from '@expressive/mvc';\n\nconst MAX_STRING = 240;\nconst MAX_ARRAY = 24;\nconst MAX_KEYS = 40;\n\nexport type Address = { target: string; path?: string };\n\nexport function parsePath(raw: string): Address {\n const trimmed = raw.trim();\n const dot = trimmed.indexOf('.');\n if (dot <= 0) return { target: trimmed };\n return { target: trimmed.slice(0, dot), path: trimmed.slice(dot + 1) };\n}\n\n/** Raw stored entries of a Model - never reads through accessors. */\nexport function entries(state: Model): Map<string, unknown> {\n return new Map(state);\n}\n\n/** Walk `path` without triggering getters, factories, or suspense. */\nexport function walk(value: unknown, path?: string): unknown {\n if (!path) return value;\n let cur: unknown = value;\n for (const part of path.split('.')) {\n if (cur == null || typeof cur !== 'object') return undefined;\n if (cur instanceof Model)\n cur = part[0] == '_' ? Object.getOwnPropertyDescriptor(cur, part)?.get?.() : entries(cur).get(part);\n else if (cur instanceof Map) cur = cur.get(part);\n else cur = (cur as Record<string, unknown>)[part];\n }\n return cur;\n}\n\nexport function ref(state: Model) {\n return { $ref: String(state), $type: state.constructor.name };\n}\n\n/** `true` takes a value as `serialize` would; an object picks keys and descends, applying to each element of a list. */\nexport type Select = true | { [key: string]: Select };\n\n/** Only the selected keys, read in one synchronous pass - a consistent snapshot. Models keep their `$ref`. */\nexport function project(value: unknown, select: Select): unknown {\n if (select === true || value == null || typeof value !== 'object') return serialize(value);\n\n const items = value instanceof Model ? undefined : list(value);\n\n if (items) {\n const out = items.slice(0, MAX_ARRAY).map((row) => project(row, select));\n if (items.length > MAX_ARRAY) out.push(`…+${items.length - MAX_ARRAY}`);\n return out;\n }\n\n const out: Record<string, unknown> = value instanceof Model ? ref(value) : {};\n for (const key in select) out[key] = project(walk(value, key), select[key]);\n return out;\n}\n\n/** JSON-safe, size-capped view. Nested Models collapse to `$ref`. */\nexport function serialize(value: unknown, depth = 2): unknown {\n if (value instanceof Model) {\n const out: Record<string, unknown> = ref(value);\n for (const [key, child] of [...entries(value)].slice(0, MAX_KEYS))\n out[key] = write(child, depth - 1);\n return out;\n }\n return write(value, depth);\n}\n\nfunction write(value: unknown, depth: number): unknown {\n if (value == null || typeof value === 'boolean') return value;\n if (typeof value === 'number') return Number.isFinite(value) ? value : String(value);\n if (typeof value === 'string')\n return value.length > MAX_STRING ? `${value.slice(0, MAX_STRING - 1)}…` : value;\n if (typeof value === 'bigint') return `${value}n`;\n if (typeof value !== 'object') return undefined;\n if (value instanceof Model) return ref(value);\n if (value instanceof Date) return value.toISOString();\n if (value instanceof Error) return { name: value.name, message: value.message };\n if (typeof (value as PromiseLike<unknown>).then === 'function') return '(pending)';\n\n const items = list(value);\n\n if (items) {\n if (depth <= 0) return `[${items.length}]`;\n const out = items.slice(0, MAX_ARRAY).map((row) => write(row, depth - 1));\n if (items.length > MAX_ARRAY) out.push(`…+${items.length - MAX_ARRAY}`);\n return out;\n }\n\n const pairs = value instanceof Map\n ? [...value].map(([k, v]) => [String(k), v] as const)\n : Object.entries(value);\n\n if (depth <= 0) return `{${pairs.length}}`;\n\n const out: Record<string, unknown> = {};\n for (const [key, child] of pairs.slice(0, MAX_KEYS)) {\n if (key === 'is') continue;\n const next = write(child, depth - 1);\n if (next !== undefined) out[key] = next;\n }\n if (pairs.length > MAX_KEYS) out['…'] = pairs.length - MAX_KEYS;\n return out;\n}\n\nfunction list(value: object): unknown[] | undefined {\n if (Array.isArray(value)) return value;\n if (value instanceof Map) return undefined;\n if (typeof (value as Iterable<unknown>)[Symbol.iterator] === 'function')\n return [...(value as Iterable<unknown>)];\n return undefined;\n}\n","import { Model } from '@expressive/mvc';\n\nexport interface TypeInfo {\n /** Opaque, stable for the life of the process. */\n typeId: string;\n /** Resolved display name - see `label`. */\n type: string;\n /** Construction stack captured at first sight, for a source-map resolver. */\n site: string;\n}\n\nconst info = new Map<typeof Model, TypeInfo>();\nconst labels = new Map<typeof Model, string>();\nconst names = new Map<string, string>();\nlet count = 0;\n\nfunction register(Type: typeof Model): TypeInfo {\n let row = info.get(Type);\n if (!row) {\n const site = String(new Error().stack).split('\\n').slice(1, 16).join('\\n');\n info.set(Type, (row = { typeId: `T${++count}`, type: '', site }));\n }\n return row;\n}\n\nexport function seen(Type: typeof Model): TypeInfo {\n const row = register(Type);\n row.type = labelOf(Type);\n return { ...row };\n}\n\nexport function labelOf(Type: typeof Model): string {\n const row = register(Type);\n const explicit = labels.get(Type) ?? (Type as { displayName?: string }).displayName;\n if (explicit) return explicit;\n const named = names.get(row.typeId) ?? names.get(row.site);\n if (named) return named;\n return Type.name.length > 2 ? Type.name : row.typeId;\n}\n\nexport function label(Type: typeof Model, name: string): void {\n labels.set(Type, name);\n}\n\n/** Supply resolved names keyed by `typeId` or `site`, e.g. from a source-map pass. */\nexport function resolve(table: Record<string, string>): void {\n for (const [key, name] of Object.entries(table)) names.set(key, name);\n}\n\nexport function forget(): void {\n info.clear();\n labels.clear();\n names.clear();\n count = 0;\n}\n","import { Model } from '@expressive/mvc';\n\nimport { parsePath, serialize } from './serialize';\nimport { labelOf, seen } from './types';\n\nexport type Level = 'off' | 'keys' | 'values';\n\nexport interface Options {\n level?: Level;\n /** Labels to record. */\n types?: string[];\n /** `Type.key` addresses to record - label, `typeId`, or instance id on the left, property on the right. */\n paths?: string[];\n /** Property names to record on any type. */\n keys?: string[];\n /** Also record method calls, except `render`. */\n calls?: boolean;\n}\n\nexport interface Event {\n id: string;\n type: string;\n key: string;\n kind: 'update' | 'event' | 'call' | 'destroy' | 'caught' | 'hot';\n value?: unknown;\n args?: unknown[];\n}\n\nexport interface Frame {\n seq: number;\n at: number;\n /** Frame whose flush scheduled the work that opened this one. */\n cause?: number;\n events: Event[];\n}\n\nexport interface Summary {\n id: string;\n type: string;\n /** Seq of the last frame touching this instance. */\n last: number;\n /** Updates and events per key, with the last recorded value at `values` level. */\n keys: Record<string, { count: number; value?: unknown }>;\n calls: Record<string, number>;\n /** `caught` reports. */\n caught: number;\n /** Hot patches applied to it. */\n hot: number;\n destroyed: boolean;\n}\n\nexport interface Query {\n since?: number;\n type?: string;\n id?: string;\n key?: string;\n cause?: number;\n}\n\nconst FRAME_CAP = 500;\n\nconst frames: Frame[] = [];\nconst config: Required<Options> = { level: 'off', types: [], paths: [], keys: [], calls: false };\nlet seq = 0;\nlet open: Frame | undefined;\nlet cause: number | undefined;\n\nexport const journal = {\n record(options: Options = {}): Required<Options> {\n Object.assign(config, options);\n if (!options.level && options.calls && config.level === 'off') config.level = 'keys';\n return { ...config, types: [...config.types], paths: [...config.paths], keys: [...config.keys] };\n },\n\n frames(query: Query = {}): Frame[] {\n const out: Frame[] = [];\n for (const frame of frames) {\n if (query.since !== undefined && frame.seq <= query.since) continue;\n if (query.cause !== undefined && frame.cause !== query.cause) continue;\n const events = frame.events.filter((e) => matches(e, query));\n if (events.length) out.push({ ...frame, events });\n }\n return out;\n },\n\n history(query: Query): Array<{ seq: number; at: number; event: Event }> {\n const out = [];\n for (const frame of journal.frames(query))\n for (const event of frame.events) out.push({ seq: frame.seq, at: frame.at, event });\n return out;\n },\n\n /** Frames reachable from `seq` through `cause` links, in order. */\n downstream(from: number): Frame[] {\n const roots = new Set([from]);\n return frames.filter((frame) => {\n if (frame.cause === undefined || !roots.has(frame.cause)) return false;\n roots.add(frame.seq);\n return true;\n });\n },\n\n /** Current sequence - pass as `since` to read only what follows. */\n seq(): number {\n return seq;\n },\n\n /** One event per line, for bulk export to a sidecar. */\n export(query: Query = {}): string {\n return journal\n .frames(query)\n .flatMap((frame) =>\n frame.events.map((event) =>\n JSON.stringify({ seq: frame.seq, at: frame.at, cause: frame.cause, ...event })\n )\n )\n .join('\\n');\n },\n\n /** Per-instance digest of recorded frames, most recently active first. */\n summary(query: Query = {}): Summary[] {\n const by = new Map<string, Summary>();\n\n for (const frame of journal.frames(query))\n for (const event of frame.events) {\n if (!event.id) continue;\n\n let entry = by.get(event.id);\n\n if (!entry) by.set(event.id, (entry = { id: event.id, type: event.type, last: 0, keys: {}, calls: {}, caught: 0, hot: 0, destroyed: false }));\n\n entry.last = frame.seq;\n\n if (event.kind === 'destroy') entry.destroyed = true;\n else if (event.kind === 'call') entry.calls[event.key] = (entry.calls[event.key] || 0) + 1;\n else if (event.kind === 'caught') entry.caught++;\n else if (event.kind === 'hot') entry.hot++;\n else {\n const key = (entry.keys[event.key] ||= { count: 0 });\n key.count++;\n if ('value' in event) key.value = event.value;\n }\n }\n\n return [...by.values()].sort((a, b) => b.last - a.last);\n },\n\n /**\n * Record a page-level hot update: `key` names it (`update`, `reload`), `value`\n * its detail. Recorded unfiltered while the journal is on.\n */\n hot(key: string, value?: unknown): void {\n if (config.level === 'off') return;\n\n const event: Event = { id: '', type: 'vite', key, kind: 'hot' };\n if (value !== undefined) event.value = value;\n push(event);\n },\n\n clear(): void {\n frames.length = 0;\n open = undefined;\n cause = undefined;\n seq = 0;\n },\n\n reset(): void {\n journal.clear();\n Object.assign(config, { level: 'off', types: [], paths: [], keys: [], calls: false });\n }\n};\n\nfunction matches(event: Event, query: Query) {\n return (\n (!query.type || event.type === query.type) &&\n (!query.id || event.id === query.id) &&\n (!query.key || event.key === query.key)\n );\n}\n\n/** Filters OR together; none set records everything. Without a key only type-level filters apply. */\nexport function wants(state: Model, key?: string): boolean {\n if (config.level === 'off') return false;\n\n const { types, paths, keys } = config;\n if (!types.length && !paths.length && !keys.length) return true;\n\n const Type = state.constructor as typeof Model;\n const label = labelOf(Type);\n if (types.includes(label)) return true;\n if (key !== undefined && keys.includes(key)) return true;\n\n const targets = [label, seen(Type).typeId, String(state)];\n for (const address of paths) {\n const { target, path } = parsePath(address);\n if (targets.includes(target) && (key === undefined || path === key)) return true;\n }\n return false;\n}\n\nexport function recordsCalls(): boolean {\n return config.calls && config.level !== 'off';\n}\n\n\nexport function note(state: Model, key: unknown, store: Map<string, unknown>): void {\n const name = String(key);\n if (!wants(state, name)) return;\n\n const event: Event = {\n id: String(state),\n type: labelOf(state.constructor as typeof Model),\n key: name,\n kind: typeof key === 'string' && store.has(key) ? 'update' : 'event'\n };\n\n if (config.level === 'values' && event.kind === 'update')\n event.value = serialize(store.get(name), 1);\n\n push(event);\n}\n\nexport function noteCall(state: Model, key: string, args: unknown[]): void {\n if (!recordsCalls() || !wants(state, key)) return;\n\n const event: Event = { id: String(state), type: labelOf(state.constructor as typeof Model), key, kind: 'call' };\n if (config.level === 'values') event.args = args.map((arg) => serialize(arg, 1));\n push(event);\n}\n\nexport function noteCaught(state: Model, error: unknown, kind: string, key?: string): { handled: boolean } | undefined {\n if (!wants(state, key)) return;\n const value = {\n case: kind,\n message: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n handled: true\n };\n push({ id: String(state), type: labelOf(state.constructor as typeof Model), key: key ?? '', kind: 'caught', value });\n return value;\n}\n\nexport function notePatch(state: Model): void {\n if (wants(state)) push({ id: String(state), type: labelOf(state.constructor as typeof Model), key: 'patch', kind: 'hot' });\n}\n\nexport function noteDestroy(state: Model): void {\n if (!wants(state)) return;\n push({ id: String(state), type: labelOf(state.constructor as typeof Model), key: '', kind: 'destroy' });\n}\n\nfunction push(event: Event) {\n if (!open) {\n const frame: Frame = { seq: ++seq, at: Date.now(), events: [] };\n if (cause !== undefined) frame.cause = cause;\n open = frame;\n frames.push(frame);\n if (frames.length > FRAME_CAP) frames.splice(0, frames.length - FRAME_CAP);\n queueMicrotask(() => {\n open = undefined;\n cause = frame.seq;\n queueMicrotask(() => {\n if (seq === frame.seq) cause = undefined;\n });\n });\n }\n open.events.push(event);\n}\n","import { Context, Model, unbind } from '@expressive/mvc';\nimport { listener, observer } from '@expressive/mvc/observable';\nimport { isElement } from '@expressive/mvc/jsx-runtime';\n\nimport { journal, note, noteCall, noteCaught, noteDestroy, notePatch, type Frame, type Query } from './journal';\nimport { entries, parsePath, project, serialize, walk, type Select } from './serialize';\nimport { bracket } from './bracket';\nimport { tick, unreached, unsettled, type Act } from './settle';\nimport { forget, seen, type TypeInfo } from './types';\n\nexport interface ModelInfo extends TypeInfo {\n id: string;\n parent?: string;\n /** Keys with a stored value. */\n keys: string[];\n /** Declared keys with no stored value yet - lazy, pending, or uncomputed. */\n absent: string[];\n}\n\nexport interface Node {\n id: string;\n type: string;\n children: Node[];\n}\n\ninterface Span {\n since: number;\n until?: number;\n claimed: boolean;\n settled: boolean;\n held?: boolean;\n}\n\ninterface Row {\n ref: { deref(): Model | undefined };\n held?: Model;\n}\n\nconst Reaper: typeof FinalizationRegistry =\n typeof FinalizationRegistry === 'function'\n ? FinalizationRegistry\n : (class {\n register() {}\n unregister() {}\n } as unknown as typeof FinalizationRegistry);\n\nconst weak = (state: Model): Row['ref'] =>\n typeof WeakRef === 'function' ? new WeakRef(state) : { deref: () => state };\n\nconst live = new Map<string, Row>();\nconst hooks = new Map<typeof Model, () => void>();\n\nconst COPIES = Symbol.for('@expressive/mvc');\n\nconst REFRESH = Symbol.for('@expressive/mvc.refresh');\nconst wrappers = new WeakMap<Model, Instance>();\nconst spans = new WeakMap<Model, Span>();\nconst reaper = new Reaper<string>(collected);\n\nlet version = 0;\nlet cached: { version: number; owners: Map<Model, Model>; holders: Map<Model, Model> } | undefined;\nlet lost = 0;\nlet tally = counts();\nlet copies = 1;\nlet unwatch: (() => void) | undefined;\n\nfunction counts(): Record<string, number> {\n return { dead: 0, unused: 0, getter: 0, setup: 0, effect: 0 };\n}\n\n/** The report `observe` last saw - the chain is synchronous, so `unhandled` checks it against its own. */\nlet last: { error: unknown; event?: { handled: boolean } } | undefined;\n\nfunction observe(this: Model, error: unknown, kind: string, key?: string) {\n tally[kind]++;\n last = { error, event: noteCaught(this, error, kind, key) };\n return error;\n}\n\nfunction unhandled(this: Model, error: unknown, kind: string, key?: string) {\n if (last?.error !== error) observe.call(this, error, kind, key);\n if (last!.event) last!.event.handled = false;\n last = undefined;\n return error;\n}\n\nexport function clearCaught(): void {\n tally = counts();\n}\n\n/** Count loaded copies of mvc from the list each one joins on first construction; warn once on a second. */\nfunction watchCopies() {\n const list = ((globalThis as { [COPIES]?: unknown[] })[COPIES] ||= []);\n const { push } = list;\n const check = () => {\n const was = copies;\n copies = new Set([Model, ...list]).size;\n if (copies > 1 && was === 1)\n console.warn(`${copies} copies of @expressive/mvc are loaded - inspect sees only the one it imports.`);\n };\n\n list.push = (...items) => {\n const length = push.apply(list, items);\n check();\n return length;\n };\n\n check();\n unwatch = () => {\n list.push = push;\n };\n}\n\n/** Registered instances still reachable, claimed or not. */\nfunction registered(): Model[] {\n return [...live.values()]\n .map((row) => row.held ?? row.ref.deref())\n .filter((state): state is Model => !!state);\n}\n\n/** Instances on the mainline: claimed, or too young to judge, or every one when no host renders. */\nfunction* mainline(): Generator<Model> {\n const parents = reach();\n for (const state of registered()) if (!orphaned(state, parents)) yield state;\n}\n\nfunction orphaned(state: Model, parents: Map<Model, Model>, seen = new Set<Model>()): boolean {\n const span = spans.get(state)!;\n if (span.claimed || !span.settled || !hosted()) return false;\n if (provided(state)) {\n claim(state);\n return false;\n }\n const owner = parents.get(state);\n if (!owner || seen.has(owner)) return true;\n seen.add(state);\n if (orphaned(owner, parents, seen)) return true;\n if (spans.get(owner)!.claimed) claim(state);\n return false;\n}\n\nfunction claim(state: Model) {\n const span = spans.get(state)!;\n if (span.claimed) return;\n span.claimed = true;\n const row = live.get(String(state));\n if (!row) return;\n row.held = state;\n reaper.unregister(state);\n version++;\n}\n\n/** An instance held in the root context. */\nfunction provided(state: Model): boolean {\n for (const set of Context.root.provide.values())\n if (set) for (const [member] of set) if (member === state) return true;\n return false;\n}\n\nfunction hosted(): boolean {\n try {\n isElement(null);\n return true;\n } catch {\n return false;\n }\n}\n\n/** A registered, unclaimed instance was garbage collected - it was abandoned. */\nexport function collected(id: string): void {\n if (!live.delete(id)) return;\n lost++;\n version++;\n}\n\n/** Navigable view of one instance - identity, ownership, reads, observation. One per state; outlives it. */\nexport class Instance {\n private constructor(readonly state: Model) {}\n\n static of(state: Model): Instance {\n let instance = wrappers.get(state);\n if (!instance) wrappers.set(state, (instance = new Instance(state)));\n return instance;\n }\n\n get id() {\n return String(this.state);\n }\n\n get type() {\n return seen(this.state.constructor as typeof Model).type;\n }\n\n get alive() {\n return live.has(this.id);\n }\n\n /** Reached by a host commit (`mount`), a claimed owner, or the root context. Always true without a host. */\n get claimed() {\n return !orphaned(this.state, reach());\n }\n\n /** Registration time (ms). */\n get since() {\n return spans.get(this.state)!.since;\n }\n\n /** Destruction time (ms), once destroyed. */\n get until() {\n return spans.get(this.state)!.until;\n }\n\n get parent(): Instance | undefined {\n const owner = ownership().get(this.state);\n return owner && Instance.of(owner);\n }\n\n get children(): Instance[] {\n const parents = ownership();\n return [...registered()]\n .filter((state) => parents.get(state) === this.state)\n .map(Instance.of);\n }\n\n /** First instance in this subtree, depth-first, matching `where` (a label or predicate). */\n find(where: string | ((instance: Instance) => boolean)): Instance | undefined {\n const test = typeof where === 'string' ? (h: Instance) => h.type === where : where;\n for (const child of this.children) {\n if (test(child)) return child;\n const deep = child.find(test);\n if (deep) return deep;\n }\n return undefined;\n }\n\n get(path?: string, select?: Select): unknown {\n const value = walk(this.state, path);\n return select ? project(value, select) : serialize(value);\n }\n\n model(): ModelInfo {\n return describe(this.state, ownership());\n }\n\n /** Run `work`, settle, and return the frames it produced. */\n act(work: (state: Model) => unknown, options?: Act): Promise<Frame[]> {\n return act(() => work(this.state), options);\n }\n\n /** Call `fn` on each update, and with `null` on destroy; `keys` narrows updates. Returns unsubscribe. */\n watch(fn: (key: string | null) => void, keys?: string[]): () => void {\n const updates = this.state.set((key) => {\n if (typeof key === 'string' && (!keys || keys.includes(key))) fn(key);\n });\n const destroy = this.state.get(null, () => fn(null));\n return () => {\n updates();\n destroy();\n };\n }\n\n frames(query: Query = {}): Frame[] {\n return journal.frames({ ...query, id: this.id });\n }\n}\n\nexport function attach(Type: typeof Model = Model): () => void {\n if (!unwatch) watchCopies();\n\n if (!hooks.has(Type)) {\n const observed = new Map<typeof Model, () => void>();\n const stopCatch = Type.on({ catch: unhandled });\n const stopCall = Type.on({ type: trace, method: retrace });\n const stopSetup = Type.on({\n ready(this: Model) {\n const self = this.is;\n if (spans.get(self)!.held) claim(self);\n },\n setup(this: Model) {\n const self = this.is;\n const T = self.constructor as typeof Model;\n const id = String(self);\n const span: Span = { since: Date.now(), claimed: false, settled: false };\n if (!observed.has(T)) observed.set(T, T.on({ catch: observe }));\n seen(T);\n live.set(id, { ref: weak(self) });\n spans.set(self, span);\n reaper.register(self, id, self);\n setTimeout(() => {\n span.settled = true;\n }, 0);\n queueMicrotask(() => {\n span.held = !!observer(self)?.wait;\n });\n version++;\n const unpatch = listener(self, () => notePatch(self), REFRESH);\n const stop = self.set((key) => {\n const store = entries(self);\n if (typeof key === 'string' && typeof store.get(key) === 'object') version++;\n note(self, key, store);\n });\n return () => {\n stop();\n unpatch();\n live.delete(id);\n reaper.unregister(self);\n span.until = Date.now();\n version++;\n noteDestroy(self);\n };\n }\n });\n hooks.set(Type, () => {\n for (const stop of observed.values()) stop();\n stopCatch();\n stopCall();\n stopSetup();\n });\n }\n\n return () => {\n hooks.get(Type)?.();\n hooks.delete(Type);\n };\n}\n\nexport function detach(): void {\n for (const stop of hooks.values()) stop();\n hooks.clear();\n live.clear();\n cached = undefined;\n lost = 0;\n tally = counts();\n copies = 1;\n unwatch?.();\n unwatch = undefined;\n journal.reset();\n forget();\n}\n\n/** Resolve an id or label to an instance - mainline first, then orphans. */\nexport function find(target: string): Instance | undefined {\n const byId = live.get(target);\n const held = byId && (byId.held ?? byId.ref.deref());\n if (held) return Instance.of(held);\n\n const types = new Map<typeof Model, string>();\n let first: Model | undefined;\n\n for (const pool of [mainline(), abandoned()])\n for (const state of pool) {\n const Type = state.constructor as typeof Model;\n const info = seen(Type);\n if (info.type !== target) continue;\n first ??= state;\n types.set(Type, info.typeId);\n }\n\n if (types.size > 1)\n throw new Error(\n `${target} matches ${types.size} classes (${[...types.values()].join(', ')}) - address by instance id or owner path, or label() one. models() lists their construction sites.`\n );\n\n return first && Instance.of(first);\n}\n\nexport function instances(): Instance[] {\n return [...mainline()].map(Instance.of);\n}\n\n/** Registered and settled, but never claimed by a host commit, an owner, or root context. */\nexport function orphans(): Instance[] {\n return [...abandoned()].map(Instance.of);\n}\n\nfunction* abandoned(): Generator<Model> {\n const parents = reach();\n for (const state of registered()) if (orphaned(state, parents)) yield state;\n}\n\nexport interface Health {\n /** Live instances no host, owner, or root slot claimed. */\n orphans: number;\n /** Unclaimed instances the collector already reaped. */\n collected: number;\n /** Loaded copies of `@expressive/mvc` - more than 1 means inspect cannot see every Model. */\n copies: number;\n /** Reports by kind, including ones an app handler went on to handle; zeroed by `journal.clear()`. */\n caught: Record<string, number>;\n}\n\n/** Counts worth a look before trusting what inspect shows. */\nexport function health(): Health {\n return { orphans: orphans().length, collected: lost, copies, caught: { ...tally } };\n}\n\nexport function roots(): Instance[] {\n const parents = ownership();\n return instances().filter((instance) => !parents.has(instance.state));\n}\n\nexport function models(): ModelInfo[] {\n const parents = ownership();\n return [...mainline()].map((state) => describe(state, parents));\n}\n\nexport function tree(): Node[] {\n const parents = ownership();\n const nodes = new Map<Model, Node>();\n const out: Node[] = [];\n\n for (const state of mainline())\n nodes.set(state, { id: String(state), type: seen(state.constructor as typeof Model).type, children: [] });\n\n for (const [state, node] of nodes) {\n const parent = parents.get(state);\n const owner = parent && nodes.get(parent);\n if (owner) owner.children.push(node);\n else out.push(node);\n }\n\n return out;\n}\n\n/** Run `work` recording values; returns the frames it produced once `until` holds and activity goes quiet. */\nexport async function act(work: () => unknown, options: Act = {}): Promise<Frame[]> {\n const { frames, settled, pending, missing, timeout } = await bracket({ ...journal, get }, work, tick, options, true);\n if (pending.length) throw unreached(timeout, pending, missing, frames);\n if (!settled) unsettled(timeout);\n return frames;\n}\n\nexport function get(address?: string, select?: Select): unknown {\n if (!address) return models();\n const { target, path } = parsePath(address);\n return find(target)?.get(path, select);\n}\n\nexport function set(address: string, value: unknown): void {\n const { target, path } = parsePath(address);\n const instance = find(target);\n if (!instance || !path) throw new Error(`No model at ${address}.`);\n\n const dot = path.lastIndexOf('.');\n const key = path.slice(dot + 1);\n const owner = dot < 0 ? instance.state : walk(instance.state, path.slice(0, dot));\n\n if (owner == null || typeof owner !== 'object') throw new Error(`No model at ${address}.`);\n\n if (owner instanceof Map) owner.set(key, value);\n else (owner as Record<string, unknown>)[key] = value;\n}\n\nexport async function call(address: string, ...args: unknown[]): Promise<unknown> {\n const { target, path } = parsePath(address);\n const state = find(target)?.state;\n const method = state && path && (state as unknown as Record<string, unknown>)[path];\n\n if (typeof method !== 'function') throw new Error(`No method at ${address}.`);\n\n return serialize(await method.apply(state, args));\n}\n\nconst TRACED = new WeakSet<Function>();\n\n/** Wrap a class's own methods before they bind, so each call is recorded. */\nfunction trace(type: typeof Model) {\n const proto = type.prototype as unknown as Record<string, Function>;\n\n for (const [key, desc] of Object.entries(Object.getOwnPropertyDescriptors(proto)))\n if (key != 'constructor' && key != 'render' && typeof desc.value == 'function' && desc.configurable)\n proto[key] = traced(key, desc.value);\n}\n\n/**\n * Rebind a method replaced through `set()` to a traced copy, so `unbind` still yields a function honoring `this`.\n * A class bootstrapped before attach keeps its methods untraced - wrapped per instance, a hot patch would keep them.\n */\nfunction retrace(this: Model, key: string, fn: Function) {\n const source = unbind(fn);\n let proto = Object.getPrototypeOf(this);\n\n while (!Object.prototype.hasOwnProperty.call(proto, key)) proto = Object.getPrototypeOf(proto);\n\n if (key == 'render' || TRACED.has(source) || source === unbind(Object.getOwnPropertyDescriptor(proto, key)!.get!)) return;\n\n const self = this as unknown as Record<string, Function>;\n\n delete self[key];\n self[key] = traced(key, source);\n}\n\n/** A `super` call reaches the base wrapper too; only the one `this[key]` resolves to records. */\nfunction traced(key: string, fn: Function) {\n const wrapper = Object.defineProperties(\n function (this: Record<string, Function>, ...args: unknown[]) {\n if (unbind(this[key]) === wrapper) noteCall(this as unknown as Model, key, args);\n return fn.apply(this, args);\n },\n { name: { value: fn.name }, length: { value: fn.length } }\n );\n\n TRACED.add(wrapper);\n\n return wrapper;\n}\n\nfunction describe(state: Model, parents: Map<Model, Model>): ModelInfo {\n const stored = entries(state);\n const declared = Object.entries(Object.getOwnPropertyDescriptors(state))\n .filter(([, desc]) => typeof desc.get === 'function')\n .map(([key]) => key);\n const model: ModelInfo = {\n id: String(state),\n ...seen(state.constructor as typeof Model),\n keys: [...stored.keys()],\n absent: declared.filter((key) => !stored.has(key))\n };\n const parent = parents.get(state);\n if (parent) model.parent = String(parent);\n return model;\n}\n\n/** Each instance's owner, from mvc. */\nfunction ownership(): Map<Model, Model> {\n return graph().owners;\n}\n\n/** Owner, else the first instance holding it - what keeps an instance from being abandoned. */\nfunction reach(): Map<Model, Model> {\n return graph().holders;\n}\n\nfunction graph() {\n if (cached?.version !== version) {\n const owners = new Map<Model, Model>();\n const holders = new Map<Model, Model>();\n\n for (const state of registered()) {\n const owner = state.get(Model, false);\n if (owner) owners.set(state, owner);\n\n for (const [key, value] of entries(state)) {\n const field = Object.getOwnPropertyDescriptor(state, key)?.enumerable;\n if (field || !(value instanceof Model)) hold(holders, state, value);\n }\n }\n\n for (const [state, owner] of owners) holders.set(state, owner);\n\n cached = { version, owners, holders };\n }\n\n return cached;\n}\n\nfunction hold(holders: Map<Model, Model>, holder: Model, value: unknown) {\n if (value instanceof Model) {\n if (!holders.has(value) && value !== holder) holders.set(value, holder);\n } else if (value && typeof value === 'object' && Symbol.iterator in value) {\n const items = value instanceof Map ? value.values() : (value as Iterable<unknown>);\n for (const item of items) if (item instanceof Model) hold(holders, holder, item);\n }\n}\n"],"mappings":";;;;;;AAEA,MAAM,aAAa;AACnB,MAAM,YAAY;AAClB,MAAM,WAAW;AAIjB,SAAgB,UAAU,KAAsB;CAC9C,MAAM,UAAU,IAAI,MAAM;CAC1B,MAAM,MAAM,QAAQ,QAAQ,IAAI;AAChC,KAAI,OAAO,EAAG,QAAO,EAAE,QAAQ,SAAS;AACxC,QAAO;EAAE,QAAQ,QAAQ,MAAM,GAAG,IAAI;EAAE,MAAM,QAAQ,MAAM,MAAM,EAAE;EAAE;;;AAIxE,SAAgB,QAAQ,OAAoC;AAC1D,QAAO,IAAI,IAAI,MAAM;;;AAIvB,SAAgB,KAAK,OAAgB,MAAwB;AAC3D,KAAI,CAAC,KAAM,QAAO;CAClB,IAAI,MAAe;AACnB,MAAK,MAAM,QAAQ,KAAK,MAAM,IAAI,EAAE;AAClC,MAAI,OAAO,QAAQ,OAAO,QAAQ,SAAU,QAAO;AACnD,MAAI,eAAe,MACjB,OAAM,KAAK,MAAM,MAAM,OAAO,yBAAyB,KAAK,KAAK,EAAE,OAAO,GAAG,QAAQ,IAAI,CAAC,IAAI,KAAK;WAC5F,eAAe,IAAK,OAAM,IAAI,IAAI,KAAK;MAC3C,OAAO,IAAgC;;AAE9C,QAAO;;AAGT,SAAgB,IAAI,OAAc;AAChC,QAA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