{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "service-explorer",
  "type": "registry:block",
  "title": "Service explorer",
  "description": "A live service map that drives the rest of the page: pick a service to see its latency, its slowest request and a CPU flame graph.",
  "categories": [
    "blocks"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/service-explorer.tsx",
      "type": "registry:component",
      "target": "components/overtrue/service-explorer.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconPointer } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  ServiceMap,\n  type ServiceMapEdge,\n  type ServiceMapNode,\n} from \"./service-map\";\nimport { FlameGraph, type FlameNode } from \"./flame-graph\";\nimport { LatencyHistogram } from \"./latency-histogram\";\nimport { JsonViewer } from \"./json-viewer\";\n\nexport interface ExploredService {\n  /** Request latencies in milliseconds for the window. */\n  latency: number[];\n  /** Objective drawn on the histogram, in milliseconds. */\n  threshold?: number;\n  /** A sampled CPU profile for the service. */\n  profile: FlameNode;\n  /** The slowest request in the window, shown as JSON. */\n  slowest?: unknown;\n}\n\nexport interface ServiceExplorerData {\n  title: string;\n  /** Context under the title, e.g. \"Production · last 5 minutes\". */\n  description?: string;\n  nodes: ServiceMapNode[];\n  edges: ServiceMapEdge[];\n  /** Detail per service id. Nodes without an entry can be selected but show a hint. */\n  services: Record<string, ExploredService>;\n}\n\nexport interface ServiceExplorerProps\n  extends Omit<React.ComponentProps<\"section\">, \"title\" | \"onSelect\"> {\n  data: ServiceExplorerData;\n  /** Controlled selection. */\n  selectedId?: string | null;\n  defaultSelectedId?: string | null;\n  onSelect?: (id: string | null) => void;\n  actions?: React.ReactNode;\n}\n\n/** Pick a service on the live map to see its latency, its slowest request and a CPU profile. */\nexport function ServiceExplorer({\n  data,\n  selectedId,\n  defaultSelectedId = null,\n  onSelect,\n  actions,\n  className,\n  ...props\n}: ServiceExplorerProps) {\n  const [internal, setInternal] = React.useState<string | null>(\n    defaultSelectedId,\n  );\n  const selected = selectedId !== undefined ? selectedId : internal;\n  const select = (id: string | null) => {\n    if (selectedId === undefined) setInternal(id);\n    onSelect?.(id);\n  };\n  const node = data.nodes.find((entry) => entry.id === selected) ?? null;\n  const detail = selected ? data.services[selected] : undefined;\n\n  return (\n    <section\n      data-slot=\"service-explorer\"\n      aria-label={data.title}\n      className={cn(\n        \"@container/explorer flex min-w-0 flex-col gap-3 text-foreground sm:gap-4\",\n        className,\n      )}\n      {...props}\n    >\n      <header className=\"flex flex-wrap items-end justify-between gap-3\">\n        <div className=\"min-w-0\">\n          <h2 className=\"truncate text-base font-semibold tracking-tight\">\n            {data.title}\n          </h2>\n          {data.description && (\n            <p className=\"truncate text-xs text-muted-foreground\">\n              {data.description}\n            </p>\n          )}\n        </div>\n        {actions && (\n          <div className=\"flex flex-wrap items-center gap-2\">{actions}</div>\n        )}\n      </header>\n\n      <div className=\"grid gap-3 sm:gap-4\">\n        <ServiceMap\n          title=\"Service map\"\n          description=\"Select a service to inspect it\"\n          nodes={data.nodes}\n          edges={data.edges}\n          selectedId={selected}\n          onSelect={(id) => select(id)}\n        />\n\n        {node && detail ? (\n          <div\n            key={node.id}\n            data-slot=\"service-explorer-detail\"\n            className=\"grid gap-3 sm:gap-4\"\n          >\n            <div className=\"grid gap-3 sm:gap-4 @4xl/explorer:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]\">\n              <LatencyHistogram\n                title=\"Latency\"\n                description={`Every ${node.label} request in the window`}\n                values={detail.latency}\n                threshold={detail.threshold}\n                thresholdLabel=\"SLO\"\n              />\n              {detail.slowest !== undefined && (\n                <JsonViewer\n                  title=\"Slowest request\"\n                  description=\"Span attributes and timings\"\n                  data={detail.slowest}\n                  rootName=\"span\"\n                  defaultExpandDepth={1}\n                  maxHeight={360}\n                />\n              )}\n            </div>\n            <FlameGraph\n              title=\"CPU profile\"\n              description={`Sampled from ${node.label} during the window`}\n              data={detail.profile}\n              showTopFunctions={5}\n              height={320}\n            />\n          </div>\n        ) : (\n          <div\n            data-slot=\"service-explorer-empty\"\n            className=\"flex flex-col items-center gap-2 rounded-2xl border border-dashed border-border/80 px-6 py-10 text-center\"\n          >\n            <span className=\"grid size-10 place-items-center rounded-xl bg-muted/60 text-muted-foreground\">\n              <IconPointer aria-hidden=\"true\" className=\"size-5\" />\n            </span>\n            <p className=\"text-sm font-medium\">\n              {node\n                ? `No profile for ${node.label}`\n                : \"Select a service on the map\"}\n            </p>\n            <p className=\"max-w-sm text-[13px] text-muted-foreground\">\n              {node\n                ? \"Clients, data stores and external providers have no CPU profile here. Select one of the services.\"\n                : \"Its latency, its slowest request and a CPU profile appear here.\"}\n            </p>\n          </div>\n        )}\n      </div>\n    </section>\n  );\n}\n\n/* Sample data --------------------------------------------------------------- */\n\nfunction random(seed: number) {\n  return () => {\n    seed |= 0;\n    seed = (seed + 0x6d2b79f5) | 0;\n    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\nfunction logNormal(count: number, median: number, spread: number, seed: number) {\n  const next = random(seed);\n  return Array.from({ length: count }, () => {\n    const u = Math.max(next(), 1e-9);\n    const v = next();\n    const z = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);\n    return Math.round(median * Math.exp(spread * z) * 10) / 10;\n  });\n}\n/** A frame with children; the value includes the frame's own self time. */\nconst f = (name: string, self: number, ...children: FlameNode[]): FlameNode => ({\n  name,\n  value: self + children.reduce((sum, child) => sum + child.value, 0),\n  ...(children.length ? { children } : {}),\n});\nconst http = (...children: FlameNode[]) =>\n  f(\"node.main\", 4, f(\"http.Server.emit\", 6, f(\"router.handle\", 8, f(\"middleware.auth\", 14, f(\"jwt.verify\", 22)), ...children)));\n\nconst checkoutProfile = http(\n  f(\"checkout.submit\", 18,\n    f(\"cart.load\", 12, f(\"db.query\", 64, f(\"pg.Client.query\", 21)), f(\"cart.normalize\", 18)),\n    f(\"pricing.quote\", 26, f(\"promotions.match\", 44, f(\"db.query\", 120, f(\"pg.Client.query\", 38))), f(\"tax.calculate\", 31)),\n    f(\"payments.authorize\", 9, f(\"http.request\", 182, f(\"tls.handshake\", 26), f(\"JSON.parse\", 14))),\n    f(\"orders.create\", 15, f(\"db.transaction\", 36, f(\"pg.Client.query\", 22)), f(\"kafka.produce\", 17)),\n  ),\n  f(\"render.response\", 8, f(\"JSON.stringify\", 46), f(\"zlib.gzip\", 28)),\n);\nconst paymentsProfile = http(\n  f(\"payments.authorize\", 22,\n    f(\"fraud.score\", 38, f(\"features.load\", 41, f(\"db.query\", 58)), f(\"model.predict\", 92)),\n    f(\"provider.authorize\", 14, f(\"http.request\", 296, f(\"tls.handshake\", 31), f(\"JSON.parse\", 12)), f(\"retry.backoff\", 64)),\n    f(\"ledger.write\", 11, f(\"db.transaction\", 44, f(\"pg.Client.query\", 27))),\n  ),\n  f(\"render.response\", 6, f(\"JSON.stringify\", 12)),\n);\nconst catalogProfile = http(\n  f(\"catalog.list\", 12,\n    f(\"cache.get\", 9, f(\"redis.GET\", 14)),\n    f(\"db.query\", 52, f(\"pg.Client.query\", 26)),\n    f(\"products.hydrate\", 34, f(\"images.sign\", 41), f(\"prices.attach\", 22)),\n  ),\n  f(\"render.response\", 6, f(\"JSON.stringify\", 58), f(\"zlib.gzip\", 31)),\n);\nconst searchProfile = http(\n  f(\"search.query\", 16,\n    f(\"query.parse\", 18),\n    f(\"index.lookup\", 24, f(\"bm25.score\", 66), f(\"vector.knn\", 88)),\n    f(\"results.rerank\", 14, f(\"model.predict\", 47)),\n    f(\"catalog.fetch\", 9, f(\"http.request\", 42)),\n  ),\n  f(\"render.response\", 5, f(\"JSON.stringify\", 21)),\n);\nconst cartProfile = http(\n  f(\"cart.update\", 10, f(\"cache.get\", 7, f(\"redis.GET\", 9)), f(\"cart.normalize\", 14), f(\"cache.set\", 6, f(\"redis.SET\", 8))),\n  f(\"render.response\", 4, f(\"JSON.stringify\", 9)),\n);\nconst authProfile = http(\n  f(\"session.verify\", 8, f(\"cache.get\", 5, f(\"redis.GET\", 6)), f(\"crypto.verify\", 31)),\n  f(\"render.response\", 3, f(\"JSON.stringify\", 4)),\n);\nconst gatewayProfile = f(\"node.main\", 4,\n  f(\"proxy.handle\", 12, f(\"ratelimit.check\", 9, f(\"redis.INCR\", 7)), f(\"route.match\", 14), f(\"upstream.request\", 21, f(\"http.request\", 38), f(\"tls.handshake\", 12))),\n  f(\"access.log\", 6, f(\"JSON.stringify\", 8)),\n);\n\nconst slowest = (service: string, route: string, duration: number, extra: Record<string, unknown>) => ({\n  traceId: \"4bf92f3577b34da6a3ce929d0e0e4736\",\n  spanId: \"00f067aa0ba902b7\",\n  service,\n  name: route,\n  startTime: \"2026-10-14T14:05:12.284Z\",\n  durationMs: duration,\n  status: { code: duration > 400 ? \"error\" : \"ok\", message: duration > 400 ? \"deadline exceeded\" : null },\n  attributes: {\n    \"http.method\": route.split(\" \")[0],\n    \"http.route\": route.split(\" \")[1],\n    \"http.status_code\": duration > 400 ? 504 : 200,\n    \"net.peer.ip\": \"10.4.18.231\",\n    ...extra,\n  },\n});\n\n/** A fictional checkout platform with profiles for its services, for demos and tests. */\nexport const sampleServiceExplorer: ServiceExplorerData = {\n  title: \"Service explorer\",\n  description: \"Acme Shop checkout platform · production · last 5 minutes\",\n  nodes: [\n    { id: \"web\", label: \"Web\", kind: \"client\", metrics: { rps: 1840, errorRate: 0.002, p95: 182 } },\n    { id: \"mobile\", label: \"Mobile\", kind: \"client\", metrics: { rps: 1260, errorRate: 0.003, p95: 214 } },\n    { id: \"gateway\", label: \"API gateway\", kind: \"gateway\", group: \"edge\", metrics: { rps: 3100, errorRate: 0.004, p95: 96 } },\n    { id: \"auth\", label: \"Auth\", kind: \"service\", group: \"identity\", metrics: { rps: 2980, errorRate: 0.001, p95: 12 } },\n    { id: \"search\", label: \"Search\", kind: \"service\", group: \"discovery\", metrics: { rps: 860, errorRate: 0.006, p95: 74 } },\n    { id: \"catalog\", label: \"Catalog\", kind: \"service\", group: \"discovery\", metrics: { rps: 1840, errorRate: 0.002, p95: 38 } },\n    { id: \"cart\", label: \"Cart\", kind: \"service\", group: \"commerce\", metrics: { rps: 610, errorRate: 0.003, p95: 28 } },\n    { id: \"checkout\", label: \"Checkout\", kind: \"service\", group: \"commerce\", metrics: { rps: 124, errorRate: 0.004, p95: 220 } },\n    { id: \"payments\", label: \"Payments\", kind: \"service\", group: \"commerce\", status: \"degraded\", metrics: { rps: 118, errorRate: 0.012, p95: 340 } },\n    { id: \"postgres\", label: \"Postgres\", kind: \"database\", group: \"data\", metrics: { rps: 1650, errorRate: 0, p95: 6.4 } },\n    { id: \"redis\", label: \"Redis\", kind: \"cache\", group: \"data\", metrics: { rps: 5440, errorRate: 0, p95: 0.8 } },\n    { id: \"kafka\", label: \"Kafka\", kind: \"queue\", group: \"data\", metrics: { rps: 116, errorRate: 0, p95: 3.1 } },\n    { id: \"payrail\", label: \"PayRail\", kind: \"external\", metrics: { rps: 116, errorRate: 0.018, p95: 410 } },\n  ],\n  edges: [\n    { source: \"web\", target: \"gateway\", rps: 1840, errorRate: 0.002, p95: 182 },\n    { source: \"mobile\", target: \"gateway\", rps: 1260, errorRate: 0.003, p95: 214 },\n    { source: \"gateway\", target: \"auth\", rps: 2980, errorRate: 0.001, p95: 12 },\n    { source: \"gateway\", target: \"search\", rps: 860, errorRate: 0.006, p95: 74 },\n    { source: \"gateway\", target: \"catalog\", rps: 1420, errorRate: 0.002, p95: 38 },\n    { source: \"gateway\", target: \"cart\", rps: 490, errorRate: 0.003, p95: 28 },\n    { source: \"gateway\", target: \"checkout\", rps: 124, errorRate: 0.004, p95: 220 },\n    { source: \"search\", target: \"catalog\", rps: 420, errorRate: 0.002, p95: 22 },\n    { source: \"auth\", target: \"redis\", rps: 2980, errorRate: 0, p95: 0.8 },\n    { source: \"catalog\", target: \"postgres\", rps: 1180, errorRate: 0, p95: 6.2 },\n    { source: \"catalog\", target: \"redis\", rps: 1640, errorRate: 0, p95: 0.7 },\n    { source: \"cart\", target: \"redis\", rps: 820, errorRate: 0, p95: 0.6 },\n    { source: \"checkout\", target: \"cart\", rps: 120, errorRate: 0.002, p95: 18 },\n    { source: \"checkout\", target: \"payments\", rps: 118, errorRate: 0.012, p95: 340 },\n    { source: \"checkout\", target: \"kafka\", rps: 116, errorRate: 0, p95: 3.1 },\n    { source: \"checkout\", target: \"postgres\", rps: 240, errorRate: 0.001, p95: 7.8 },\n    { source: \"payments\", target: \"payrail\", rps: 116, errorRate: 0.018, p95: 410 },\n    { source: \"payments\", target: \"postgres\", rps: 230, errorRate: 0, p95: 5.4 },\n  ],\n  services: {\n    gateway: {\n      latency: logNormal(2400, 44, 0.55, 3),\n      threshold: 150,\n      profile: gatewayProfile,\n      slowest: slowest(\"api-gateway\", \"POST /api/checkout\", 248, { \"upstream.service\": \"checkout\", \"ratelimit.remaining\": 412 }),\n    },\n    auth: {\n      latency: logNormal(2400, 5, 0.6, 5),\n      threshold: 25,\n      profile: authProfile,\n      slowest: slowest(\"auth\", \"GET /session\", 31, { \"session.cache\": \"miss\", \"jwt.alg\": \"EdDSA\" }),\n    },\n    search: {\n      latency: logNormal(2000, 33, 0.58, 7),\n      threshold: 120,\n      profile: searchProfile,\n      slowest: slowest(\"search\", \"GET /search\", 186, { \"search.query\": \"linen throw blanket\", \"search.results\": 48, \"rerank.model\": \"rerank-v2\" }),\n    },\n    catalog: {\n      latency: logNormal(2400, 16, 0.55, 9),\n      threshold: 80,\n      profile: catalogProfile,\n      slowest: slowest(\"catalog\", \"GET /products\", 112, { \"cache.hit\": false, \"db.rows\": 240, \"images.signed\": 240 }),\n    },\n    cart: {\n      latency: logNormal(2000, 12, 0.5, 11),\n      threshold: 60,\n      profile: cartProfile,\n      slowest: slowest(\"cart\", \"PATCH /cart\", 64, { \"cart.items\": 14, \"cache.hit\": true }),\n    },\n    checkout: {\n      latency: [...logNormal(1800, 96, 0.5, 13), ...logNormal(300, 320, 0.3, 17)],\n      threshold: 400,\n      profile: checkoutProfile,\n      slowest: slowest(\"checkout\", \"POST /api/checkout\", 1243, {\n        \"cart.items\": 14,\n        \"db.queries\": 15,\n        \"payment.provider\": \"payrail\",\n        \"order.id\": \"ord_8F3k2Lq\",\n        timings: { cart: 84, pricing: 962, payments: 118, orders: 61 },\n      }),\n    },\n    payments: {\n      latency: [...logNormal(1600, 150, 0.45, 19), ...logNormal(400, 520, 0.3, 23)],\n      threshold: 500,\n      profile: paymentsProfile,\n      slowest: slowest(\"payments\", \"POST /authorize\", 1980, {\n        \"payment.provider\": \"payrail\",\n        \"provider.attempts\": 3,\n        \"provider.status\": 504,\n        \"fraud.score\": 0.08,\n        retries: [\n          { attempt: 1, status: 504, durationMs: 640 },\n          { attempt: 2, status: 504, durationMs: 610 },\n          { attempt: 3, status: 200, durationMs: 412 },\n        ],\n      }),\n    },\n  },\n};\n"
    },
    {
      "path": "src/registry/overtrue/service-map.tsx",
      "type": "registry:component",
      "target": "components/overtrue/service-map.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconBolt,\n  IconCloud,\n  IconDatabase,\n  IconRoute,\n  IconServer,\n  IconStack2,\n  IconWorld,\n  IconX,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------ */\n/* Types                                                                     */\n/* ------------------------------------------------------------------------ */\n\nexport type ServiceKind =\n  | \"client\"\n  | \"gateway\"\n  | \"service\"\n  | \"database\"\n  | \"cache\"\n  | \"queue\"\n  | \"external\";\n\nexport type ServiceStatus = \"healthy\" | \"degraded\" | \"down\";\n\nexport interface ServiceMetrics {\n  /** Requests per second. */\n  rps?: number;\n  /** Share of failed requests as a 0–1 fraction, e.g. 0.012 for 1.2%. */\n  errorRate?: number;\n  /** 95th percentile latency in milliseconds. */\n  p95?: number;\n}\n\nexport interface ServiceMapNode {\n  id: string;\n  label: string;\n  kind?: ServiceKind;\n  /** Health. Defaults to healthy, or degraded when the error rate crosses the critical threshold. */\n  status?: ServiceStatus;\n  metrics?: ServiceMetrics;\n  /** Team, namespace or region. Shown in the detail readout. */\n  group?: string;\n  /** Replaces the icon picked from `kind`. */\n  icon?: React.ReactNode;\n}\n\nexport interface ServiceMapEdge {\n  id?: string;\n  /** Id of the calling node. */\n  source: string;\n  /** Id of the called node. */\n  target: string;\n  rps?: number;\n  /** Share of failed calls as a 0–1 fraction. */\n  errorRate?: number;\n  /** 95th percentile latency in milliseconds. */\n  p95?: number;\n  /** Overrides the color picked from the error rate. */\n  status?: ServiceStatus;\n}\n\nexport interface ServiceMapThresholds {\n  /** Error rate, as a 0–1 fraction, at which traffic turns amber. Defaults to 0.01. */\n  warn?: number;\n  /** Error rate at which traffic turns destructive. Defaults to 0.05. */\n  critical?: number;\n}\n\n/** Everything known about a node, passed to `renderNode`. */\nexport interface ServiceMapNodeInfo {\n  kind: ServiceKind;\n  status: ServiceStatus;\n  /** Column (or row, top to bottom) the node was placed in, from 0. */\n  layer: number;\n  inbound: ServiceMapEdge[];\n  outbound: ServiceMapEdge[];\n  /** Hovered or focused. */\n  active: boolean;\n  selected: boolean;\n  /** Outside the paths of the hovered, focused or selected node. */\n  dimmed: boolean;\n  /** Metrics run through the formatters; missing metrics are undefined. */\n  formatted: { rps?: string; errorRate?: string; p95?: string };\n  /** The default icon for the node's kind, or its own `icon`. */\n  icon: React.ReactNode;\n}\n\nexport interface ServiceMapProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"onSelect\" | \"children\"\n> {\n  nodes: ServiceMapNode[];\n  edges: ServiceMapEdge[];\n  /** Flow left to right or top to bottom. Defaults to LR. */\n  direction?: \"LR\" | \"TB\";\n  /** Controlled selection. Pass null for none. */\n  selectedId?: string | null;\n  defaultSelectedId?: string | null;\n  onSelect?: (id: string | null, node: ServiceMapNode | null) => void;\n  /** Replaces the content of every node card. The card keeps its size, focus and status ring. */\n  renderNode?: (node: ServiceMapNode, info: ServiceMapNodeInfo) => React.ReactNode;\n  thresholds?: ServiceMapThresholds;\n  rpsFormatter?: (rps: number) => string;\n  latencyFormatter?: (ms: number) => string;\n  errorRateFormatter?: (rate: number) => string;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right. */\n  actions?: React.ReactNode;\n  /** Show the traffic legend. Defaults to true. */\n  showLegend?: boolean;\n  /** Animate traffic along the edges. Defaults to true; reduced motion shows static dashes. */\n  animate?: boolean;\n  /** Card size in pixels before scaling. Defaults to 148 × 60. */\n  nodeWidth?: number;\n  nodeHeight?: number;\n  /** Smallest scale used to fit the container; below it the map scrolls sideways. Defaults to 0.5. */\n  minScale?: number;\n  /**\n   * Full cards with a metrics line, or compact icon tiles with a label. \"auto\" switches\n   * to compact when cards would have to shrink below a readable size. Defaults to auto.\n   */\n  density?: \"auto\" | \"comfortable\" | \"compact\";\n}\n\n/* ------------------------------------------------------------------------ */\n/* Formatting                                                                */\n/* ------------------------------------------------------------------------ */\n\nfunction formatRps(rps: number) {\n  if (!Number.isFinite(rps)) return \"—\";\n  if (rps >= 1_000_000) return `${+(rps / 1_000_000).toFixed(1)}M rps`;\n  if (rps >= 1000) return `${+(rps / 1000).toFixed(rps >= 10_000 ? 0 : 1)}k rps`;\n  if (rps >= 10) return `${Math.round(rps)} rps`;\n  return `${+rps.toFixed(1)} rps`;\n}\n\nfunction formatErrorRate(rate: number) {\n  if (!Number.isFinite(rate)) return \"—\";\n  const pct = rate * 100;\n  if (pct === 0) return \"0%\";\n  if (pct < 0.1) return `${+pct.toFixed(2)}%`;\n  if (pct < 10) return `${+pct.toFixed(1)}%`;\n  return `${Math.round(pct)}%`;\n}\n\nfunction formatLatency(ms: number) {\n  if (!Number.isFinite(ms)) return \"—\";\n  if (ms < 10) return `${+ms.toFixed(1)} ms`;\n  if (ms < 1000) return `${Math.round(ms)} ms`;\n  return `${+(ms / 1000).toFixed(ms < 10_000 ? 2 : 1)} s`;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Layout                                                                    */\n/* ------------------------------------------------------------------------ */\n\ninterface Item {\n  id: string;\n  layer: number;\n  /** Center on the cross axis, in world pixels. */\n  pos: number;\n  size: number;\n  dummy: boolean;\n  /** Index in `nodes`, used to break ties so the layout follows data order. */\n  rank: number;\n  node?: ServiceMapNode;\n}\n\ninterface Route {\n  key: string;\n  edge: ServiceMapEdge;\n  index: number;\n  /** Item ids from the source to the target in layer order (target first for back edges). */\n  chain: string[];\n  reversed: boolean;\n}\n\ninterface Structure {\n  layers: Item[][];\n  items: Map<string, Item>;\n  routes: Route[];\n  layerOf: Map<string, number>;\n  /** Extent on the cross axis, center to center plus the node size. */\n  span: number;\n}\n\ninterface Point {\n  x: number;\n  y: number;\n}\n\ninterface PlacedEdge {\n  key: string;\n  edge: ServiceMapEdge;\n  index: number;\n  d: string;\n  length: number;\n  mid: Point;\n  start: Point;\n  end: Point;\n}\n\nconst NODE_GAP = 18;\nconst DUMMY_GAP = 12;\nconst PAD = 22;\nconst GAP_MIN = 28;\nconst GAP_MAX = 136;\nconst GAP_TB = 64;\nconst FALLBACK_WIDTH = 720;\nconst COMPACT_W = 76;\nconst COMPACT_TILE = 36;\nconst COMPACT_H = 56;\nconst COMPACT_PAD = 16;\nconst COMPACT_GAP_MIN = 10;\nconst COMPACT_GAP_TB = 40;\n/** Below this scale, \"auto\" density switches cards to compact tiles. */\nconst AUTO_COMPACT_BELOW = 0.62;\n\n/** Pool adjacent violators: positions as close to `desired` as the separations allow, order kept. */\nfunction project(desired: number[], separation: number[]) {\n  const n = desired.length;\n  const offset = new Array<number>(n).fill(0);\n  for (let i = 1; i < n; i++) offset[i] = offset[i - 1] + separation[i - 1];\n  const blocks: { sum: number; count: number; start: number }[] = [];\n  for (let i = 0; i < n; i++) {\n    blocks.push({ sum: desired[i] - offset[i], count: 1, start: i });\n    while (blocks.length > 1) {\n      const b = blocks[blocks.length - 1];\n      const a = blocks[blocks.length - 2];\n      if (a.sum / a.count <= b.sum / b.count) break;\n      a.sum += b.sum;\n      a.count += b.count;\n      blocks.pop();\n    }\n  }\n  const out = new Array<number>(n);\n  blocks.forEach((block, i) => {\n    const end = i + 1 < blocks.length ? blocks[i + 1].start : n;\n    for (let j = block.start; j < end; j++)\n      out[j] = block.sum / block.count + offset[j];\n  });\n  return out;\n}\n\nfunction buildStructure(\n  nodes: ServiceMapNode[],\n  edges: ServiceMapEdge[],\n  crossSize: number,\n  nodeGap = NODE_GAP,\n): Structure {\n  const known = new Map(nodes.map((node, i) => [node.id, i]));\n  const valid = edges\n    .map((edge, index) => ({ edge, index }))\n    .filter(\n      ({ edge }) =>\n        known.has(edge.source) &&\n        known.has(edge.target) &&\n        edge.source !== edge.target,\n    );\n\n  // Break cycles: edges that close a loop in a depth-first walk are laid out reversed.\n  const out = new Map<string, number[]>();\n  const indegree = new Map<string, number>(nodes.map((n) => [n.id, 0]));\n  valid.forEach(({ edge }, i) => {\n    if (!out.has(edge.source)) out.set(edge.source, []);\n    out.get(edge.source)!.push(i);\n    indegree.set(edge.target, (indegree.get(edge.target) ?? 0) + 1);\n  });\n  const state = new Map<string, 1 | 2>();\n  const reversed = new Set<number>();\n  const walk = (id: string) => {\n    state.set(id, 1);\n    for (const i of out.get(id) ?? []) {\n      const target = valid[i].edge.target;\n      const seen = state.get(target);\n      if (seen === 1) reversed.add(i);\n      else if (!seen) walk(target);\n    }\n    state.set(id, 2);\n  };\n  const starts = [\n    ...nodes.filter((n) => indegree.get(n.id) === 0),\n    ...nodes.filter((n) => indegree.get(n.id) !== 0),\n  ];\n  for (const node of starts) if (!state.has(node.id)) walk(node.id);\n\n  // Layer by the longest path from the sources.\n  const dag = valid.map(({ edge }, i) =>\n    reversed.has(i)\n      ? { from: edge.target, to: edge.source }\n      : { from: edge.source, to: edge.target },\n  );\n  const succ = new Map<string, string[]>();\n  const pending = new Map<string, number>(nodes.map((n) => [n.id, 0]));\n  for (const { from, to } of dag) {\n    if (!succ.has(from)) succ.set(from, []);\n    succ.get(from)!.push(to);\n    pending.set(to, (pending.get(to) ?? 0) + 1);\n  }\n  const layerOf = new Map<string, number>(nodes.map((n) => [n.id, 0]));\n  const queue = nodes.filter((n) => pending.get(n.id) === 0).map((n) => n.id);\n  while (queue.length) {\n    const id = queue.shift()!;\n    for (const next of succ.get(id) ?? []) {\n      layerOf.set(next, Math.max(layerOf.get(next)!, layerOf.get(id)! + 1));\n      pending.set(next, pending.get(next)! - 1);\n      if (pending.get(next) === 0) queue.push(next);\n    }\n  }\n\n  // Items: one per node, plus a dummy wherever an edge crosses a layer.\n  const items = new Map<string, Item>();\n  nodes.forEach((node, rank) =>\n    items.set(node.id, {\n      id: node.id,\n      layer: layerOf.get(node.id) ?? 0,\n      pos: 0,\n      size: crossSize,\n      dummy: false,\n      rank,\n      node,\n    }),\n  );\n  const routes: Route[] = [];\n  const up = new Map<string, string[]>();\n  const down = new Map<string, string[]>();\n  const link = (a: string, b: string) => {\n    if (!down.has(a)) down.set(a, []);\n    if (!up.has(b)) up.set(b, []);\n    down.get(a)!.push(b);\n    up.get(b)!.push(a);\n  };\n  valid.forEach(({ edge, index }, i) => {\n    const { from, to } = dag[i];\n    const a = layerOf.get(from)!;\n    const b = layerOf.get(to)!;\n    const key = edge.id ?? `${edge.source}->${edge.target}#${index}`;\n    const chain = [from];\n    for (let layer = a + 1; layer < b; layer++) {\n      const id = `\\u0000${key}\\u0000${layer}`;\n      items.set(id, {\n        id,\n        layer,\n        pos: 0,\n        size: 0,\n        dummy: true,\n        rank: items.get(from)!.rank + 0.5,\n      });\n      chain.push(id);\n    }\n    chain.push(to);\n    for (let j = 1; j < chain.length; j++) link(chain[j - 1], chain[j]);\n    routes.push({ key, edge, index, chain, reversed: reversed.has(i) });\n  });\n\n  const count = Math.max(0, ...[...items.values()].map((item) => item.layer)) + 1;\n  const layers: Item[][] = Array.from({ length: count }, () => []);\n  for (const item of items.values()) layers[item.layer].push(item);\n  for (const layer of layers) layer.sort((a, b) => a.rank - b.rank);\n\n  // Order within layers: barycenter sweeps, keeping the arrangement with fewest crossings.\n  const index = new Map<string, number>();\n  const reindex = () =>\n    layers.forEach((layer) => layer.forEach((item, i) => index.set(item.id, i)));\n  const crossings = () => {\n    let total = 0;\n    for (let l = 0; l + 1 < layers.length; l++) {\n      const segments: [number, number][] = [];\n      for (const item of layers[l])\n        for (const next of down.get(item.id) ?? [])\n          segments.push([index.get(item.id)!, index.get(next)!]);\n      for (let i = 0; i < segments.length; i++)\n        for (let j = i + 1; j < segments.length; j++) {\n          const [a1, b1] = segments[i];\n          const [a2, b2] = segments[j];\n          if ((a1 - a2) * (b1 - b2) < 0) total++;\n        }\n    }\n    return total;\n  };\n  reindex();\n  let best = layers.map((layer) => [...layer]);\n  let bestCrossings = crossings();\n  for (let sweep = 0; sweep < 12 && bestCrossings > 0; sweep++) {\n    const downward = sweep % 2 === 0;\n    const order = downward\n      ? layers.map((_, i) => i).slice(1)\n      : layers.map((_, i) => i).slice(0, -1).reverse();\n    for (const l of order) {\n      const neighbors = downward ? up : down;\n      const weight = new Map<string, number>();\n      layers[l].forEach((item, i) => {\n        const list = neighbors.get(item.id) ?? [];\n        weight.set(\n          item.id,\n          list.length\n            ? list.reduce((sum, id) => sum + index.get(id)!, 0) / list.length\n            : i,\n        );\n      });\n      layers[l].sort(\n        (a, b) => weight.get(a.id)! - weight.get(b.id)! || a.rank - b.rank,\n      );\n      layers[l].forEach((item, i) => index.set(item.id, i));\n    }\n    const score = crossings();\n    if (score < bestCrossings) {\n      bestCrossings = score;\n      best = layers.map((layer) => [...layer]);\n    }\n  }\n  best.forEach((layer, l) => (layers[l] = layer));\n  reindex();\n\n  // Cross-axis positions: pull each item toward its neighbors, keeping order and spacing.\n  const gapBetween = (a: Item, b: Item) =>\n    (a.size + b.size) / 2 +\n    (a.dummy && b.dummy ? DUMMY_GAP : a.dummy || b.dummy ? DUMMY_GAP + 4 : nodeGap);\n  for (const layer of layers) {\n    let cursor = 0;\n    layer.forEach((item, i) => {\n      if (i > 0) cursor += gapBetween(layer[i - 1], item);\n      item.pos = cursor;\n    });\n    const mid = cursor / 2;\n    for (const item of layer) item.pos -= mid;\n  }\n  const center = (id: string) => items.get(id)!.pos;\n  for (let pass = 0; pass < 24; pass++) {\n    const downward = pass % 2 === 0;\n    const order = downward\n      ? layers.map((_, i) => i)\n      : layers.map((_, i) => i).reverse();\n    for (const l of order) {\n      const layer = layers[l];\n      if (!layer.length) continue;\n      const desired = layer.map((item) => {\n        const near = [...(up.get(item.id) ?? []), ...(down.get(item.id) ?? [])];\n        if (!near.length) return item.pos;\n        return near.reduce((sum, id) => sum + center(id), 0) / near.length;\n      });\n      const separation = layer\n        .slice(1)\n        .map((item, i) => gapBetween(layer[i], item));\n      const placed = project(desired, separation);\n      layer.forEach((item, i) => (item.pos = placed[i]));\n    }\n  }\n  let min = Infinity;\n  let max = -Infinity;\n  for (const item of items.values()) {\n    min = Math.min(min, item.pos - item.size / 2);\n    max = Math.max(max, item.pos + item.size / 2);\n  }\n  if (!Number.isFinite(min)) {\n    min = 0;\n    max = 0;\n  }\n  for (const item of items.values()) item.pos -= min;\n  return { layers, items, routes, layerOf, span: max - min };\n}\n\nfunction cubic(a: Point, b: Point, horizontal: boolean, sag = 0) {\n  if (horizontal) {\n    const dx = (b.x - a.x) / 2;\n    return {\n      c1: { x: a.x + dx, y: a.y + sag },\n      c2: { x: b.x - dx, y: b.y + sag },\n    };\n  }\n  const dy = (b.y - a.y) / 2;\n  return {\n    c1: { x: a.x + sag, y: a.y + dy },\n    c2: { x: b.x + sag, y: b.y - dy },\n  };\n}\n\nfunction bezierAt(a: Point, c1: Point, c2: Point, b: Point, t: number): Point {\n  const u = 1 - t;\n  return {\n    x: u * u * u * a.x + 3 * u * u * t * c1.x + 3 * u * t * t * c2.x + t * t * t * b.x,\n    y: u * u * u * a.y + 3 * u * u * t * c1.y + 3 * u * t * t * c2.y + t * t * t * b.y,\n  };\n}\n\nconst r1 = (n: number) => Math.round(n * 10) / 10;\n\n/* ------------------------------------------------------------------------ */\n/* Visual vocabulary                                                         */\n/* ------------------------------------------------------------------------ */\n\nconst kindIcon: Record<ServiceKind, React.ComponentType<{ size?: number; stroke?: number; className?: string; \"aria-hidden\"?: boolean | \"true\" }>> = {\n  client: IconWorld,\n  gateway: IconRoute,\n  service: IconServer,\n  database: IconDatabase,\n  cache: IconBolt,\n  queue: IconStack2,\n  external: IconCloud,\n};\n\nconst kindLabel: Record<ServiceKind, string> = {\n  client: \"client\",\n  gateway: \"gateway\",\n  service: \"service\",\n  database: \"database\",\n  cache: \"cache\",\n  queue: \"queue\",\n  external: \"external service\",\n};\n\nconst statusLabel: Record<ServiceStatus, string> = {\n  healthy: \"Healthy\",\n  degraded: \"Degraded\",\n  down: \"Down\",\n};\n\nconst statusDot: Record<ServiceStatus, string> = {\n  healthy: \"bg-emerald-500\",\n  degraded: \"bg-amber-500\",\n  down: \"bg-destructive\",\n};\n\nconst statusPill: Record<ServiceStatus, string> = {\n  healthy: \"bg-emerald-500/10 text-emerald-700 dark:text-emerald-400\",\n  degraded: \"bg-amber-500/10 text-amber-700 dark:text-amber-400\",\n  down: \"bg-destructive/10 text-destructive\",\n};\n\ntype Severity = \"ok\" | \"warn\" | \"critical\";\n\nconst severityStroke: Record<Severity, string> = {\n  ok: \"var(--sm-ok)\",\n  warn: \"var(--sm-warn)\",\n  critical: \"var(--sm-critical)\",\n};\nconst severityFlow: Record<Severity, string> = {\n  ok: \"var(--sm-flow)\",\n  warn: \"var(--sm-warn)\",\n  critical: \"var(--sm-critical)\",\n};\n\nconst useIsomorphicLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction StatusDot({ status, className }: { status: ServiceStatus; className?: string }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      data-status={status}\n      className={cn(\"relative inline-flex size-2 shrink-0 rounded-full\", statusDot[status], className)}\n    >\n      {status !== \"healthy\" ? (\n        <span\n          className={cn(\n            \"absolute inset-0 rounded-full opacity-60 motion-safe:animate-[service-map-ping_1.8s_cubic-bezier(0,0,0.2,1)_infinite]\",\n            statusDot[status],\n          )}\n        />\n      ) : null}\n    </span>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Component                                                                 */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A live service dependency map. Nodes are laid out as a layered graph, left to\n * right by default; edges carry animated traffic whose width follows request rate\n * and whose color follows error rate. Hover or focus a node to trace its upstream\n * and downstream paths; select it to list its inbound and outbound traffic.\n */\nfunction ServiceMap({\n  nodes,\n  edges,\n  direction = \"LR\",\n  selectedId: selectedProp,\n  defaultSelectedId = null,\n  onSelect,\n  renderNode,\n  thresholds,\n  rpsFormatter = formatRps,\n  latencyFormatter = formatLatency,\n  errorRateFormatter = formatErrorRate,\n  title,\n  description,\n  actions,\n  showLegend = true,\n  animate = true,\n  nodeWidth = 148,\n  nodeHeight = 60,\n  minScale = 0.5,\n  density = \"auto\",\n  className,\n  onKeyDown,\n  ...props\n}: ServiceMapProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const viewportRef = React.useRef<HTMLDivElement>(null);\n  const [available, setAvailable] = React.useState(0);\n  const [hoveredId, setHoveredId] = React.useState<string | null>(null);\n  const [focusedId, setFocusedId] = React.useState<string | null>(null);\n  const [hoveredEdge, setHoveredEdge] = React.useState<string | null>(null);\n  const [innerSelected, setInnerSelected] = React.useState<string | null>(\n    defaultSelectedId,\n  );\n  const [revealed, setRevealed] = React.useState(false);\n  const selectedId = selectedProp !== undefined ? selectedProp : innerSelected;\n\n  const warn = thresholds?.warn ?? 0.01;\n  const critical = thresholds?.critical ?? 0.05;\n  const horizontal = direction === \"LR\";\n\n  const byId = React.useMemo(\n    () => new Map(nodes.map((node) => [node.id, node])),\n    [nodes],\n  );\n  const selectedNode = selectedId ? (byId.get(selectedId) ?? null) : null;\n\n  const select = (next: string | null) => {\n    if (selectedProp === undefined) setInnerSelected(next);\n    onSelect?.(next, next ? (byId.get(next) ?? null) : null);\n  };\n\n  const statusOf = React.useCallback(\n    (node: ServiceMapNode): ServiceStatus =>\n      node.status ??\n      ((node.metrics?.errorRate ?? 0) >= critical ? \"degraded\" : \"healthy\"),\n    [critical],\n  );\n  const severityOf = (edge: ServiceMapEdge): Severity => {\n    if (edge.status === \"down\") return \"critical\";\n    if (edge.status === \"degraded\") return \"warn\";\n    if (edge.status === \"healthy\") return \"ok\";\n    const rate = edge.errorRate ?? 0;\n    if (rate >= critical) return \"critical\";\n    if (rate >= warn) return \"warn\";\n    return \"ok\";\n  };\n\n  /* ---------------------------------------------------------- layout */\n\n  const width = available || FALLBACK_WIDTH;\n  const comfortable = React.useMemo(\n    () => buildStructure(nodes, edges, horizontal ? nodeHeight : nodeWidth),\n    [nodes, edges, horizontal, nodeWidth, nodeHeight],\n  );\n  // Cards when they fit at a readable scale; icon tiles with labels otherwise.\n  const comfortableWidth = horizontal\n    ? comfortable.layers.length * nodeWidth +\n      Math.max(0, comfortable.layers.length - 1) * GAP_MIN +\n      PAD * 2\n    : comfortable.span + PAD * 2;\n  const compact =\n    density === \"compact\" ||\n    (density === \"auto\" && width / comfortableWidth < AUTO_COMPACT_BELOW);\n  const compactStructure = React.useMemo(\n    () =>\n      compact\n        ? buildStructure(\n            nodes,\n            edges,\n            horizontal ? COMPACT_H : COMPACT_W,\n            horizontal ? 8 : 12,\n          )\n        : null,\n    [compact, nodes, edges, horizontal],\n  );\n  const structure = compactStructure ?? comfortable;\n  const cardW = compact ? COMPACT_W : nodeWidth;\n  const cardH = compact ? COMPACT_H : nodeHeight;\n  const pad = compact ? COMPACT_PAD : PAD;\n  const mainSize = horizontal ? cardW : cardH;\n  const crossSize = horizontal ? cardH : cardW;\n  // Edges meet the icon tile in compact mode, not the label under it.\n  const portInset = compact && horizontal ? (COMPACT_W - COMPACT_TILE) / 2 : 0;\n  const portShift = compact && horizontal ? (COMPACT_TILE - COMPACT_H) / 2 : 0;\n  const portSpan = compact ? COMPACT_TILE : crossSize;\n  const layerCount = structure.layers.length;\n\n  const gapMin = horizontal\n    ? compact\n      ? COMPACT_GAP_MIN\n      : GAP_MIN\n    : compact\n      ? COMPACT_GAP_TB\n      : GAP_TB;\n  let gap = gapMin;\n  if (horizontal && layerCount > 1) {\n    const fit = (width - pad * 2 - layerCount * mainSize) / (layerCount - 1);\n    gap = Math.min(GAP_MAX, Math.max(gapMin, fit));\n  }\n  const mainExtent = layerCount * mainSize + Math.max(0, layerCount - 1) * gap;\n  const worldW = horizontal ? mainExtent + pad * 2 : structure.span + pad * 2;\n  const worldH = horizontal ? structure.span + pad * 2 : mainExtent + pad * 2;\n  const scale = Math.max(minScale, Math.min(1, width / worldW));\n\n  const placement = React.useMemo(() => {\n    const rects = new Map<string, { x: number; y: number }>();\n    const at = (item: Item): Point => {\n      const main = pad + item.layer * (mainSize + gap);\n      const cross = pad + item.pos;\n      return horizontal ? { x: main, y: cross } : { x: cross, y: main };\n    };\n    for (const item of structure.items.values()) {\n      if (item.dummy) continue;\n      const p = at(item);\n      rects.set(\n        item.id,\n        horizontal\n          ? { x: p.x, y: p.y - cardH / 2 }\n          : { x: p.x - cardW / 2, y: p.y },\n      );\n    }\n\n    // Spread the ports on each side of a node so parallel edges do not merge.\n    const ports = new Map<string, number>();\n    const sides = new Map<string, { key: string; toward: number }[]>();\n    const sideKey = (nodeId: string, side: \"in\" | \"out\") => `${nodeId}|${side}`;\n    const neighborCross = (route: Route, end: \"source\" | \"target\") => {\n      const chain = route.reversed ? [...route.chain].reverse() : route.chain;\n      const id = end === \"source\" ? chain[1] : chain[chain.length - 2];\n      return structure.items.get(id)!.pos;\n    };\n    for (const route of structure.routes) {\n      const outSide = route.reversed ? \"in\" : \"out\";\n      const inSide = route.reversed ? \"out\" : \"in\";\n      const s = sideKey(route.edge.source, outSide);\n      const t = sideKey(route.edge.target, inSide);\n      if (!sides.has(s)) sides.set(s, []);\n      if (!sides.has(t)) sides.set(t, []);\n      sides.get(s)!.push({ key: `${route.key}|s`, toward: neighborCross(route, \"source\") });\n      sides.get(t)!.push({ key: `${route.key}|t`, toward: neighborCross(route, \"target\") });\n    }\n    for (const list of sides.values()) {\n      list.sort((a, b) => a.toward - b.toward);\n      const step =\n        list.length > 1\n          ? Math.min(compact ? 5 : 7, (portSpan - (compact ? 12 : 24)) / (list.length - 1))\n          : 0;\n      list.forEach((entry, i) =>\n        ports.set(entry.key, (i - (list.length - 1) / 2) * step),\n      );\n    }\n\n    const placed: PlacedEdge[] = [];\n    for (const route of structure.routes) {\n      const chain = route.reversed ? [...route.chain].reverse() : route.chain;\n      const source = structure.items.get(chain[0])!;\n      const target = structure.items.get(chain[chain.length - 1])!;\n      const forward = !route.reversed;\n      const ps = at(source);\n      const pt = at(target);\n      const so = ports.get(`${route.key}|s`) ?? 0;\n      const to = ports.get(`${route.key}|t`) ?? 0;\n      const start: Point = horizontal\n        ? {\n            x: forward ? ps.x + mainSize - portInset : ps.x + portInset,\n            y: ps.y + portShift + so,\n          }\n        : { x: ps.x + so, y: forward ? ps.y + mainSize : ps.y };\n      const end: Point = horizontal\n        ? {\n            x: forward ? pt.x + portInset : pt.x + mainSize - portInset,\n            y: pt.y + portShift + to,\n          }\n        : { x: pt.x + to, y: forward ? pt.y : pt.y + mainSize };\n      const waypoints: Point[] = [start];\n      for (const id of chain.slice(1, -1)) {\n        const p = at(structure.items.get(id)!);\n        const enter = forward ? 0 : mainSize;\n        const leave = forward ? mainSize : 0;\n        waypoints.push(\n          horizontal ? { x: p.x + enter, y: p.y } : { x: p.x, y: p.y + enter },\n          horizontal ? { x: p.x + leave, y: p.y } : { x: p.x, y: p.y + leave },\n        );\n      }\n      waypoints.push(end);\n\n      let d = `M${r1(start.x)} ${r1(start.y)}`;\n      const samples: Point[] = [start];\n      for (let i = 1; i < waypoints.length; i++) {\n        const a = waypoints[i - 1];\n        const b = waypoints[i];\n        // Odd segments cross a gap and curve; even ones run straight through a layer.\n        if (i % 2 === 1) {\n          const sag = !forward && waypoints.length === 2 ? crossSize * 0.75 : 0;\n          const { c1, c2 } = cubic(a, b, horizontal, sag);\n          d += ` C${r1(c1.x)} ${r1(c1.y)} ${r1(c2.x)} ${r1(c2.y)} ${r1(b.x)} ${r1(b.y)}`;\n          for (let s = 1; s <= 16; s++) samples.push(bezierAt(a, c1, c2, b, s / 16));\n        } else {\n          d += ` L${r1(b.x)} ${r1(b.y)}`;\n          samples.push(b);\n        }\n      }\n      let length = 0;\n      const cumulative = [0];\n      for (let i = 1; i < samples.length; i++) {\n        length += Math.hypot(samples[i].x - samples[i - 1].x, samples[i].y - samples[i - 1].y);\n        cumulative.push(length);\n      }\n      const half = length / 2;\n      let mid = samples[0];\n      for (let i = 1; i < samples.length; i++)\n        if (cumulative[i] >= half) {\n          const f = (half - cumulative[i - 1]) / (cumulative[i] - cumulative[i - 1] || 1);\n          mid = {\n            x: samples[i - 1].x + (samples[i].x - samples[i - 1].x) * f,\n            y: samples[i - 1].y + (samples[i].y - samples[i - 1].y) * f,\n          };\n          break;\n        }\n      placed.push({ key: route.key, edge: route.edge, index: route.index, d, length, mid, start, end });\n    }\n    return { rects, edges: placed };\n  }, [\n    structure,\n    gap,\n    pad,\n    horizontal,\n    compact,\n    mainSize,\n    crossSize,\n    cardW,\n    cardH,\n    portInset,\n    portShift,\n    portSpan,\n  ]);\n\n  /* ---------------------------------------------------------- measure */\n\n  useIsomorphicLayoutEffect(() => {\n    const element = viewportRef.current;\n    if (!element) return;\n    const measure = () => setAvailable(element.clientWidth);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(element);\n    return () => observer.disconnect();\n  }, []);\n\n  // When the map scrolls sideways, keep the selected service in view.\n  useIsomorphicLayoutEffect(() => {\n    const viewport = viewportRef.current;\n    const rect = selectedId ? placement.rects.get(selectedId) : undefined;\n    if (!viewport || !rect || viewport.scrollWidth <= viewport.clientWidth) return;\n    const center = (rect.x + cardW / 2) * scale;\n    viewport.scrollLeft = Math.max(0, center - viewport.clientWidth / 2);\n  }, [selectedId, scale, compact]);\n\n  React.useEffect(() => {\n    const timer = window.setTimeout(() => setRevealed(true), 1800);\n    return () => window.clearTimeout(timer);\n  }, []);\n\n  /* ---------------------------------------------------------- relationships */\n\n  const inbound = React.useMemo(() => {\n    const map = new Map<string, ServiceMapEdge[]>();\n    for (const edge of edges) {\n      if (!map.has(edge.target)) map.set(edge.target, []);\n      map.get(edge.target)!.push(edge);\n    }\n    return map;\n  }, [edges]);\n  const outbound = React.useMemo(() => {\n    const map = new Map<string, ServiceMapEdge[]>();\n    for (const edge of edges) {\n      if (!map.has(edge.source)) map.set(edge.source, []);\n      map.get(edge.source)!.push(edge);\n    }\n    return map;\n  }, [edges]);\n\n  const hoveredPlaced = hoveredEdge\n    ? (placement.edges.find((edge) => edge.key === hoveredEdge) ?? null)\n    : null;\n  const activeId = hoveredId ?? focusedId ?? (hoveredPlaced ? null : selectedId);\n  const readoutId = hoveredId ?? focusedId;\n  const readoutNode = readoutId ? (byId.get(readoutId) ?? null) : null;\n\n  // Everything upstream and downstream of the active node, edge by edge.\n  const lit = React.useMemo(() => {\n    if (hoveredPlaced) {\n      return {\n        nodes: new Set([hoveredPlaced.edge.source, hoveredPlaced.edge.target]),\n        edges: new Set([hoveredPlaced.key]),\n      };\n    }\n    if (!activeId || !byId.has(activeId)) return null;\n    const litNodes = new Set<string>([activeId]);\n    const litEdges = new Set<string>();\n    const keyOf = new Map(\n      placement.edges.map((placed) => [placed.edge, placed.key]),\n    );\n    const visit = (start: string, along: \"up\" | \"down\") => {\n      const stack = [start];\n      const seen = new Set([start]);\n      while (stack.length) {\n        const current = stack.pop()!;\n        const list =\n          along === \"down\" ? outbound.get(current) : inbound.get(current);\n        for (const edge of list ?? []) {\n          const key = keyOf.get(edge);\n          if (key) litEdges.add(key);\n          const next = along === \"down\" ? edge.target : edge.source;\n          litNodes.add(next);\n          if (!seen.has(next)) {\n            seen.add(next);\n            stack.push(next);\n          }\n        }\n      }\n    };\n    visit(activeId, \"up\");\n    visit(activeId, \"down\");\n    return { nodes: litNodes, edges: litEdges };\n  }, [activeId, hoveredPlaced, byId, inbound, outbound, placement.edges]);\n\n  /* ---------------------------------------------------------- keyboard */\n\n  const tabOrder = React.useMemo(\n    () =>\n      structure.layers.flatMap((layer) =>\n        layer.filter((item) => !item.dummy).map((item) => item.id),\n      ),\n    [structure],\n  );\n\n  const focusNode = (nodeId: string | undefined) => {\n    if (!nodeId) return;\n    viewportRef.current\n      ?.querySelector<HTMLElement>(\n        `[data-slot=\"service-map-node\"][data-id=\"${CSS.escape(nodeId)}\"]`,\n      )\n      ?.focus();\n  };\n\n  const onNodeKeyDown = (event: React.KeyboardEvent<HTMLElement>, nodeId: string) => {\n    const item = structure.items.get(nodeId);\n    if (!item) return;\n    const layer = structure.layers[item.layer].filter((entry) => !entry.dummy);\n    const position = layer.indexOf(item);\n    const across = (delta: 1 | -1) => {\n      for (\n        let l = item.layer + delta;\n        l >= 0 && l < structure.layers.length;\n        l += delta\n      ) {\n        const candidates = structure.layers[l].filter((entry) => !entry.dummy);\n        if (!candidates.length) continue;\n        return candidates.reduce((best, entry) =>\n          Math.abs(entry.pos - item.pos) < Math.abs(best.pos - item.pos)\n            ? entry\n            : best,\n        ).id;\n      }\n      return undefined;\n    };\n    const keys: Record<string, () => string | undefined> = horizontal\n      ? {\n          ArrowUp: () => layer[position - 1]?.id,\n          ArrowDown: () => layer[position + 1]?.id,\n          ArrowLeft: () => across(-1),\n          ArrowRight: () => across(1),\n        }\n      : {\n          ArrowLeft: () => layer[position - 1]?.id,\n          ArrowRight: () => layer[position + 1]?.id,\n          ArrowUp: () => across(-1),\n          ArrowDown: () => across(1),\n        };\n    keys.Home = () => tabOrder[0];\n    keys.End = () => tabOrder[tabOrder.length - 1];\n    const move = keys[event.key];\n    if (!move) return;\n    event.preventDefault();\n    focusNode(move());\n  };\n\n  /* ---------------------------------------------------------- render helpers */\n\n  const maxRps = Math.max(1, ...edges.map((edge) => edge.rps ?? 0));\n  const formatMetrics = (metrics?: ServiceMetrics) => ({\n    rps: metrics?.rps != null ? rpsFormatter(metrics.rps) : undefined,\n    errorRate:\n      metrics?.errorRate != null ? errorRateFormatter(metrics.errorRate) : undefined,\n    p95: metrics?.p95 != null ? latencyFormatter(metrics.p95) : undefined,\n  });\n  const errorClass = (rate: number | undefined) =>\n    rate == null\n      ? \"\"\n      : rate >= critical\n        ? \"text-destructive\"\n        : rate >= warn\n          ? \"text-amber-700 dark:text-amber-400\"\n          : \"\";\n  const iconFor = (node: ServiceMapNode, size = 15) => {\n    if (node.icon) return node.icon;\n    const Icon = kindIcon[node.kind ?? \"service\"];\n    return <Icon aria-hidden=\"true\" size={size} stroke={1.75} />;\n  };\n\n  const describeNode = (node: ServiceMapNode) => {\n    const status = statusOf(node);\n    const parts = [node.label, kindLabel[node.kind ?? \"service\"], statusLabel[status]];\n    const m = formatMetrics(node.metrics);\n    if (m.rps) parts.push(m.rps);\n    if (m.errorRate) parts.push(`${m.errorRate} errors`);\n    if (m.p95) parts.push(`p95 ${m.p95}`);\n    const ins = inbound.get(node.id)?.length ?? 0;\n    const outs = outbound.get(node.id)?.length ?? 0;\n    parts.push(`${ins} inbound, ${outs} outbound`);\n    return parts.join(\", \");\n  };\n\n  const edgeSummary = (edge: ServiceMapEdge) =>\n    [\n      edge.rps != null ? rpsFormatter(edge.rps) : null,\n      edge.errorRate != null ? `${errorRateFormatter(edge.errorRate)} errors` : null,\n      edge.p95 != null ? `p95 ${latencyFormatter(edge.p95)}` : null,\n    ]\n      .filter(Boolean)\n      .join(\" · \");\n\n  const counts = { healthy: 0, degraded: 0, down: 0 };\n  for (const node of nodes) counts[statusOf(node)] += 1;\n\n  const hasHeader = title != null || description != null || actions != null;\n  const mapLabel = typeof title === \"string\" ? title : \"Service map\";\n  const motion = animate && !reduced;\n  const offsetX = Math.max(0, (width - worldW * scale) / 2);\n\n  /* ---------------------------------------------------------- render */\n\n  return (\n    <div\n      data-slot=\"service-map\"\n      data-direction={direction}\n      data-selected={selectedNode ? true : undefined}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        if (event.defaultPrevented || event.key !== \"Escape\") return;\n        if (selectedId == null && !hoveredEdge) return;\n        event.preventDefault();\n        setHoveredEdge(null);\n        if (selectedId != null) select(null);\n      }}\n      className={cn(\n        \"@container/service-map flex min-w-0 flex-col rounded-2xl border border-border/70 bg-card text-card-foreground shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\",\n        \"[--sm-ok:color-mix(in_oklab,var(--color-muted-foreground)_34%,var(--color-card))] dark:[--sm-ok:color-mix(in_oklab,var(--color-chart-1)_26%,var(--color-muted))]\",\n        \"[--sm-flow:var(--color-chart-1)] [--sm-warn:var(--color-amber-500,oklch(76.9%_0.188_70.08))] [--sm-critical:var(--color-destructive)]\",\n        className,\n      )}\n      {...props}\n    >\n      <style href=\"overtrue-service-map\" precedence=\"default\">\n        {`@keyframes service-map-ping{75%,100%{transform:scale(2.4);opacity:0}}@keyframes service-map-draw{from{stroke-dashoffset:var(--len)}}@keyframes service-map-rise{from{opacity:0;transform:translateY(6px) scale(.97)}}@keyframes service-map-fade{from{opacity:0}}@keyframes service-map-glow{0%,100%{opacity:.55}50%{opacity:1}}`}\n      </style>\n\n      {hasHeader || nodes.length > 0 ? (\n        <div className=\"flex flex-wrap items-start justify-between gap-x-6 gap-y-3 px-5 pt-5\">\n          <div className=\"min-w-0 space-y-1\">\n            {title != null ? (\n              <h3 className=\"text-sm leading-5 font-semibold tracking-tight\">\n                {title}\n              </h3>\n            ) : null}\n            {description != null ? (\n              <p\n                id={`${id}-description`}\n                className=\"text-[13px] leading-5 text-muted-foreground\"\n              >\n                {description}\n              </p>\n            ) : null}\n          </div>\n          <div className=\"flex shrink-0 flex-wrap items-center gap-3\">\n            {nodes.length > 0 ? (\n              <ul\n                data-slot=\"service-map-summary\"\n                aria-label=\"Health summary\"\n                className=\"flex items-center gap-3 text-xs text-muted-foreground\"\n              >\n                {([\"healthy\", \"degraded\", \"down\"] as const)\n                  .filter((status) => status === \"healthy\" || counts[status] > 0)\n                  .map((status) => (\n                    <li key={status} className=\"flex items-center gap-1.5\">\n                      <StatusDot status={status} />\n                      <span className=\"font-medium text-foreground tabular-nums\">\n                        {counts[status]}\n                      </span>\n                      {statusLabel[status].toLowerCase()}\n                    </li>\n                  ))}\n              </ul>\n            ) : null}\n            {actions != null ? (\n              <div className=\"flex items-center gap-1\">{actions}</div>\n            ) : null}\n          </div>\n        </div>\n      ) : null}\n\n      <div className=\"px-3 pt-4 pb-3\">\n        <div\n          ref={viewportRef}\n          data-slot=\"service-map-viewport\"\n          className=\"relative overflow-x-auto overflow-y-hidden overscroll-x-contain rounded-xl bg-muted/35 ring-1 ring-border/50 ring-inset [scrollbar-width:thin]\"\n        >\n          {nodes.length === 0 ? (\n            <p className=\"grid h-40 place-items-center text-xs text-muted-foreground\">\n              No services to show.\n            </p>\n          ) : (\n            <div\n              className=\"relative\"\n              style={{\n                width: worldW * scale,\n                height: worldH * scale,\n                marginLeft: offsetX,\n              }}\n            >\n              <div\n                role=\"group\"\n                aria-roledescription=\"service map\"\n                aria-label={`${mapLabel}: ${nodes.length} services, ${edges.length} connections. Arrow keys move between services, Enter selects, Escape clears.`}\n                aria-describedby={description != null ? `${id}-description` : undefined}\n                data-slot=\"service-map-world\"\n                className=\"absolute top-0 left-0 origin-top-left\"\n                style={{\n                  width: worldW,\n                  height: worldH,\n                  transform: scale === 1 ? undefined : `scale(${scale})`,\n                }}\n                onPointerLeave={() => {\n                  setHoveredId(null);\n                  setHoveredEdge(null);\n                }}\n              >\n                <svg\n                  aria-hidden=\"true\"\n                  data-slot=\"service-map-edges\"\n                  className=\"absolute inset-0 overflow-visible\"\n                  width={worldW}\n                  height={worldH}\n                  viewBox={`0 0 ${worldW} ${worldH}`}\n                >\n                  {placement.edges.map((placed) => {\n                    const { edge } = placed;\n                    const severity = severityOf(edge);\n                    const share = Math.sqrt(Math.max(0, edge.rps ?? 0) / maxRps);\n                    const strokeWidth = edge.rps != null ? 1 + share * 3 : 1.25;\n                    const highlighted = lit?.edges.has(placed.key) ?? false;\n                    const dimmed = lit != null && !highlighted;\n                    const sourceLayer = structure.layerOf.get(edge.source) ?? 0;\n                    const particles = Math.min(4, Math.max(1, Math.round(1 + share * 3)));\n                    const speed = 38 + share * 72;\n                    const duration = Math.max(1.2, placed.length / speed);\n                    const stroke =\n                      severity === \"ok\" && highlighted\n                        ? \"color-mix(in oklab, var(--sm-flow) 70%, var(--sm-ok))\"\n                        : severityStroke[severity];\n                    return (\n                      <g\n                        key={placed.key}\n                        data-slot=\"service-map-edge\"\n                        data-id={placed.key}\n                        data-severity={severity}\n                        data-active={highlighted || undefined}\n                        data-dimmed={dimmed || undefined}\n                        className=\"transition-opacity duration-150 motion-reduce:transition-none\"\n                        style={{\n                          opacity: dimmed ? 0.16 : 1,\n                          color: severityFlow[severity],\n                        }}\n                      >\n                        <path\n                          d={placed.d}\n                          fill=\"none\"\n                          stroke={stroke}\n                          strokeWidth={strokeWidth}\n                          strokeLinecap=\"round\"\n                          className={cn(\n                            \"transition-[stroke] duration-150 motion-reduce:transition-none\",\n                            severity !== \"ok\" &&\n                              \"dark:[filter:drop-shadow(0_0_5px_color-mix(in_oklab,currentColor_55%,transparent))]\",\n                            highlighted &&\n                              \"dark:[filter:drop-shadow(0_0_6px_color-mix(in_oklab,currentColor_60%,transparent))]\",\n                            !revealed &&\n                              \"motion-safe:[stroke-dasharray:var(--len)] motion-safe:animate-[service-map-draw_900ms_cubic-bezier(0.22,1,0.36,1)_backwards]\",\n                          )}\n                          style={\n                            {\n                              \"--len\": Math.ceil(placed.length + 4),\n                              animationDelay: revealed ? undefined : `${160 + sourceLayer * 110}ms`,\n                            } as React.CSSProperties\n                          }\n                        />\n                        {motion ? (\n                          <g\n                            data-slot=\"service-map-flow\"\n                            className={cn(\n                              \"dark:[filter:drop-shadow(0_0_3px_currentColor)]\",\n                              !revealed &&\n                                \"motion-safe:animate-[service-map-fade_600ms_ease-out_backwards]\",\n                            )}\n                            style={{\n                              animationDelay: revealed ? undefined : `${700 + sourceLayer * 110}ms`,\n                            }}\n                          >\n                            {Array.from({ length: particles }, (_, i) => (\n                              <circle\n                                key={i}\n                                r={highlighted ? 2.4 : 2}\n                                fill=\"currentColor\"\n                                opacity={severity === \"ok\" ? 0.9 : 1}\n                              >\n                                <animateMotion\n                                  dur={`${duration.toFixed(2)}s`}\n                                  begin={`${(-(duration * i) / particles - (placed.index % 5) * 0.37).toFixed(2)}s`}\n                                  repeatCount=\"indefinite\"\n                                  path={placed.d}\n                                />\n                              </circle>\n                            ))}\n                          </g>\n                        ) : (\n                          <path\n                            data-slot=\"service-map-flow\"\n                            d={placed.d}\n                            fill=\"none\"\n                            stroke=\"currentColor\"\n                            strokeWidth={Math.min(2.6, strokeWidth + 0.4)}\n                            strokeLinecap=\"round\"\n                            strokeDasharray=\"0 11\"\n                            opacity={severity === \"ok\" ? 0.8 : 0.95}\n                          />\n                        )}\n                        <circle\n                          cx={placed.end.x}\n                          cy={placed.end.y}\n                          r={2.5}\n                          fill=\"var(--color-card)\"\n                          stroke={stroke}\n                          strokeWidth={1.5}\n                          className={cn(\n                            !revealed &&\n                              \"motion-safe:animate-[service-map-fade_300ms_ease-out_backwards]\",\n                          )}\n                          style={{\n                            animationDelay: revealed\n                              ? undefined\n                              : `${760 + sourceLayer * 110}ms`,\n                          }}\n                        />\n                        <path\n                          d={placed.d}\n                          fill=\"none\"\n                          stroke=\"transparent\"\n                          strokeWidth={14}\n                          className=\"pointer-events-[stroke] cursor-default\"\n                          onPointerEnter={() => {\n                            setHoveredId(null);\n                            setHoveredEdge(placed.key);\n                          }}\n                          onPointerLeave={() => setHoveredEdge(null)}\n                        />\n                      </g>\n                    );\n                  })}\n                </svg>\n\n                {tabOrder.map((nodeId) => {\n                  const node = byId.get(nodeId)!;\n                  const rect = placement.rects.get(nodeId)!;\n                  const status = statusOf(node);\n                  const kind = node.kind ?? \"service\";\n                  const selected = selectedId === nodeId;\n                  const active = hoveredId === nodeId || focusedId === nodeId;\n                  const onPath = lit?.nodes.has(nodeId) ?? false;\n                  const dimmed = lit != null && !onPath;\n                  const formatted = formatMetrics(node.metrics);\n                  const layer = structure.layerOf.get(nodeId) ?? 0;\n                  // The lit surface: a card in comfortable density, the icon tile in compact.\n                  const surface = cn(\n                    \"border border-border/80 bg-card\",\n                    \"shadow-[0_1px_2px_rgb(0_0_0/0.05),0_4px_12px_-6px_rgb(0_0_0/0.12)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06),0_1px_2px_rgb(0_0_0/0.5)]\",\n                    \"transition-[opacity,box-shadow,border-color,translate] duration-150 ease-out motion-reduce:transition-none\",\n                    active &&\n                      status === \"healthy\" &&\n                      !selected &&\n                      \"border-foreground/25 shadow-[0_1px_2px_rgb(0_0_0/0.06),0_10px_24px_-10px_rgb(0_0_0/0.25)]\",\n                    status === \"degraded\" &&\n                      \"border-amber-500/70 shadow-[0_0_0_3px_color-mix(in_oklab,var(--sm-warn)_16%,transparent),0_8px_24px_-8px_color-mix(in_oklab,var(--sm-warn)_45%,transparent)] dark:shadow-[0_0_0_3px_color-mix(in_oklab,var(--sm-warn)_18%,transparent),0_0_28px_-6px_color-mix(in_oklab,var(--sm-warn)_55%,transparent)]\",\n                    status === \"down\" &&\n                      \"border-destructive/80 shadow-[0_0_0_3px_color-mix(in_oklab,var(--sm-critical)_16%,transparent),0_8px_24px_-8px_color-mix(in_oklab,var(--sm-critical)_50%,transparent)] dark:shadow-[0_0_0_3px_color-mix(in_oklab,var(--sm-critical)_20%,transparent),0_0_32px_-6px_color-mix(in_oklab,var(--sm-critical)_60%,transparent)]\",\n                    selected &&\n                      \"border-primary/70 shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-primary)_22%,transparent),0_10px_30px_-10px_color-mix(in_oklab,var(--color-primary)_55%,transparent)] dark:shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-primary)_26%,transparent),0_0_32px_-4px_color-mix(in_oklab,var(--color-primary)_55%,transparent)]\",\n                  );\n                  const downRing =\n                    status === \"down\" ? (\n                      <span\n                        aria-hidden=\"true\"\n                        className=\"pointer-events-none absolute -inset-[5px] rounded-[inherit] border border-destructive/50 opacity-60 motion-safe:animate-[service-map-glow_2.2s_ease-in-out_infinite]\"\n                      />\n                    ) : null;\n                  const iconTint = cn(\n                    \"text-muted-foreground transition-colors duration-150 motion-reduce:transition-none\",\n                    (active || selected) && \"text-foreground\",\n                    status === \"degraded\" && \"text-amber-700 dark:text-amber-400\",\n                    status === \"down\" && \"text-destructive\",\n                  );\n                  const shared = {\n                    type: \"button\" as const,\n                    \"data-slot\": \"service-map-node\",\n                    \"data-id\": nodeId,\n                    \"data-status\": status,\n                    \"data-kind\": kind,\n                    \"data-density\": compact ? \"compact\" : \"comfortable\",\n                    \"data-active\": active || (lit != null && onPath) || undefined,\n                    \"data-selected\": selected || undefined,\n                    \"data-dimmed\": dimmed || undefined,\n                    \"aria-label\": describeNode(node),\n                    \"aria-pressed\": selected,\n                    onClick: () => select(selected ? null : nodeId),\n                    onPointerEnter: () => {\n                      setHoveredEdge(null);\n                      setHoveredId(nodeId);\n                    },\n                    onPointerLeave: () => setHoveredId(null),\n                    onFocus: (event: React.FocusEvent<HTMLButtonElement>) =>\n                      setFocusedId(\n                        event.currentTarget.matches(\":focus-visible\") ? nodeId : null,\n                      ),\n                    onBlur: () => setFocusedId(null),\n                    onKeyDown: (event: React.KeyboardEvent<HTMLButtonElement>) =>\n                      onNodeKeyDown(event, nodeId),\n                    style: {\n                      left: rect.x,\n                      top: rect.y,\n                      width: cardW,\n                      height: cardH,\n                      animationDelay: revealed ? undefined : `${layer * 110}ms`,\n                    } as React.CSSProperties,\n                  };\n                  const reveal =\n                    !revealed &&\n                    \"motion-safe:animate-[service-map-rise_700ms_cubic-bezier(0.22,1,0.36,1)_backwards]\";\n\n                  if (compact) {\n                    return (\n                      <button\n                        key={nodeId}\n                        {...shared}\n                        className={cn(\n                          \"group/node absolute flex flex-col items-center gap-1 bg-transparent p-0 text-center outline-none select-none transition-opacity duration-150 motion-reduce:transition-none\",\n                          dimmed && \"opacity-40\",\n                          reveal,\n                        )}\n                      >\n                        <span\n                          aria-hidden=\"true\"\n                          data-slot=\"service-map-node-tile\"\n                          className={cn(\n                            \"relative grid shrink-0 place-items-center rounded-[11px] [&>svg]:size-4\",\n                            surface,\n                            iconTint,\n                            \"group-hover/node:-translate-y-px group-focus-visible/node:ring-2 group-focus-visible/node:ring-ring/60 group-focus-visible/node:ring-offset-2 group-focus-visible/node:ring-offset-card\",\n                          )}\n                          style={{ width: COMPACT_TILE, height: COMPACT_TILE }}\n                        >\n                          {downRing}\n                          {iconFor(node, 16)}\n                          <StatusDot\n                            status={status}\n                            className=\"absolute -top-1 -right-1 ring-2 ring-card\"\n                          />\n                        </span>\n                        <span className=\"max-w-full truncate px-0.5 text-[11.5px] leading-4 font-medium tracking-tight\">\n                          {node.label}\n                        </span>\n                      </button>\n                    );\n                  }\n\n                  const info: ServiceMapNodeInfo = {\n                    kind,\n                    status,\n                    layer,\n                    inbound: inbound.get(nodeId) ?? [],\n                    outbound: outbound.get(nodeId) ?? [],\n                    active,\n                    selected,\n                    dimmed,\n                    formatted,\n                    icon: iconFor(node),\n                  };\n                  return (\n                    <button\n                      key={nodeId}\n                      {...shared}\n                      className={cn(\n                        \"group/node absolute flex flex-col overflow-visible rounded-xl p-0 text-left text-card-foreground outline-none select-none hover:-translate-y-px\",\n                        surface,\n                        \"focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-2 focus-visible:ring-offset-card\",\n                        dimmed && \"opacity-40\",\n                        reveal,\n                      )}\n                    >\n                      {downRing}\n                      {renderNode ? (\n                        renderNode(node, info)\n                      ) : (\n                        <>\n                          <span className=\"flex min-w-0 items-center gap-2 px-2.5 pt-2.5\">\n                            <span\n                              aria-hidden=\"true\"\n                              className={cn(\n                                \"grid size-6 shrink-0 place-items-center rounded-md bg-muted ring-1 ring-border/60 ring-inset [&>svg]:size-3.5\",\n                                iconTint,\n                                status === \"degraded\" && \"bg-amber-500/12 ring-amber-500/25\",\n                                status === \"down\" && \"bg-destructive/12 ring-destructive/25\",\n                              )}\n                            >\n                              {iconFor(node, 14)}\n                            </span>\n                            <span className=\"min-w-0 flex-1 truncate text-[13px] leading-5 font-medium tracking-tight\">\n                              {node.label}\n                            </span>\n                            <StatusDot status={status} />\n                          </span>\n                          <span className=\"flex min-w-0 items-center gap-1 overflow-hidden px-2.5 pt-1.5 text-[11px] leading-4 whitespace-nowrap text-muted-foreground tabular-nums\">\n                            {[\n                              formatted.rps ? (\n                                <span key=\"rps\" className=\"text-foreground/85\">\n                                  {formatted.rps}\n                                </span>\n                              ) : null,\n                              formatted.errorRate ? (\n                                <span key=\"err\" className={errorClass(node.metrics?.errorRate)}>\n                                  {formatted.errorRate}\n                                </span>\n                              ) : null,\n                              formatted.p95 ? <span key=\"p95\">{formatted.p95}</span> : null,\n                            ]\n                              .filter(Boolean)\n                              .flatMap((part, i) =>\n                                i === 0\n                                  ? [part]\n                                  : [\n                                      <span key={`sep${i}`} aria-hidden=\"true\" className=\"text-muted-foreground/45\">\n                                        ·\n                                      </span>,\n                                      part,\n                                    ],\n                              )}\n                          </span>\n                        </>\n                      )}\n                    </button>\n                  );\n                })}\n              </div>\n\n              {compact && readoutNode && !hoveredPlaced ? (\n                <NodeReadout\n                  node={readoutNode}\n                  status={statusOf(readoutNode)}\n                  formatted={formatMetrics(readoutNode.metrics)}\n                  errorClass={errorClass(readoutNode.metrics?.errorRate)}\n                  rect={placement.rects.get(readoutNode.id)!}\n                  cardW={cardW}\n                  cardH={cardH}\n                  scale={scale}\n                  worldWidth={worldW * scale}\n                />\n              ) : null}\n\n              {hoveredPlaced ? (\n                <div\n                  aria-hidden=\"true\"\n                  data-slot=\"service-map-edge-readout\"\n                  className=\"pointer-events-none absolute z-30 w-max -translate-x-1/2 -translate-y-[calc(100%+10px)] rounded-xl border border-border/70 bg-popover/90 px-3 py-2 text-popover-foreground shadow-xl backdrop-blur-md motion-safe:animate-[service-map-fade_150ms_ease-out]\"\n                  style={{\n                    left: Math.min(\n                      Math.max(hoveredPlaced.mid.x * scale, 96),\n                      worldW * scale - 96,\n                    ),\n                    top: Math.max(hoveredPlaced.mid.y * scale, 64),\n                  }}\n                >\n                  <p className=\"flex items-center gap-1.5 text-xs font-medium\">\n                    {byId.get(hoveredPlaced.edge.source)?.label}\n                    <span aria-hidden=\"true\" className=\"text-muted-foreground\">\n                      →\n                    </span>\n                    {byId.get(hoveredPlaced.edge.target)?.label}\n                  </p>\n                  <EdgeMetrics\n                    edge={hoveredPlaced.edge}\n                    className=\"mt-1\"\n                    rpsFormatter={rpsFormatter}\n                    latencyFormatter={latencyFormatter}\n                    errorRateFormatter={errorRateFormatter}\n                    errorClass={errorClass}\n                  />\n                </div>\n              ) : null}\n            </div>\n          )}\n        </div>\n      </div>\n\n      {selectedNode ? (\n        <ServiceDetail\n          key={selectedNode.id}\n          node={selectedNode}\n          status={statusOf(selectedNode)}\n          icon={iconFor(selectedNode, 16)}\n          inbound={inbound.get(selectedNode.id) ?? []}\n          outbound={outbound.get(selectedNode.id) ?? []}\n          byId={byId}\n          statusOf={statusOf}\n          severityOf={severityOf}\n          formatMetrics={formatMetrics}\n          errorClass={errorClass}\n          edgeKey={(edge) =>\n            placement.edges.find((placed) => placed.edge === edge)?.key ?? null\n          }\n          onHoverEdge={setHoveredEdge}\n          onSelect={(nodeId) => {\n            select(nodeId);\n            requestAnimationFrame(() => focusNode(nodeId));\n          }}\n          onClose={() => select(null)}\n          rpsFormatter={rpsFormatter}\n          latencyFormatter={latencyFormatter}\n          errorRateFormatter={errorRateFormatter}\n        />\n      ) : null}\n\n      {showLegend ? (\n        <div\n          data-slot=\"service-map-legend\"\n          className=\"flex flex-wrap items-center gap-x-5 gap-y-2 border-t border-border/60 px-5 py-3 text-xs text-muted-foreground\"\n        >\n          {(\n            [\n              [\"ok\", \"Healthy traffic\"],\n              [\"warn\", `Errors ≥ ${errorRateFormatter(warn)}`],\n              [\"critical\", `Errors ≥ ${errorRateFormatter(critical)}`],\n            ] as const\n          ).map(([severity, label]) => (\n            <span key={severity} className=\"flex items-center gap-2\">\n              <svg aria-hidden=\"true\" width=\"22\" height=\"8\" className=\"shrink-0 overflow-visible\">\n                <line\n                  x1=\"1\"\n                  y1=\"4\"\n                  x2=\"21\"\n                  y2=\"4\"\n                  stroke={severityStroke[severity]}\n                  strokeWidth=\"2\"\n                  strokeLinecap=\"round\"\n                />\n                <circle cx=\"13\" cy=\"4\" r=\"2\" fill={severityFlow[severity]} />\n              </svg>\n              {label}\n            </span>\n          ))}\n          <span className=\"flex items-center gap-2 @2xl/service-map:ml-auto\">\n            <svg aria-hidden=\"true\" width=\"22\" height=\"8\" className=\"shrink-0\">\n              <path d=\"M1 3.5 L21 1 L21 7 L1 4.5 Z\" fill=\"var(--sm-ok)\" />\n            </svg>\n            Width shows requests per second\n          </span>\n        </div>\n      ) : null}\n\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {selectedNode\n          ? `${selectedNode.label} selected, ${statusLabel[statusOf(selectedNode)].toLowerCase()}. ${inbound.get(selectedNode.id)?.length ?? 0} inbound and ${outbound.get(selectedNode.id)?.length ?? 0} outbound connections.`\n          : \"\"}\n        {hoveredPlaced ? ` ${byId.get(hoveredPlaced.edge.source)?.label} to ${byId.get(hoveredPlaced.edge.target)?.label}: ${edgeSummary(hoveredPlaced.edge)}` : \"\"}\n      </p>\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Detail                                                                    */\n/* ------------------------------------------------------------------------ */\n\n/** Floating readout for compact tiles, which have no room for a metrics line. */\nfunction NodeReadout({\n  node,\n  status,\n  formatted,\n  errorClass,\n  rect,\n  cardW,\n  cardH,\n  scale,\n  worldWidth,\n}: {\n  node: ServiceMapNode;\n  status: ServiceStatus;\n  formatted: { rps?: string; errorRate?: string; p95?: string };\n  errorClass: string;\n  rect: { x: number; y: number };\n  cardW: number;\n  cardH: number;\n  scale: number;\n  worldWidth: number;\n}) {\n  const above = rect.y * scale > 56;\n  const parts = [\n    formatted.rps ? <span key=\"rps\" className=\"font-medium text-foreground\">{formatted.rps}</span> : null,\n    formatted.errorRate ? (\n      <span key=\"err\" className={cn(\"font-medium text-foreground\", errorClass)}>\n        {formatted.errorRate}\n      </span>\n    ) : null,\n    formatted.p95 ? <span key=\"p95\">p95 {formatted.p95}</span> : null,\n  ].filter(Boolean);\n  return (\n    <div\n      aria-hidden=\"true\"\n      data-slot=\"service-map-node-readout\"\n      className={cn(\n        \"pointer-events-none absolute z-30 w-max -translate-x-1/2 rounded-xl border border-border/70 bg-popover/90 px-3 py-2 text-popover-foreground shadow-xl backdrop-blur-md motion-safe:animate-[service-map-fade_150ms_ease-out]\",\n        above ? \"-translate-y-[calc(100%+6px)]\" : \"translate-y-1.5\",\n      )}\n      style={{\n        left: Math.min(Math.max((rect.x + cardW / 2) * scale, 84), worldWidth - 84),\n        top: above ? rect.y * scale : (rect.y + cardH) * scale,\n      }}\n    >\n      <p className=\"flex items-center gap-1.5 text-xs font-medium\">\n        <StatusDot status={status} />\n        {node.label}\n        <span className=\"font-normal text-muted-foreground\">\n          {statusLabel[status].toLowerCase()}\n        </span>\n      </p>\n      {parts.length ? (\n        <p className=\"mt-1 flex items-center gap-1.5 text-xs text-muted-foreground tabular-nums\">\n          {parts.flatMap((part, i) =>\n            i === 0\n              ? [part]\n              : [\n                  <span key={`sep${i}`} aria-hidden=\"true\" className=\"text-muted-foreground/45\">\n                    ·\n                  </span>,\n                  part,\n                ],\n          )}\n        </p>\n      ) : null}\n    </div>\n  );\n}\n\nfunction EdgeMetrics({\n  edge,\n  className,\n  rpsFormatter,\n  latencyFormatter,\n  errorRateFormatter,\n  errorClass,\n}: {\n  edge: ServiceMapEdge;\n  className?: string;\n  rpsFormatter: (rps: number) => string;\n  latencyFormatter: (ms: number) => string;\n  errorRateFormatter: (rate: number) => string;\n  errorClass: (rate: number | undefined) => string;\n}) {\n  return (\n    <p className={cn(\"flex items-center gap-3 text-xs text-muted-foreground tabular-nums\", className)}>\n      {edge.rps != null ? (\n        <span>\n          <span className=\"font-medium text-foreground\">{rpsFormatter(edge.rps)}</span>\n        </span>\n      ) : null}\n      {edge.errorRate != null ? (\n        <span>\n          <span className={cn(\"font-medium text-foreground\", errorClass(edge.errorRate))}>\n            {errorRateFormatter(edge.errorRate)}\n          </span>{\" \"}\n          errors\n        </span>\n      ) : null}\n      {edge.p95 != null ? (\n        <span>\n          p95{\" \"}\n          <span className=\"font-medium text-foreground\">{latencyFormatter(edge.p95)}</span>\n        </span>\n      ) : null}\n    </p>\n  );\n}\n\nfunction ServiceDetail({\n  node,\n  status,\n  icon,\n  inbound,\n  outbound,\n  byId,\n  statusOf,\n  severityOf,\n  formatMetrics,\n  errorClass,\n  edgeKey,\n  onHoverEdge,\n  onSelect,\n  onClose,\n  rpsFormatter,\n  latencyFormatter,\n  errorRateFormatter,\n}: {\n  node: ServiceMapNode;\n  status: ServiceStatus;\n  icon: React.ReactNode;\n  inbound: ServiceMapEdge[];\n  outbound: ServiceMapEdge[];\n  byId: Map<string, ServiceMapNode>;\n  statusOf: (node: ServiceMapNode) => ServiceStatus;\n  severityOf: (edge: ServiceMapEdge) => Severity;\n  formatMetrics: (metrics?: ServiceMetrics) => { rps?: string; errorRate?: string; p95?: string };\n  errorClass: (rate: number | undefined) => string;\n  edgeKey: (edge: ServiceMapEdge) => string | null;\n  onHoverEdge: (key: string | null) => void;\n  onSelect: (id: string) => void;\n  onClose: () => void;\n  rpsFormatter: (rps: number) => string;\n  latencyFormatter: (ms: number) => string;\n  errorRateFormatter: (rate: number) => string;\n}) {\n  const formatted = formatMetrics(node.metrics);\n  const figures = [\n    { key: \"rps\", label: \"Requests\", value: formatted.rps, className: \"\" },\n    {\n      key: \"err\",\n      label: \"Error rate\",\n      value: formatted.errorRate,\n      className: errorClass(node.metrics?.errorRate),\n    },\n    { key: \"p95\", label: \"p95 latency\", value: formatted.p95, className: \"\" },\n  ].filter((figure) => figure.value != null);\n\n  const list = (title: string, items: ServiceMapEdge[], side: \"in\" | \"out\") => (\n    <div className=\"min-w-0\">\n      <h4 className=\"mb-1.5 flex items-baseline gap-1.5 text-xs text-muted-foreground\">\n        {title}\n        <span className=\"tabular-nums\">{items.length}</span>\n      </h4>\n      {items.length ? (\n        <ul className=\"-mx-2 flex flex-col\">\n          {items.map((edge, i) => {\n            const otherId = side === \"in\" ? edge.source : edge.target;\n            const other = byId.get(otherId);\n            const severity = severityOf(edge);\n            const key = edgeKey(edge);\n            return (\n              <li key={`${otherId}-${i}`}>\n                <button\n                  type=\"button\"\n                  data-slot=\"service-map-detail-edge\"\n                  data-severity={severity}\n                  onPointerEnter={() => onHoverEdge(key)}\n                  onPointerLeave={() => onHoverEdge(null)}\n                  onFocus={() => onHoverEdge(key)}\n                  onBlur={() => onHoverEdge(null)}\n                  onClick={() => other && onSelect(other.id)}\n                  aria-label={`${side === \"in\" ? \"From\" : \"To\"} ${other?.label ?? otherId}${edge.rps != null ? `, ${rpsFormatter(edge.rps)}` : \"\"}${edge.errorRate != null ? `, ${errorRateFormatter(edge.errorRate)} errors` : \"\"}${edge.p95 != null ? `, p95 ${latencyFormatter(edge.p95)}` : \"\"}. Select ${other?.label ?? otherId}.`}\n                  className=\"grid h-8 w-full grid-cols-[minmax(0,1fr)_3.75rem_2.75rem_3.25rem] items-center gap-2 rounded-lg px-2 @md/service-map:grid-cols-[minmax(0,1fr)_4.5rem_3.5rem_4rem] text-left text-xs outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none\"\n                >\n                  <span className=\"flex min-w-0 items-center gap-2\">\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"h-0.5 w-3 shrink-0 rounded-full\"\n                      style={{ backgroundColor: severityStroke[severity] === \"var(--sm-ok)\" ? \"var(--sm-flow)\" : severityStroke[severity] }}\n                    />\n                    <span className=\"truncate font-medium text-foreground\">\n                      {other?.label ?? otherId}\n                    </span>\n                    {other && statusOf(other) !== \"healthy\" ? (\n                      <StatusDot status={statusOf(other)} className=\"size-1.5\" />\n                    ) : null}\n                  </span>\n                  <span className=\"text-right text-foreground tabular-nums\">\n                    {edge.rps != null ? rpsFormatter(edge.rps) : \"—\"}\n                  </span>\n                  <span className={cn(\"text-right text-muted-foreground tabular-nums\", errorClass(edge.errorRate))}>\n                    {edge.errorRate != null ? errorRateFormatter(edge.errorRate) : \"—\"}\n                  </span>\n                  <span className=\"text-right text-muted-foreground tabular-nums\">\n                    {edge.p95 != null ? latencyFormatter(edge.p95) : \"—\"}\n                  </span>\n                </button>\n              </li>\n            );\n          })}\n        </ul>\n      ) : (\n        <p className=\"py-1.5 text-xs text-muted-foreground\">None</p>\n      )}\n    </div>\n  );\n\n  return (\n    <section\n      data-slot=\"service-map-detail\"\n      aria-label={`${node.label} details`}\n      className=\"border-t border-border/60 px-5 pt-4 pb-4 motion-safe:animate-[service-map-fade_240ms_ease-out]\"\n    >\n      <div className=\"flex items-start gap-3\">\n        <span\n          aria-hidden=\"true\"\n          className={cn(\n            \"grid size-9 shrink-0 place-items-center rounded-lg bg-muted text-foreground ring-1 ring-border/60 ring-inset [&>svg]:size-4\",\n            status === \"degraded\" && \"bg-amber-500/12 text-amber-700 ring-amber-500/25 dark:text-amber-400\",\n            status === \"down\" && \"bg-destructive/12 text-destructive ring-destructive/25\",\n          )}\n        >\n          {icon}\n        </span>\n        <div className=\"min-w-0 flex-1\">\n          <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n            <h4 className=\"text-sm leading-5 font-semibold tracking-tight\">\n              {node.label}\n            </h4>\n            <span\n              className={cn(\n                \"inline-flex h-5 items-center gap-1.5 rounded-full px-2 text-[11px] font-medium\",\n                statusPill[status],\n              )}\n            >\n              <span aria-hidden=\"true\" className={cn(\"size-1.5 rounded-full\", statusDot[status])} />\n              {statusLabel[status]}\n            </span>\n          </div>\n          <p className=\"text-xs text-muted-foreground\">\n            {kindLabel[node.kind ?? \"service\"][0].toUpperCase() + kindLabel[node.kind ?? \"service\"].slice(1)}\n            {node.group ? (\n              <>\n                {\" · \"}\n                <span className=\"font-mono\">{node.group}</span>\n              </>\n            ) : null}\n          </p>\n        </div>\n        <button\n          type=\"button\"\n          onClick={onClose}\n          aria-label=\"Clear selection\"\n          className=\"inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none\"\n        >\n          <IconX aria-hidden=\"true\" size={15} />\n        </button>\n      </div>\n\n      {figures.length ? (\n        <dl className=\"mt-3 grid grid-cols-3 gap-2\">\n          {figures.map((figure) => {\n            const match = /^([-+<]?[\\d.,]+)\\s*(\\D.*)?$/.exec(figure.value!);\n            return (\n              <div\n                key={figure.key}\n                className=\"rounded-lg bg-muted/40 px-3 py-2 ring-1 ring-border/50 ring-inset\"\n              >\n                <dt className=\"text-[11px] text-muted-foreground\">{figure.label}</dt>\n                <dd className={cn(\"text-lg leading-7 font-semibold tracking-[-0.02em] tabular-nums\", figure.className)}>\n                  {match ? (\n                    <>\n                      {match[1]}\n                      {match[2] ? (\n                        <span\n                          className={cn(\n                            \"text-xs font-medium tracking-normal text-muted-foreground\",\n                            /^[a-zµ]/i.test(match[2]) && \"ml-0.5\",\n                          )}\n                        >\n                          {match[2]}\n                        </span>\n                      ) : null}\n                    </>\n                  ) : (\n                    figure.value\n                  )}\n                </dd>\n              </div>\n            );\n          })}\n        </dl>\n      ) : null}\n\n      <div className=\"mt-4 grid gap-x-8 gap-y-4 @2xl/service-map:grid-cols-2\">\n        {list(\"Inbound\", inbound, \"in\")}\n        {list(\"Outbound\", outbound, \"out\")}\n      </div>\n    </section>\n  );\n}\n\nexport { ServiceMap };\n"
    },
    {
      "path": "src/registry/overtrue/flame-graph.tsx",
      "type": "registry:component",
      "target": "components/overtrue/flame-graph.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconSearch, IconX, IconZoomReset } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------ */\n/* Types                                                                     */\n/* ------------------------------------------------------------------------ */\n\nexport interface FlameNode {\n  /** Stable id. Defaults to the node's position in the tree. Must be unique when set. */\n  id?: string;\n  /** Function or frame name, e.g. \"db.query\" or \"react-dom.renderToString\". */\n  name: string;\n  /** Total (inclusive) cost of the frame. When the children add up to more, their sum is used. */\n  value: number;\n  children?: FlameNode[];\n  /** Color group. Defaults to the name's package prefix, e.g. \"db\" for \"db.query\". */\n  group?: string;\n  /** Anything else your tooltip or handlers need, such as a file and line. */\n  meta?: Record<string, unknown>;\n}\n\nexport type FlameGraphOrientation = \"icicle\" | \"flame\";\n\n/** Everything derived about one frame, passed to `renderTooltip`, `onSelect` and `colorBy`. */\nexport interface FlameFrameInfo {\n  id: string;\n  node: FlameNode;\n  /** 0 for the root. */\n  depth: number;\n  /** Resolved color group. */\n  group: string;\n  /** Inclusive value: the frame and everything it called. */\n  total: number;\n  /** Value spent in the frame itself: total minus children. */\n  self: number;\n  /** Total as a 0–1 share of the root. */\n  share: number;\n  /** Self as a 0–1 share of the root. */\n  selfShare: number;\n  /** Total as a 0–1 share of the parent; 1 for the root. */\n  parentShare: number;\n  parent: FlameNode | null;\n  /** Nodes from the root down to and including this one. */\n  path: FlameNode[];\n  /** Resolved fill and a readable ink for it. */\n  fill: string;\n  ink: string;\n  /** Whether the frame matches the current search. */\n  match: boolean;\n}\n\n/** Context passed to a `colorBy` function. */\nexport interface FlameColorContext {\n  depth: number;\n  group: string;\n  total: number;\n  self: number;\n  /** Total as a 0–1 share of the root. */\n  share: number;\n  /** Self time relative to the hottest frame in the profile, 0–1. */\n  heat: number;\n}\n\nexport type FlameGraphColorBy =\n  | \"group\"\n  | \"self\"\n  | ((node: FlameNode, context: FlameColorContext) => string);\n\nexport interface FlameGraphProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\" | \"onSelect\"\n> {\n  /** The root frame, or several roots that are drawn under one `rootName` frame. */\n  data: FlameNode | FlameNode[];\n  /** Name of the synthetic root when `data` is an array. Defaults to \"all\". */\n  rootName?: string;\n  /** \"icicle\" draws the root on top; \"flame\" draws it at the bottom. Defaults to icicle. */\n  orientation?: FlameGraphOrientation;\n  /** Row height in pixels. Defaults to 22. */\n  rowHeight?: number;\n  /** Frames narrower than this many pixels are skipped. Defaults to 2. */\n  minFrameWidth?: number;\n  /** Maximum height of the frame area in pixels; deeper profiles scroll. Defaults to fitting every row. */\n  height?: number;\n  /** Color by package group, by self time as a heat scale, or with your own function. Defaults to group. */\n  colorBy?: FlameGraphColorBy;\n  /**\n   * Group palette, hashed by group. With `colorBy=\"self\"`, the stops of the heat\n   * scale from cold to hot. Defaults to accent-to-neutral group tones, and to a\n   * neutral, amber and destructive heat ramp.\n   */\n  colors?: string[];\n  /** Controlled zoom: the id of the frame drawn at full width, or null for the root. */\n  zoomedId?: string | null;\n  defaultZoomedId?: string | null;\n  onZoomChange?: (id: string | null, node: FlameNode | null) => void;\n  /** Show the built-in search field. Defaults to true. */\n  showSearch?: boolean;\n  /** Controlled search. Frames whose name contains it are highlighted. */\n  search?: string;\n  defaultSearch?: string;\n  onSearchChange?: (search: string) => void;\n  searchPlaceholder?: string;\n  /** Formats values. Defaults to milliseconds. */\n  valueFormatter?: (value: number) => string;\n  /** Replaces the content of the hover and focus readout. */\n  renderTooltip?: (info: FlameFrameInfo) => React.ReactNode;\n  /** List the heaviest functions by aggregated self time. Pass a number for the count; true shows 8. */\n  showTopFunctions?: boolean | number;\n  /** Called when a frame is clicked or activated with Enter, before it zooms. */\n  onSelect?: (node: FlameNode, info: FlameFrameInfo) => void;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right, before the total. */\n  actions?: React.ReactNode;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Model                                                                     */\n/* ------------------------------------------------------------------------ */\n\ninterface Frame {\n  id: string;\n  node: FlameNode;\n  name: string;\n  lower: string;\n  group: string;\n  depth: number;\n  /** Start and end as 0–1 fractions of the root. */\n  start: number;\n  end: number;\n  total: number;\n  self: number;\n  heat: number;\n  parent: Frame | null;\n  children: Frame[];\n}\n\ninterface Model {\n  root: Frame | null;\n  byId: Map<string, Frame>;\n  maxDepth: number;\n  count: number;\n}\n\ninterface View {\n  v0: number;\n  vs: number;\n}\n\nconst ROOT_KEY = \"root\";\nconst DURATION = 300;\n/** Horizontal padding plus about four monospace characters: anything less is noise. */\nconst labelFits = (frame: { name: string }, px: number) =>\n  px >= 13 + 6.7 * Math.min(frame.name.length, 4);\nconst FALLBACK_WIDTH = 640;\n\nconst defaultPalette = [\n  \"var(--color-primary)\",\n  \"color-mix(in oklab, var(--color-primary) 80%, var(--color-muted-foreground))\",\n  \"color-mix(in oklab, var(--color-primary) 60%, var(--color-muted-foreground))\",\n  \"color-mix(in oklab, var(--color-primary) 40%, var(--color-muted-foreground))\",\n  \"var(--color-muted-foreground)\",\n];\n\nconst AMBER = \"var(--color-amber-400, oklch(82.8% 0.189 84.429))\";\nconst defaultHeat = [\n  \"color-mix(in oklab, var(--color-muted-foreground) 24%, var(--color-card))\",\n  AMBER,\n  \"var(--color-destructive)\",\n];\n\n/** The package a frame belongs to: \"db\" for \"db.query\", \"react-dom\" for \"react-dom.render\". */\nfunction packageOf(name: string) {\n  const match =\n    /^\\s*(@[\\w.-]+\\/[\\w-]+|[\\w$-]+)(?:\\.|\\/|::|:|#)/.exec(name) ??\n    /^\\s*([\\w$-]+)/.exec(name);\n  return match ? match[1] : name;\n}\n\nfunction hash(text: string) {\n  let h = 0x811c9dc5;\n  for (let i = 0; i < text.length; i++) {\n    h ^= text.charCodeAt(i);\n    h = Math.imul(h, 0x01000193);\n  }\n  return h >>> 0;\n}\n\nfunction buildModel(data: FlameNode | FlameNode[], rootName: string): Model {\n  const byId = new Map<string, Frame>();\n  const order: Frame[] = [];\n  let maxDepth = 0;\n  const rootNode: FlameNode = Array.isArray(data)\n    ? { name: rootName, value: 0, children: data }\n    : data;\n\n  const visit = (\n    node: FlameNode,\n    parent: Frame | null,\n    depth: number,\n    offset: number,\n    key: string,\n  ): Frame | null => {\n    const id = node.id ?? key;\n    const frame: Frame = {\n      id,\n      node,\n      name: node.name,\n      lower: node.name.toLowerCase(),\n      group: node.group ?? packageOf(node.name),\n      depth,\n      start: offset,\n      end: offset,\n      total: 0,\n      self: 0,\n      heat: 0,\n      parent,\n      children: [],\n    };\n    const at = order.length;\n    order.push(frame);\n    let cursor = offset;\n    node.children?.forEach((child, index) => {\n      const built = visit(child, frame, depth + 1, cursor, `${id}/${index}`);\n      if (!built) return;\n      frame.children.push(built);\n      cursor += built.total;\n    });\n    const childSum = cursor - offset;\n    const own = Number(node.value);\n    frame.total = Math.max(Number.isFinite(own) && own > 0 ? own : 0, childSum);\n    frame.self = Math.max(0, frame.total - childSum);\n    frame.end = offset + frame.total;\n    if (!(frame.total > 0)) {\n      order.length = at;\n      return null;\n    }\n    return frame;\n  };\n\n  const root = visit(rootNode, null, 0, 0, ROOT_KEY);\n  if (!root) return { root: null, byId, maxDepth: 0, count: 0 };\n  const scale = root.total;\n  let maxSelf = 0;\n  for (const frame of order) maxSelf = Math.max(maxSelf, frame.self);\n  for (const frame of order) {\n    frame.start /= scale;\n    frame.end /= scale;\n    frame.heat = maxSelf > 0 ? Math.sqrt(frame.self / maxSelf) : 0;\n    maxDepth = Math.max(maxDepth, frame.depth);\n    byId.set(frame.id, frame);\n  }\n  return { root, byId, maxDepth, count: order.length };\n}\n\nfunction lineage(frame: Frame) {\n  const chain: Frame[] = [];\n  for (let current: Frame | null = frame; current; current = current.parent)\n    chain.unshift(current);\n  return chain;\n}\n\n/** Frames wider than `minWidth` pixels inside the view, in depth-first order. */\nfunction visibleFrames(root: Frame, view: View, width: number, min: number) {\n  const out: Frame[] = [];\n  const lo = view.v0;\n  const hi = view.v0 + view.vs;\n  const stack = [root];\n  while (stack.length) {\n    const frame = stack.pop()!;\n    const a = Math.max(frame.start, lo);\n    const b = Math.min(frame.end, hi);\n    if (b <= a || ((b - a) / view.vs) * width < min) continue;\n    out.push(frame);\n    for (let i = frame.children.length - 1; i >= 0; i--)\n      stack.push(frame.children[i]);\n  }\n  return out;\n}\n\nfunction pixelWidth(frame: Frame, view: View, width: number) {\n  const a = Math.max(frame.start, view.v0);\n  const b = Math.min(frame.end, view.v0 + view.vs);\n  return b > a ? ((b - a) / view.vs) * width : 0;\n}\n\n/**\n * Zoom about the one point that stays put on screen, with the scale changing\n * geometrically, so deep zooms feel as steady as shallow ones.\n */\nfunction interpolate(a: View, b: View, t: number): View {\n  if (Math.abs(a.vs - b.vs) < 1e-12)\n    return { v0: a.v0 + (b.v0 - a.v0) * t, vs: a.vs };\n  const vs = a.vs * Math.pow(b.vs / a.vs, t);\n  const fixed = (b.v0 * a.vs - a.v0 * b.vs) / (a.vs - b.vs);\n  return { v0: fixed - (fixed - a.v0) * (vs / a.vs), vs };\n}\n\nconst easeOut = (t: number) => 1 - Math.pow(1 - t, 3);\n\n/* ------------------------------------------------------------------------ */\n/* Formatting and color                                                     */\n/* ------------------------------------------------------------------------ */\n\nfunction formatMs(ms: number) {\n  if (!Number.isFinite(ms)) return \"—\";\n  const a = Math.abs(ms);\n  if (a === 0) return \"0 ms\";\n  if (a < 1) return `${ms.toFixed(2)} ms`;\n  if (a < 10) return `${ms.toFixed(1)} ms`;\n  if (a < 1000) return `${Math.round(ms)} ms`;\n  if (a < 10_000) return `${(ms / 1000).toFixed(2)} s`;\n  return `${(ms / 1000).toFixed(1)} s`;\n}\n\nfunction percent(share: number) {\n  const pct = share * 100;\n  if (!(pct > 0)) return \"0%\";\n  if (pct < 0.1) return \"<0.1%\";\n  if (pct >= 99.95) return \"100%\";\n  return `${+pct.toFixed(1)}%`;\n}\n\n/** Pick black or white from relative luminance (XYZ Y), with D65's white point. */\nfunction inkFor(fill: string) {\n  const light = \"clamp(0, (0.179 - y) * 100000000, 1)\";\n  return `color(from ${fill} xyz-d65 calc(${light} * 0.95047) ${light} calc(${light} * 1.08883))`;\n}\n\nfunction mix(a: string, b: string, t: number) {\n  const pct = Math.round(Math.min(1, Math.max(0, t)) * 100);\n  if (pct <= 0) return b;\n  if (pct >= 100) return a;\n  return `color-mix(in oklab, ${a} ${pct}%, ${b})`;\n}\n\nfunction rampAt(stops: string[], t: number) {\n  if (stops.length === 1) return stops[0];\n  const scaled = Math.min(1, Math.max(0, t)) * (stops.length - 1);\n  const i = Math.min(stops.length - 2, Math.floor(scaled));\n  return mix(stops[i + 1], stops[i], scaled - i);\n}\n\n/** Splits \"482 ms\" into digits and a quieter unit. */\nfunction Figure({ text, className }: { text: string; className?: string }) {\n  const match = /^([-+]?[\\d.,]+)\\s*(\\D.*)$/.exec(text);\n  if (!match) return <span className={className}>{text}</span>;\n  return (\n    <span className={className}>\n      {match[1]}\n      <span className=\"ml-0.5 text-[0.62em] font-medium tracking-normal text-muted-foreground\">\n        {match[2]}\n      </span>\n    </span>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Hooks                                                                     */\n/* ------------------------------------------------------------------------ */\n\nconst useIsomorphicLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange?: (value: T) => void,\n) {\n  const [inner, setInner] = React.useState(defaultValue);\n  const controlled = value !== undefined;\n  const current = controlled ? value : inner;\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [current, set] as const;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Frame                                                                     */\n/* ------------------------------------------------------------------------ */\n\ninterface FrameProps {\n  frame: Frame;\n  top: number;\n  height: number;\n  fill: string;\n  label: boolean;\n  query: string;\n  match: boolean;\n  dimmed: boolean;\n  ancestor: boolean;\n  zoomed: boolean;\n  active: boolean;\n  tabStop: boolean;\n  ariaLabel: string;\n  reveal: number | null;\n}\n\nfunction Highlighted({ text, query }: { text: string; query: string }) {\n  const at = query ? text.toLowerCase().indexOf(query) : -1;\n  if (at < 0) return <>{text}</>;\n  return (\n    <>\n      {text.slice(0, at)}\n      <mark className=\"bg-transparent font-bold text-inherit underline decoration-current/70 decoration-[1.5px] underline-offset-[3px]\">\n        {text.slice(at, at + query.length)}\n      </mark>\n      {text.slice(at + query.length)}\n    </>\n  );\n}\n\n/** Memoised so hovering one frame re-renders two, not the whole profile. */\nconst FlameFrame = React.memo(function FlameFrame({\n  frame,\n  top,\n  height,\n  fill: baseFill,\n  label,\n  query,\n  match,\n  dimmed,\n  ancestor,\n  zoomed,\n  active,\n  tabStop,\n  ariaLabel,\n  reveal,\n}: FrameProps) {\n  // Dimming mixes the fill toward the surface instead of fading it, so the ink is\n  // always picked against the color that is actually on screen.\n  const fill = active\n    ? baseFill\n    : dimmed\n      ? `color-mix(in oklab, ${baseFill} 26%, var(--color-muted))`\n      : ancestor\n        ? `color-mix(in oklab, ${baseFill} 48%, var(--color-card))`\n        : baseFill;\n  const ink = inkFor(fill);\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"flame-graph-frame\"\n      data-id={frame.id}\n      data-depth={frame.depth}\n      data-match={match || undefined}\n      data-dimmed={dimmed || undefined}\n      data-ancestor={ancestor || undefined}\n      data-zoomed={zoomed || undefined}\n      data-active={active || undefined}\n      aria-label={ariaLabel}\n      aria-current={zoomed ? \"true\" : undefined}\n      tabIndex={tabStop ? 0 : -1}\n      className={cn(\n        \"group/frame absolute block overflow-hidden rounded-[3px] p-0 text-left outline-none select-none\",\n        ancestor ? \"cursor-zoom-out\" : zoomed ? \"cursor-default\" : \"cursor-zoom-in\",\n        \"data-[active]:z-10 focus-visible:z-20\",\n        reveal != null &&\n          \"motion-safe:animate-[flame-frame-in_720ms_cubic-bezier(0.22,1,0.36,1)_backwards]\",\n      )}\n      style={\n        {\n          \"--x0\": +frame.start.toFixed(9),\n          \"--x1\": +frame.end.toFixed(9),\n          \"--frame-fill\": baseFill,\n          top,\n          height,\n          color: ink,\n          animationDelay: reveal != null ? `${reveal}ms` : undefined,\n        } as React.CSSProperties\n      }\n    >\n      <span\n        aria-hidden=\"true\"\n        data-slot=\"flame-graph-frame-fill\"\n        className={cn(\n          \"absolute inset-0 rounded-[inherit] transition-[background-color,box-shadow] duration-150 motion-reduce:transition-none\",\n          match &&\n            \"shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--frame-fill)_55%,var(--color-foreground))] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.4),0_0_14px_-3px_var(--frame-fill)]\",\n          \"group-data-[active]/frame:shadow-[inset_0_0_0_1.5px_color-mix(in_oklab,var(--color-foreground)_82%,transparent),0_0_18px_-4px_var(--frame-fill)]\",\n          \"group-focus-visible/frame:shadow-[inset_0_0_0_2px_var(--color-ring),inset_0_0_0_3px_var(--color-card)]\",\n        )}\n        style={{ backgroundColor: fill }}\n      />\n      {label ? (\n        <span\n          aria-hidden=\"true\"\n          className=\"relative block truncate px-1.5 font-mono text-[11px] transition-colors duration-150 motion-reduce:transition-none\"\n          style={{ lineHeight: `${height}px` }}\n        >\n          {match ? <Highlighted text={frame.name} query={query} /> : frame.name}\n        </span>\n      ) : null}\n    </button>\n  );\n});\n\n/* ------------------------------------------------------------------------ */\n/* Tooltip                                                                   */\n/* ------------------------------------------------------------------------ */\n\nfunction DefaultTooltip({\n  info,\n  format,\n}: {\n  info: FlameFrameInfo;\n  format: (value: number) => string;\n}) {\n  return (\n    <div className=\"w-max max-w-72 min-w-52\">\n      <div className=\"flex items-start gap-2 px-3 pt-2.5 pb-2\">\n        <span\n          aria-hidden=\"true\"\n          className=\"mt-[3px] size-2.5 shrink-0 rounded-[3px]\"\n          style={{ backgroundColor: info.fill }}\n        />\n        <div className=\"min-w-0 space-y-0.5\">\n          <p className=\"font-mono text-xs leading-4 font-medium break-all text-foreground\">\n            {info.node.name}\n          </p>\n          <p className=\"text-[11px] leading-4 text-muted-foreground\">\n            {info.group !== info.node.name ? (\n              <>\n                <span className=\"font-mono\">{info.group}</span>\n                {\" · \"}\n              </>\n            ) : null}\n            depth <span className=\"tabular-nums\">{info.depth}</span>\n          </p>\n        </div>\n      </div>\n      <dl className=\"grid grid-cols-[auto_1fr_auto] items-baseline gap-x-4 gap-y-1 border-t border-border/60 px-3 py-2 text-xs tabular-nums\">\n        <dt className=\"text-muted-foreground\">Total</dt>\n        <dd className=\"text-right font-medium text-foreground\">\n          {format(info.total)}\n        </dd>\n        <dd className=\"text-right text-muted-foreground\">\n          {percent(info.share)}\n        </dd>\n        <dt className=\"text-muted-foreground\">Self</dt>\n        <dd className=\"text-right font-medium text-foreground\">\n          {format(info.self)}\n        </dd>\n        <dd className=\"text-right text-muted-foreground\">\n          {percent(info.selfShare)}\n        </dd>\n        {info.parent ? (\n          <>\n            <dt className=\"text-muted-foreground\">Of parent</dt>\n            <dd className=\"col-span-2 flex min-w-0 items-baseline justify-end gap-1 text-right\">\n              <span className=\"font-medium text-foreground\">\n                {percent(info.parentShare)}\n              </span>\n              <span className=\"truncate font-mono text-[11px] text-muted-foreground\">\n                {info.parent.name}\n              </span>\n            </dd>\n          </>\n        ) : null}\n      </dl>\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Component                                                                 */\n/* ------------------------------------------------------------------------ */\n\nconst toolButton =\n  \"inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none\";\n\n/**\n * A profiler flame graph. Frames are HTML, so labels stay crisp at any zoom.\n * Click or press Enter on a frame to zoom it to full width; Escape zooms out.\n * Search highlights matching frames and reports their share of the total.\n */\nfunction FlameGraph({\n  data,\n  rootName = \"all\",\n  orientation = \"icicle\",\n  rowHeight = 22,\n  minFrameWidth = 2,\n  height,\n  colorBy = \"group\",\n  colors,\n  zoomedId: zoomedIdProp,\n  defaultZoomedId = null,\n  onZoomChange,\n  showSearch = true,\n  search: searchProp,\n  defaultSearch = \"\",\n  onSearchChange,\n  searchPlaceholder = \"Search functions\",\n  valueFormatter = formatMs,\n  renderTooltip,\n  showTopFunctions = false,\n  onSelect,\n  title,\n  description,\n  actions,\n  className,\n  onKeyDown,\n  ...props\n}: FlameGraphProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const format = valueFormatter;\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLDivElement>(null);\n  const tipRef = React.useRef<HTMLDivElement>(null);\n  const pointer = React.useRef<{ x: number; y: number } | null>(null);\n  const pendingFocus = React.useRef(false);\n\n  const model = React.useMemo(() => buildModel(data, rootName), [data, rootName]);\n  const { root, byId, maxDepth } = model;\n\n  /* ---------------------------------------------------------- state */\n\n  const [innerZoom, setInnerZoom] = React.useState<string | null>(\n    defaultZoomedId,\n  );\n  const requestedZoom =\n    zoomedIdProp !== undefined ? zoomedIdProp : innerZoom;\n  const focus =\n    (requestedZoom != null ? byId.get(requestedZoom) : undefined) ?? root;\n  const zoomed = focus != null && focus !== root;\n\n  const [search, setSearch] = useControllable(\n    searchProp,\n    defaultSearch,\n    onSearchChange,\n  );\n  const query = search.trim().toLowerCase();\n\n  const [width, setWidth] = React.useState(0);\n  const [hoveredId, setHoveredId] = React.useState<string | null>(null);\n  const [focusedId, setFocusedId] = React.useState<string | null>(null);\n  const [tabStopId, setTabStopId] = React.useState<string | null>(null);\n  const [tween, setTween] = React.useState<{ from: View; to: View } | null>(\n    null,\n  );\n  const [revealed, setRevealed] = React.useState(false);\n\n  const target: View = focus\n    ? { v0: focus.start, vs: focus.end - focus.start || 1 }\n    : { v0: 0, vs: 1 };\n  const [initialView] = React.useState(target);\n  const shown = React.useRef<View>(target);\n\n  const commitZoom = (frame: Frame | null) => {\n    const next = frame && frame !== root ? frame : null;\n    if (zoomedIdProp === undefined) setInnerZoom(next?.id ?? null);\n    onZoomChange?.(next?.id ?? null, next?.node ?? null);\n  };\n\n  /* ---------------------------------------------------------- measure */\n\n  useIsomorphicLayoutEffect(() => {\n    const element = canvasRef.current;\n    if (!element) return;\n    const measure = () => setWidth(element.clientWidth);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(element);\n    return () => observer.disconnect();\n  }, [root != null]);\n\n  React.useEffect(() => {\n    const timer = window.setTimeout(() => setRevealed(true), 1400);\n    return () => window.clearTimeout(timer);\n  }, []);\n\n  // Flame graphs grow upward, so a scrolling one starts at the root.\n  useIsomorphicLayoutEffect(() => {\n    const scroller = scrollRef.current;\n    if (scroller && orientation === \"flame\")\n      scroller.scrollTop = scroller.scrollHeight;\n  }, [orientation, height]);\n\n  /* ---------------------------------------------------------- zoom tween */\n\n  useIsomorphicLayoutEffect(() => {\n    const element = canvasRef.current;\n    if (!element) return;\n    const to = target;\n    const from = shown.current;\n    const apply = (view: View) => {\n      element.style.setProperty(\"--flame-v0\", String(view.v0));\n      element.style.setProperty(\"--flame-vs\", String(view.vs));\n      shown.current = view;\n    };\n    const same =\n      Math.abs(from.v0 - to.v0) < 1e-12 && Math.abs(from.vs - to.vs) < 1e-12;\n    if (same || reduced) {\n      apply(to);\n      setTween(null);\n      return;\n    }\n    setTween({ from, to });\n    const startedAt = performance.now();\n    let frame = requestAnimationFrame(function step(now) {\n      const t = Math.min(1, (now - startedAt) / DURATION);\n      apply(interpolate(from, to, easeOut(t)));\n      if (t < 1) frame = requestAnimationFrame(step);\n      else setTween(null);\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [target.v0, target.vs, reduced]);\n\n  /* ---------------------------------------------------------- colors */\n\n  const paletteKey = (colors ?? []).join(\"|\");\n  const colorMap = React.useMemo(() => {\n    const map = new Map<string, string>();\n    if (!root) return map;\n    const custom = paletteKey ? paletteKey.split(\"|\") : null;\n    for (const frame of byId.values()) {\n      let fill: string;\n      if (typeof colorBy === \"function\") {\n        fill = colorBy(frame.node, {\n          depth: frame.depth,\n          group: frame.group,\n          total: frame.total,\n          self: frame.self,\n          share: frame.total / root.total,\n          heat: frame.heat,\n        });\n      } else if (colorBy === \"self\") {\n        fill = rampAt(custom ?? defaultHeat, frame.heat);\n      } else {\n        const palette = custom ?? defaultPalette;\n        const base = palette[hash(frame.group) % palette.length];\n        // Group picks the tone; the function picks one of three tints within it.\n        const tint = hash(frame.name) % 3;\n        fill = `color-mix(in oklab, ${base} var(--flame-tint-${tint}), var(--color-card))`;\n      }\n      map.set(frame.id, fill);\n    }\n    return map;\n    // paletteKey stands in for `colors`, so inline arrays do not recolor.\n  }, [byId, root, colorBy, paletteKey]);\n\n  /* ---------------------------------------------------------- search */\n\n  const matches = React.useMemo(() => {\n    if (!root || !query) return null;\n    const ids = new Set<string>();\n    let covered = 0;\n    const walk = (frame: Frame, inside: boolean) => {\n      const hit = frame.lower.includes(query);\n      if (hit) {\n        ids.add(frame.id);\n        if (!inside) covered += frame.total;\n      }\n      for (const child of frame.children) walk(child, inside || hit);\n    };\n    walk(root, false);\n    return { ids, count: ids.size, share: covered / root.total };\n  }, [root, query]);\n\n  /* ---------------------------------------------------------- frames */\n\n  const measured = width || FALLBACK_WIDTH;\n  const rendered = React.useMemo(() => {\n    if (!root) return [] as Frame[];\n    const now = visibleFrames(root, target, measured, minFrameWidth);\n    if (!tween) return now;\n    const seen = new Set(now);\n    for (const frame of visibleFrames(\n      root,\n      tween.from,\n      measured,\n      minFrameWidth,\n    ))\n      if (!seen.has(frame)) now.push(frame);\n    return now;\n  }, [root, target.v0, target.vs, measured, minFrameWidth, tween]);\n\n  const renderedIds = React.useMemo(\n    () => new Set(rendered.map((frame) => frame.id)),\n    [rendered],\n  );\n  const stopId =\n    tabStopId && renderedIds.has(tabStopId)\n      ? tabStopId\n      : (focus?.id ?? null);\n\n  const infoFor = (frame: Frame): FlameFrameInfo => {\n    const fill = colorMap.get(frame.id) ?? defaultPalette[0];\n    const rootTotal = root?.total || 1;\n    return {\n      id: frame.id,\n      node: frame.node,\n      depth: frame.depth,\n      group: frame.group,\n      total: frame.total,\n      self: frame.self,\n      share: frame.total / rootTotal,\n      selfShare: frame.self / rootTotal,\n      parentShare: frame.parent ? frame.total / frame.parent.total : 1,\n      parent: frame.parent?.node ?? null,\n      path: lineage(frame).map((entry) => entry.node),\n      fill,\n      ink: inkFor(fill),\n      match: matches?.ids.has(frame.id) ?? false,\n    };\n  };\n\n  const describe = (frame: Frame) =>\n    `${frame.name}, ${format(frame.total)}, ${percent(frame.total / (root?.total || 1))} of total` +\n    (frame.children.length ? `, self ${format(frame.self)}` : \"\");\n\n  /* ---------------------------------------------------------- top functions */\n\n  const topCount =\n    showTopFunctions === true\n      ? 8\n      : typeof showTopFunctions === \"number\"\n        ? Math.max(1, Math.floor(showTopFunctions))\n        : 0;\n  const topFunctions = React.useMemo(() => {\n    if (!focus || !topCount) return [];\n    const map = new Map<\n      string,\n      { name: string; self: number; calls: number; sample: Frame }\n    >();\n    const stack = [focus];\n    while (stack.length) {\n      const frame = stack.pop()!;\n      if (frame.self > 0) {\n        const entry = map.get(frame.name);\n        if (entry) {\n          entry.self += frame.self;\n          entry.calls += 1;\n          if (frame.self > entry.sample.self) entry.sample = frame;\n        } else\n          map.set(frame.name, {\n            name: frame.name,\n            self: frame.self,\n            calls: 1,\n            sample: frame,\n          });\n      }\n      stack.push(...frame.children);\n    }\n    return [...map.values()]\n      .sort((a, b) => b.self - a.self)\n      .slice(0, topCount);\n  }, [focus, topCount]);\n\n  /* ---------------------------------------------------------- interaction */\n\n  const activeId = tween ? null : (hoveredId ?? focusedId);\n  const activeFrame = activeId ? (byId.get(activeId) ?? null) : null;\n\n  const placeTip = React.useCallback(() => {\n    const tip = tipRef.current;\n    const host = rootRef.current;\n    if (!tip || !host) return;\n    const box = host.getBoundingClientRect();\n    const w = tip.offsetWidth;\n    const h = tip.offsetHeight;\n    let x: number;\n    let y: number;\n    const p = pointer.current;\n    if (p) {\n      x = p.x - box.left + 14;\n      y = p.y - box.top + 18;\n      if (x + w > box.width - 8) x = p.x - box.left - w - 14;\n      if (y + h > box.height + 24) y = p.y - box.top - h - 14;\n    } else {\n      const id = tip.dataset.for;\n      const element = id\n        ? canvasRef.current?.querySelector<HTMLElement>(\n            `[data-slot=\"flame-graph-frame\"][data-id=\"${CSS.escape(id)}\"]`,\n          )\n        : null;\n      if (!element) return;\n      const r = element.getBoundingClientRect();\n      x = Math.min(r.left - box.left, box.width - w - 8);\n      y = r.bottom - box.top + 6;\n      if (y + h > box.height + 24) y = r.top - box.top - h - 6;\n    }\n    x = Math.max(8, x);\n    tip.style.transform = `translate3d(${Math.round(x)}px, ${Math.round(y)}px, 0)`;\n  }, []);\n\n  useIsomorphicLayoutEffect(() => {\n    if (activeFrame) placeTip();\n  }, [activeFrame, placeTip]);\n\n  const frameFromEvent = (event: React.SyntheticEvent) => {\n    const element = (event.target as HTMLElement).closest<HTMLElement>(\n      '[data-slot=\"flame-graph-frame\"]',\n    );\n    return element ? (byId.get(element.dataset.id ?? \"\") ?? null) : null;\n  };\n\n  const focusFrame = (frame: Frame | null | undefined) => {\n    if (!frame) return;\n    setTabStopId(frame.id);\n    canvasRef.current\n      ?.querySelector<HTMLElement>(\n        `[data-slot=\"flame-graph-frame\"][data-id=\"${CSS.escape(frame.id)}\"]`,\n      )\n      ?.focus({ preventScroll: false });\n  };\n\n  const activate = (frame: Frame, fromKeyboard: boolean) => {\n    onSelect?.(frame.node, infoFor(frame));\n    // Activating the zoomed frame steps out; anything else zooms to it.\n    const next = frame === focus ? (frame.parent ?? null) : frame;\n    commitZoom(next);\n    if (fromKeyboard) setTabStopId(frame.id);\n  };\n\n  const zoomOut = () => {\n    if (focus?.parent) commitZoom(focus.parent);\n  };\n\n  const onCanvasKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const frame = frameFromEvent(event);\n    if (!frame || !root) return;\n    const visible = (candidate: Frame | null | undefined) =>\n      candidate && renderedIds.has(candidate.id) ? candidate : null;\n    const firstChild = () =>\n      frame.children.find((child) => renderedIds.has(child.id)) ?? null;\n    const along = (direction: 1 | -1) => {\n      const row = rendered\n        .filter((candidate) => candidate.depth === frame.depth)\n        .sort((a, b) => a.start - b.start);\n      return row[row.indexOf(frame) + direction] ?? null;\n    };\n    const up = orientation === \"icicle\" ? frame.parent : firstChild();\n    const down = orientation === \"icicle\" ? firstChild() : frame.parent;\n    switch (event.key) {\n      case \"ArrowUp\":\n        focusFrame(visible(up));\n        break;\n      case \"ArrowDown\":\n        focusFrame(visible(down));\n        break;\n      case \"ArrowLeft\":\n        focusFrame(along(-1));\n        break;\n      case \"ArrowRight\":\n        focusFrame(along(1));\n        break;\n      case \"Home\":\n        focusFrame(focus);\n        break;\n      case \"Enter\":\n      case \" \":\n        activate(frame, true);\n        break;\n      case \"Escape\":\n        if (zoomed) zoomOut();\n        else if (query) setSearch(\"\");\n        else return;\n        break;\n      default:\n        return;\n    }\n    event.preventDefault();\n  };\n\n  // Keep keyboard focus on a frame that is still drawn after a zoom, and move it\n  // into the graph when the reset button that had it becomes disabled.\n  React.useEffect(() => {\n    const canvas = canvasRef.current;\n    if (!canvas || !focus) return;\n    if (pendingFocus.current) {\n      pendingFocus.current = false;\n      focusFrame(focus);\n      return;\n    }\n    const active = document.activeElement as HTMLElement | null;\n    if (!active || !canvas.contains(active)) return;\n    if (\n      active.dataset.slot === \"flame-graph-frame\" &&\n      renderedIds.has(active.dataset.id ?? \"\")\n    )\n      return;\n    focusFrame(focus);\n    // Only after a zoom settles.\n  }, [focus, tween == null]);\n\n  /* ---------------------------------------------------------- render */\n\n  const rowTop = (depth: number) =>\n    (orientation === \"icicle\" ? depth : maxDepth - depth) * rowHeight;\n  const canvasHeight = (maxDepth + 1) * rowHeight;\n  const focusChain = focus ? new Set(lineage(focus)) : new Set<Frame>();\n  const rootTotal = root?.total ?? 0;\n  const hasHeader = title != null || description != null || actions != null;\n  const graphLabel = typeof title === \"string\" ? title : \"Flame graph\";\n  const activeInfo = activeFrame ? infoFor(activeFrame) : null;\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"flame-graph\"\n      data-orientation={orientation}\n      data-zoomed={zoomed || undefined}\n      data-searching={query ? true : undefined}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        if (event.key !== \"Escape\" || event.defaultPrevented || !zoomed) return;\n        if ((event.target as HTMLElement).tagName === \"INPUT\") return;\n        event.preventDefault();\n        zoomOut();\n      }}\n      className={cn(\n        \"@container/flame relative flex min-w-0 flex-col rounded-2xl border border-border/70 bg-card text-card-foreground shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\",\n        \"[--flame-tint-0:70%] [--flame-tint-1:54%] [--flame-tint-2:40%] dark:[--flame-tint-0:92%] dark:[--flame-tint-1:78%] dark:[--flame-tint-2:64%]\",\n        className,\n      )}\n      {...props}\n    >\n      <style href=\"overtrue-flame-graph\" precedence=\"default\">\n        {`[data-slot=flame-graph-frame]{left:max(0%,calc((var(--x0) - var(--flame-v0)) / var(--flame-vs) * 100%));width:max(0px,calc(min(100%,(var(--x1) - var(--flame-v0)) / var(--flame-vs) * 100%) - max(0%,(var(--x0) - var(--flame-v0)) / var(--flame-vs) * 100%) - 1px))}@keyframes flame-frame-in{from{opacity:0;clip-path:inset(0 100% 0 0)}to{clip-path:inset(0 0 0 0)}}`}\n      </style>\n\n      {hasHeader || rootTotal > 0 ? (\n        <div className=\"flex items-start justify-between gap-x-6 gap-y-3 px-5 pt-5\">\n          <div className=\"min-w-0 space-y-1\">\n            {title != null ? (\n              <h3 className=\"truncate text-sm leading-5 font-semibold tracking-tight\">\n                {title}\n              </h3>\n            ) : null}\n            {description != null ? (\n              <p\n                id={`${id}-description`}\n                className=\"text-[13px] leading-5 text-muted-foreground\"\n              >\n                {description}\n              </p>\n            ) : null}\n          </div>\n          <div className=\"flex shrink-0 items-start gap-3\">\n            {actions != null ? (\n              <div className=\"flex items-center gap-1\">{actions}</div>\n            ) : null}\n            {rootTotal > 0 ? (\n              <p\n                data-slot=\"flame-graph-total\"\n                className=\"flex flex-col items-end gap-0.5\"\n              >\n                <span className=\"text-xs leading-4 text-muted-foreground\">\n                  Total\n                </span>\n                <Figure\n                  text={format(rootTotal)}\n                  className=\"text-xl leading-6 font-semibold tracking-[-0.02em] tabular-nums\"\n                />\n              </p>\n            ) : null}\n          </div>\n        </div>\n      ) : null}\n\n      <div\n        data-slot=\"flame-graph-toolbar\"\n        className=\"flex min-h-7 flex-wrap items-center gap-x-3 gap-y-2 px-5 pt-4\"\n      >\n        {showSearch ? (\n          <div className=\"relative min-w-0 flex-1 @lg/flame:w-60 @lg/flame:flex-none\">\n            <IconSearch\n              aria-hidden=\"true\"\n              size={15}\n              className=\"pointer-events-none absolute top-1/2 left-2.5 -translate-y-1/2 text-muted-foreground\"\n            />\n            <input\n              type=\"search\"\n              data-slot=\"flame-graph-search\"\n              value={search}\n              onChange={(event) => setSearch(event.target.value)}\n              onKeyDown={(event) => {\n                if (event.key === \"Escape\" && search) {\n                  event.preventDefault();\n                  setSearch(\"\");\n                }\n              }}\n              placeholder={searchPlaceholder}\n              aria-label=\"Search frames\"\n              aria-describedby={query ? `${id}-matches` : undefined}\n              spellCheck={false}\n              autoComplete=\"off\"\n              className=\"h-8 w-full rounded-lg border border-input/80 bg-transparent pr-8 pl-8 font-mono text-xs shadow-[0_1px_1px_rgb(0_0_0/0.03)] outline-none transition-[border-color,box-shadow] placeholder:font-sans placeholder:text-[13px] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 motion-reduce:transition-none [&::-webkit-search-cancel-button]:hidden\"\n            />\n            {search ? (\n              <button\n                type=\"button\"\n                aria-label=\"Clear search\"\n                onClick={() => setSearch(\"\")}\n                className=\"absolute top-1/2 right-1 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50\"\n              >\n                <IconX aria-hidden=\"true\" size={13} />\n              </button>\n            ) : null}\n          </div>\n        ) : null}\n\n        {(query && matches) || zoomed ? (\n          <div className=\"order-2 flex min-w-0 basis-full flex-wrap items-center justify-between gap-x-4 gap-y-1 @lg/flame:order-1 @lg/flame:basis-0 @lg/flame:flex-1\">\n            {query && matches ? (\n              <p\n                id={`${id}-matches`}\n                data-slot=\"flame-graph-matches\"\n                className=\"text-xs text-muted-foreground tabular-nums\"\n              >\n                {matches.count > 0 ? (\n                  <>\n                    <span className=\"font-medium text-foreground\">\n                      {matches.count}\n                    </span>{\" \"}\n                    {matches.count === 1 ? \"match\" : \"matches\"}\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"px-1.5 text-muted-foreground/50\"\n                    >\n                      ·\n                    </span>\n                    <span className=\"font-medium text-foreground\">\n                      {percent(matches.share)}\n                    </span>{\" \"}\n                    of total\n                  </>\n                ) : (\n                  \"No matches\"\n                )}\n              </p>\n            ) : (\n              <span />\n            )}\n            {zoomed && focus ? (\n              <p\n                data-slot=\"flame-graph-zoom\"\n                className=\"flex min-w-0 items-baseline gap-1.5 text-xs text-muted-foreground tabular-nums motion-safe:animate-[flame-fade_200ms_ease-out]\"\n              >\n                <span className=\"max-w-[12rem] truncate font-mono text-foreground\">\n                  {focus.name}\n                </span>\n                <span className=\"shrink-0\">\n                  {format(focus.total)} · {percent(focus.total / rootTotal)}\n                </span>\n              </p>\n            ) : null}\n          </div>\n        ) : null}\n\n        <button\n          type=\"button\"\n          data-slot=\"flame-graph-reset\"\n          className={cn(toolButton, \"order-1 ml-auto @lg/flame:order-2\")}\n          disabled={!zoomed}\n          onClick={(event) => {\n            if (event.detail === 0) pendingFocus.current = true;\n            commitZoom(null);\n          }}\n          title=\"Reset zoom\"\n        >\n          <IconZoomReset aria-hidden=\"true\" size={16} />\n          <span className=\"sr-only\">Reset zoom</span>\n        </button>\n      </div>\n\n      <div className=\"px-5 pt-3 pb-5\">\n        {root ? (\n          <div\n            ref={scrollRef}\n            className={cn(\n              \"relative\",\n              height != null && \"overflow-y-auto overscroll-contain\",\n            )}\n            style={height != null ? { maxHeight: height } : undefined}\n          >\n            <div\n              ref={canvasRef}\n              role=\"group\"\n              aria-roledescription=\"flame graph\"\n              aria-label={`${graphLabel}: ${model.count} frames. Arrow keys move between frames, Enter zooms in, Escape zooms out.`}\n              aria-describedby={\n                description != null ? `${id}-description` : undefined\n              }\n              data-slot=\"flame-graph-canvas\"\n              data-tweening={tween ? true : undefined}\n              className=\"relative w-full overflow-hidden\"\n              style={\n                {\n                  height: canvasHeight,\n                  \"--flame-v0\": initialView.v0,\n                  \"--flame-vs\": initialView.vs,\n                } as React.CSSProperties\n              }\n              onPointerMove={(event) => {\n                if (event.pointerType === \"touch\") return;\n                pointer.current = { x: event.clientX, y: event.clientY };\n                const frame = frameFromEvent(event);\n                const next = frame?.id ?? null;\n                if (next !== hoveredId) setHoveredId(next);\n                else placeTip();\n              }}\n              onPointerLeave={() => {\n                pointer.current = null;\n                setHoveredId(null);\n              }}\n              onClick={(event) => {\n                const frame = frameFromEvent(event);\n                if (frame) activate(frame, false);\n              }}\n              onKeyDown={onCanvasKeyDown}\n              onFocus={(event) => {\n                const frame = frameFromEvent(event);\n                if (!frame) return;\n                setTabStopId(frame.id);\n                const visible = (event.target as HTMLElement).matches(\n                  \":focus-visible\",\n                );\n                setFocusedId(visible ? frame.id : null);\n              }}\n              onBlur={(event) => {\n                if (!event.currentTarget.contains(event.relatedTarget as Node))\n                  setFocusedId(null);\n              }}\n            >\n              {rendered.map((frame) => {\n                const fill = colorMap.get(frame.id) ?? defaultPalette[0];\n                const ancestor = zoomed && focusChain.has(frame) && frame !== focus;\n                const match = matches?.ids.has(frame.id) ?? false;\n                const labelWide =\n                  labelFits(frame, pixelWidth(frame, target, measured)) ||\n                  (tween != null &&\n                    labelFits(frame, pixelWidth(frame, tween.from, measured)));\n                return (\n                  <FlameFrame\n                    key={frame.id}\n                    frame={frame}\n                    top={rowTop(frame.depth)}\n                    height={rowHeight - 1}\n                    fill={fill}\n                    label={labelWide}\n                    query={match ? query : \"\"}\n                    match={match}\n                    dimmed={matches != null && !match}\n                    ancestor={ancestor}\n                    zoomed={frame === focus && zoomed}\n                    active={frame.id === activeId}\n                    tabStop={frame.id === stopId}\n                    ariaLabel={describe(frame)}\n                    reveal={\n                      revealed ? null : Math.min(frame.depth, 16) * 34\n                    }\n                  />\n                );\n              })}\n            </div>\n          </div>\n        ) : (\n          <p className=\"grid h-28 place-items-center rounded-xl bg-muted/40 text-xs text-muted-foreground ring-1 ring-border/60 ring-inset\">\n            No samples to show.\n          </p>\n        )}\n      </div>\n\n      {topCount > 0 && topFunctions.length > 0 && focus ? (\n        <div\n          data-slot=\"flame-graph-top-functions\"\n          className=\"border-t border-border/60 px-5 pt-4 pb-5\"\n        >\n          <div className=\"mb-2.5 flex items-baseline justify-between gap-3\">\n            <h4 className=\"text-xs font-medium text-foreground\">\n              Top functions by self time\n            </h4>\n            <span className=\"truncate text-xs text-muted-foreground\">\n              {zoomed ? (\n                <>\n                  in <span className=\"font-mono\">{focus.name}</span>\n                </>\n              ) : (\n                \"Select one to search\"\n              )}\n            </span>\n          </div>\n          <ol className=\"grid gap-x-6 gap-y-0.5 @4xl/flame:grid-cols-2\">\n            {topFunctions.map((entry, index) => {\n              const share = entry.self / focus.total;\n              const lead = topFunctions[0].self || 1;\n              const pressed = search === entry.name;\n              const fill = colorMap.get(entry.sample.id) ?? defaultPalette[0];\n              return (\n                <li key={entry.name} className=\"min-w-0\">\n                  <button\n                    type=\"button\"\n                    data-slot=\"flame-graph-top-function\"\n                    aria-pressed={pressed}\n                    onClick={() => setSearch(pressed ? \"\" : entry.name)}\n                    className=\"group/top grid h-8 w-full grid-cols-[1rem_minmax(0,1fr)_4rem_3rem] items-center gap-2.5 rounded-lg px-2 text-left text-xs @md/flame:grid-cols-[1rem_minmax(0,1fr)_6rem_4.5rem_3.25rem] @md/flame:gap-3 @2xl/flame:grid-cols-[1rem_minmax(0,1fr)_12rem_4.5rem_3.25rem] outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring/50 aria-pressed:bg-muted motion-reduce:transition-none\"\n                  >\n                    <span className=\"text-right text-[11px] text-muted-foreground tabular-nums\">\n                      {index + 1}\n                    </span>\n                    <span className=\"flex min-w-0 items-center gap-2\">\n                      <span\n                        aria-hidden=\"true\"\n                        className=\"size-2 shrink-0 rounded-[2px]\"\n                        style={{ backgroundColor: fill }}\n                      />\n                      <span className=\"truncate font-mono text-foreground\">\n                        {entry.name}\n                      </span>\n                      {entry.calls > 1 ? (\n                        <span className=\"shrink-0 text-[11px] text-muted-foreground tabular-nums\">\n                          ×{entry.calls}\n                        </span>\n                      ) : null}\n                    </span>\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"relative hidden h-1.5 overflow-hidden rounded-full bg-muted @md/flame:block\"\n                    >\n                      <span\n                        className=\"absolute inset-y-0 left-0 rounded-full motion-safe:animate-[flame-bar-in_700ms_cubic-bezier(0.22,1,0.36,1)_backwards]\"\n                        style={{\n                          width: `${Math.max(4, (entry.self / lead) * 100)}%`,\n                          backgroundImage: `linear-gradient(to right, color-mix(in oklab, ${fill} 72%, transparent), ${fill})`,\n                          animationDelay: `${index * 30}ms`,\n                        }}\n                      />\n                    </span>\n                    <span className=\"text-right font-medium text-foreground tabular-nums\">\n                      {format(entry.self)}\n                    </span>\n                    <span className=\"text-right text-muted-foreground tabular-nums\">\n                      {percent(share)}\n                    </span>\n                  </button>\n                </li>\n              );\n            })}\n          </ol>\n        </div>\n      ) : null}\n\n      {activeFrame && activeInfo ? (\n        <div\n          ref={tipRef}\n          aria-hidden=\"true\"\n          data-slot=\"flame-graph-tooltip\"\n          data-for={activeFrame.id}\n          className=\"pointer-events-none absolute top-0 left-0 z-30 overflow-hidden rounded-xl border border-border/70 bg-popover/90 text-popover-foreground shadow-xl backdrop-blur-md\"\n        >\n          {renderTooltip ? (\n            renderTooltip(activeInfo)\n          ) : (\n            <DefaultTooltip info={activeInfo} format={format} />\n          )}\n        </div>\n      ) : null}\n\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {zoomed && focus\n          ? `Zoomed to ${focus.name}, ${format(focus.total)}, ${percent(focus.total / rootTotal)} of total.`\n          : \"\"}\n        {query && matches\n          ? ` ${matches.count} ${matches.count === 1 ? \"match\" : \"matches\"}, ${percent(matches.share)} of total.`\n          : \"\"}\n      </p>\n      <style href=\"overtrue-flame-graph-motion\" precedence=\"default\">\n        {`@keyframes flame-fade{from{opacity:0}}@keyframes flame-bar-in{from{transform:scaleX(0);transform-origin:left}}`}\n      </style>\n    </div>\n  );\n}\n\nexport { FlameGraph };\n"
    },
    {
      "path": "src/registry/overtrue/latency-histogram.tsx",
      "type": "registry:component",
      "target": "components/overtrue/latency-histogram.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconX as X } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type LatencyScale = \"linear\" | \"log\";\n\nexport type LatencyRange = [min: number, max: number];\n\nexport interface LatencyBucket {\n  /** Inclusive lower edge. */\n  start: number;\n  /** Exclusive upper edge. */\n  end: number;\n  count: number;\n}\n\n/** One bar as drawn, passed to `renderTooltip`. */\nexport interface LatencyHistogramBucket extends LatencyBucket {\n  index: number;\n  /** Share of all requests in this bucket, 0–1. */\n  share: number;\n  /** Share of requests at or below this bucket's upper edge, 0–1. */\n  cumulative: number;\n  /** Raw comparison count in the same range, when `compare` is set. */\n  compare?: number;\n  /** Comparison share of its own total, 0–1. */\n  compareShare?: number;\n  /** The catch-all bar for values past the linear domain. */\n  overflow: boolean;\n  /** Whether the bucket lies past `threshold`. */\n  overThreshold: boolean;\n}\n\nexport interface LatencyHistogramColors {\n  bar: string;\n  compare: string;\n  threshold: string;\n  marker: string;\n  selection: string;\n}\n\nexport interface LatencyHistogramProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\" | \"color\"\n> {\n  /** Raw samples. Bucketed for you, with exact percentiles. */\n  values?: number[];\n  /** Pre-bucketed counts, used when `values` is not given. Percentiles are interpolated. */\n  buckets?: LatencyBucket[];\n  /** A comparison distribution, e.g. yesterday. Scaled to the main total so shapes compare. */\n  compare?: number[] | LatencyBucket[];\n  /** Name of the comparison in the legend and tooltip. */\n  compareLabel?: string;\n  /** Name of the main series in the legend. */\n  seriesLabel?: string;\n  /** Draw the comparison as a stepped line or as outlined bars. */\n  compareStyle?: \"step\" | \"outline\";\n  /** Percentiles to mark, as numbers such as 50 or 99.9. */\n  percentiles?: number[];\n  /** Latency objective. The slow tail past it is shaded and measured. */\n  threshold?: number;\n  thresholdLabel?: string;\n  /** X scale. Pass with `onScaleChange` to control the built-in toggle. */\n  scale?: LatencyScale;\n  defaultScale?: LatencyScale;\n  onScaleChange?: (scale: LatencyScale) => void;\n  /** Show the linear/log toggle. Defaults to true. */\n  showScaleToggle?: boolean;\n  /** Brushed range. Pass `null` for none; leave undefined to let the component manage it. */\n  range?: LatencyRange | null;\n  defaultRange?: LatencyRange | null;\n  onRangeChange?: (range: LatencyRange | null) => void;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right, before the scale toggle. */\n  actions?: React.ReactNode;\n  /** Unit of the values. Defaults to \"ms\"; ms readouts switch to seconds from 1,000. */\n  unit?: string;\n  /** Formats latencies in readouts, markers, and ticks. */\n  valueFormatter?: (value: number) => string;\n  /** Target number of bars. Defaults to 40. */\n  bucketCount?: number;\n  /** Fix the latency domain. Linear charts otherwise end near p99.5 and gather the rest in an overflow bar. */\n  domain?: LatencyRange;\n  /** Plot height in pixels. Defaults to a third of the plot width, between 140 and 220. */\n  height?: number;\n  /** Override any series color with a CSS color. */\n  colors?: Partial<LatencyHistogramColors>;\n  /** Replaces the hover tooltip content. */\n  renderTooltip?: (bucket: LatencyHistogramBucket) => React.ReactNode;\n  /** Show the percentile summary above the plot. Defaults to true. */\n  showSummary?: boolean;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Formatting                                                                */\n/* ------------------------------------------------------------------------ */\n\nconst tidy = (value: number) => +value.toPrecision(12);\nconst compact = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\nconst whole = new Intl.NumberFormat(\"en-US\");\n\nfunction makeFormatter(unit: string) {\n  const tight = unit.length <= 2;\n  const join = (text: string, u: string) =>\n    u ? `${text}${tight ? \"\" : \" \"}${u}` : text;\n  return (value: number) => {\n    if (!Number.isFinite(value)) return \"—\";\n    const a = Math.abs(value);\n    if (unit === \"ms\" && a >= 1000)\n      return `${tidy(+(value / 1000).toFixed(a >= 10_000 ? 1 : 2))}s`;\n    const digits = a >= 100 || a === 0 ? 0 : a >= 10 ? 1 : a >= 1 ? 2 : 3;\n    return join(String(tidy(+value.toFixed(digits))), unit);\n  };\n}\n\nfunction makeTickFormatter(unit: string) {\n  const tight = unit.length <= 2;\n  return (value: number) => {\n    if (value === 0) return \"0\";\n    if (unit === \"ms\" && Math.abs(value) >= 1000)\n      return `${tidy(value / 1000)}s`;\n    return `${tidy(value)}${tight ? \"\" : \" \"}${unit}`;\n  };\n}\n\nfunction percentLabel(share: number) {\n  const pct = share * 100;\n  if (pct === 0) return \"0%\";\n  if (pct < 0.1) return \"<0.1%\";\n  if (pct > 99.9 && pct < 100) return \">99.9%\";\n  return `${pct >= 10 ? pct.toFixed(1) : pct.toFixed(2)}%`;\n}\n\nfunction niceStep(raw: number) {\n  if (!(raw > 0)) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const r = raw / magnitude;\n  return (\n    (r <= 1 ? 1 : r <= 2 ? 2 : r <= 2.5 ? 2.5 : r <= 5 ? 5 : 10) * magnitude\n  );\n}\n\n/** Round down or up to the nearest 1, 2, or 5 times a power of ten. */\nfunction nice125(value: number, up: boolean) {\n  const magnitude = 10 ** Math.floor(Math.log10(value));\n  const r = value / magnitude;\n  const steps = [1, 2, 5, 10];\n  if (up) return (steps.find((s) => s >= r - 1e-9) ?? 10) * magnitude;\n  return ([...steps].reverse().find((s) => s <= r + 1e-9) ?? 1) * magnitude;\n}\n\nfunction lowerBound(sorted: Float64Array, value: number) {\n  let lo = 0;\n  let hi = sorted.length;\n  while (lo < hi) {\n    const mid = (lo + hi) >> 1;\n    if (sorted[mid] < value) lo = mid + 1;\n    else hi = mid;\n  }\n  return lo;\n}\n\nfunction upperBound(sorted: Float64Array, value: number) {\n  let lo = 0;\n  let hi = sorted.length;\n  while (lo < hi) {\n    const mid = (lo + hi) >> 1;\n    if (sorted[mid] <= value) lo = mid + 1;\n    else hi = mid;\n  }\n  return lo;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Model                                                                     */\n/* ------------------------------------------------------------------------ */\n\ninterface Bar extends LatencyBucket {\n  overflow: boolean;\n  /** Left and right edges as 0–1 positions. */\n  x0: number;\n  x1: number;\n}\n\ninterface Distribution {\n  sorted: Float64Array | null;\n  buckets: LatencyBucket[] | null;\n  total: number;\n  min: number;\n  max: number;\n  mean: number;\n}\n\nfunction distributionOf(\n  values?: number[],\n  buckets?: LatencyBucket[],\n): Distribution {\n  if (values) {\n    const clean = values.filter((value) => Number.isFinite(value));\n    const sorted = Float64Array.from(clean).sort();\n    let sum = 0;\n    for (const value of sorted) sum += value;\n    return {\n      sorted,\n      buckets: null,\n      total: sorted.length,\n      min: sorted.length ? sorted[0] : 0,\n      max: sorted.length ? sorted[sorted.length - 1] : 0,\n      mean: sorted.length ? sum / sorted.length : 0,\n    };\n  }\n  const list = (buckets ?? [])\n    .filter(\n      (b) =>\n        Number.isFinite(b.start) && Number.isFinite(b.end) && b.end > b.start,\n    )\n    .sort((a, b) => a.start - b.start);\n  let total = 0;\n  let sum = 0;\n  for (const b of list) {\n    total += Math.max(0, b.count);\n    sum += (Math.max(0, b.count) * (b.start + b.end)) / 2;\n  }\n  return {\n    sorted: null,\n    buckets: list,\n    total,\n    min: list.length ? list[0].start : 0,\n    max: list.length ? list[list.length - 1].end : 0,\n    mean: total ? sum / total : 0,\n  };\n}\n\n/** Nearest-rank percentile from samples; interpolated inside buckets otherwise. */\nfunction quantile(d: Distribution, p: number) {\n  if (!d.total) return 0;\n  if (d.sorted)\n    return d.sorted[\n      Math.min(d.total - 1, Math.max(0, Math.ceil(p * d.total) - 1))\n    ];\n  const target = p * d.total;\n  let cumulative = 0;\n  for (const b of d.buckets!) {\n    if (cumulative + b.count >= target && b.count > 0)\n      return b.start + ((target - cumulative) / b.count) * (b.end - b.start);\n    cumulative += b.count;\n  }\n  return d.max;\n}\n\n/** Requests with a value in [a, b]. Partial buckets count in proportion. */\nfunction countBetween(d: Distribution, a: number, b: number) {\n  if (d.sorted) return upperBound(d.sorted, b) - lowerBound(d.sorted, a);\n  let count = 0;\n  for (const bucket of d.buckets!) {\n    const overlap = Math.min(b, bucket.end) - Math.max(a, bucket.start);\n    if (overlap > 0)\n      count += (bucket.count * overlap) / (bucket.end - bucket.start);\n  }\n  return count;\n}\n\nfunction countAbove(d: Distribution, value: number) {\n  if (d.sorted) return d.total - upperBound(d.sorted, value);\n  return countBetween(d, value, Infinity);\n}\n\ninterface Layout {\n  bars: Bar[];\n  lo: number;\n  hi: number;\n  /** Largest value covered, including the overflow bar. */\n  top: number;\n  pos: (value: number) => number;\n  inv: (x: number) => number;\n}\n\nfunction layoutOf(\n  d: Distribution,\n  scale: LatencyScale,\n  bucketCount: number,\n  reach: number,\n  domain?: LatencyRange,\n): Layout {\n  const count = Math.max(4, Math.round(bucketCount));\n  // Pre-bucketed data keeps its own edges.\n  if (d.buckets) {\n    const list = d.buckets;\n    const first = list[0]?.start ?? 0;\n    const last = list[list.length - 1]?.end ?? 1;\n    if (scale === \"log\") {\n      const positive =\n        list.find((b) => b.start > 0)?.start ?? list[0]?.end ?? 1;\n      const lo = first > 0 ? first : positive / 2;\n      const span = Math.log(last / lo) || 1;\n      const pos = (v: number) =>\n        Math.min(1, Math.max(0, Math.log(Math.max(v, lo) / lo) / span));\n      const inv = (x: number) => lo * Math.exp(x * span);\n      return {\n        bars: list.map((b) => ({\n          ...b,\n          overflow: false,\n          x0: pos(b.start),\n          x1: pos(b.end),\n        })),\n        lo,\n        hi: last,\n        top: last,\n        pos,\n        inv,\n      };\n    }\n    const span = last - first || 1;\n    const pos = (v: number) => Math.min(1, Math.max(0, (v - first) / span));\n    const inv = (x: number) => first + x * span;\n    return {\n      bars: list.map((b) => ({\n        ...b,\n        overflow: false,\n        x0: pos(b.start),\n        x1: pos(b.end),\n      })),\n      lo: first,\n      hi: last,\n      top: last,\n      pos,\n      inv,\n    };\n  }\n\n  const sorted = d.sorted!;\n  if (scale === \"log\") {\n    const positive = sorted[lowerBound(sorted, Number.MIN_VALUE)] ?? 1;\n    const lo =\n      domain?.[0] && domain[0] > 0\n        ? domain[0]\n        : nice125(Math.max(positive, 1e-9), false);\n    const hi = Math.max(\n      domain?.[1] ?? nice125(Math.max(d.max, lo * 10), true),\n      lo * 1.0001,\n    );\n    const span = Math.log(hi / lo);\n    const step = span / count;\n    const bars: Bar[] = Array.from({ length: count }, (_, i) => ({\n      start: lo * Math.exp(i * step),\n      end: lo * Math.exp((i + 1) * step),\n      count: 0,\n      overflow: false,\n      x0: i / count,\n      x1: (i + 1) / count,\n    }));\n    for (const v of sorted) {\n      const i = v <= lo ? 0 : Math.floor(Math.log(v / lo) / step);\n      bars[Math.min(count - 1, Math.max(0, i))].count += 1;\n    }\n    const pos = (v: number) =>\n      Math.min(1, Math.max(0, Math.log(Math.max(v, lo) / lo) / span));\n    return { bars, lo, hi, top: hi, pos, inv: (x) => lo * Math.exp(x * span) };\n  }\n\n  const lo = domain?.[0] ?? (d.min >= 0 ? 0 : -niceStep(-d.min));\n  const wanted = domain?.[1] ?? Math.max(reach, lo + 1e-9);\n  const step = niceStep((wanted - lo) / count);\n  const n = Math.max(1, Math.ceil((wanted - lo) / step - 1e-9));\n  const hi = lo + n * step;\n  const overflowCount = d.total - upperBound(sorted, hi);\n  const units = overflowCount > 0 ? n + 1.7 : n;\n  const bars: Bar[] = Array.from({ length: n }, (_, i) => ({\n    start: tidy(lo + i * step),\n    end: tidy(lo + (i + 1) * step),\n    count: 0,\n    overflow: false,\n    x0: i / units,\n    x1: (i + 1) / units,\n  }));\n  for (\n    let k = lowerBound(sorted, lo), end = upperBound(sorted, hi);\n    k < end;\n    k++\n  )\n    bars[Math.min(n - 1, Math.floor((sorted[k] - lo) / step))].count += 1;\n  // Values below a fixed domain fold into the first bar.\n  bars[0].count += lowerBound(sorted, lo);\n  const top = Math.max(hi, d.max);\n  if (overflowCount > 0)\n    bars.push({\n      start: hi,\n      end: top,\n      count: overflowCount,\n      overflow: true,\n      x0: (n + 0.7) / units,\n      x1: 1,\n    });\n  const mainEnd = n / units;\n  const overflowStart = (n + 0.7) / units;\n  const pos = (v: number) => {\n    if (v <= hi) return Math.max(0, ((v - lo) / (hi - lo)) * mainEnd);\n    if (overflowCount <= 0 || top <= hi) return mainEnd;\n    return Math.min(\n      1,\n      overflowStart + ((v - hi) / (top - hi)) * (1 - overflowStart),\n    );\n  };\n  const inv = (x: number) => {\n    if (x <= mainEnd) return lo + (x / mainEnd) * (hi - lo);\n    if (x < overflowStart || overflowCount <= 0) return hi;\n    return hi + ((x - overflowStart) / (1 - overflowStart)) * (top - hi);\n  };\n  return { bars, lo, hi, top, pos, inv };\n}\n\n/** Bin a comparison into the main bars' edges. */\nfunction binCompare(compare: number[] | LatencyBucket[], bars: Bar[]) {\n  const counts = new Array<number>(bars.length).fill(0);\n  if (!bars.length) return { counts, total: 0 };\n  const find = (v: number) => {\n    let lo = 0;\n    let hi = bars.length - 1;\n    while (lo < hi) {\n      const mid = (lo + hi + 1) >> 1;\n      if (bars[mid].start <= v) lo = mid;\n      else hi = mid - 1;\n    }\n    return lo;\n  };\n  let total = 0;\n  for (const item of compare as (number | LatencyBucket)[]) {\n    if (typeof item === \"number\") {\n      if (!Number.isFinite(item)) continue;\n      counts[find(item)] += 1;\n      total += 1;\n    } else if (Number.isFinite(item.count)) {\n      counts[find((item.start + item.end) / 2)] += item.count;\n      total += item.count;\n    }\n  }\n  return { counts, total };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Hooks                                                                     */\n/* ------------------------------------------------------------------------ */\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange?: (value: T) => void,\n) {\n  const [inner, setInner] = React.useState(defaultValue);\n  const controlled = value !== undefined;\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [controlled ? value : inner, set] as const;\n}\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50\";\nconst percentileName = (p: number) => `p${tidy(p)}`;\n\n/* ------------------------------------------------------------------------ */\n/* LatencyHistogram                                                          */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A latency distribution: bucketed requests with percentile markers, an SLO tail,\n * an optional comparison, and brushing to measure any range.\n */\nexport function LatencyHistogram({\n  values,\n  buckets,\n  compare,\n  compareLabel = \"Previous\",\n  seriesLabel = \"Current\",\n  compareStyle = \"step\",\n  percentiles = [50, 90, 95, 99],\n  threshold,\n  thresholdLabel = \"SLO\",\n  scale: scaleProp,\n  defaultScale = \"linear\",\n  onScaleChange,\n  showScaleToggle = true,\n  range: rangeProp,\n  defaultRange = null,\n  onRangeChange,\n  title,\n  description,\n  actions,\n  unit = \"ms\",\n  valueFormatter,\n  bucketCount = 40,\n  domain,\n  height,\n  colors: colorsProp,\n  renderTooltip,\n  showSummary = true,\n  className,\n  ...props\n}: LatencyHistogramProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const format = React.useMemo(\n    () => valueFormatter ?? makeFormatter(unit),\n    [valueFormatter, unit],\n  );\n  const formatTick = React.useMemo(\n    () => valueFormatter ?? makeTickFormatter(unit),\n    [valueFormatter, unit],\n  );\n  const colors: LatencyHistogramColors = {\n    bar: \"var(--color-chart-1)\",\n    compare: \"var(--color-muted-foreground)\",\n    threshold: \"var(--color-destructive)\",\n    marker: \"var(--color-foreground)\",\n    selection: \"var(--color-primary)\",\n    ...colorsProp,\n  };\n  const [scale, setScale] = useControllable(\n    scaleProp,\n    defaultScale,\n    onScaleChange,\n  );\n  const [range, setRange] = useControllable<LatencyRange | null>(\n    rangeProp,\n    defaultRange,\n    onRangeChange,\n  );\n  const hasThreshold = threshold != null && Number.isFinite(threshold);\n\n  const dist = React.useMemo(\n    () => distributionOf(values, buckets),\n    [values, buckets],\n  );\n  const sortedPercentiles = React.useMemo(\n    () =>\n      [...new Set(percentiles.filter((p) => p > 0 && p < 100))].sort(\n        (a, b) => a - b,\n      ),\n    [percentiles],\n  );\n  const empty = dist.total === 0;\n  const marks = React.useMemo(\n    () =>\n      dist.total === 0\n        ? []\n        : sortedPercentiles.map((p) => ({ p, value: quantile(dist, p / 100) })),\n    [dist, sortedPercentiles],\n  );\n\n  // Linear charts end just past the slow tail (and the SLO); the rest lands in an overflow bar.\n  const reach = Math.max(\n    quantile(dist, 0.995),\n    (marks[marks.length - 1]?.value ?? 0) * 1.04,\n    hasThreshold ? threshold! * 1.12 : 0,\n  );\n  const layout = React.useMemo(\n    () => layoutOf(dist, scale, bucketCount, reach, domain),\n    [dist, scale, bucketCount, reach, domain],\n  );\n  const { bars, pos, inv } = layout;\n\n  const comparison = React.useMemo(() => {\n    if (!compare?.length) return null;\n    const { counts, total } = binCompare(compare, bars);\n    const percentilesOf = (() => {\n      if (typeof compare[0] === \"number\") {\n        const d = distributionOf(compare as number[]);\n        return sortedPercentiles.map((p) => quantile(d, p / 100));\n      }\n      const d = distributionOf(undefined, compare as LatencyBucket[]);\n      return sortedPercentiles.map((p) => quantile(d, p / 100));\n    })();\n    const factor = total ? dist.total / total : 0;\n    return {\n      counts,\n      total,\n      scaled: counts.map((c) => c * factor),\n      percentiles: percentilesOf,\n    };\n  }, [compare, bars, dist.total, sortedPercentiles]);\n\n  const maxCount = Math.max(\n    1,\n    ...bars.map((b) => b.count),\n    ...(comparison?.scaled ?? [0]),\n  );\n  // The tallest bar fills the plot; gridlines sit at round counts below it.\n  const yMax = maxCount * 1.06;\n  const yStep = niceStep(maxCount / 3.2);\n  const yTicks = Array.from(\n    { length: Math.floor(yMax / yStep + 1e-9) + 1 },\n    (_, i) => tidy(i * yStep),\n  );\n\n  const over = hasThreshold ? countAbove(dist, threshold!) : 0;\n  const overShare = dist.total ? over / dist.total : 0;\n  const thresholdX = hasThreshold ? pos(threshold!) : 1;\n\n  const cumulative = React.useMemo(() => {\n    let running = 0;\n    return bars.map((b) => (running += b.count) / (dist.total || 1));\n  }, [bars, dist.total]);\n\n  const bucketAt = (index: number): LatencyHistogramBucket => {\n    const b = bars[index];\n    return {\n      index,\n      start: b.start,\n      end: b.end,\n      count: b.count,\n      share: dist.total ? b.count / dist.total : 0,\n      cumulative: cumulative[index] ?? 0,\n      compare: comparison ? comparison.counts[index] : undefined,\n      compareShare: comparison?.total\n        ? comparison.counts[index] / comparison.total\n        : undefined,\n      overflow: b.overflow,\n      overThreshold: hasThreshold && b.start >= threshold!,\n    };\n  };\n\n  /* -------------------------------------------------------------- layout */\n\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const [width, setWidth] = React.useState(0);\n  React.useLayoutEffect(() => {\n    const el = plotRef.current;\n    if (!el) return;\n    const measure = () => setWidth(el.clientWidth);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n  const W = width || 560;\n\n  // Percentile chips stack into lanes only when they would collide.\n  // With the summary on show, crowded chips drop their values, which the summary repeats.\n  const chips = React.useMemo(() => {\n    const place = (withValue: boolean) => {\n      const lanes: number[] = [];\n      return marks.map((mark) => {\n        const text = withValue\n          ? `${percentileName(mark.p)} ${format(mark.value)}`\n          : percentileName(mark.p);\n        const w = text.length * 6.1 + 14;\n        const x = pos(mark.value) * W;\n        const left = Math.min(Math.max(0, x - w / 2), Math.max(0, W - w));\n        let lane = lanes.findIndex((right) => right + 4 <= left);\n        if (lane < 0) lane = lanes.push(0) - 1;\n        lanes[lane] = left + w;\n        return { ...mark, x, left, lane, w, withValue };\n      });\n    };\n    const full = place(true);\n    if (!showSummary || full.every((chip) => chip.lane === 0)) return full;\n    return place(false);\n  }, [marks, pos, W, format, showSummary]);\n  const laneCount = Math.max(1, ...chips.map((chip) => chip.lane + 1));\n  const chipTop = laneCount * 20 + 6;\n  // Without a fixed height the plot follows the card width, shorter on narrow cards.\n  const H = Math.max(\n    80,\n    height ?? Math.round(Math.min(220, Math.max(140, W * 0.34))),\n  );\n  const barsHeight = H - chipTop;\n\n  const xTicks = React.useMemo(() => {\n    const ticks: number[] = [];\n    if (empty) return ticks;\n    if (scale === \"log\" || dist.buckets) {\n      if (scale === \"log\") {\n        const lo = layout.lo;\n        const hi = layout.hi;\n        const candidates: number[] = [];\n        for (\n          let e = Math.floor(Math.log10(lo));\n          e <= Math.ceil(Math.log10(hi));\n          e++\n        )\n          for (const m of [1, 2, 5]) {\n            const v = tidy(m * 10 ** e);\n            if (v >= lo * 0.999 && v <= hi * 1.001) candidates.push(v);\n          }\n        // Thin out 2s and then 5s until labels have room.\n        for (const keep of [[1, 2, 5], [1, 5], [1]]) {\n          const list = candidates.filter((v) =>\n            keep.includes(\n              Math.round(v / 10 ** Math.floor(Math.log10(v) + 1e-9)),\n            ),\n          );\n          let ok = true;\n          for (let i = 1; i < list.length; i++)\n            if ((pos(list[i]) - pos(list[i - 1])) * W < 44) ok = false;\n          if (ok || keep.length === 1) return list;\n        }\n      }\n    }\n    const lo = layout.lo;\n    const hi = layout.hi;\n    const step = niceStep((hi - lo) / Math.max(2, Math.floor(W / 76)));\n    for (\n      let v = Math.ceil(lo / step - 1e-9) * step;\n      v <= hi + step * 1e-6;\n      v += step\n    )\n      ticks.push(tidy(v));\n    return ticks;\n  }, [scale, dist.buckets, layout, pos, W, empty]);\n\n  /* ----------------------------------------------------------- animation */\n\n  // Bars grow in on mount and whenever the bucket layout changes; data updates tween.\n  // Keyed on scale and bar count only, so live data with a drifting tail tweens instead of regrowing.\n  const structure = `${scale}:${bars.length}`;\n  const [grown, setGrown] = React.useState<string | null>(null);\n  const [intro, setIntro] = React.useState(true);\n  React.useEffect(() => {\n    if (reduced) {\n      setGrown(structure);\n      setIntro(false);\n      return;\n    }\n    setIntro(true);\n    let frame = requestAnimationFrame(() => {\n      frame = requestAnimationFrame(() => setGrown(structure));\n    });\n    const timer = window.setTimeout(\n      () => setIntro(false),\n      900 + bars.length * 9,\n    );\n    return () => {\n      cancelAnimationFrame(frame);\n      window.clearTimeout(timer);\n    };\n  }, [structure, reduced, bars.length]);\n  const isGrown = grown === structure;\n\n  /* --------------------------------------------------------- interaction */\n\n  const [hover, setHover] = React.useState<number | null>(null);\n  const [active, setActive] = React.useState<number | null>(null);\n  const [brush, setBrush] = React.useState<LatencyRange | null>(null);\n  const drag = React.useRef<{\n    x: number;\n    value: number;\n    moved: boolean;\n  } | null>(null);\n  const anchor = React.useRef<number | null>(null);\n\n  const xToFraction = (clientX: number) => {\n    const rect = plotRef.current!.getBoundingClientRect();\n    return Math.min(1, Math.max(0, (clientX - rect.left) / (rect.width || 1)));\n  };\n  const barAt = (x: number) => {\n    for (let i = 0; i < bars.length; i++)\n      if (x >= bars[i].x0 && x <= bars[i].x1) return i;\n    // In a gap: the nearest bar.\n    let best = -1;\n    let distance = Infinity;\n    bars.forEach((b, i) => {\n      const dd = Math.min(Math.abs(x - b.x0), Math.abs(x - b.x1));\n      if (dd < distance) {\n        distance = dd;\n        best = i;\n      }\n    });\n    return best < 0 ? null : best;\n  };\n\n  const clampRange = (a: number, b: number): LatencyRange => [\n    Math.min(a, b),\n    Math.max(a, b),\n  ];\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (event.button !== 0 || !bars.length) return;\n    const x = xToFraction(event.clientX);\n    drag.current = { x: event.clientX, value: inv(x), moved: false };\n    event.currentTarget.setPointerCapture(event.pointerId);\n  };\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (!bars.length) return;\n    const x = xToFraction(event.clientX);\n    const d = drag.current;\n    if (d) {\n      if (!d.moved && Math.abs(event.clientX - d.x) > 3) d.moved = true;\n      if (d.moved) {\n        setBrush(clampRange(d.value, inv(x)));\n        setHover(null);\n        return;\n      }\n    }\n    setHover(barAt(x));\n  };\n  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    drag.current = null;\n    if (!d) return;\n    if (d.moved) {\n      const next = clampRange(d.value, inv(xToFraction(event.clientX)));\n      setBrush(null);\n      setRange(next[1] - next[0] > 0 ? next : null);\n    } else if (range) setRange(null);\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (!bars.length) return;\n    const current = active ?? -1;\n    const step = (delta: number) =>\n      Math.min(\n        bars.length - 1,\n        Math.max(\n          0,\n          current < 0 ? (delta > 0 ? 0 : bars.length - 1) : current + delta,\n        ),\n      );\n    let next: number | null = null;\n    if (event.key === \"ArrowRight\") next = step(1);\n    else if (event.key === \"ArrowLeft\") next = step(-1);\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = bars.length - 1;\n    else if (event.key === \"Enter\" && current >= 0) {\n      setRange([bars[current].start, bars[current].end]);\n      event.preventDefault();\n      return;\n    } else if (event.key === \"Escape\") {\n      if (range) setRange(null);\n      else setActive(null);\n      anchor.current = null;\n      event.preventDefault();\n      return;\n    }\n    if (next == null) return;\n    event.preventDefault();\n    if (event.shiftKey) {\n      if (anchor.current == null) anchor.current = current < 0 ? next : current;\n      const a = Math.min(anchor.current, next);\n      const b = Math.max(anchor.current, next);\n      setRange([bars[a].start, bars[b].end]);\n    } else anchor.current = null;\n    setActive(next);\n  };\n\n  const shownRange = brush ?? range;\n  const rangeCount = shownRange\n    ? countBetween(dist, shownRange[0], shownRange[1])\n    : 0;\n  const rangeShare = dist.total ? rangeCount / dist.total : 0;\n  const focusIndex = hover ?? active;\n  const focusBucket =\n    focusIndex != null && bars[focusIndex] ? bucketAt(focusIndex) : null;\n\n  /* -------------------------------------------------------------- render */\n\n  const describeBucket = (b: LatencyHistogramBucket) =>\n    `${b.overflow ? `${format(b.start)} and above` : `${format(b.start)} to ${format(b.end)}`}: ${whole.format(Math.round(b.count))} requests, ${percentLabel(b.share)}`;\n  const summaryText = [\n    `${whole.format(Math.round(dist.total))} requests.`,\n    marks\n      .map((mark) => `${percentileName(mark.p)} ${format(mark.value)}`)\n      .join(\", \") + \".\",\n    hasThreshold\n      ? `${percentLabel(overShare)} over the ${thresholdLabel} of ${format(threshold!)}.`\n      : \"\",\n  ]\n    .filter(Boolean)\n    .join(\" \");\n  const hasHeader =\n    title != null || description != null || actions != null || showScaleToggle;\n  const transition = intro\n    ? \"transform 760ms cubic-bezier(.16,1,.3,1)\"\n    : \"transform 520ms cubic-bezier(.16,1,.3,1)\";\n  const barFill = (color: string) =>\n    `color-mix(in oklab, ${color} 72%, var(--color-card))`;\n\n  // The comparison as one stepped path across the bars.\n  const comparePath = React.useMemo(() => {\n    if (!comparison || compareStyle !== \"step\") return null;\n    let path = \"\";\n    let previousEnd = -1;\n    bars.forEach((b, i) => {\n      const y = 100 - (comparison.scaled[i] / yMax) * 100;\n      const x0 = b.x0 * 1000;\n      const x1 = b.x1 * 1000;\n      if (Math.abs(x0 - previousEnd) > 0.5)\n        path += `${path ? \"V100\" : \"\"}M${x0.toFixed(2)} 100`;\n      path += `V${y.toFixed(2)}H${x1.toFixed(2)}`;\n      previousEnd = x1;\n    });\n    return path + \"V100\";\n  }, [comparison, compareStyle, bars, yMax]);\n\n  return (\n    <div\n      data-slot=\"latency-histogram\"\n      data-scale={scale}\n      data-brushing={brush ? true : undefined}\n      className={cn(\n        \"@container/histogram flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      {...props}\n    >\n      {hasHeader && (\n        <div className=\"flex items-start gap-3 px-4 pt-3.5\">\n          <div className=\"min-w-0 flex-1 space-y-1\">\n            {title != null && (\n              <h3 className=\"truncate text-sm leading-6 font-semibold tracking-tight\">\n                {title}\n              </h3>\n            )}\n            {description != null && (\n              <p\n                id={`${id}-description`}\n                className=\"text-xs text-muted-foreground\"\n              >\n                {description}\n              </p>\n            )}\n          </div>\n          <div className=\"flex shrink-0 items-center gap-2\">\n            {actions}\n            {showScaleToggle && (\n              <div\n                role=\"group\"\n                aria-label=\"X axis scale\"\n                data-slot=\"histogram-scale-toggle\"\n                className=\"inline-flex h-7 items-center rounded-md border bg-muted/40 p-0.5\"\n              >\n                {([\"linear\", \"log\"] as const).map((option) => (\n                  <button\n                    key={option}\n                    type=\"button\"\n                    aria-pressed={scale === option}\n                    onClick={() => setScale(option)}\n                    className={cn(\n                      \"h-full rounded-[5px] px-2 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground aria-pressed:bg-card aria-pressed:text-foreground aria-pressed:shadow-xs motion-reduce:transition-none\",\n                      focusRing,\n                    )}\n                  >\n                    {option === \"linear\" ? \"Linear\" : \"Log\"}\n                  </button>\n                ))}\n              </div>\n            )}\n          </div>\n        </div>\n      )}\n\n      {showSummary && (marks.length > 0 || hasThreshold) && (\n        // Narrow cards trade the stat grid for one line, so the distribution stays in view.\n        <dl\n          data-slot=\"histogram-summary-compact\"\n          className={cn(\n            \"mx-4 flex flex-wrap items-baseline gap-x-3 gap-y-1 text-xs @md/histogram:hidden\",\n            hasHeader ? \"mt-1.5\" : \"mt-4\",\n          )}\n        >\n          {marks.map((mark, i) => {\n            const previous = comparison?.percentiles[i];\n            const delta = previous != null ? mark.value - previous : null;\n            const hot = hasThreshold && mark.value > threshold!;\n            return (\n              <div key={mark.p} className=\"flex items-baseline gap-1\">\n                <dt className=\"font-mono text-[11px] text-muted-foreground\">\n                  {percentileName(mark.p)}\n                </dt>\n                <dd\n                  className={cn(\n                    \"font-semibold tabular-nums\",\n                    hot && \"text-destructive\",\n                  )}\n                >\n                  {format(mark.value)}\n                </dd>\n                {delta != null && Math.abs(delta) > 0 && (\n                  <dd\n                    className={cn(\n                      \"font-mono text-[10px] tabular-nums\",\n                      delta > 0\n                        ? \"text-destructive\"\n                        : \"text-emerald-700 dark:text-emerald-400\",\n                    )}\n                  >\n                    {delta > 0 ? \"▲\" : \"▼\"}\n                    {format(Math.abs(delta))}\n                  </dd>\n                )}\n              </div>\n            );\n          })}\n          {hasThreshold && (\n            <div className=\"flex items-baseline gap-1\">\n              <dd\n                className={cn(\n                  \"font-semibold tabular-nums\",\n                  over > 0\n                    ? \"text-destructive\"\n                    : \"text-emerald-700 dark:text-emerald-400\",\n                )}\n              >\n                {percentLabel(overShare)}\n              </dd>\n              <dt className=\"text-[11px] text-muted-foreground\">\n                over {thresholdLabel}\n              </dt>\n            </div>\n          )}\n        </dl>\n      )}\n\n      {showSummary && (marks.length > 0 || hasThreshold) && (\n        <dl\n          data-slot=\"histogram-summary\"\n          className={cn(\n            \"mx-4 hidden overflow-hidden rounded-lg bg-muted/50 @md/histogram:grid dark:bg-muted/30\",\n            hasHeader ? \"mt-3\" : \"mt-4\",\n          )}\n          style={{\n            gridTemplateColumns: `repeat(${marks.length + (hasThreshold ? 1 : 0)}, minmax(0, 1fr))`,\n          }}\n        >\n          {marks.map((mark, i) => {\n            const previous = comparison?.percentiles[i];\n            const delta = previous != null ? mark.value - previous : null;\n            const hot = hasThreshold && mark.value > threshold!;\n            return (\n              <div\n                key={mark.p}\n                className=\"min-w-0 border-s border-border/60 px-2 py-1.5 first:border-s-0 @sm/histogram:px-2.5 @md/histogram:px-3 @md/histogram:py-2\"\n              >\n                <dt className=\"font-mono text-[11px] leading-4 text-muted-foreground\">\n                  {percentileName(mark.p)}\n                </dt>\n                <dd\n                  className={cn(\n                    \"truncate text-sm leading-6 font-semibold tracking-tight tabular-nums @sm/histogram:text-base @md/histogram:text-lg\",\n                    hot && \"text-destructive\",\n                  )}\n                >\n                  {format(mark.value)}\n                </dd>\n                {delta != null && Math.abs(delta) > 0 && (\n                  <dd\n                    className={cn(\n                      \"truncate font-mono text-[11px] leading-4 whitespace-nowrap tabular-nums\",\n                      delta > 0\n                        ? \"text-destructive\"\n                        : \"text-emerald-700 dark:text-emerald-400\",\n                    )}\n                    title={`${compareLabel}: ${format(previous!)}`}\n                  >\n                    {delta > 0 ? \"▲\" : \"▼\"} {format(Math.abs(delta))}\n                  </dd>\n                )}\n              </div>\n            );\n          })}\n          {hasThreshold && (\n            <div className=\"min-w-0 border-s border-border/60 px-2 py-1.5 first:border-s-0 @sm/histogram:px-2.5 @md/histogram:px-3 @md/histogram:py-2\">\n              <dt className=\"truncate text-[11px] leading-4 text-muted-foreground\">\n                Over {thresholdLabel}\n              </dt>\n              <dd\n                className={cn(\n                  \"truncate text-sm leading-6 font-semibold tracking-tight tabular-nums @sm/histogram:text-base @md/histogram:text-lg\",\n                  over > 0\n                    ? \"text-destructive\"\n                    : \"text-emerald-700 dark:text-emerald-400\",\n                )}\n              >\n                {percentLabel(overShare)}\n              </dd>\n              <dd className=\"truncate font-mono text-[11px] leading-4 text-muted-foreground tabular-nums\">\n                {whole.format(Math.round(over))}\n                <span className=\"hidden @sm/histogram:inline\">\n                  {\" \"}\n                  of {compact.format(dist.total).replace(\"K\", \"k\")}\n                </span>\n              </dd>\n            </div>\n          )}\n        </dl>\n      )}\n\n      <div className=\"mt-3 flex px-4 @md/histogram:mt-4\">\n        <div className=\"min-w-0 flex-1\">\n          <div\n            ref={plotRef}\n            data-slot=\"histogram-plot\"\n            role=\"group\"\n            aria-roledescription=\"histogram\"\n            aria-label={`${typeof title === \"string\" ? `${title}. ` : \"\"}${summaryText} Use the arrow keys to read buckets, Shift to select a range.`}\n            aria-describedby={\n              description != null ? `${id}-description` : undefined\n            }\n            tabIndex={0}\n            onPointerDown={onPointerDown}\n            onPointerMove={onPointerMove}\n            onPointerUp={onPointerUp}\n            onPointerCancel={() => {\n              drag.current = null;\n              setBrush(null);\n            }}\n            onPointerLeave={() => {\n              if (!drag.current) setHover(null);\n            }}\n            onKeyDown={onKeyDown}\n            onBlur={() => setActive(null)}\n            className={cn(\n              \"relative cursor-crosshair touch-pan-y rounded-sm select-none\",\n              \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-card\",\n            )}\n            style={{ height: H }}\n          >\n            {empty && (\n              <p className=\"absolute inset-0 grid place-items-center text-xs text-muted-foreground\">\n                No requests to show.\n              </p>\n            )}\n\n            {/* Value grid */}\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-x-0 bottom-0\"\n              style={{ top: chipTop }}\n            >\n              {yTicks.map((tick) => (\n                <span\n                  key={tick}\n                  className={cn(\n                    \"absolute inset-x-0 h-px\",\n                    tick === 0 ? \"bg-border\" : \"bg-border/55\",\n                  )}\n                  style={{ bottom: `${(tick / yMax) * 100}%` }}\n                />\n              ))}\n            </div>\n\n            {/* SLO tail */}\n            {hasThreshold && thresholdX < 1 && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-threshold-region\"\n                className=\"pointer-events-none absolute inset-y-0 right-0\"\n                style={{\n                  left: `${thresholdX * 100}%`,\n                  background: `linear-gradient(to bottom, color-mix(in oklab, ${colors.threshold} 9%, transparent), color-mix(in oklab, ${colors.threshold} 3%, transparent)), repeating-linear-gradient(-45deg, color-mix(in oklab, ${colors.threshold} 9%, transparent) 0 1px, transparent 1px 6px)`,\n                }}\n              />\n            )}\n\n            {/* Bars */}\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-x-0 bottom-0\"\n              style={{ top: chipTop }}\n            >\n              {comparison &&\n                compareStyle === \"outline\" &&\n                bars.map((b, i) => (\n                  <span\n                    key={`c-${structure}-${i}`}\n                    className=\"absolute bottom-0 origin-bottom rounded-t-[2px] border border-b-0 border-dashed\"\n                    style={{\n                      left: `calc(${b.x0 * 100}% + 1px)`,\n                      width: `calc(${(b.x1 - b.x0) * 100}% - 2px)`,\n                      height: `${(comparison.scaled[i] / yMax) * 100}%`,\n                      borderColor: `color-mix(in oklab, ${colors.compare} 70%, transparent)`,\n                      transform: `scaleY(${isGrown ? 1 : 0})`,\n                      transition: reduced ? undefined : transition,\n                    }}\n                  />\n                ))}\n              {bars.map((b, i) => {\n                const h = b.count / yMax;\n                const inRange = shownRange\n                  ? b.end > shownRange[0] && b.start < shownRange[1]\n                  : true;\n                const dim =\n                  (focusIndex != null && focusIndex !== i) || !inRange;\n                const split =\n                  hasThreshold && b.start < threshold! && b.end > threshold!;\n                const hot = hasThreshold && b.start >= threshold!;\n                const color = hot ? colors.threshold : colors.bar;\n                const cut = split\n                  ? ((thresholdX - b.x0) / (b.x1 - b.x0)) * 100\n                  : 0;\n                const fill = split\n                  ? `linear-gradient(to right, ${barFill(colors.bar)} ${cut}%, ${barFill(colors.threshold)} ${cut}%)`\n                  : barFill(color);\n                const cap = split\n                  ? `linear-gradient(to right, ${colors.bar} ${cut}%, ${colors.threshold} ${cut}%)`\n                  : color;\n                return (\n                  <span\n                    key={`${structure}-${i}`}\n                    data-slot=\"histogram-bar\"\n                    data-index={i}\n                    data-over={hot || undefined}\n                    data-overflow={b.overflow || undefined}\n                    className={cn(\n                      \"absolute inset-y-0 transition-opacity duration-200 motion-reduce:transition-none\",\n                      dim &&\n                        (shownRange && !inRange ? \"opacity-30\" : \"opacity-55\"),\n                    )}\n                    style={{\n                      left: `${b.x0 * 100}%`,\n                      width: `${(b.x1 - b.x0) * 100}%`,\n                    }}\n                  >\n                    <span\n                      className=\"absolute inset-x-px bottom-0 h-full origin-bottom @lg/histogram:inset-x-[1.5px]\"\n                      style={{\n                        transform: `scaleY(${isGrown ? h : 0})`,\n                        transition: reduced ? undefined : transition,\n                        transitionDelay:\n                          intro && !reduced ? `${i * 9}ms` : undefined,\n                      }}\n                    >\n                      <span\n                        className={cn(\n                          \"absolute inset-0 rounded-t-[2px]\",\n                          b.overflow &&\n                            \"[mask-image:repeating-linear-gradient(-45deg,#000_0_3px,rgb(0_0_0/0.55)_3px_5px)]\",\n                        )}\n                        style={{ background: fill }}\n                      />\n                    </span>\n                    {/* The cap is drawn unscaled so it stays a crisp line at any height. */}\n                    {b.count > 0 && (\n                      <span\n                        className=\"absolute inset-x-px h-[1.5px] rounded-full @lg/histogram:inset-x-[1.5px]\"\n                        style={{\n                          bottom: `calc(${(isGrown ? h : 0) * 100}% - 1px)`,\n                          background: cap,\n                          transition: reduced\n                            ? undefined\n                            : intro\n                              ? \"bottom 760ms cubic-bezier(.16,1,.3,1)\"\n                              : \"bottom 520ms cubic-bezier(.16,1,.3,1)\",\n                          transitionDelay:\n                            intro && !reduced ? `${i * 9}ms` : undefined,\n                        }}\n                      />\n                    )}\n                  </span>\n                );\n              })}\n              {comparePath && (\n                <svg\n                  data-slot=\"histogram-compare\"\n                  className=\"absolute inset-0 size-full origin-bottom overflow-visible\"\n                  viewBox=\"0 0 1000 100\"\n                  preserveAspectRatio=\"none\"\n                  style={{\n                    transform: `scaleY(${isGrown ? 1 : 0})`,\n                    transition: reduced ? undefined : transition,\n                  }}\n                >\n                  <path\n                    d={comparePath}\n                    fill=\"none\"\n                    stroke={colors.compare}\n                    strokeWidth={1.5}\n                    strokeDasharray=\"4 3\"\n                    strokeLinejoin=\"round\"\n                    vectorEffect=\"non-scaling-stroke\"\n                    opacity={0.85}\n                  />\n                </svg>\n              )}\n            </div>\n\n            {/* Selection */}\n            {shownRange && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-selection\"\n                className=\"pointer-events-none absolute inset-y-0\"\n                style={{\n                  left: `${pos(shownRange[0]) * 100}%`,\n                  width: `${Math.max(0, pos(shownRange[1]) - pos(shownRange[0])) * 100}%`,\n                  background: `color-mix(in oklab, ${colors.selection} 9%, transparent)`,\n                  boxShadow: `inset 1.5px 0 0 ${colors.selection}, inset -1.5px 0 0 ${colors.selection}`,\n                }}\n              >\n                <span\n                  className=\"absolute top-1/2 -left-[3px] h-5 w-1.5 -translate-y-1/2 rounded-full border border-card\"\n                  style={{ background: colors.selection }}\n                />\n                <span\n                  className=\"absolute top-1/2 -right-[3px] h-5 w-1.5 -translate-y-1/2 rounded-full border border-card\"\n                  style={{ background: colors.selection }}\n                />\n              </div>\n            )}\n\n            {/* Threshold line */}\n            {hasThreshold && thresholdX < 1 && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-threshold\"\n                className=\"pointer-events-none absolute bottom-0\"\n                style={{ left: `${thresholdX * 100}%`, top: chipTop - 2 }}\n              >\n                <span\n                  className=\"absolute inset-y-0 w-0 border-l-[1.5px] border-dashed\"\n                  style={{ borderColor: colors.threshold }}\n                />\n                <span\n                  className=\"absolute top-1 left-1 rounded-sm bg-card/85 px-1 font-mono text-[10px] leading-4 font-medium whitespace-nowrap\"\n                  style={{ color: colors.threshold }}\n                >\n                  {thresholdLabel} {format(threshold!)}\n                </span>\n              </div>\n            )}\n\n            {/* Percentile markers */}\n            {chips.map((chip) => {\n              const hot = hasThreshold && chip.value > threshold!;\n              const color = hot ? colors.threshold : colors.marker;\n              return (\n                <div\n                  key={chip.p}\n                  data-slot=\"histogram-marker\"\n                  data-percentile={chip.p}\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none\"\n                >\n                  <span\n                    className=\"absolute bottom-0 w-0 border-l border-dashed opacity-55\"\n                    style={{\n                      left: chip.x,\n                      top: chip.lane * 20 + 18,\n                      borderColor: color,\n                    }}\n                  />\n                  <span\n                    className={cn(\n                      \"absolute flex h-[18px] items-center gap-1 rounded-[5px] border bg-card px-1.5 font-mono text-[10px] leading-none whitespace-nowrap shadow-xs tabular-nums\",\n                      intro &&\n                        !reduced &&\n                        \"motion-safe:animate-[histogram-rise_.5s_.35s_cubic-bezier(.16,1,.3,1)_both]\",\n                    )}\n                    style={{\n                      left: chip.left,\n                      top: chip.lane * 20,\n                      borderColor: `color-mix(in oklab, ${color} 28%, var(--color-border))`,\n                    }}\n                  >\n                    <span className=\"text-muted-foreground\">\n                      {percentileName(chip.p)}\n                    </span>\n                    {chip.withValue && (\n                      <span className=\"font-semibold\" style={{ color }}>\n                        {format(chip.value)}\n                      </span>\n                    )}\n                  </span>\n                </div>\n              );\n            })}\n\n            {/* Tooltip */}\n            {focusBucket && !brush && (\n              <div\n                data-slot=\"histogram-tooltip\"\n                aria-hidden=\"true\"\n                className=\"pointer-events-none absolute z-10 min-w-36 rounded-lg border bg-popover px-2.5 py-2 text-xs text-popover-foreground shadow-md\"\n                style={{\n                  top: chipTop + 4,\n                  // Sit beside the bar, on the side with more room, so it never hides it.\n                  ...(bars[focusBucket.index].x0 + bars[focusBucket.index].x1 <\n                  1\n                    ? { left: bars[focusBucket.index].x1 * W + 8 }\n                    : { right: W - bars[focusBucket.index].x0 * W + 8 }),\n                }}\n              >\n                {renderTooltip ? (\n                  renderTooltip(focusBucket)\n                ) : (\n                  <>\n                    <p className=\"font-mono text-[11px] text-muted-foreground tabular-nums\">\n                      {focusBucket.overflow\n                        ? `≥ ${format(focusBucket.start)}`\n                        : `${format(focusBucket.start)} – ${format(focusBucket.end)}`}\n                    </p>\n                    <p className=\"mt-0.5 flex items-baseline gap-1.5\">\n                      <span className=\"text-sm font-semibold tabular-nums\">\n                        {whole.format(Math.round(focusBucket.count))}\n                      </span>\n                      <span className=\"text-muted-foreground tabular-nums\">\n                        {percentLabel(focusBucket.share)}\n                      </span>\n                    </p>\n                    <p className=\"mt-1 text-[11px] text-muted-foreground tabular-nums\">\n                      {percentLabel(focusBucket.cumulative)} at or faster\n                    </p>\n                    {focusBucket.compare != null && comparison && (\n                      <p className=\"mt-1.5 flex items-center gap-1.5 border-t border-dashed pt-1.5 text-[11px] text-muted-foreground tabular-nums\">\n                        <span\n                          aria-hidden=\"true\"\n                          className=\"w-3 border-t-[1.5px] border-dashed\"\n                          style={{ borderColor: colors.compare }}\n                        />\n                        {compareLabel}\n                        <span className=\"ml-auto font-medium text-foreground\">\n                          {whole.format(Math.round(focusBucket.compare))}\n                        </span>\n                        <span>\n                          {percentLabel(focusBucket.compareShare ?? 0)}\n                        </span>\n                      </p>\n                    )}\n                  </>\n                )}\n              </div>\n            )}\n          </div>\n\n          {/* Latency axis */}\n          <div\n            aria-hidden=\"true\"\n            className=\"relative mt-1.5 h-4 font-mono text-[10px] leading-4 text-muted-foreground tabular-nums\"\n          >\n            {xTicks.map((tick, i) => {\n              const x = pos(tick);\n              if (x > layout.pos(layout.hi) + 1e-6) return null;\n              return (\n                <span\n                  key={tick}\n                  className={cn(\n                    \"absolute whitespace-nowrap\",\n                    i === 0 && x < 0.02\n                      ? \"\"\n                      : x > 0.97\n                        ? \"-translate-x-full\"\n                        : \"-translate-x-1/2\",\n                  )}\n                  style={{ left: `${x * 100}%` }}\n                >\n                  {formatTick(tick)}\n                </span>\n              );\n            })}\n            {bars[bars.length - 1]?.overflow && (\n              <span\n                className=\"absolute -translate-x-1/2 whitespace-nowrap\"\n                style={{\n                  left: `${((bars[bars.length - 1].x0 + 1) / 2) * 100}%`,\n                }}\n              >\n                +\n              </span>\n            )}\n          </div>\n        </div>\n        <div\n          aria-hidden=\"true\"\n          className=\"relative ml-2 w-8 shrink-0\"\n          style={{ height: H }}\n        >\n          {yTicks.map((tick) => (\n            <span\n              key={tick}\n              className=\"absolute right-0 translate-y-1/2 font-mono text-[10px] leading-none text-muted-foreground tabular-nums\"\n              style={{ bottom: `${(tick / yMax) * (barsHeight / H) * 100}%` }}\n            >\n              {tick === 0 ? \"0\" : compact.format(tick).replace(\"K\", \"k\")}\n            </span>\n          ))}\n        </div>\n      </div>\n\n      <div\n        data-slot=\"histogram-footer\"\n        className=\"mt-3 flex min-h-11 flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t px-4 py-2\"\n      >\n        <div\n          data-slot=\"histogram-status\"\n          className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-xs\"\n        >\n          {shownRange ? (\n            <>\n              <span\n                className=\"rounded-[4px] px-1.5 py-px font-mono text-[11px] tabular-nums\"\n                style={{\n                  background: `color-mix(in oklab, ${colors.selection} 10%, transparent)`,\n                  color: colors.selection,\n                }}\n              >\n                {format(shownRange[0])} – {format(shownRange[1])}\n              </span>\n              <span className=\"font-semibold tabular-nums\">\n                {percentLabel(rangeShare)}\n              </span>\n              <span className=\"text-muted-foreground tabular-nums\">\n                {whole.format(Math.round(rangeCount))} of{\" \"}\n                {whole.format(Math.round(dist.total))} requests\n              </span>\n              {!brush && (\n                <button\n                  type=\"button\"\n                  onClick={() => setRange(null)}\n                  className={cn(\n                    \"inline-flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground\",\n                    focusRing,\n                  )}\n                >\n                  <X className=\"size-3.5\" aria-hidden=\"true\" />\n                  <span className=\"sr-only\">Clear selection</span>\n                </button>\n              )}\n            </>\n          ) : (\n            <span className=\"text-muted-foreground tabular-nums\">\n              <span className=\"font-medium text-foreground\">\n                {whole.format(Math.round(dist.total))}\n              </span>{\" \"}\n              requests\n              <span aria-hidden=\"true\"> · </span>mean{\" \"}\n              <span className=\"font-medium text-foreground\">\n                {format(dist.mean)}\n              </span>\n              <span className=\"hidden @md/histogram:inline\">\n                <span aria-hidden=\"true\"> · </span>max{\" \"}\n                <span className=\"font-medium text-foreground\">\n                  {format(dist.max)}\n                </span>\n              </span>\n              <span className=\"hidden @lg/histogram:inline\">\n                {\" \"}\n                · drag to measure a range\n              </span>\n            </span>\n          )}\n        </div>\n        {comparison && (\n          <div\n            data-slot=\"histogram-legend\"\n            className=\"flex items-center gap-3 text-[11px] text-muted-foreground\"\n          >\n            <span className=\"flex items-center gap-1.5\">\n              <span\n                aria-hidden=\"true\"\n                className=\"size-2.5 rounded-[2px]\"\n                style={{\n                  background: barFill(colors.bar),\n                  boxShadow: `inset 0 1.5px 0 ${colors.bar}`,\n                }}\n              />\n              {seriesLabel}\n            </span>\n            <span className=\"flex items-center gap-1.5\">\n              <span\n                aria-hidden=\"true\"\n                className=\"w-3.5 border-t-[1.5px] border-dashed\"\n                style={{ borderColor: colors.compare }}\n              />\n              {compareLabel}\n            </span>\n          </div>\n        )}\n      </div>\n\n      <div className=\"sr-only\">\n        <table>\n          <caption>{summaryText}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">Latency</th>\n              <th scope=\"col\">Requests</th>\n              {comparison && <th scope=\"col\">{compareLabel}</th>}\n            </tr>\n          </thead>\n          <tbody>\n            {bars.map((b, i) =>\n              b.count > 0 || comparison?.counts[i] ? (\n                <tr key={i}>\n                  <th scope=\"row\">\n                    {b.overflow\n                      ? `${format(b.start)} and above`\n                      : `${format(b.start)} to ${format(b.end)}`}\n                  </th>\n                  <td>{whole.format(Math.round(b.count))}</td>\n                  {comparison && (\n                    <td>{whole.format(Math.round(comparison.counts[i]))}</td>\n                  )}\n                </tr>\n              ) : null,\n            )}\n          </tbody>\n        </table>\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {active != null && bars[active]\n          ? describeBucket(bucketAt(active))\n          : range\n            ? `Selected ${format(range[0])} to ${format(range[1])}: ${percentLabel(dist.total ? countBetween(dist, range[0], range[1]) / dist.total : 0)} of requests.`\n            : \"\"}\n      </p>\n\n      <style href=\"overtrue-latency-histogram\" precedence=\"default\">\n        {`@keyframes histogram-rise{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}`}\n      </style>\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/json-viewer.tsx",
      "type": "registry:component",
      "target": "components/overtrue/json-viewer.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconCheck as Check,\n  IconChevronDown as ChevronDown,\n  IconChevronRight as ChevronRight,\n  IconChevronUp as ChevronUp,\n  IconCopy as Copy,\n  IconFoldDown as FoldDown,\n  IconFoldUp as FoldUp,\n  IconRoute as Route,\n  IconSearch as Search,\n  IconX as X,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* -------------------------------------------------------------------------------------------------\n * Types\n * -----------------------------------------------------------------------------------------------*/\n\nexport type JsonValueType =\n  | \"object\"\n  | \"array\"\n  | \"string\"\n  | \"number\"\n  | \"bigint\"\n  | \"boolean\"\n  | \"null\"\n  | \"undefined\"\n  | \"date\"\n  | \"function\"\n  | \"symbol\"\n  | \"circular\";\n\nexport interface JsonViewerLabels {\n  tree: string;\n  search: string;\n  clearSearch: string;\n  previousMatch: string;\n  nextMatch: string;\n  noMatches: string;\n  matchCount: (current: number, total: number) => string;\n  expandAll: string;\n  collapseAll: string;\n  copyJson: string;\n  copyPath: string;\n  copyValue: string;\n  copied: string;\n  showMore: string;\n  showLess: string;\n  showMoreItems: (count: number) => string;\n  hiddenItems: (count: number) => string;\n  keys: (count: number) => string;\n  items: (count: number) => string;\n  characters: (count: number) => string;\n  root: string;\n  statusHint: string;\n}\n\nexport type JsonCopyKind = \"value\" | \"path\" | \"json\";\n\nexport interface JsonViewerProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"onSelect\" | \"children\" | \"defaultValue\" | \"onCopy\"\n> {\n  /** Any JSON-like value. Dates, Maps, Sets, bigints and circular references are handled. */\n  data: unknown;\n  /** Name of the root node and the first segment of every path, e.g. \"payload\". */\n  rootName?: string;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Containers shallower than this start expanded. Defaults to 2. */\n  defaultExpandDepth?: number;\n  /** Expanded container paths. Pass with `onExpandedChange` to control expansion. */\n  expanded?: readonly string[] | ReadonlySet<string>;\n  /** Initially expanded paths, instead of `defaultExpandDepth`. */\n  defaultExpanded?: readonly string[];\n  onExpandedChange?: (expanded: string[]) => void;\n  /** Shows the search field. Defaults to true. */\n  showSearch?: boolean;\n  /** Search text. Pass with `onSearchChange` to control it. */\n  search?: string;\n  defaultSearch?: string;\n  onSearchChange?: (search: string) => void;\n  /** Longer strings are cut with an inline Show more. Defaults to 120 characters. */\n  maxStringLength?: number;\n  /** Children rendered per container before Show more. Defaults to 100. */\n  pageSize?: number;\n  /** Sort object keys alphabetically, or with your own comparator. */\n  sortKeys?: boolean | ((a: string, b: string) => number);\n  /** Selected path. Pass `null` for none; leave undefined to let the viewer manage it. */\n  selectedPath?: string | null;\n  defaultSelectedPath?: string | null;\n  /** Called when a node is clicked, or chosen with Enter or Space. */\n  onSelect?: (path: string, value: unknown) => void;\n  /** Draw a leaf value yourself. Return `undefined` to keep the built-in rendering. */\n  renderValue?: (value: unknown, path: string) => React.ReactNode | undefined;\n  /** Copy actions on rows, in the status bar and in the toolbar. Defaults to true. */\n  copyable?: boolean;\n  /** Receives copied text. Without it, copies go to the clipboard. */\n  onCopy?: (text: string, detail: { kind: JsonCopyKind; path: string }) => void;\n  /** Expand all, Collapse all and Copy JSON. Defaults to true. */\n  showToolbar?: boolean;\n  /** Path, type and copy actions for the focused node. Defaults to true. */\n  showStatusBar?: boolean;\n  /** Extra buttons placed before the built-in toolbar actions. */\n  actions?: React.ReactNode;\n  /** Height limit of the tree; it scrolls beyond this. */\n  maxHeight?: number | string;\n  /** Formats the hint shown for ISO-8601 timestamps. */\n  formatDate?: (date: Date) => string;\n  labels?: Partial<JsonViewerLabels>;\n}\n\nconst plural = (count: number, one: string, many: string) =>\n  `${count.toLocaleString()} ${count === 1 ? one : many}`;\n\nconst LABELS: JsonViewerLabels = {\n  tree: \"JSON\",\n  search: \"Search keys and values\",\n  clearSearch: \"Clear search\",\n  previousMatch: \"Previous match\",\n  nextMatch: \"Next match\",\n  noMatches: \"No matches\",\n  matchCount: (current, total) => `${current} of ${total}`,\n  expandAll: \"Expand all\",\n  collapseAll: \"Collapse all\",\n  copyJson: \"Copy JSON\",\n  copyPath: \"Copy path\",\n  copyValue: \"Copy value\",\n  copied: \"Copied\",\n  showMore: \"Show more\",\n  showLess: \"Show less\",\n  showMoreItems: (count) => `Show ${count.toLocaleString()} more`,\n  hiddenItems: (count) => `${count.toLocaleString()} hidden`,\n  keys: (count) => plural(count, \"key\", \"keys\"),\n  items: (count) => plural(count, \"item\", \"items\"),\n  characters: (count) => plural(count, \"character\", \"characters\"),\n  root: \"root\",\n  statusHint: \"Focus a node to see its path\",\n};\n\n/* -------------------------------------------------------------------------------------------------\n * Helpers\n * -----------------------------------------------------------------------------------------------*/\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:shadow-[0_0_14px_-2px_color-mix(in_oklab,var(--color-primary)_45%,transparent)]\";\n\nconst useIsoLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nconst subscribeNothing = () => () => {};\nfunction useMounted() {\n  return React.useSyncExternalStore(\n    subscribeNothing,\n    () => true,\n    () => false,\n  );\n}\n\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/;\nconst ISO_DATE =\n  /^\\d{4}-\\d{2}-\\d{2}(?:[T ]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:?\\d{2})?)?$/;\nconst URL_VALUE = /^https?:\\/\\/[^\\s\"]+$/i;\n\n/** Path of a child, e.g. `payload.items[2].sku` or `headers[\"content-type\"]`. */\nexport function jsonChildPath(parent: string, key: string | number, inArray: boolean) {\n  if (inArray) return `${parent}[${key}]`;\n  const name = String(key);\n  if (IDENTIFIER.test(name)) return parent ? `${parent}.${name}` : name;\n  return `${parent}[${JSON.stringify(name)}]`;\n}\n\nfunction typeOf(value: unknown, ancestors: Set<object>): JsonValueType {\n  if (value === null) return \"null\";\n  switch (typeof value) {\n    case \"string\":\n      return \"string\";\n    case \"number\":\n      return \"number\";\n    case \"bigint\":\n      return \"bigint\";\n    case \"boolean\":\n      return \"boolean\";\n    case \"undefined\":\n      return \"undefined\";\n    case \"function\":\n      return \"function\";\n    case \"symbol\":\n      return \"symbol\";\n  }\n  if (value instanceof Date) return \"date\";\n  if (ancestors.has(value as object)) return \"circular\";\n  if (Array.isArray(value) || value instanceof Set) return \"array\";\n  return \"object\";\n}\n\ntype Entry = [key: string | number, value: unknown];\n\nfunction entriesOf(\n  value: unknown,\n  type: JsonValueType,\n  sortKeys: JsonViewerProps[\"sortKeys\"],\n): Entry[] {\n  if (type === \"array\")\n    return (value instanceof Set ? [...value] : (value as unknown[])).map((child, index) => [index, child]);\n  const entries: Entry[] =\n    value instanceof Map\n      ? [...value.entries()].map(([key, child]) => [String(key), child])\n      : Object.keys(value as object).map((key) => [key, (value as Record<string, unknown>)[key]]);\n  if (sortKeys) {\n    const compare =\n      typeof sortKeys === \"function\"\n        ? sortKeys\n        : (a: string, b: string) => a.localeCompare(b, undefined, { numeric: true });\n    entries.sort((a, b) => compare(String(a[0]), String(b[0])));\n  }\n  return entries;\n}\n\n/** Text shown for a leaf, without string quotes. Search matches against this. */\nfunction displayText(value: unknown, type: JsonValueType) {\n  switch (type) {\n    case \"string\":\n      return JSON.stringify(value).slice(1, -1);\n    case \"bigint\":\n      return `${value as bigint}n`;\n    case \"date\": {\n      const time = (value as Date).getTime();\n      return Number.isNaN(time) ? \"Invalid Date\" : (value as Date).toISOString();\n    }\n    case \"function\":\n      return `ƒ ${(value as { name?: string }).name || \"anonymous\"}()`;\n    case \"circular\":\n      return \"[Circular]\";\n    case \"symbol\":\n      return String(value);\n    default:\n      return String(value);\n  }\n}\n\n/** JSON.stringify that survives bigints, Maps, Sets and circular references. */\nexport function toJsonString(value: unknown, space = 2) {\n  const stack: unknown[] = [];\n  const text = JSON.stringify(\n    value,\n    function (this: unknown, _key, current: unknown) {\n      if (typeof current === \"bigint\") return current.toString();\n      if (current instanceof Map) return Object.fromEntries(current);\n      if (current instanceof Set) return [...current];\n      if (typeof current === \"object\" && current !== null) {\n        while (stack.length && stack[stack.length - 1] !== this) stack.pop();\n        if (stack.includes(current)) return \"[Circular]\";\n        stack.push(current);\n      }\n      return current;\n    },\n    space,\n  );\n  return text ?? String(value);\n}\n\nfunction copyText(value: unknown, type: JsonValueType) {\n  if (type === \"object\" || type === \"array\") return toJsonString(value);\n  if (type === \"string\") return value as string;\n  return displayText(value, type);\n}\n\nasync function writeClipboard(text: string) {\n  try {\n    await navigator.clipboard.writeText(text);\n    return true;\n  } catch {\n    try {\n      const area = document.createElement(\"textarea\");\n      area.value = text;\n      area.setAttribute(\"readonly\", \"\");\n      area.style.position = \"fixed\";\n      area.style.opacity = \"0\";\n      document.body.appendChild(area);\n      area.select();\n      const ok = document.execCommand(\"copy\");\n      area.remove();\n      return ok;\n    } catch {\n      return false;\n    }\n  }\n}\n\nfunction formatBytes(bytes: number) {\n  if (bytes < 1024) return `${bytes} B`;\n  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;\n  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;\n}\n\nconst defaultDateFormat = (date: Date) =>\n  new Intl.DateTimeFormat(undefined, { dateStyle: \"medium\", timeStyle: \"long\" }).format(date);\n\n/* -------------------------------------------------------------------------------------------------\n * Flattening\n * -----------------------------------------------------------------------------------------------*/\n\ninterface Row {\n  kind: \"node\" | \"close\" | \"more\";\n  /** Unique row id; equals the node path for \"node\" rows. */\n  id: string;\n  path: string;\n  parent: string | null;\n  /** Container paths from the root down to the parent. */\n  ancestors: string[];\n  depth: number;\n  key: string | number | null;\n  inArray: boolean;\n  type: JsonValueType;\n  value: unknown;\n  size: number;\n  expanded: boolean;\n  last: boolean;\n  position: number;\n  setSize: number;\n  hidden: number;\n}\n\ninterface FlattenOptions {\n  isExpanded: (path: string, depth: number) => boolean;\n  limits: ReadonlyMap<string, number>;\n  pageSize: number;\n  sortKeys: JsonViewerProps[\"sortKeys\"];\n}\n\nfunction flatten(data: unknown, rootPath: string, rootName: string | undefined, options: FlattenOptions) {\n  const rows: Row[] = [];\n  const stack = new Set<object>();\n  const visit = (\n    value: unknown,\n    key: string | number | null,\n    path: string,\n    parent: string | null,\n    ancestors: string[],\n    depth: number,\n    inArray: boolean,\n    last: boolean,\n    position: number,\n    setSize: number,\n  ) => {\n    const type = typeOf(value, stack);\n    const container = type === \"object\" || type === \"array\";\n    const entries = container ? entriesOf(value, type, options.sortKeys) : [];\n    const expanded = container && entries.length > 0 && options.isExpanded(path, depth);\n    rows.push({\n      kind: \"node\",\n      id: path,\n      path,\n      parent,\n      ancestors,\n      depth,\n      key,\n      inArray,\n      type,\n      value,\n      size: entries.length,\n      expanded,\n      last,\n      position,\n      setSize,\n      hidden: 0,\n    });\n    if (!expanded) return;\n    stack.add(value as object);\n    const limit = Math.max(options.pageSize, options.limits.get(path) ?? 0);\n    const shown = Math.min(entries.length, limit);\n    const childAncestors = [...ancestors, path];\n    for (let index = 0; index < shown; index++) {\n      const [childKey, child] = entries[index];\n      visit(\n        child,\n        childKey,\n        jsonChildPath(path, childKey, type === \"array\"),\n        path,\n        childAncestors,\n        depth + 1,\n        type === \"array\",\n        index === entries.length - 1,\n        index + 1,\n        entries.length,\n      );\n    }\n    if (shown < entries.length)\n      rows.push({\n        kind: \"more\",\n        id: `${path}\\u0000more`,\n        path,\n        parent: path,\n        ancestors: childAncestors,\n        depth: depth + 1,\n        key: null,\n        inArray: type === \"array\",\n        type,\n        value,\n        size: entries.length,\n        expanded: false,\n        last: true,\n        position: shown + 1,\n        setSize: entries.length,\n        hidden: entries.length - shown,\n      });\n    stack.delete(value as object);\n    rows.push({\n      kind: \"close\",\n      id: `${path}\\u0000close`,\n      path,\n      parent,\n      ancestors,\n      depth,\n      key: null,\n      inArray,\n      type,\n      value,\n      size: entries.length,\n      expanded: true,\n      last,\n      position,\n      setSize,\n      hidden: 0,\n    });\n  };\n  visit(data, rootName ?? null, rootPath, null, [], 0, false, true, 1, 1);\n  return rows;\n}\n\ninterface Match {\n  path: string;\n  /** Each ancestor container with the index of the next step inside it. */\n  chain: { path: string; depth: number; index: number }[];\n}\n\nconst MAX_SEARCH_NODES = 50_000;\n\nfunction findMatches(data: unknown, rootPath: string, rootName: string | undefined, query: string, sortKeys: JsonViewerProps[\"sortKeys\"]) {\n  const matches: Match[] = [];\n  if (!query) return matches;\n  const stack = new Set<object>();\n  let visited = 0;\n  const visit = (value: unknown, key: string | number | null, path: string, depth: number, chain: Match[\"chain\"]) => {\n    if (++visited > MAX_SEARCH_NODES) return;\n    const type = typeOf(value, stack);\n    const keyHit = typeof key === \"string\" && key.toLowerCase().includes(query);\n    const container = type === \"object\" || type === \"array\";\n    const valueHit = !container && displayText(value, type).toLowerCase().includes(query);\n    if (keyHit || valueHit) matches.push({ path, chain });\n    if (!container) return;\n    stack.add(value as object);\n    entriesOf(value, type, sortKeys).forEach(([childKey, child], index) =>\n      visit(child, childKey, jsonChildPath(path, childKey, type === \"array\"), depth + 1, [\n        ...chain,\n        { path, depth, index },\n      ]),\n    );\n    stack.delete(value as object);\n  };\n  visit(data, rootName ?? null, rootPath, 0, []);\n  return matches;\n}\n\nfunction collectContainers(\n  data: unknown,\n  rootPath: string,\n  sortKeys: JsonViewerProps[\"sortKeys\"],\n  include: (path: string, depth: number) => boolean,\n) {\n  const paths: string[] = [];\n  const stack = new Set<object>();\n  let visited = 0;\n  const visit = (value: unknown, path: string, depth: number) => {\n    if (++visited > MAX_SEARCH_NODES) return;\n    const type = typeOf(value, stack);\n    if (type !== \"object\" && type !== \"array\") return;\n    if (include(path, depth)) paths.push(path);\n    stack.add(value as object);\n    for (const [key, child] of entriesOf(value, type, sortKeys))\n      visit(child, jsonChildPath(path, key, type === \"array\"), depth + 1);\n    stack.delete(value as object);\n  };\n  visit(data, rootPath, 0);\n  return paths;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Pieces\n * -----------------------------------------------------------------------------------------------*/\n\nconst styles = `@keyframes json-viewer-sweep{from{background-size:0% 100%}to{background-size:100% 100%}}`;\n\nconst markBase =\n  \"rounded-[3px] bg-no-repeat text-inherit [background-position:left] motion-safe:animate-[json-viewer-sweep_520ms_cubic-bezier(0.22,1,0.36,1)_both]\";\nconst markIdle =\n  \"bg-transparent [background-image:linear-gradient(color-mix(in_oklab,var(--color-amber-400)_38%,transparent),color-mix(in_oklab,var(--color-amber-400)_38%,transparent))] dark:[background-image:linear-gradient(color-mix(in_oklab,var(--color-amber-400)_30%,transparent),color-mix(in_oklab,var(--color-amber-400)_30%,transparent))]\";\nconst markCurrent =\n  \"bg-transparent text-foreground shadow-[0_0_0_1px_color-mix(in_oklab,var(--color-amber-500)_70%,transparent)] [background-image:linear-gradient(color-mix(in_oklab,var(--color-amber-400)_75%,transparent),color-mix(in_oklab,var(--color-amber-400)_75%,transparent))] dark:[background-image:linear-gradient(color-mix(in_oklab,var(--color-amber-400)_55%,transparent),color-mix(in_oklab,var(--color-amber-400)_55%,transparent))]\";\n\nfunction highlight(text: string, query: string, current: boolean): React.ReactNode {\n  if (!query) return text;\n  const lower = text.toLowerCase();\n  let at = lower.indexOf(query);\n  if (at === -1) return text;\n  const parts: React.ReactNode[] = [];\n  let from = 0;\n  while (at !== -1) {\n    if (at > from) parts.push(text.slice(from, at));\n    parts.push(\n      <mark key={at} className={cn(markBase, current ? markCurrent : markIdle)}>\n        {text.slice(at, at + query.length)}\n      </mark>,\n    );\n    from = at + query.length;\n    at = lower.indexOf(query, from);\n  }\n  if (from < text.length) parts.push(text.slice(from));\n  return parts;\n}\n\nconst PAD = 10;\nconst INDENT = 16;\n\nconst typeClass: Partial<Record<JsonValueType, string>> = {\n  string: \"text-[color-mix(in_oklab,var(--color-chart-2)_70%,var(--color-foreground))]\",\n  date: \"text-[color-mix(in_oklab,var(--color-chart-2)_70%,var(--color-foreground))]\",\n  number: \"text-chart-1\",\n  bigint: \"text-chart-1\",\n  boolean: \"text-[color-mix(in_oklab,var(--color-chart-4)_70%,var(--color-foreground))]\",\n  null: \"text-muted-foreground italic\",\n  undefined: \"text-muted-foreground italic\",\n  function: \"text-muted-foreground italic\",\n  symbol: \"text-muted-foreground italic\",\n  circular: \"text-muted-foreground italic\",\n};\n\nfunction Guides({ row, activeContainer }: { row: Row; activeContainer: string | null }) {\n  return row.ancestors.map((ancestor, level) => (\n    <span\n      key={level}\n      aria-hidden=\"true\"\n      className={cn(\n        \"pointer-events-none absolute inset-y-0 w-px transition-colors duration-150 motion-reduce:transition-none\",\n        ancestor === activeContainer ? \"bg-foreground/22\" : \"bg-border/80\",\n      )}\n      style={{ left: PAD + level * INDENT + 7.5 }}\n    />\n  ));\n}\n\n/* -------------------------------------------------------------------------------------------------\n * JsonViewer\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * A collapsible, searchable JSON tree for payloads, logs and trace attributes, with indent guides,\n * typed colors, copyable paths and full tree keyboard support.\n */\nexport function JsonViewer({\n  data,\n  rootName,\n  title,\n  description,\n  defaultExpandDepth = 2,\n  expanded: expandedProp,\n  defaultExpanded,\n  onExpandedChange,\n  showSearch = true,\n  search: searchProp,\n  defaultSearch = \"\",\n  onSearchChange,\n  maxStringLength = 120,\n  pageSize = 100,\n  sortKeys,\n  selectedPath: selectedProp,\n  defaultSelectedPath = null,\n  onSelect,\n  renderValue,\n  copyable = true,\n  onCopy,\n  showToolbar = true,\n  showStatusBar = true,\n  actions,\n  maxHeight,\n  formatDate = defaultDateFormat,\n  labels: labelsProp,\n  className,\n  onKeyDown,\n  ...props\n}: JsonViewerProps) {\n  const labels = { ...LABELS, ...labelsProp };\n  const id = React.useId();\n  const mounted = useMounted();\n  const rootPath = rootName ?? \"\";\n\n  // Expansion: controlled as a set of paths, or uncontrolled as a base rule plus overrides.\n  const controlled = React.useMemo(\n    () => (expandedProp ? new Set<string>(expandedProp) : null),\n    [expandedProp],\n  );\n  const [expansion, setExpansion] = React.useState<{\n    base: \"depth\" | \"all\" | \"none\";\n    overrides: ReadonlyMap<string, boolean>;\n  }>(() =>\n    defaultExpanded\n      ? { base: \"none\", overrides: new Map(defaultExpanded.map((path) => [path, true])) }\n      : { base: \"depth\", overrides: new Map() },\n  );\n  const ruleFor = React.useCallback(\n    (state: typeof expansion) => (path: string, depth: number) =>\n      state.overrides.get(path) ??\n      (state.base === \"all\" || (state.base === \"depth\" && depth < defaultExpandDepth)),\n    [defaultExpandDepth],\n  );\n  const isExpanded = React.useMemo(\n    () => (controlled ? (path: string) => controlled.has(path) : ruleFor(expansion)),\n    [controlled, expansion, ruleFor],\n  );\n\n  const commitExpansion = (next: typeof expansion) => {\n    setExpansion(next);\n    onExpandedChange?.(collectContainers(data, rootPath, sortKeys, ruleFor(next)));\n  };\n  const setPaths = (paths: { path: string; depth: number }[], value: boolean) => {\n    const changed = paths.filter(({ path, depth }) => isExpanded(path, depth) !== value);\n    if (!changed.length) return;\n    if (controlled) {\n      const next = new Set(controlled);\n      for (const { path } of changed) {\n        if (value) next.add(path);\n        else next.delete(path);\n      }\n      onExpandedChange?.([...next]);\n      return;\n    }\n    const overrides = new Map(expansion.overrides);\n    for (const { path } of changed) overrides.set(path, value);\n    commitExpansion({ base: expansion.base, overrides });\n  };\n  const expandAll = () => {\n    if (controlled) onExpandedChange?.(collectContainers(data, rootPath, sortKeys, () => true));\n    else commitExpansion({ base: \"all\", overrides: new Map() });\n  };\n  const collapseAll = () => {\n    if (controlled) onExpandedChange?.([rootPath]);\n    else commitExpansion({ base: \"none\", overrides: new Map([[rootPath, true]]) });\n  };\n\n  // Pagination per container, and full strings.\n  const [limits, setLimits] = React.useState<ReadonlyMap<string, number>>(() => new Map());\n  const [fullStrings, setFullStrings] = React.useState<ReadonlySet<string>>(() => new Set());\n\n  // Search\n  const [searchState, setSearchState] = React.useState(defaultSearch);\n  const search = searchProp ?? searchState;\n  const setSearch = (next: string) => {\n    if (searchProp === undefined) setSearchState(next);\n    onSearchChange?.(next);\n  };\n  const deferredSearch = React.useDeferredValue(search);\n  const query = deferredSearch.trim().toLowerCase();\n  const matches = React.useMemo(\n    () => findMatches(data, rootPath, rootName, query, sortKeys),\n    [data, rootPath, rootName, query, sortKeys],\n  );\n  const matchSet = React.useMemo(() => new Set(matches.map((match) => match.path)), [matches]);\n  const [current, setCurrent] = React.useState(0);\n  const currentMatch = matches[Math.min(current, matches.length - 1)];\n\n  // Selection and roving focus\n  const [selectedState, setSelectedState] = React.useState<string | null>(defaultSelectedPath);\n  const selected = selectedProp !== undefined ? selectedProp : selectedState;\n  const [activeId, setActiveId] = React.useState<string | null>(null);\n\n  const rows = React.useMemo(\n    () => flatten(data, rootPath, rootName, { isExpanded, limits, pageSize, sortKeys }),\n    [data, rootPath, rootName, isExpanded, limits, pageSize, sortKeys],\n  );\n  const navigable = React.useMemo(() => rows.filter((row) => row.kind !== \"close\"), [rows]);\n  const active = navigable.find((row) => row.id === activeId) ?? null;\n  const tabStop = active?.id ?? navigable[0]?.id;\n  const activeContainer = active\n    ? active.kind === \"node\" && active.expanded\n      ? active.path\n      : active.parent\n    : null;\n\n  const treeRef = React.useRef<HTMLDivElement>(null);\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const searchRef = React.useRef<HTMLInputElement>(null);\n  const rowRefs = React.useRef(new Map<string, HTMLDivElement>());\n  const [focusRequest, setFocusRequest] = React.useState<{ id: string; tick: number } | null>(null);\n  const [scrollRequest, setScrollRequest] = React.useState<{ id: string; tick: number } | null>(null);\n  const scrollOnResults = React.useRef(false);\n\n  useIsoLayoutEffect(() => {\n    if (!focusRequest) return;\n    rowRefs.current.get(focusRequest.id)?.focus();\n  }, [focusRequest]);\n\n  useIsoLayoutEffect(() => {\n    if (!scrollRequest) return;\n    const element = rowRefs.current.get(scrollRequest.id);\n    const container = scrollRef.current;\n    if (!element || !container) return;\n    if (container.scrollHeight > container.clientHeight + 1) {\n      const top = element.offsetTop - container.offsetTop;\n      const bottom = top + element.offsetHeight;\n      if (top < container.scrollTop + 8 || bottom > container.scrollTop + container.clientHeight - 8)\n        container.scrollTop = Math.max(0, top - container.clientHeight / 2 + element.offsetHeight / 2);\n    } else element.scrollIntoView({ block: \"nearest\" });\n  }, [scrollRequest]);\n\n  const reveal = (match: Match) => {\n    setPaths(\n      match.chain.filter(({ path, depth }) => !isExpanded(path, depth)).map(({ path, depth }) => ({ path, depth })),\n      true,\n    );\n    const raise = match.chain.filter(\n      ({ path, index }) => index >= Math.max(pageSize, limits.get(path) ?? 0),\n    );\n    if (raise.length)\n      setLimits((currentLimits) => {\n        const next = new Map(currentLimits);\n        for (const { path, index } of raise)\n          next.set(path, Math.ceil((index + 1) / pageSize) * pageSize);\n        return next;\n      });\n    setActiveId(match.path);\n    setScrollRequest({ id: match.path, tick: Date.now() });\n  };\n\n  // Open the ancestors of every match when the query changes.\n  const matchKey = matches.map((match) => match.path).join(\"\\n\");\n  useIsoLayoutEffect(() => {\n    setCurrent(0);\n    if (!matches.length) return;\n    const needed = new Map<string, number>();\n    for (const match of matches)\n      for (const { path, depth } of match.chain) if (!isExpanded(path, depth)) needed.set(path, depth);\n    if (needed.size) setPaths([...needed].map(([path, depth]) => ({ path, depth })), true);\n    if (scrollOnResults.current) {\n      scrollOnResults.current = false;\n      reveal(matches[0]);\n    }\n  }, [matchKey]);\n\n  const goToMatch = (direction: 1 | -1) => {\n    if (!matches.length) return;\n    const next = (Math.min(current, matches.length - 1) + direction + matches.length) % matches.length;\n    setCurrent(next);\n    reveal(matches[next]);\n  };\n\n  // Copying\n  const [copied, setCopied] = React.useState<string | null>(null);\n  React.useEffect(() => {\n    if (!copied) return;\n    const timer = window.setTimeout(() => setCopied(null), 1400);\n    return () => window.clearTimeout(timer);\n  }, [copied]);\n  const copy = async (text: string, kind: JsonCopyKind, path: string) => {\n    if (onCopy) onCopy(text, { kind, path });\n    else if (!(await writeClipboard(text))) return;\n    setCopied(`${kind}:${path}`);\n  };\n\n  const json = React.useMemo(() => toJsonString(data), [data]);\n  const bytes = React.useMemo(() => new TextEncoder().encode(json).length, [json]);\n\n  const select = (row: Row) => {\n    if (row.kind !== \"node\") return;\n    if (selectedProp === undefined) setSelectedState(row.path);\n    onSelect?.(row.path, row.value);\n  };\n  const toggle = (row: Row) => {\n    if (row.kind !== \"node\" || !row.size) return;\n    setPaths([{ path: row.path, depth: row.depth }], !row.expanded);\n  };\n  const showMore = (row: Row) => {\n    setLimits((currentLimits) => {\n      const next = new Map(currentLimits);\n      next.set(row.path, Math.max(pageSize, currentLimits.get(row.path) ?? 0) + pageSize);\n      return next;\n    });\n  };\n  const moveTo = (row: Row | undefined) => {\n    if (!row) return;\n    setActiveId(row.id);\n    setFocusRequest({ id: row.id, tick: Date.now() });\n  };\n\n  const handleTreeKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (event.target instanceof HTMLButtonElement || event.target instanceof HTMLAnchorElement) {\n      if (event.key !== \"ArrowUp\" && event.key !== \"ArrowDown\") return;\n    }\n    const index = navigable.findIndex((row) => row.id === (active?.id ?? tabStop));\n    const row = navigable[index];\n    if (!row) return;\n    const mod = event.metaKey || event.ctrlKey;\n    let handled = true;\n    switch (event.key) {\n      case \"ArrowDown\":\n        moveTo(navigable[Math.min(index + 1, navigable.length - 1)]);\n        break;\n      case \"ArrowUp\":\n        moveTo(navigable[Math.max(index - 1, 0)]);\n        break;\n      case \"PageDown\":\n        moveTo(navigable[Math.min(index + 10, navigable.length - 1)]);\n        break;\n      case \"PageUp\":\n        moveTo(navigable[Math.max(index - 10, 0)]);\n        break;\n      case \"Home\":\n        moveTo(navigable[0]);\n        break;\n      case \"End\":\n        moveTo(navigable[navigable.length - 1]);\n        break;\n      case \"ArrowRight\":\n        if (row.kind === \"node\" && row.size) {\n          if (!row.expanded) toggle(row);\n          else moveTo(navigable[index + 1]);\n        }\n        break;\n      case \"ArrowLeft\":\n        if (row.kind === \"node\" && row.expanded) toggle(row);\n        else if (row.parent !== null) moveTo(navigable.find((item) => item.id === row.parent));\n        break;\n      case \"Enter\":\n        if (row.kind === \"more\") showMore(row);\n        else if (row.size) toggle(row);\n        else select(row);\n        break;\n      case \" \":\n        if (row.kind === \"more\") showMore(row);\n        else select(row);\n        break;\n      case \"*\": {\n        const siblings = navigable.filter(\n          (item) => item.kind === \"node\" && item.parent === row.parent && item.size && !item.expanded,\n        );\n        setPaths(siblings.map((item) => ({ path: item.path, depth: item.depth })), true);\n        break;\n      }\n      case \"/\":\n        if (showSearch) searchRef.current?.focus();\n        else handled = false;\n        break;\n      default:\n        if (mod && (event.key === \"c\" || event.key === \"C\") && copyable && row.kind === \"node\") {\n          if (window.getSelection()?.toString()) {\n            handled = false;\n            break;\n          }\n          void copy(copyText(row.value, row.type), \"value\", row.path);\n        } else handled = false;\n    }\n    if (handled) {\n      event.preventDefault();\n      event.stopPropagation();\n    }\n  };\n\n  /* --------------------------------- Row rendering --------------------------------- */\n\n  const renderLeaf = (row: Row, isCurrent: boolean) => {\n    const custom = renderValue?.(row.value, row.path);\n    if (custom !== undefined) return custom;\n    const text = displayText(row.value, row.type);\n    if (row.type === \"string\") {\n      const raw = row.value as string;\n      const full = fullStrings.has(row.path);\n      const hitAt = query ? text.toLowerCase().indexOf(query) : -1;\n      const long = text.length > maxStringLength;\n      const cut = long && !full && !(hitAt >= maxStringLength - query.length);\n      const shown = cut ? text.slice(0, maxStringLength) : text;\n      const isUrl = URL_VALUE.test(raw);\n      const isDate = !isUrl && ISO_DATE.test(raw) && !Number.isNaN(Date.parse(raw));\n      const body = highlight(shown, query, isCurrent);\n      return (\n        <>\n          <span className={typeClass.string}>\n            <span className=\"opacity-55\">\"</span>\n            {isUrl ? (\n              <a\n                href={raw}\n                target=\"_blank\"\n                rel=\"noreferrer\"\n                tabIndex={-1}\n                onClick={(event) => event.stopPropagation()}\n                className=\"underline decoration-current/35 underline-offset-[3px] transition-[text-decoration-color] hover:decoration-current\"\n              >\n                {body}\n              </a>\n            ) : isDate ? (\n              <span className=\"underline decoration-current/30 decoration-dotted underline-offset-[3px]\">{body}</span>\n            ) : (\n              body\n            )}\n            {cut && <span className=\"opacity-55\">…</span>}\n            <span className=\"opacity-55\">\"</span>\n          </span>\n          {isDate && mounted && (\n            <span\n              data-slot=\"json-viewer-hint\"\n              className=\"ml-2 hidden font-sans text-[11px] whitespace-nowrap text-muted-foreground group-hover/row:inline group-data-[active=true]/row:inline\"\n            >\n              {formatDate(new Date(raw))}\n            </span>\n          )}\n          {long && (\n            <button\n              type=\"button\"\n              tabIndex={-1}\n              onClick={(event) => {\n                event.stopPropagation();\n                setFullStrings((currentSet) => {\n                  const next = new Set(currentSet);\n                  if (!next.delete(row.path)) next.add(row.path);\n                  return next;\n                });\n              }}\n              aria-label={full ? labels.showLess : `${labels.showMore}, ${labels.characters(text.length - maxStringLength)}`}\n              className=\"ml-1.5 inline-flex h-[18px] translate-y-[-1px] items-center rounded-md bg-muted px-1.5 align-middle font-sans text-[11px] font-medium text-muted-foreground transition-colors hover:bg-primary/10 hover:text-primary\"\n            >\n              {full ? labels.showLess : `${labels.showMore} · ${(text.length - maxStringLength).toLocaleString()}`}\n            </button>\n          )}\n        </>\n      );\n    }\n    if (row.type === \"date\") {\n      const date = row.value as Date;\n      return (\n        <>\n          <span className={cn(typeClass.date, \"underline decoration-current/30 decoration-dotted underline-offset-[3px]\")}>\n            {highlight(text, query, isCurrent)}\n          </span>\n          {mounted && !Number.isNaN(date.getTime()) && (\n            <span className=\"ml-2 hidden font-sans text-[11px] text-muted-foreground group-hover/row:inline group-data-[active=true]/row:inline\">\n              {formatDate(date)}\n            </span>\n          )}\n        </>\n      );\n    }\n    return (\n      <span className={cn(typeClass[row.type], (row.type === \"number\" || row.type === \"bigint\") && \"tabular-nums\")}>\n        {highlight(text, query, isCurrent)}\n      </span>\n    );\n  };\n\n  const renderRow = (row: Row) => {\n    const indent = PAD + row.depth * INDENT;\n    if (row.kind === \"close\") {\n      return (\n        <div\n          key={row.id}\n          aria-hidden=\"true\"\n          className=\"relative flex min-h-[22px] items-start pr-3\"\n          style={{ paddingLeft: indent }}\n        >\n          <Guides row={row} activeContainer={activeContainer} />\n          <span className=\"w-4 shrink-0\" />\n          <span className=\"text-muted-foreground/70\">\n            {row.type === \"array\" ? \"]\" : \"}\"}\n            {!row.last && \",\"}\n          </span>\n        </div>\n      );\n    }\n\n    const isActive = row.id === tabStop;\n    if (row.kind === \"more\") {\n      return (\n        <div\n          key={row.id}\n          ref={(node) => {\n            if (node) rowRefs.current.set(row.id, node);\n            else rowRefs.current.delete(row.id);\n          }}\n          role=\"treeitem\"\n          aria-level={row.depth + 1}\n          aria-posinset={row.position}\n          aria-setsize={row.setSize}\n          aria-label={`${labels.showMoreItems(Math.min(pageSize, row.hidden))}, ${labels.hiddenItems(row.hidden)}`}\n          tabIndex={isActive ? 0 : -1}\n          data-slot=\"json-viewer-more\"\n          data-active={isActive && activeId !== null ? true : undefined}\n          onFocus={() => setActiveId(row.id)}\n          onClick={() => showMore(row)}\n          className={cn(\n            \"group/row relative flex min-h-[26px] cursor-pointer items-center pr-3 outline-none\",\n            \"focus-visible:bg-primary/[0.05] focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-inset\",\n          )}\n          style={{ paddingLeft: indent }}\n        >\n          <Guides row={row} activeContainer={activeContainer} />\n          <span className=\"w-4 shrink-0\" />\n          <span className=\"inline-flex items-center gap-2 font-sans text-xs\">\n            <span className=\"rounded-md bg-muted px-1.5 py-px font-medium text-foreground/80 transition-colors group-hover/row:bg-primary/10 group-hover/row:text-primary\">\n              {labels.showMoreItems(Math.min(pageSize, row.hidden))}\n            </span>\n            <span className=\"text-muted-foreground tabular-nums\">{labels.hiddenItems(row.hidden)}</span>\n          </span>\n        </div>\n      );\n    }\n\n    const container = row.type === \"object\" || row.type === \"array\";\n    const isMatch = matchSet.has(row.path);\n    const isCurrent = isMatch && currentMatch?.path === row.path;\n    const isSelected = selected === row.path;\n    const keyText = row.key === null ? null : String(row.key);\n    const keyHighlighted = typeof row.key === \"string\" && keyText !== null ? highlight(keyText, query, isCurrent) : keyText;\n    const count = row.type === \"array\" ? labels.items(row.size) : labels.keys(row.size);\n    const open = row.type === \"array\" ? \"[\" : \"{\";\n    const close = row.type === \"array\" ? \"]\" : \"}\";\n    const copiedValue = copied === `value:${row.path}`;\n    const copiedPath = copied === `path:${row.path}`;\n\n    return (\n      <div\n        key={row.id}\n        ref={(node) => {\n          if (node) rowRefs.current.set(row.id, node);\n          else rowRefs.current.delete(row.id);\n        }}\n        role=\"treeitem\"\n        aria-level={row.depth + 1}\n        aria-posinset={row.position}\n        aria-setsize={row.setSize}\n        aria-expanded={container && row.size ? row.expanded : undefined}\n        aria-selected={isSelected}\n        aria-label={container ? `${keyText ?? labels.root}, ${count}` : undefined}\n        tabIndex={isActive ? 0 : -1}\n        data-slot=\"json-viewer-node\"\n        data-type={row.type}\n        data-path={row.path}\n        data-match={isMatch ? (isCurrent ? \"current\" : \"true\") : undefined}\n        data-selected={isSelected || undefined}\n        data-active={isActive && activeId !== null ? true : undefined}\n        onFocus={() => setActiveId(row.id)}\n        onClick={() => {\n          if (window.getSelection()?.toString()) return;\n          setActiveId(row.id);\n          select(row);\n          if (container) toggle(row);\n        }}\n        className={cn(\n          \"group/row relative flex min-h-[22px] cursor-default items-start pr-3 outline-none\",\n          \"hover:bg-muted/45 focus-visible:bg-primary/[0.05] focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-inset\",\n          isSelected &&\n            \"bg-primary/[0.07] hover:bg-primary/[0.09] before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-primary\",\n          isCurrent && !isSelected && \"bg-amber-400/[0.08]\",\n        )}\n        style={{ paddingLeft: indent }}\n      >\n        <Guides row={row} activeContainer={activeContainer} />\n        <span aria-hidden=\"true\" className=\"flex h-[22px] w-4 shrink-0 items-center justify-center\">\n          {container && row.size > 0 && (\n            <ChevronRight\n              className={cn(\n                \"size-3.5 text-muted-foreground/80 transition-transform duration-150 ease-[cubic-bezier(0.22,1,0.36,1)] group-hover/row:text-foreground motion-reduce:transition-none\",\n                row.expanded && \"rotate-90\",\n              )}\n              stroke={2}\n            />\n          )}\n        </span>\n        <span className=\"min-w-0 flex-1 [overflow-wrap:anywhere]\">\n          {keyText !== null && (\n            <>\n              <span\n                className={cn(\n                  row.inArray ? \"text-muted-foreground/75 tabular-nums\" : \"text-foreground\",\n                  row.depth === 0 && \"font-semibold\",\n                )}\n              >\n                {keyHighlighted}\n              </span>\n              <span className=\"text-muted-foreground/60\">: </span>\n            </>\n          )}\n          {container ? (\n            row.expanded ? (\n              <>\n                <span className=\"text-muted-foreground/70\">{open}</span>\n                {row.type === \"array\" && (\n                  <span className=\"ml-2 font-sans text-[11px] text-muted-foreground tabular-nums\">{count}</span>\n                )}\n              </>\n            ) : (\n              <>\n                <span className=\"text-muted-foreground/70\">{open}</span>\n                {row.size > 0 && (\n                  <span className=\"mx-px rounded-[4px] bg-muted px-1 text-muted-foreground transition-colors group-hover/row:bg-primary/10 group-hover/row:text-primary\">\n                    …\n                  </span>\n                )}\n                <span className=\"text-muted-foreground/70\">\n                  {close}\n                  {!row.last && \",\"}\n                </span>\n                <span className=\"ml-2 font-sans text-[11px] text-muted-foreground tabular-nums\">{count}</span>\n              </>\n            )\n          ) : (\n            <>\n              {renderLeaf(row, isCurrent)}\n              {!row.last && <span className=\"text-muted-foreground/70\">,</span>}\n            </>\n          )}\n        </span>\n        {copyable && (\n          <span\n            data-slot=\"json-viewer-row-actions\"\n            className=\"absolute top-[2px] right-1.5 hidden items-center gap-px rounded-lg border border-border/70 bg-popover/90 p-px shadow-sm backdrop-blur-md group-hover/row:flex group-focus-visible/row:flex\"\n          >\n            {row.path && (\n              <button\n                type=\"button\"\n                tabIndex={-1}\n                aria-label={`${labels.copyPath} ${row.path}`}\n                title={labels.copyPath}\n                onClick={(event) => {\n                  event.stopPropagation();\n                  void copy(row.path, \"path\", row.path);\n                }}\n                className=\"inline-flex size-[18px] items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground\"\n              >\n                {copiedPath ? (\n                  <Check className=\"size-3 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n                ) : (\n                  <Route className=\"size-3\" aria-hidden=\"true\" />\n                )}\n              </button>\n            )}\n            <button\n              type=\"button\"\n              tabIndex={-1}\n              aria-label={labels.copyValue}\n              title={labels.copyValue}\n              onClick={(event) => {\n                event.stopPropagation();\n                void copy(copyText(row.value, row.type), \"value\", row.path);\n              }}\n              className=\"inline-flex size-[18px] items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground\"\n            >\n              {copiedValue ? (\n                <Check className=\"size-3 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n              ) : (\n                <Copy className=\"size-3\" aria-hidden=\"true\" />\n              )}\n            </button>\n          </span>\n        )}\n      </div>\n    );\n  };\n\n  /* --------------------------------- Layout --------------------------------- */\n\n  const iconButton = cn(\n    \"inline-flex h-7 min-w-7 items-center justify-center gap-1.5 rounded-md px-1.5 text-xs font-medium text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none\",\n    focusRing,\n  );\n  const toolbarActions = (showToolbar || actions) && (\n    <div className=\"flex shrink-0 items-center gap-0.5\">\n      {actions}\n      {showToolbar && (\n        <>\n          <button type=\"button\" onClick={expandAll} aria-label={labels.expandAll} title={labels.expandAll} className={iconButton}>\n            <FoldDown className=\"size-4\" aria-hidden=\"true\" stroke={1.75} />\n          </button>\n          <button type=\"button\" onClick={collapseAll} aria-label={labels.collapseAll} title={labels.collapseAll} className={iconButton}>\n            <FoldUp className=\"size-4\" aria-hidden=\"true\" stroke={1.75} />\n          </button>\n          {copyable && (\n            <button\n              type=\"button\"\n              onClick={() => void copy(json, \"json\", rootPath)}\n              aria-label={copied === `json:${rootPath}` ? labels.copied : labels.copyJson}\n              title={labels.copyJson}\n              className={iconButton}\n            >\n              {copied === `json:${rootPath}` ? (\n                <Check className=\"size-4 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n              ) : (\n                <Copy className=\"size-4\" aria-hidden=\"true\" stroke={1.75} />\n              )}\n              <span className=\"hidden @md/json:inline\">\n                {copied === `json:${rootPath}` ? labels.copied : labels.copyJson}\n              </span>\n            </button>\n          )}\n        </>\n      )}\n    </div>\n  );\n\n  const searchField = showSearch && (\n    <div\n      data-slot=\"json-viewer-search\"\n      className={cn(\n        \"flex h-8 min-w-0 flex-1 items-center gap-1.5 rounded-lg bg-muted/50 pr-1 pl-2.5 ring-1 ring-border/60 transition-[box-shadow,background-color] duration-150 ring-inset focus-within:bg-card focus-within:ring-2 focus-within:ring-primary/30 focus-within:shadow-[0_0_14px_-4px_color-mix(in_oklab,var(--color-primary)_45%,transparent)] motion-reduce:transition-none\",\n      )}\n    >\n      <Search className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n      <input\n        ref={searchRef}\n        type=\"text\"\n        value={search}\n        spellCheck={false}\n        autoComplete=\"off\"\n        aria-label={labels.search}\n        aria-controls={`${id}-tree`}\n        placeholder={labels.search}\n        onChange={(event) => {\n          scrollOnResults.current = true;\n          setSearch(event.target.value);\n        }}\n        onKeyDown={(event) => {\n          if (event.key === \"Enter\") {\n            event.preventDefault();\n            goToMatch(event.shiftKey ? -1 : 1);\n          } else if (event.key === \"Escape\" && search) {\n            event.preventDefault();\n            setSearch(\"\");\n          } else if (event.key === \"ArrowDown\" && currentMatch) {\n            event.preventDefault();\n            reveal(currentMatch);\n            setFocusRequest({ id: currentMatch.path, tick: Date.now() });\n          }\n        }}\n        className=\"h-full min-w-0 flex-1 bg-transparent text-[13px] text-foreground outline-none placeholder:text-muted-foreground\"\n      />\n      {query && (\n        <>\n          <span\n            aria-live=\"polite\"\n            className={cn(\n              \"shrink-0 px-1 text-xs whitespace-nowrap tabular-nums\",\n              matches.length ? \"text-muted-foreground\" : \"text-destructive\",\n            )}\n          >\n            {matches.length\n              ? labels.matchCount(Math.min(current, matches.length - 1) + 1, matches.length)\n              : labels.noMatches}\n          </span>\n          <span className=\"flex shrink-0 items-center\">\n            <button\n              type=\"button\"\n              onClick={() => goToMatch(-1)}\n              disabled={!matches.length}\n              aria-label={labels.previousMatch}\n              title={`${labels.previousMatch} (Shift+Enter)`}\n              className={cn(iconButton, \"h-6 min-w-6 px-0\")}\n            >\n              <ChevronUp className=\"size-3.5\" aria-hidden=\"true\" />\n            </button>\n            <button\n              type=\"button\"\n              onClick={() => goToMatch(1)}\n              disabled={!matches.length}\n              aria-label={labels.nextMatch}\n              title={`${labels.nextMatch} (Enter)`}\n              className={cn(iconButton, \"h-6 min-w-6 px-0\")}\n            >\n              <ChevronDown className=\"size-3.5\" aria-hidden=\"true\" />\n            </button>\n          </span>\n        </>\n      )}\n      {search && (\n        <button\n          type=\"button\"\n          onClick={() => {\n            setSearch(\"\");\n            searchRef.current?.focus();\n          }}\n          aria-label={labels.clearSearch}\n          title={labels.clearSearch}\n          className={cn(iconButton, \"h-6 min-w-6 px-0\")}\n        >\n          <X className=\"size-3.5\" aria-hidden=\"true\" />\n        </button>\n      )}\n    </div>\n  );\n\n  const meta = (\n    <span className=\"shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums\">{formatBytes(bytes)}</span>\n  );\n  // The status bar follows focus, then the selection, then the root.\n  const status =\n    (active?.kind === \"node\" ? active : null) ??\n    navigable.find((row) => row.kind === \"node\" && row.path === selected) ??\n    navigable[0] ??\n    null;\n  const statusType = status\n    ? status.type === \"object\"\n      ? labels.keys(status.size)\n      : status.type === \"array\"\n        ? labels.items(status.size)\n        : status.type === \"string\"\n          ? labels.characters((status.value as string).length)\n          : status.type\n    : null;\n\n  return (\n    <div\n      data-slot=\"json-viewer\"\n      className={cn(\n        \"@container/json flex min-w-0 flex-col overflow-hidden rounded-2xl border border-border/70 bg-card text-card-foreground shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\",\n        className,\n      )}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        const target = event.target as HTMLElement;\n        if (\n          event.key === \"/\" &&\n          showSearch &&\n          !event.defaultPrevented &&\n          !(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement)\n        ) {\n          event.preventDefault();\n          searchRef.current?.focus();\n        }\n      }}\n      {...props}\n    >\n      <style href=\"overtrue-json-viewer\" precedence=\"default\">\n        {styles}\n      </style>\n\n      {(title || description) && (\n        <div className=\"flex items-start gap-3 px-4 pt-3.5 pb-2.5\">\n          <div className=\"min-w-0 flex-1\">\n            <div className=\"flex min-w-0 items-baseline gap-2\">\n              {title && <p className=\"truncate text-sm leading-6 font-semibold tracking-tight\">{title}</p>}\n              {meta}\n            </div>\n            {description && <p className=\"truncate text-[13px] leading-5 text-muted-foreground\">{description}</p>}\n          </div>\n          {toolbarActions}\n        </div>\n      )}\n      {(showSearch || (!title && !description && (showToolbar || actions))) && (\n        <div\n          data-slot=\"json-viewer-toolbar\"\n          className={cn(\"flex items-center gap-2 px-3 pb-3\", title || description ? \"pt-0\" : \"pt-3\")}\n        >\n          {searchField || <span className=\"flex-1 pl-1\">{meta}</span>}\n          {!(title || description) && toolbarActions}\n        </div>\n      )}\n\n      <div\n        ref={scrollRef}\n        className=\"relative min-h-0 flex-1 overflow-auto border-t border-border/60\"\n        style={{ maxHeight }}\n      >\n        <div\n          ref={treeRef}\n          id={`${id}-tree`}\n          role=\"tree\"\n          aria-label={typeof title === \"string\" ? title : (rootName ?? labels.tree)}\n          onKeyDown={handleTreeKeyDown}\n          data-slot=\"json-viewer-tree\"\n          className=\"min-w-0 py-2 font-mono text-[12px] leading-[22px] [font-variant-ligatures:none] @md/json:text-[13px]\"\n        >\n          {rows.map(renderRow)}\n        </div>\n      </div>\n\n      {showStatusBar && (\n        <div\n          data-slot=\"json-viewer-status\"\n          className=\"flex h-9 shrink-0 items-center gap-2 border-t border-border/60 bg-muted/25 pr-1.5 pl-3\"\n        >\n          {status ? (\n            <>\n              <span className=\"min-w-0 flex-1 truncate font-mono text-xs text-foreground/85 [font-variant-ligatures:none]\" title={status.path}>\n                {status.path || labels.root}\n              </span>\n              {statusType && (\n                <span className=\"hidden shrink-0 text-[11px] text-muted-foreground tabular-nums @sm/json:inline\">\n                  {statusType}\n                </span>\n              )}\n              {copyable && (\n                <span className=\"flex shrink-0 items-center\">\n                  {status.path && (\n                    <button\n                      type=\"button\"\n                      onClick={() => void copy(status.path, \"path\", status.path)}\n                      aria-label={copied === `path:${status.path}` ? labels.copied : labels.copyPath}\n                      className={iconButton}\n                    >\n                      {copied === `path:${status.path}` ? (\n                        <Check className=\"size-3.5 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n                      ) : (\n                        <Route className=\"size-3.5\" aria-hidden=\"true\" />\n                      )}\n                      <span className=\"hidden @md/json:inline\">{labels.copyPath}</span>\n                    </button>\n                  )}\n                  <button\n                    type=\"button\"\n                    onClick={() => void copy(copyText(status.value, status.type), \"value\", status.path)}\n                    aria-label={copied === `value:${status.path}` ? labels.copied : labels.copyValue}\n                    className={iconButton}\n                  >\n                    {copied === `value:${status.path}` ? (\n                      <Check className=\"size-3.5 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n                    ) : (\n                      <Copy className=\"size-3.5\" aria-hidden=\"true\" />\n                    )}\n                    <span className=\"hidden @md/json:inline\">{labels.copyValue}</span>\n                  </button>\n                </span>\n              )}\n            </>\n          ) : (\n            <span className=\"truncate text-xs text-muted-foreground\">{labels.statusHint}</span>\n          )}\n        </div>\n      )}\n\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {copied ? labels.copied : \"\"}\n      </span>\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/blocks/service-explorer. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
