{"version":3,"file":"uiTrace.cjs","names":[],"sources":["../../../src/web/lib/uiTrace.ts"],"sourcesContent":["/**\n * Store-update and render rollups for the client log sink, shared by the web cockpit and the\n * native app. Each window becomes one record per store and per component: how often it changed or\n * rendered, which state paths changed, and how long renders took. A rollup over its storm rate is\n * a warning, so a render storm names its store and component without a debugger attached.\n *\n * Nothing is counted until a client binds a sink. React and the stores are the only dependencies,\n * so this stays importable from the DOM-free core entry.\n */\nimport { type ProfilerOnRenderCallback, useLayoutEffect } from 'react';\n\nexport interface UiTraceRecord {\n  event: 'ui.store_updates' | 'ui.renders';\n  level: 'info' | 'warn';\n  attributes: Record<string, string | number>;\n}\nexport type UiTraceSink = (records: UiTraceRecord[]) => void;\n\nconst WINDOW_MS = 10_000;\n/** Per-second rates over which a rollup is a storm. */\nconst STORE_STORM_PER_SECOND = 10;\nconst RENDER_STORM_PER_SECOND = 30;\n/** Store paths are walked this deep, so `byId.-.updatedAt` names the churning field. */\nconst PATH_DEPTH = 3;\nconst MAX_PATHS = 8;\n/** The server sanitizer drops a longer string attribute outright, so the busiest paths that fit are kept. */\nconst MAX_PATHS_LENGTH = 128;\n/** Ranked by rate, so a busy window drops its quietest rows; the web queue holds 32. */\nconst MAX_RECORDS = 20;\n/**\n * Field names stay; map keys such as session and tool ids collapse to `-`, which keeps ids out of\n * telemetry. Markers use only characters the server's attribute sanitizer keeps.\n */\nconst FIELD_KEY = /^[A-Za-z_$][A-Za-z0-9_$]{0,23}$/u;\nconst ANY_KEY = '-';\nconst SAME_FIELDS = '-same';\n\ninterface StoreRow {\n  updates: number;\n  paths: Map<string, number>;\n}\ninterface RenderRow {\n  renders: number;\n  timed: number;\n  totalMs: number;\n  maxMs: number;\n}\n\nconst storeRows = new Map<string, StoreRow>();\nconst renderRows = new Map<string, RenderRow>();\nlet sink: UiTraceSink | undefined;\nlet timer: ReturnType<typeof setInterval> | undefined;\nlet windowStart = 0;\n\nfunction isPlain(value: unknown): value is Record<string, unknown> {\n  if (typeof value !== 'object' || value === null) return false;\n  const prototype = Object.getPrototypeOf(value) as unknown;\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction changedPaths(previous: unknown, next: unknown, path: string, depth: number, into: string[]): void {\n  if (depth === PATH_DEPTH || !isPlain(previous) || !isPlain(next)) {\n    into.push(path);\n    return;\n  }\n  const before = into.length;\n  for (const key of new Set([...Object.keys(previous), ...Object.keys(next)]))\n    if (previous[key] !== next[key]) {\n      const segment = FIELD_KEY.test(key) ? key : ANY_KEY;\n      changedPaths(previous[key], next[key], path ? `${path}.${segment}` : segment, depth + 1, into);\n    }\n  // A new object with equal fields still wakes every subscriber.\n  if (into.length === before) into.push(path ? `${path}.${SAME_FIELDS}` : SAME_FIELDS);\n}\n\n/** Counts one store change and the state paths it touched. */\nexport function noteStoreUpdate(name: string, previous: unknown, next: unknown): void {\n  if (sink === undefined) return;\n  const row = storeRows.get(name) ?? { updates: 0, paths: new Map<string, number>() };\n  storeRows.set(name, row);\n  row.updates += 1;\n  const paths: string[] = [];\n  changedPaths(previous, next, '', 0, paths);\n  // Once per update, however many ids collapsed onto the same path.\n  for (const path of new Set(paths.map((path) => path || '(value)')))\n    row.paths.set(path, (row.paths.get(path) ?? 0) + 1);\n}\n\ninterface TraceableStore {\n  readonly state: unknown;\n  subscribe(listener: (value: unknown) => void): unknown;\n}\n\n/** Reports every change of `store` under `name`; returns the store so it can wrap the constructor. */\nexport function traceStore<S extends TraceableStore>(name: string, store: S): S {\n  let previous = store.state;\n  store.subscribe((next) => {\n    noteStoreUpdate(name, previous, next);\n    previous = next;\n  });\n  return store;\n}\n\n/** Counts one render of `name`; `ms` is its duration when known. */\nexport function noteRender(name: string, ms?: number): void {\n  if (sink === undefined) return;\n  const row = renderRows.get(name) ?? { renders: 0, timed: 0, totalMs: 0, maxMs: 0 };\n  renderRows.set(name, row);\n  if (ms === undefined) {\n    row.renders += 1;\n    return;\n  }\n  row.timed += 1;\n  row.totalMs += ms;\n  row.maxMs = Math.max(row.maxMs, ms);\n}\n\n/**\n * Counts the renders of the calling component, and times render start to layout effect, which\n * includes its children. Works in production builds, unlike `<Profiler>`.\n */\nexport function useRenderTrace(name: string): void {\n  // ponytail: the hook runs only while a sink is bound. Both clients bind it at module load, before\n  // the first render, so every mounted component keeps one hook order. Bind later and a component\n  // mounted before then changes its hook count; move the bind into a provider if that is ever needed.\n  if (sink === undefined) return;\n  const started = performance.now();\n  noteRender(name);\n  // oxlint-disable-next-line react-hooks/rules-of-hooks\n  useLayoutEffect(() => noteRender(name, performance.now() - started));\n}\n\n/**\n * `<Profiler onRender>` for subtrees the host does not own, such as template screens. React calls\n * it only in development and profiling builds.\n */\nexport const traceProfilerRender: ProfilerOnRenderCallback = (id, _phase, actualDuration) => {\n  noteRender(id);\n  noteRender(id, actualDuration);\n};\n\nfunction round(value: number): number {\n  return Math.round(value * 10) / 10;\n}\n\nfunction topPaths(paths: Map<string, number>): string {\n  let joined = '';\n  for (const [path, count] of [...paths].sort((a, b) => b[1] - a[1]).slice(0, MAX_PATHS)) {\n    const next = `${joined}${joined ? ' ' : ''}${path}:${String(count)}`;\n    if (next.length > MAX_PATHS_LENGTH) break;\n    joined = next;\n  }\n  return joined;\n}\n\n/** Hands the current window to the sink and starts the next one. Exported for tests. */\nexport function flushUiTrace(now = Date.now()): void {\n  const seconds = Math.max(1, (now - windowStart) / 1000);\n  windowStart = now;\n  const window_ms = Math.round(seconds * 1000);\n  const ranked: [number, UiTraceRecord][] = [];\n  for (const [store, row] of storeRows) {\n    const perSecond = row.updates / seconds;\n    ranked.push([\n      perSecond,\n      {\n        event: 'ui.store_updates',\n        level: perSecond >= STORE_STORM_PER_SECOND ? 'warn' : 'info',\n        attributes: {\n          store_name: store,\n          updates: row.updates,\n          per_second: round(perSecond),\n          window_ms,\n          changed_state: topPaths(row.paths),\n        },\n      },\n    ]);\n  }\n  for (const [component, row] of renderRows) {\n    const count = Math.max(row.renders, row.timed);\n    const perSecond = count / seconds;\n    ranked.push([\n      perSecond,\n      {\n        event: 'ui.renders',\n        level: perSecond >= RENDER_STORM_PER_SECOND ? 'warn' : 'info',\n        attributes: {\n          component_name: component,\n          renders: count,\n          per_second: round(perSecond),\n          window_ms,\n          ...(row.timed === 0\n            ? {}\n            : { total_ms: round(row.totalMs), avg_ms: round(row.totalMs / row.timed), max_ms: round(row.maxMs) }),\n        },\n      },\n    ]);\n  }\n  storeRows.clear();\n  renderRows.clear();\n  if (ranked.length === 0 || sink === undefined) return;\n  sink(\n    ranked\n      .sort((a, b) => b[0] - a[0])\n      .slice(0, MAX_RECORDS)\n      .map(([, record]) => record),\n  );\n}\n\n/** Starts the rollups and sends each window to `next`; `undefined` stops them. */\nexport function setUiTraceSink(next: UiTraceSink | undefined): void {\n  sink = next;\n  storeRows.clear();\n  renderRows.clear();\n  if (timer !== undefined) clearInterval(timer);\n  timer = undefined;\n  if (next === undefined) return;\n  windowStart = Date.now();\n  timer = setInterval(() => flushUiTrace(), WINDOW_MS);\n}\n"],"mappings":";;;;;;;;;;;AAkBA,MAAM,YAAY;;AAElB,MAAM,yBAAyB;AAC/B,MAAM,0BAA0B;;AAEhC,MAAM,aAAa;AACnB,MAAM,YAAY;;AAElB,MAAM,mBAAmB;;AAEzB,MAAM,cAAc;;;;;AAKpB,MAAM,YAAY;AAClB,MAAM,UAAU;AAChB,MAAM,cAAc;AAapB,MAAM,4BAAY,IAAI,IAAsB;AAC5C,MAAM,6BAAa,IAAI,IAAuB;AAC9C,IAAI;AACJ,IAAI;AACJ,IAAI,cAAc;AAElB,SAAS,QAAQ,OAAkD;CACjE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,aAAa,UAAmB,MAAe,MAAc,OAAe,MAAsB;CACzG,IAAI,UAAU,cAAc,CAAC,QAAQ,QAAQ,KAAK,CAAC,QAAQ,IAAI,GAAG;EAChE,KAAK,KAAK,IAAI;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