{"spec_id":"flamegraph-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// flamegraph-basic: Flame Graph for Performance Profiling\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 84/100 | Updated: 2026-10-24\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"flamegraph-basic · javascript · muix · anyplot.ai\";\nconst DEPTH_LABEL = \"Depth\";\nconst ROOT_ROLE_LABEL = \"root\";\nconst LEGEND_LOW_PREFIX = \"fewer\";\nconst LEGEND_HIGH_PREFIX = \"more\";\n\ntype RGB = [number, number, number];\nconst hexToRgb = (hex: string): RGB => [\n  parseInt(hex.slice(1, 3), 16),\n  parseInt(hex.slice(3, 5), 16),\n  parseInt(hex.slice(5, 7), 16),\n];\n// Warm ramp: amber → ochre → matte red. The root holds every sample, so it takes the hot end.\nconst WARM_STOPS: RGB[] = [t.amber, t.palette[3], t.palette[4]].map(hexToRgb);\nconst ROOT_RGB: RGB = WARM_STOPS[WARM_STOPS.length - 1];\nconst LABEL_INKS = [\"#1A1A17\", \"#FAF8F1\"];\n\nconst ROW_H_SHARE = 0.92;\nconst LABEL_FONT_SIZE = 14;\nconst CHAR_WIDTH_RATIO = 0.58;\nconst MARGIN = { top: 150, right: 40, bottom: 28, left: 118 };\n\n// Columns: set these to your data's column names\nconst STACK = \"Stack\"; // role: stack\nconst FUNCTION = \"Function\"; // role: function\nconst SAMPLES = \"Samples\"; // role: value\n\n// Data: replace this block with your own records, e.g. folded stacks from a CPU profiler\nconst foldedStacks: [string, number][] = [\n  [\"main;parse_request;read_body;socket_recv\", 260],\n  [\"main;parse_request;read_body;buffer_append\", 120],\n  [\"main;parse_request;read_body;inflate_gzip;inflate_block\", 180],\n  [\"main;parse_request;read_body;inflate_gzip;crc32_update\", 60],\n  [\"main;parse_request;json_decode;scan_tokens;utf8_validate\", 140],\n  [\"main;parse_request;json_decode;scan_tokens;next_token\", 220],\n  [\"main;parse_request;json_decode;build_object;alloc_dict\", 110],\n  [\"main;parse_request;json_decode;build_object;intern_string\", 90],\n  [\"main;parse_request;parse_headers;split_lines\", 70],\n  [\"main;parse_request;parse_headers;normalize_header_name\", 50],\n  [\"main;parse_request;parse_query_string;url_decode\", 60],\n  [\"main;parse_request;parse_query_string;split_params\", 40],\n  [\"main;authenticate_user;verify_jwt;base64_decode\", 90],\n  [\"main;authenticate_user;verify_jwt;rsa_verify;bignum_modexp;mont_mul\", 280],\n  [\"main;authenticate_user;verify_jwt;rsa_verify;bignum_modexp;mont_reduce\", 60],\n  [\"main;authenticate_user;verify_jwt;rsa_verify;sha256_digest\", 120],\n  [\"main;authenticate_user;verify_jwt;check_claims\", 40],\n  [\"main;authenticate_user;load_session;redis_get;socket_send\", 60],\n  [\"main;authenticate_user;load_session;redis_get;socket_recv\", 140],\n  [\"main;authenticate_user;load_session;deserialize_session\", 80],\n  [\"main;authenticate_user;check_permissions;load_role_grants\", 70],\n  [\"main;authenticate_user;check_permissions;match_policy\", 50],\n  [\"main;handle_business_logic;fetch_orders;db_query;pg_send_query\", 180],\n  [\"main;handle_business_logic;fetch_orders;db_query;pg_wait_result;poll_socket;epoll_wait\", 820],\n  [\"main;handle_business_logic;fetch_orders;db_query;pg_wait_result;poll_socket;sys_futex\", 80],\n  [\"main;handle_business_logic;fetch_orders;db_query;pg_wait_result;read_packet\", 260],\n  [\"main;handle_business_logic;fetch_orders;db_query;decode_rows;parse_numeric\", 310],\n  [\"main;handle_business_logic;fetch_orders;db_query;decode_rows;parse_timestamp\", 240],\n  [\"main;handle_business_logic;fetch_orders;db_query;decode_rows;alloc_row\", 150],\n  [\"main;handle_business_logic;fetch_orders;orm_hydrate;map_columns\", 260],\n  [\"main;handle_business_logic;fetch_orders;orm_hydrate;build_relations;lazy_load_customer\", 220],\n  [\"main;handle_business_logic;fetch_orders;orm_hydrate;build_relations;lazy_load_items\", 380],\n  [\"main;handle_business_logic;compute_totals;apply_discounts;match_promo_rules\", 420],\n  [\"main;handle_business_logic;compute_totals;apply_discounts;round_currency\", 90],\n  [\"main;handle_business_logic;compute_totals;calculate_tax;lookup_tax_rate;cache_get\", 150],\n  [\"main;handle_business_logic;compute_totals;calculate_tax;lookup_tax_rate;db_query_tax\", 210],\n  [\"main;handle_business_logic;compute_totals;calculate_tax;multiply_decimal\", 130],\n  [\"main;handle_business_logic;compute_totals;sum_line_items\", 260],\n  [\"main;handle_business_logic;enrich_recommendations;load_user_history\", 340],\n  [\"main;handle_business_logic;enrich_recommendations;score_products;dot_product\", 760],\n  [\"main;handle_business_logic;enrich_recommendations;score_products;sort_candidates\", 280],\n  [\"main;handle_business_logic;enrich_recommendations;filter_in_stock\", 160],\n  [\"main;handle_business_logic;validate_order;check_inventory\", 230],\n  [\"main;handle_business_logic;validate_order;validate_address;regex_match\", 170],\n  [\"main;handle_business_logic;validate_order;validate_address;postal_lookup\", 110],\n  [\"main;write_response;render_template;compile_template\", 120],\n  [\"main;write_response;render_template;render_nodes;escape_html\", 320],\n  [\"main;write_response;render_template;render_nodes;format_currency\", 140],\n  [\"main;write_response;render_template;render_nodes;render_partial;concat_strings\", 210],\n  [\"main;write_response;render_template;render_nodes;render_partial;escape_html\", 90],\n  [\"main;write_response;json_encode;serialize_dict\", 380],\n  [\"main;write_response;json_encode;encode_string\", 240],\n  [\"main;write_response;json_encode;float_to_string\", 160],\n  [\"main;write_response;compress_gzip;deflate_block\", 460],\n  [\"main;write_response;compress_gzip;crc32_update\", 70],\n  [\"main;write_response;socket_write;tcp_send\", 180],\n  [\"main;write_response;socket_write;flush_buffer\", 60],\n  [\"main;gc_collect;mark_objects\", 220],\n  [\"main;gc_collect;sweep_heap\", 130],\n];\nconst data: Record<string, string | number>[] = foldedStacks.map(([stack, samples]) => ({\n  [STACK]: stack,\n  [FUNCTION]: stack.split(\";\").pop()!,\n  [SAMPLES]: samples,\n}));\n\n// Plot: reads only data and the constants above\ntype FrameNode = {\n  pathKey: string;\n  name: string;\n  depth: number;\n  samples: number;\n  childKeys: string[];\n};\n\nconst nodeMap = new Map<string, FrameNode>();\nconst rootKeys: string[] = [];\n\nfor (const row of data) {\n  const stackStr = String(row[STACK]);\n  const leafFn = String(row[FUNCTION]);\n  const samples = Number(row[SAMPLES]);\n  const parts = stackStr.split(\";\");\n  if (parts.length > 0 && parts[parts.length - 1] !== leafFn) {\n    parts[parts.length - 1] = leafFn;\n  }\n  let prefix = \"\";\n  for (let d = 0; d < parts.length; d++) {\n    const fn = parts[d];\n    const nextPrefix = d === 0 ? fn : `${prefix};${fn}`;\n    if (d === 0 && !rootKeys.includes(nextPrefix)) {\n      rootKeys.push(nextPrefix);\n    }\n    let node = nodeMap.get(nextPrefix);\n    if (!node) {\n      node = { pathKey: nextPrefix, name: fn, depth: d, samples: 0, childKeys: [] };\n      nodeMap.set(nextPrefix, node);\n      if (d > 0) {\n        const parentNode = nodeMap.get(prefix)!;\n        parentNode.childKeys.push(nextPrefix);\n      }\n    }\n    node.samples += samples;\n    prefix = nextPrefix;\n  }\n}\n\ntype PositionedFrame = {\n  pathKey: string;\n  name: string;\n  depth: number;\n  x0: number;\n  width: number;\n  samples: number;\n  pct: number;\n  fill: string;\n  labelFill: string;\n};\n\nconst rawFrames: { pathKey: string; name: string; depth: number; x0: number; width: number; samples: number }[] = [];\nconst layoutQueue: { key: string; x0: number }[] = [];\nlet rootCursor = 0;\nconst rootEntries: { key: string; x0: number }[] = [];\nfor (const rKey of rootKeys) {\n  rootEntries.push({ key: rKey, x0: rootCursor });\n  rootCursor += nodeMap.get(rKey)!.samples;\n}\nfor (let i = rootEntries.length - 1; i >= 0; i--) {\n  layoutQueue.push(rootEntries[i]);\n}\n\nwhile (layoutQueue.length > 0) {\n  const { key, x0 } = layoutQueue.pop()!;\n  const node = nodeMap.get(key)!;\n  rawFrames.push({\n    pathKey: node.pathKey,\n    name: node.name,\n    depth: node.depth,\n    x0,\n    width: node.samples,\n    samples: node.samples,\n  });\n  let cursor = x0;\n  const childEntries: { key: string; x0: number }[] = [];\n  for (const cKey of node.childKeys) {\n    const child = nodeMap.get(cKey)!;\n    childEntries.push({ key: cKey, x0: cursor });\n    cursor += child.samples;\n  }\n  for (let i = childEntries.length - 1; i >= 0; i--) {\n    layoutQueue.push(childEntries[i]);\n  }\n}\n\nconst totalSamples = rootCursor;\nconst maxDepth = Math.max(...rawFrames.map((f) => f.depth));\nconst nonRootPcts = rawFrames.filter((f) => f.depth > 0).map((f) => f.samples / totalSamples);\nconst minPct = Math.min(...nonRootPcts);\nconst maxPct = Math.max(...nonRootPcts);\n\nconst relLuminance = (rgb: RGB) => {\n  const [r, g, b] = rgb.map((v) => {\n    const c = v / 255;\n    return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);\n  });\n  return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n};\nconst contrast = (a: RGB, b: RGB) => {\n  const [hi, lo] = [relLuminance(a), relLuminance(b)].sort((x, y) => y - x);\n  return (hi + 0.05) / (lo + 0.05);\n};\n\nconst frames: PositionedFrame[] = rawFrames.map((f) => {\n  const isRoot = f.depth === 0;\n  const pct = (f.samples / totalSamples) * 100;\n  let rgb: RGB = ROOT_RGB;\n  if (!isRoot) {\n    const u = (pct / 100 - minPct) / (maxPct - minPct);\n    const scaled = u * (WARM_STOPS.length - 1);\n    const idx = Math.min(WARM_STOPS.length - 2, Math.floor(scaled));\n    const frac = scaled - idx;\n    rgb = WARM_STOPS[idx].map((c, k) => Math.round(c + (WARM_STOPS[idx + 1][k] - c) * frac)) as RGB;\n  }\n  // Pick whichever label ink reads better against this fill.\n  const labelFill = LABEL_INKS.reduce((best, ink) =>\n    contrast(hexToRgb(ink), rgb) > contrast(hexToRgb(best), rgb) ? ink : best,\n  );\n  return {\n    ...f,\n    pct,\n    fill: `rgb(${rgb.join(\",\")})`,\n    labelFill,\n  };\n});\n\nfunction FlameGraphCanvas() {\n  const xs = useXScale();\n  const ys = useYScale();\n  const { width } = window.ANYPLOT_SIZE;\n\n  // Legend: gradient bar with its end labels anchored beneath it, root swatch to the right.\n  const legendFs = 14;\n  const barW = 360;\n  const barH = 14;\n  const barY = 92;\n  const barX = width / 2 - barW - 40;\n  const endLabelY = barY + barH + 18;\n  const rootSwatchX = width / 2 + 40;\n  const rootName = rootKeys.join(\", \");\n  const rootLabel = `${rootName} (${ROOT_ROLE_LABEL} · 100% ${SAMPLES})`;\n  const leftLabel = `${LEGEND_LOW_PREFIX} ${SAMPLES} (${(minPct * 100).toFixed(1)}%)`;\n  const rightLabel = `${LEGEND_HIGH_PREFIX} ${SAMPLES} (${(maxPct * 100).toFixed(1)}%)`;\n\n  return (\n    <g>\n      <defs>\n        <linearGradient id=\"flamegraphHeatGradient\" x1=\"0%\" x2=\"100%\" y1=\"0%\" y2=\"0%\">\n          {WARM_STOPS.map((rgb, i) => (\n            <stop key={i} offset={`${(i / (WARM_STOPS.length - 1)) * 100}%`} stopColor={`rgb(${rgb.join(\",\")})`} />\n          ))}\n        </linearGradient>\n      </defs>\n\n      {/* Flame frames */}\n      {frames.map((f) => {\n        const xLeft = xs(f.x0);\n        const xRight = xs(f.x0 + f.width);\n        const yTop = ys(f.depth + ROW_H_SHARE);\n        const yBottom = ys(f.depth);\n        const w = xRight - xLeft;\n        const h = yBottom - yTop;\n        const fits = w - 14 >= f.name.length * LABEL_FONT_SIZE * CHAR_WIDTH_RATIO;\n        return (\n          <g key={f.pathKey}>\n            <rect\n              x={xLeft}\n              y={yTop}\n              width={w}\n              height={h}\n              fill={f.fill}\n              stroke={t.pageBg}\n              strokeWidth={1.5}\n            >\n              <title>{`${f.name}: ${f.samples.toLocaleString()} ${SAMPLES} (${f.pct.toFixed(1)}%)`}</title>\n            </rect>\n            {fits && (\n              <text\n                x={xLeft + w / 2}\n                y={yTop + h / 2}\n                textAnchor=\"middle\"\n                dominantBaseline=\"central\"\n                fontSize={LABEL_FONT_SIZE}\n                fontWeight={600}\n                fill={f.labelFill}\n                pointerEvents=\"none\"\n              >\n                {f.name}\n              </text>\n            )}\n          </g>\n        );\n      })}\n\n      {/* Depth row labels */}\n      <g fontSize={14} fill={t.inkSoft} textAnchor=\"end\">\n        {Array.from({ length: maxDepth + 1 }, (_, d) => (\n          <text key={d} x={MARGIN.left - 14} y={ys(d + ROW_H_SHARE / 2)} dominantBaseline=\"central\">\n            {d === 0 ? `${DEPTH_LABEL} 0 · ${ROOT_ROLE_LABEL}` : `${DEPTH_LABEL} ${d}`}\n          </text>\n        ))}\n      </g>\n\n      {/* Heat scale legend */}\n      <g fontSize={legendFs} fill={t.inkSoft}>\n        <rect x={barX} y={barY} width={barW} height={barH} rx={2} fill=\"url(#flamegraphHeatGradient)\" />\n        <text x={barX} y={endLabelY} textAnchor=\"start\">\n          {leftLabel}\n        </text>\n        <text x={barX + barW} y={endLabelY} textAnchor=\"end\">\n          {rightLabel}\n        </text>\n        <rect x={rootSwatchX} y={barY} width={barH} height={barH} rx={2} fill={`rgb(${ROOT_RGB.join(\",\")})`} />\n        <text x={rootSwatchX + barH + 8} y={barY + barH / 2} dominantBaseline=\"central\">\n          {rootLabel}\n        </text>\n      </g>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const subtitle = `${totalSamples.toLocaleString()} ${SAMPLES} across ${frames.length} stack frames (${data.length} leaf traces)`;\n\n  return (\n    <ChartsContainer\n      width={width}\n      height={height}\n      series={[]}\n      margin={MARGIN}\n      xAxis={[{ scaleType: \"linear\", min: 0, max: totalSamples, position: \"none\" }]}\n      yAxis={[{ scaleType: \"linear\", min: 0, max: maxDepth + 1, position: \"none\" }]}\n      skipAnimation\n    >\n      <FlameGraphCanvas />\n      <text x={width / 2} y={44} textAnchor=\"middle\" fontSize={22} fontWeight={600} fill={t.ink}>\n        {TITLE}\n      </text>\n      <text x={width / 2} y={70} textAnchor=\"middle\" fontSize={15} fill={t.inkSoft}>\n        {subtitle}\n      </text>\n    </ChartsContainer>\n  );\n}\n"}