@shapesos/clay 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +60 -0
  2. package/dist/artifacts.cjs +858 -132
  3. package/dist/artifacts.cjs.map +1 -1
  4. package/dist/artifacts.d.cts +38 -5
  5. package/dist/artifacts.d.ts +38 -5
  6. package/dist/artifacts.js +13 -3
  7. package/dist/blocks.cjs +1185 -467
  8. package/dist/blocks.cjs.map +1 -1
  9. package/dist/blocks.css +1 -1
  10. package/dist/blocks.d.cts +23 -10
  11. package/dist/blocks.d.ts +23 -10
  12. package/dist/blocks.js +6 -3
  13. package/dist/chart.cjs +594 -0
  14. package/dist/chart.cjs.map +1 -0
  15. package/dist/chart.d.cts +439 -0
  16. package/dist/chart.d.ts +439 -0
  17. package/dist/chart.js +32 -0
  18. package/dist/chat.cjs +1207 -489
  19. package/dist/chat.cjs.map +1 -1
  20. package/dist/chat.d.cts +3 -2
  21. package/dist/chat.d.ts +3 -2
  22. package/dist/chat.js +7 -4
  23. package/dist/{chunk-MXOPG747.js → chunk-36CB624W.js} +7 -7
  24. package/dist/chunk-36CB624W.js.map +1 -0
  25. package/dist/{chunk-L35M3OD5.js → chunk-4MZZH3WX.js} +5 -11
  26. package/dist/chunk-4MZZH3WX.js.map +1 -0
  27. package/dist/chunk-AQEJRMRN.js +1 -0
  28. package/dist/chunk-AQEJRMRN.js.map +1 -0
  29. package/dist/{chunk-OUW6PUEB.js → chunk-FFX3CAOX.js} +7 -7
  30. package/dist/chunk-P6GUNIAE.js +11 -0
  31. package/dist/chunk-P6GUNIAE.js.map +1 -0
  32. package/dist/chunk-QXGYMDIA.js +477 -0
  33. package/dist/chunk-QXGYMDIA.js.map +1 -0
  34. package/dist/{chunk-BX5TCEPR.js → chunk-Z5JWF24N.js} +388 -105
  35. package/dist/chunk-Z5JWF24N.js.map +1 -0
  36. package/dist/index.cjs +924 -198
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +4 -3
  39. package/dist/index.d.ts +4 -3
  40. package/dist/index.js +23 -15
  41. package/dist/table.js +2 -1
  42. package/dist/types-B2aYk82c.d.cts +29 -0
  43. package/dist/types-B2aYk82c.d.ts +29 -0
  44. package/dist/types-C0BvwliI.d.cts +332 -0
  45. package/dist/types-C5bFH4v3.d.ts +332 -0
  46. package/dist/{types-DuuRI4ll.d.cts → types-DCutaXjZ.d.cts} +16 -1
  47. package/dist/{types-C9XX-Uhk.d.ts → types-uPfn67Dc.d.ts} +16 -1
  48. package/package.json +13 -1
  49. package/dist/chunk-BX5TCEPR.js.map +0 -1
  50. package/dist/chunk-L35M3OD5.js.map +0 -1
  51. package/dist/chunk-MEJESPTZ.js +0 -1
  52. package/dist/chunk-MXOPG747.js.map +0 -1
  53. package/dist/types-3Gzk7cRt.d.cts +0 -121
  54. package/dist/types-3Gzk7cRt.d.ts +0 -121
  55. /package/dist/{chunk-MEJESPTZ.js.map → chart.js.map} +0 -0
  56. /package/dist/{chunk-OUW6PUEB.js.map → chunk-FFX3CAOX.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/components/artifacts/index.ts","../src/components/artifacts/types.ts","../src/components/artifacts/table-artifact/table-artifact.tsx","../src/lib/utils.ts","../src/components/ai-elements/artifact.tsx","../node_modules/@tabler/icons-react/src/defaultAttributes.ts","../node_modules/@tabler/icons-react/src/createReactComponent.ts","../node_modules/@tabler/icons-react/src/icons/IconDownload.ts","../src/components/icon-button/icon-button.tsx","../src/components/icon/icon.tsx","../src/components/icon/icon-styles.ts","../src/components/icon-button/icon-button-styles.ts","../src/tokens/colors.ts","../src/components/ui/tooltip.tsx","../src/components/artifacts/artifact-download-button/artifact-download-button.tsx","../src/components/ui/table.tsx","../src/components/table/use-scroll-shadow.ts","../src/components/artifacts/table-artifact/table-artifact-styles.ts","../src/components/artifacts/table-artifact/table-artifact-content.constants.ts","../src/components/artifacts/table-artifact/table-artifact-content.utils.ts","../src/components/artifacts/table-artifact/table-artifact-content.tsx","../src/components/artifacts/table-artifact/use-table-artifact-data.ts","../src/components/artifacts/table-artifact/parse-csv.ts","../src/components/artifacts/table-artifact/validate.ts","../src/components/artifacts/table-artifact/to-clipboard-text.ts","../src/components/artifacts/artifact-services/table-artifact-service.ts","../src/components/artifacts/artifact-services/index.ts"],"sourcesContent":["/**\n * Public surface for `@shapesos/clay/artifacts`.\n *\n * Two layers are exposed:\n *\n * 1. **Domain types** — wire-protocol shapes for the artifact union (`ArtifactRecord`,\n * `TableArtifactRecord`, `TableConfig`, etc.). Consumers use these to type their server\n * payloads and to guard branches in their own logic.\n * 2. **Components** — concrete per-type components (`TableArtifact`), the shared download utility\n * (`ArtifactDownloadButton`), and the artifact services map (`ArtifactServices` +\n * `artifactToClipboardText`) so consumers can render artifacts outside the chat block path.\n *\n * Each per-type component composes the ai-elements primitives (`Artifact`, `ArtifactHeader`,\n * `ArtifactTitle`, `ArtifactActions`, `ArtifactContent`) directly — there is no mandatory wrapper\n * shell. `ArtifactDownloadButton` is the one shared utility: it guards against unsafe URL schemes\n * and can be dropped into any per-type `<ArtifactActions>`.\n *\n * The block layer (`@shapesos/clay/blocks`) imports from here to wire `ARTIFACT_REF` blocks; the\n * separation lets a future surface render an artifact directly without touching the block layer.\n */\n\nexport { artifactTypes } from \"./types\";\nexport type {\n ArtifactRecord,\n ArtifactType,\n TableArtifactRecord,\n TableColumn,\n TableConfig,\n TableRow,\n TableStats,\n} from \"./types\";\n\nexport { ArtifactServices, artifactToClipboardText } from \"./artifact-services\";\nexport type { ArtifactService, ArtifactServiceProps } from \"./types\";\n\nexport { ArtifactDownloadButton, isSafeDownloadUrl } from \"./artifact-download-button/artifact-download-button\";\nexport type { ArtifactDownloadButtonProps } from \"./artifact-download-button/artifact-download-button\";\n\nexport { TableArtifact } from \"./table-artifact/table-artifact\";\n","/**\n * Artifact-domain types — wire-protocol shapes shared between artifact components, block-services, and\n * consumers. The block layer (`@/components/blocks`) imports these to define\n * `ArtifactRefBlockRecord`; the artifact components consume them directly.\n *\n * Mirrored from the agent / io-server contract — see the `chat-typed-content-blocks-and-artifacts`\n * plan, §6.4 (table contract).\n */\n\nimport type { ComponentType } from \"react\";\n\n/**\n * Artifact-type discriminator constants. Uppercase to match the server-side `artifactTypes`\n * constant — io-server stores `artifact.type === \"TABLE\"` (aligned with the GraphQL enum).\n */\nexport const artifactTypes = {\n TABLE: \"TABLE\",\n} as const;\n\n/** Discriminator for artifact types. Additive — new types extend this union. */\nexport type ArtifactType = (typeof artifactTypes)[keyof typeof artifactTypes];\n\n/**\n * A single column descriptor for a `TableArtifact`. Carries the ORDER and LABEL for the\n * rendered table — `key` selects a column from the CSV header; `label` overrides the rendered\n * header text. The CSV is always the source of truth for the data shape; clay never coerces,\n * reformats, or interprets cell values.\n */\nexport interface TableColumn {\n /** Matches a header in the CSV. Required. Used to project + order the CSV's columns. */\n key: string;\n /** Human-readable header text. Required. */\n label: string;\n /**\n * Accepted in the wire payload but not consulted by the renderer — every cell is rendered as\n * the raw CSV string (or empty for null). Format conversion is a server concern; if a column\n * needs to be \"Yes/No\" instead of \"true/false\", the server should emit it that way in the CSV.\n * Kept in the interface so callers that pass `type` (e.g. io-client) don't get a type error.\n */\n type?: \"string\" | \"number\" | \"date\" | \"boolean\";\n /**\n * Accepted in the wire payload but not consulted by the renderer — every column is left-aligned\n * by design. Kept in the interface for forward-compat; restore per-column alignment by editing\n * `table-artifact-content.tsx` if a future use case justifies it.\n */\n align?: \"left\" | \"center\" | \"right\";\n}\n\n/**\n * Optional stats embedded in `TableConfig` so clients can pre-render UI before fetching the\n * actual data payload (e.g. N loading shimmers sized to the eventual row count).\n *\n * Backward-compat: optional everywhere — older artifacts persisted before this field shipped\n * still validate. The renderer falls back to a single status-message line when `stats` is absent.\n */\nexport interface TableStats {\n /** Total number of rows in the materialised CSV. Lets the loading branch render shimmers. */\n rowCount: number;\n}\n\n/** Rendering config for a table artifact, stored at `artifact.config` (JSONB on the server). */\nexport interface TableConfig {\n /** Column descriptors in render order. */\n columns: TableColumn[];\n /** Optional metadata describing the underlying data — used for loading-state UI. */\n stats?: TableStats;\n}\n\n/**\n * A row inside a table artifact's parsed CSV. Every cell is the raw string from the CSV (or\n * `null` for the empty string). The renderer never coerces or interprets — type-aware formatting\n * is a server concern (the CSV's contents are what the user sees).\n */\nexport type TableRow = Record<string, string | null>;\n\n/** Common shape every artifact record carries. Discriminated by `type`. */\ninterface ArtifactBase<TType extends ArtifactType, TConfig> {\n /** Artifact-type discriminator. */\n type: TType;\n /** Human-readable label. Nullable when the artifact has no title. */\n title: string | null;\n /** Rendering config — shape varies per artifact type. */\n config: TConfig;\n /** Protected-asset metadata pointing to the underlying data payload. Null while the asset is unavailable. */\n protectedAsset: {\n /** Time-limited URL the renderer fetches the artifact's data from. */\n presignedUrl: string;\n } | null;\n}\n\n/** Concrete table artifact record. Future artifact types extend `ArtifactRecord` here. */\nexport type TableArtifactRecord = ArtifactBase<typeof artifactTypes.TABLE, TableConfig>;\n\n/**\n * Discriminated union of all supported artifacts. Single-member today; extension pattern:\n *\n * export type ArtifactRecord = TableArtifactRecord | ChartArtifactRecord;\n *\n * Every consumer that narrows on `artifact.type` must add the new branch here AND in the\n * `ArtifactServices` map (single source of truth for the type→component mapping). Older clay\n * versions that don't know about a new type silently render nothing — see `ArtifactRefBlock` guard.\n */\nexport type ArtifactRecord = TableArtifactRecord;\n\n/** Props every concrete artifact component receives from the dispatcher. */\nexport interface ArtifactServiceProps<TArtifact extends ArtifactRecord = ArtifactRecord> {\n /** The artifact metadata (config + presigned URL). */\n artifact: TArtifact;\n}\n\n/** Per-artifact-type service — registry entry that pairs a discriminator with its concrete component. */\nexport interface ArtifactService<TArtifact extends ArtifactRecord = ArtifactRecord> {\n /** Discriminator value this service handles. */\n type: ArtifactType;\n /** React component that renders an artifact of this type — composes ai-elements primitives\n * (`Artifact`, `ArtifactHeader`, `ArtifactTitle`, `ArtifactActions`, `ArtifactContent`) directly. */\n Component: ComponentType<ArtifactServiceProps<TArtifact>>;\n /**\n * Returns a plain-text / markdown string suitable for clipboard copy.\n *\n * Called by `ArtifactRefBlockService.toClipboardText` when the user copies a message that\n * contains this artifact. Must be pure and synchronous.\n *\n * Implementation notes per type:\n * - `table`: returns the artifact title as plain text (see `TableArtifactService`).\n * - Future types implement their own representation in a co-located `*-service.ts` file.\n */\n toClipboardText: (artifact: TArtifact) => string;\n}\n","import { useEffect, type ReactNode } from \"react\";\n\nimport {\n Artifact,\n ArtifactActions,\n ArtifactContent,\n ArtifactHeader,\n ArtifactTitle,\n} from \"@/components/ai-elements/artifact\";\nimport { ArtifactDownloadButton } from \"@/components/artifacts/artifact-download-button/artifact-download-button\";\nimport type { ArtifactServiceProps } from \"@/components/artifacts/types\";\nimport type { TableArtifactRecord } from \"@/components/artifacts/types\";\nimport { TableArtifactContent } from \"./table-artifact-content\";\nimport { StatusMessage } from \"./table-artifact-styles\";\nimport { useTableArtifactData } from \"./use-table-artifact-data\";\nimport { isValidTableConfig } from \"./validate\";\n\nconst TITLE_CLASSES = \"text-sm font-semibold text-foreground\";\n\n/**\n * Cap the body at ~10 rows × 48px (~480px). Long lists scroll inside the artifact so they\n * don't stretch the chat surface. Each artifact type declares its own sensible cap.\n */\nconst TABLE_MAX_BODY_HEIGHT = 480;\n\n/**\n * Cap on shimmer rows during loading. Approximates the visible viewport (`TABLE_MAX_BODY_HEIGHT`\n * ÷ 48px per row) so we don't render hundreds of placeholder DOM nodes for very large tables.\n */\nconst MAX_SHIMMER_ROWS = 10;\n\n/** User-facing copy for permanent server-side absence of the artifact's data (no presigned URL or malformed config). */\nconst MSG_UNAVAILABLE = \"Table data is unavailable.\";\n\n/**\n * Orchestrator for the `table`-typed artifact.\n *\n * Composes the ai-elements chrome primitives (`Artifact`, `ArtifactHeader`, `ArtifactTitle`,\n * `ArtifactActions`, `ArtifactContent`) directly around the table body (`TableArtifactContent`).\n * Download is handled via `ArtifactDownloadButton` — a shared utility component that applies the\n * safe-URL guard and renders nothing for non-http(s) schemes.\n */\nexport function TableArtifact({ artifact }: ArtifactServiceProps<TableArtifactRecord>): ReactNode {\n const validConfig = isValidTableConfig(artifact.config);\n const validColumns = validConfig ? artifact.config.columns : null;\n\n useEffect(() => {\n if (validConfig) return;\n console.warn(\"[clay] TableArtifact: malformed `config` — skipping render.\");\n }, [validConfig]);\n\n // Hook is always called (Rules of Hooks). Pass null URL when config is invalid so the hook\n // short-circuits at its `if (!presignedUrl) return UNAVAILABLE` path — no network fetch fires\n // for an artifact whose config shape can't be rendered.\n const data = useTableArtifactData(\n validConfig ? artifact.protectedAsset?.presignedUrl ?? null : null,\n validColumns ?? []\n );\n\n const presignedUrl = artifact.protectedAsset?.presignedUrl ?? null;\n\n if (!validConfig || !validColumns) {\n return (\n <Artifact className=\"shadow-none w-full rounded-2xl bg-background/70\">\n <ArtifactHeader className=\"bg-background/70\">\n {artifact.title ? <ArtifactTitle className={TITLE_CLASSES}>{artifact.title}</ArtifactTitle> : <span />}\n {presignedUrl ? (\n <ArtifactActions>\n <ArtifactDownloadButton href={presignedUrl} />\n </ArtifactActions>\n ) : null}\n </ArtifactHeader>\n <ArtifactContent className=\"p-0 overflow-auto\" style={{ maxHeight: TABLE_MAX_BODY_HEIGHT }}>\n <StatusMessage $tone=\"info\">{MSG_UNAVAILABLE}</StatusMessage>\n </ArtifactContent>\n </Artifact>\n );\n }\n\n return (\n // The table body owns its own scroll container (`ArtifactTable` inside `TableArtifactContent`).\n // Disable the outer overflow container so only one scroll context exists — this prevents\n // double-scroll nesting and lets `useScrollShadow` find the correct scroll ancestor.\n <Artifact className=\"shadow-none w-full rounded-2xl bg-background/70\">\n <ArtifactHeader className=\"bg-background/70\">\n {artifact.title ? <ArtifactTitle className={TITLE_CLASSES}>{artifact.title}</ArtifactTitle> : <span />}\n <ArtifactActions>\n <ArtifactDownloadButton href={presignedUrl ?? \"\"} />\n </ArtifactActions>\n </ArtifactHeader>\n <ArtifactContent className=\"p-0 overflow-visible\" style={{ maxHeight: \"none\" }}>\n <TableArtifactContent\n columns={validColumns}\n data={data}\n knownRowCount={artifact.config.stats?.rowCount}\n maxShimmerRows={MAX_SHIMMER_ROWS}\n maxBodyHeight={TABLE_MAX_BODY_HEIGHT}\n unavailableMessage={MSG_UNAVAILABLE}\n />\n </ArtifactContent>\n </Artifact>\n );\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\n/**\n * Combines class names using clsx and tailwind-merge — the standard shadcn/ui helper.\n * Tailwind classes that conflict (e.g. `p-2 p-4`) get merged so the last one wins.\n */\nexport function cn(...inputs: ClassValue[]): string {\n return twMerge(clsx(inputs));\n}\n","import type { HTMLAttributes } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------------------------------\n * Originally vendored from `@vercel/ai-elements`'s `artifact` registry entry — see\n * https://elements.ai-sdk.dev/api/registry/artifact.json. Slimmed to the chrome primitives clay\n * actually composes (`Artifact`, `ArtifactHeader`, `ArtifactTitle`, `ArtifactActions`,\n * `ArtifactContent`). The original entry also shipped `ArtifactClose`, `ArtifactDescription`, and\n * `ArtifactAction` — all dependent on the shadcn `Button` primitive, none of which clay consumes.\n * Action buttons inside the artifact header use clay's `IconButton` (see `TableArtifact`'s\n * `ExportCsvButton`) instead of a generic shadcn Button, so the design system stays single-sourced.\n *\n * If a future ai-elements re-scaffold needs one of the dropped primitives back, re-add only the\n * piece consumers need and route its inner button through clay's `Button` / `IconButton` rather\n * than re-introducing the shadcn Button file.\n * ------------------------------------------------------------------------------------------------ */\n\nexport type ArtifactProps = HTMLAttributes<HTMLDivElement>;\n\nexport const Artifact = ({ className, ...props }: ArtifactProps) => (\n <div\n className={cn(\"flex flex-col overflow-hidden rounded-lg border bg-background shadow-sm\", className)}\n {...props}\n />\n);\n\nexport type ArtifactHeaderProps = HTMLAttributes<HTMLDivElement>;\n\nexport const ArtifactHeader = ({ className, ...props }: ArtifactHeaderProps) => (\n <div className={cn(\"flex items-center justify-between border-b bg-muted/50 px-4 py-3\", className)} {...props} />\n);\n\nexport type ArtifactTitleProps = HTMLAttributes<HTMLParagraphElement>;\n\nexport const ArtifactTitle = ({ className, ...props }: ArtifactTitleProps) => (\n <p className={cn(\"font-medium text-foreground text-sm\", className)} {...props} />\n);\n\nexport type ArtifactActionsProps = HTMLAttributes<HTMLDivElement>;\n\nexport const ArtifactActions = ({ className, ...props }: ArtifactActionsProps) => (\n <div className={cn(\"flex items-center gap-1\", className)} {...props} />\n);\n\nexport type ArtifactContentProps = HTMLAttributes<HTMLDivElement>;\n\nexport const ArtifactContent = ({ className, ...props }: ArtifactContentProps) => (\n <div className={cn(\"flex-1 overflow-auto p-4\", className)} {...props} />\n);\n","export default {\n outline: {\n xmlns: 'http://www.w3.org/2000/svg',\n width: 24,\n height: 24,\n viewBox: '0 0 24 24',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 2,\n strokeLinecap: 'round',\n strokeLinejoin: 'round',\n },\n filled: {\n xmlns: 'http://www.w3.org/2000/svg',\n width: 24,\n height: 24,\n viewBox: '0 0 24 24',\n fill: 'currentColor',\n stroke: 'none',\n },\n};\n","import { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes';\nimport type { IconNode, IconProps, Icon } from './types';\n\nconst createReactComponent = (\n type: 'outline' | 'filled',\n iconName: string,\n iconNamePascal: string,\n iconNode: IconNode,\n) => {\n const Component = forwardRef<SVGSVGElement, IconProps>(\n (\n { color = 'currentColor', size = 24, stroke = 2, title, className, children, ...rest }: IconProps,\n ref,\n ) =>\n createElement(\n 'svg',\n {\n ref,\n ...defaultAttributes[type],\n width: size,\n height: size,\n className: [`tabler-icon`, `tabler-icon-${iconName}`, className].join(' '),\n ...(type === 'filled'\n ? {\n fill: color,\n }\n : {\n strokeWidth: stroke,\n stroke: color,\n }),\n ...rest,\n },\n [\n title && createElement('title', { key: 'svg-title' }, title),\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...(Array.isArray(children) ? children : [children]),\n ],\n ),\n );\n\n Component.displayName = `${iconNamePascal}`;\n\n return Component;\n};\n\nexport default createReactComponent;\n","import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M7 11l5 5l5 -5\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M12 4l0 12\",\"key\":\"svg-2\"}]]\n\nconst IconDownload = createReactComponent('outline', 'download', 'Download', __iconNode);\n\nexport default IconDownload;","import { forwardRef } from \"react\";\n\nimport { Icon } from \"../icon/icon\";\nimport { Button } from \"./icon-button-styles\";\nimport type { IconButtonProps, IconButtonSize } from \"./types\";\n\nconst ICON_SIZE_BY_BUTTON_SIZE: Record<IconButtonSize, number> = {\n small: 16,\n medium: 20,\n};\n\n/** Ghost-style icon button. `forwardRef` + the rest-props spread so Radix `Slot`-based wrappers\n * (Tooltip, Popover, DropdownMenu) can attach refs and event handlers via `asChild`. */\nexport const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton(\n {\n icon,\n size = \"small\",\n variant = \"short\",\n isSelected = false,\n disabled = false,\n onClick,\n className,\n id,\n as,\n \"aria-label\": ariaLabel,\n ...rest\n },\n ref\n) {\n // Only set `type=\"button\"` when rendering as a native button. Anchors (`as=\"a\"`) treat the\n // `type` attribute as a content-type hint for the linked resource — `type=\"button\"` on an\n // anchor is semantically wrong and shows up as an a11y / HTML-validation noise warning.\n const isNativeButton = as === undefined || as === \"button\";\n return (\n <Button\n ref={ref}\n className={className}\n id={id}\n as={as}\n $size={size}\n $variant={variant}\n $isSelected={isSelected}\n disabled={disabled}\n onClick={disabled ? undefined : onClick}\n aria-label={ariaLabel}\n {...(isNativeButton ? { type: \"button\" as const } : {})}\n {...rest}\n >\n <Icon icon={icon} size={ICON_SIZE_BY_BUTTON_SIZE[size]} />\n </Button>\n );\n});\n","import { forwardRef } from \"react\";\n\nimport { IconWrapper, getStrokeWidth } from \"./icon-styles\";\nimport type { IconProps } from \"./types\";\n\nconst DEFAULT_SIZE = 16;\n\nexport const Icon = forwardRef<HTMLSpanElement, IconProps>(function Icon(\n { icon: IconComponent, size = DEFAULT_SIZE, color, className, \"aria-label\": ariaLabel },\n ref\n) {\n return (\n <IconWrapper\n ref={ref}\n className={className}\n $color={color}\n aria-label={ariaLabel}\n role={ariaLabel ? \"img\" : undefined}\n >\n <IconComponent width={size} height={size} strokeWidth={getStrokeWidth(size)} />\n </IconWrapper>\n );\n});\n","import styled from \"styled-components\";\n\nexport const STROKE_WIDTH_BY_SIZE: Record<number, number> = {\n 12: 1.4,\n 14: 1.4,\n 16: 1.8,\n 18: 1.8,\n 20: 1.8,\n 24: 1.8,\n};\n\nexport const DEFAULT_STROKE_WIDTH = 1.8;\n\nexport function getStrokeWidth(size: number): number {\n return STROKE_WIDTH_BY_SIZE[size] ?? DEFAULT_STROKE_WIDTH;\n}\n\nexport const IconWrapper = styled.span<{ $color?: string }>`\n display: inline-flex;\n align-items: center;\n justify-content: center;\n color: ${({ $color }) => $color ?? \"currentColor\"};\n flex-shrink: 0;\n`;\n","import styled from \"styled-components\";\n\nimport { colors } from \"../../tokens/colors\";\nimport type { IconButtonSize, IconButtonVariant } from \"./types\";\n\nconst PADDING: Record<IconButtonVariant, Record<IconButtonSize, string>> = {\n short: {\n small: \"4px\",\n medium: \"6px\",\n },\n long: {\n small: \"4px 6px\",\n medium: \"6px 10px\",\n },\n};\n\nconst BORDER_RADIUS: Record<IconButtonSize, number> = {\n small: 6,\n medium: 10,\n};\n\nexport const Button = styled.button<{\n $size: IconButtonSize;\n $variant: IconButtonVariant;\n $isSelected: boolean;\n}>`\n display: inline-flex;\n align-items: center;\n justify-content: center;\n padding: ${({ $size, $variant }) => PADDING[$variant][$size]};\n border: none;\n border-radius: ${({ $size }) => BORDER_RADIUS[$size]}px;\n background: ${({ $isSelected }) => ($isSelected ? colors[\"brown-40\"] : \"transparent\")};\n color: ${colors[\"brown-100\"]};\n cursor: pointer;\n transition: background-color 100ms ease;\n\n &:hover {\n background: ${({ $isSelected }) => ($isSelected ? colors[\"brown-40\"] : colors[\"brown-20\"])};\n }\n\n &:active {\n background: ${colors[\"brown-40\"]};\n }\n\n &:disabled {\n color: ${colors[\"brown-50\"]};\n background: transparent;\n cursor: not-allowed;\n }\n`;\n","export const colors = {\n // White\n white: \"#FFFFFF\",\n \"white-alpha-85\": \"rgba(255, 255, 255, 0.85)\",\n \"white-alpha-40\": \"rgba(255, 255, 255, 0.40)\",\n\n // Brown\n \"brown-10\": \"#FAF9F8\",\n \"brown-20\": \"#F5F3F0\",\n \"brown-30\": \"#EEEBE5\",\n \"brown-40\": \"#E6E2DA\",\n \"brown-50\": \"#CFCBC4\",\n \"brown-60\": \"#A19E99\",\n \"brown-70\": \"#73716D\",\n \"brown-80\": \"#5C5A57\",\n \"brown-90\": \"#2E2D2C\",\n \"brown-100\": \"#171716\",\n \"brown-alpha-12\": \"rgba(23, 23, 22, 0.12)\",\n \"brown-alpha-20\": \"rgba(23, 23, 22, 0.20)\",\n \"brown-alpha-55\": \"rgba(23, 23, 22, 0.55)\",\n \"brown-alpha-70\": \"rgba(23, 23, 22, 0.70)\",\n \"brown-alpha-80\": \"rgba(23, 23, 22, 0.80)\",\n \"brown-alpha-90\": \"rgba(23, 23, 22, 0.90)\",\n\n // Fuchsia\n \"fuchsia-50\": \"#FAF5FF\",\n \"fuchsia-300\": \"#F0ABFC\",\n \"fuchsia-500\": \"#D946EF\",\n \"fuchsia-600\": \"#C026D3\",\n \"fuchsia-800\": \"#86198F\",\n\n // Pink\n \"pink-50\": \"#FDF2F8\",\n \"pink-400\": \"#F472B6\",\n \"pink-600\": \"#DB2777\",\n \"pink-800\": \"#9D174D\",\n\n // Violet\n \"violet-50\": \"#F5F3FF\",\n \"violet-400\": \"#A78BFA\",\n \"violet-600\": \"#7C3AED\",\n \"violet-800\": \"#5B21B6\",\n\n // Indigo\n \"indigo-50\": \"#EEF2FF\",\n \"indigo-400\": \"#818CF8\",\n \"indigo-500\": \"#6366F1\",\n \"indigo-600\": \"#4F46E5\",\n \"indigo-800\": \"#3730A3\",\n\n // Cyan\n \"cyan-50\": \"#E7FEFF\",\n \"cyan-300\": \"#67E8F9\",\n \"cyan-600\": \"#0891B2\",\n \"cyan-900\": \"#164E63\",\n\n // Teal\n \"teal-50\": \"#EBFDF9\",\n \"teal-300\": \"#5EEAD4\",\n \"teal-600\": \"#0D9488\",\n\n // Rose\n \"rose-400\": \"#FB7185\",\n\n // Purple\n \"purple-400\": \"#C084FC\",\n\n // Blue\n \"blue-50\": \"#EFF6FF\",\n \"blue-100\": \"#DBEAFE\",\n \"blue-300\": \"#93C5FD\",\n \"blue-400\": \"#60A5FA\",\n \"blue-600\": \"#2563EB\",\n \"blue-800\": \"#1E40AF\",\n\n // Sky\n \"sky-300\": \"#7DD3FC\",\n\n // Green\n \"green-50\": \"#ECF9F0\",\n \"green-100\": \"#D4F1D9\",\n \"green-400\": \"#3DC269\",\n \"green-700\": \"#277C43\",\n \"green-800\": \"#1C5930\",\n\n // Orange\n \"orange-50\": \"#FFF7ED\",\n \"orange-100\": \"#FFEDD5\",\n \"orange-200\": \"#FED7AA\",\n \"orange-500\": \"#F97316\",\n \"orange-600\": \"#EA580C\",\n\n // Red\n \"red-50\": \"#FEF2F2\",\n \"red-100\": \"#FEE2E2\",\n \"red-200\": \"#FECACA\",\n \"red-400\": \"#F7776C\",\n \"red-500\": \"#EF4444\",\n \"red-600\": \"#DC2626\",\n} as const;\n\nexport type ColorToken = keyof typeof colors;\n","import * as React from \"react\";\nimport * as TooltipPrimitive from \"@radix-ui/react-tooltip\";\n\nimport { cn } from \"@/lib/utils\";\n\nconst TooltipProvider = TooltipPrimitive.Provider;\n\nconst Tooltip = TooltipPrimitive.Root;\n\nconst TooltipTrigger = TooltipPrimitive.Trigger;\n\nconst TooltipContent = React.forwardRef<\n React.ElementRef<typeof TooltipPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>\n>(({ className, sideOffset = 4, ...props }, ref) => (\n <TooltipPrimitive.Content\n ref={ref}\n sideOffset={sideOffset}\n className={cn(\n \"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]\",\n className\n )}\n {...props}\n />\n));\nTooltipContent.displayName = TooltipPrimitive.Content.displayName;\n\nexport { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };\n","import { IconDownload } from \"@tabler/icons-react\";\nimport type { ReactNode } from \"react\";\n\nimport { IconButton } from \"@/components/icon-button/icon-button\";\nimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from \"@/components/ui/tooltip\";\n\n/** Props for `ArtifactDownloadButton`. */\nexport interface ArtifactDownloadButtonProps {\n /**\n * URL to download the artifact's underlying bytes. The button is an `<a href download>` so the\n * browser uses whatever filename the server supplies via `Content-Disposition`. No client-side\n * filename invention.\n *\n * Renders nothing when the URL is not a safe `http(s):` scheme — guards against `javascript:` or\n * `data:` URIs smuggled into `presignedUrl`.\n */\n href: string;\n}\n\n/**\n * Reusable download button for artifact headers. Anchor-based so the browser handles the download\n * natively (respects `Content-Disposition`, falls back to URL basename). `rel=\"noopener noreferrer\"`\n * defends against `window.opener` leakage if the browser opens the URL instead of downloading.\n *\n * Drop this inside `<ArtifactActions>` in any per-type artifact orchestrator.\n */\nexport function ArtifactDownloadButton({ href }: ArtifactDownloadButtonProps): ReactNode {\n if (!isSafeDownloadUrl(href)) return null;\n return (\n <TooltipProvider>\n <Tooltip>\n <TooltipTrigger asChild>\n <IconButton\n as=\"a\"\n href={href}\n download\n rel=\"noopener noreferrer\"\n icon={IconDownload}\n size=\"small\"\n aria-label=\"Download artifact\"\n />\n </TooltipTrigger>\n <TooltipContent>Download</TooltipContent>\n </Tooltip>\n </TooltipProvider>\n );\n}\n\n/**\n * Returns `true` only for `http:` and `https:` URLs. Rejects `javascript:`, `data:`, and any\n * other scheme that could execute code on click.\n */\nexport function isSafeDownloadUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n return parsed.protocol === \"https:\" || parsed.protocol === \"http:\";\n } catch {\n return false;\n }\n}\n","import * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/** Extension of shadcn's `Table` registry component: exposes `containerClassName` so callers can\n * override the wrapping `<div>`'s default `overflow-auto`. We need this for sticky-header support\n * (sticky uses the nearest overflow ancestor as its containing block — when the actual scroll\n * container is one level out, the inner overflow-auto needs to be neutralised with\n * `overflow-visible` so sticky aligns with the real scrolling parent). */\nconst Table = React.forwardRef<\n HTMLTableElement,\n React.HTMLAttributes<HTMLTableElement> & { containerClassName?: string }\n>(({ className, containerClassName, ...props }, ref) => (\n <div className={cn(\"relative w-full overflow-auto\", containerClassName)}>\n <table ref={ref} className={cn(\"w-full caption-bottom text-sm\", className)} {...props} />\n </div>\n));\nTable.displayName = \"Table\";\n\nconst TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(\n ({ className, ...props }, ref) => <thead ref={ref} className={cn(\"[&_tr]:border-b\", className)} {...props} />\n);\nTableHeader.displayName = \"TableHeader\";\n\nconst TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(\n ({ className, ...props }, ref) => (\n <tbody ref={ref} className={cn(\"[&_tr:last-child]:border-0\", className)} {...props} />\n )\n);\nTableBody.displayName = \"TableBody\";\n\nconst TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(\n ({ className, ...props }, ref) => (\n <tfoot ref={ref} className={cn(\"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0\", className)} {...props} />\n )\n);\nTableFooter.displayName = \"TableFooter\";\n\nconst TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(\n ({ className, ...props }, ref) => (\n <tr\n ref={ref}\n className={cn(\"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted\", className)}\n {...props}\n />\n )\n);\nTableRow.displayName = \"TableRow\";\n\nconst TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(\n ({ className, ...props }, ref) => (\n <th\n ref={ref}\n className={cn(\n \"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0\",\n className\n )}\n {...props}\n />\n )\n);\nTableHead.displayName = \"TableHead\";\n\nconst TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(\n ({ className, ...props }, ref) => (\n <td ref={ref} className={cn(\"p-4 align-middle [&:has([role=checkbox])]:pr-0\", className)} {...props} />\n )\n);\nTableCell.displayName = \"TableCell\";\n\nconst TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>(\n ({ className, ...props }, ref) => (\n <caption ref={ref} className={cn(\"mt-4 text-sm text-muted-foreground\", className)} {...props} />\n )\n);\nTableCaption.displayName = \"TableCaption\";\n\nexport { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };\n","import { useEffect, useRef, useState, type RefObject } from \"react\";\n\n/**\n * Tracks whether a scroll container has scrolled past its top edge, for sticky-header shadow effects.\n *\n * Returns `targetRef` (attach to the scroll container itself or any element inside it) and\n * `isScrolled` (true once the container's `scrollTop > 0`). On mount the hook walks up the DOM\n * from the target to find the nearest overflow ancestor (or uses the target itself if it already\n * has `overflowY: auto | scroll`), then listens to its `scroll` event.\n *\n * Used to surface a subtle \"scroll lift\" shadow under sticky headers so users know there is\n * content hidden above.\n *\n * **Why a scroll listener and not a sentinel + IntersectionObserver:** an earlier version used a\n * 1px sentinel as the first child of the scroll container. The sentinel's height pushed the thead\n * down by one pixel in normal flow, and as soon as the user scrolled the thead snapped up to its\n * sticky position — a visible 1px jitter. A scroll listener has no layout footprint.\n *\n * `passive: true` so the listener doesn't block native scroll smoothness; we never call\n * `preventDefault`.\n */\nexport function useScrollShadow(): {\n targetRef: RefObject<HTMLDivElement | null>;\n isScrolled: boolean;\n} {\n const targetRef = useRef<HTMLDivElement>(null);\n const [isScrolled, setIsScrolled] = useState(false);\n\n useEffect(() => {\n const target = targetRef.current;\n if (!target) return;\n\n let scrollContainer: HTMLElement | null = target;\n while (scrollContainer) {\n const overflowY = getComputedStyle(scrollContainer).overflowY;\n if (overflowY === \"auto\" || overflowY === \"scroll\") break;\n scrollContainer = scrollContainer.parentElement;\n }\n if (!scrollContainer) return;\n\n setIsScrolled(scrollContainer.scrollTop > 0);\n\n const handleScroll = () => {\n if (!scrollContainer) return;\n setIsScrolled(scrollContainer.scrollTop > 0);\n };\n scrollContainer.addEventListener(\"scroll\", handleScroll, { passive: true });\n return () => scrollContainer.removeEventListener(\"scroll\", handleScroll);\n }, []);\n\n return { targetRef, isScrolled };\n}\n","import type { ReactNode } from \"react\";\n\nimport { createElement } from \"react\";\n\ninterface StatusMessageProps {\n /** Visual tone: \"error\" renders red copy, \"info\" renders muted brown copy. */\n $tone?: \"info\" | \"error\";\n children: ReactNode;\n}\n\n/**\n * Centred status copy rendered inside the artifact when there is no table to show\n * (loading without a known row count, error, or unavailable).\n * Uses Tailwind so it stays consistent with the rest of the artifact renderer.\n */\nexport function StatusMessage({ $tone, children }: StatusMessageProps): ReactNode {\n return createElement(\n \"div\",\n {\n className: `py-6 px-2 text-center text-sm font-medium leading-5 ${\n $tone === \"error\" ? \"text-red-600\" : \"text-brown-70\"\n }`,\n },\n children\n );\n}\n","/**\n * Discriminant constants for `TableArtifactDataState.status`.\n *\n * Use these instead of inline string literals so a typo is a compile-time error rather than a\n * silent wrong-branch at runtime.\n */\nexport const TABLE_STATUS = {\n LOADING: \"loading\",\n READY: \"ready\",\n ERROR: \"error\",\n UNAVAILABLE: \"unavailable\",\n} as const;\n","import type { TableColumn, TableRow as TableRowData } from \"@/components/artifacts/types\";\n\n/**\n * Returns a cell's rendered string. The CSV is the source of truth — clay never coerces or\n * reformats values. `null` / missing keys render as the empty cell. The value comes out as it\n * went in (whatever the server wrote into the CSV).\n */\nexport function formatCell(row: TableRowData, column: TableColumn): string {\n return row[column.key] ?? \"\";\n}\n\n/**\n * Header + body cell class strings. Alignment is uniformly left in chat-embedded artifact tables\n * by design (mixing right-aligned numerics with left-aligned text reads inconsistently); the\n * wire-type `column.align` is preserved for forward-compat but ignored at render time. See\n * `TableColumn.align` doc in `@/components/artifacts/types`.\n */\nexport const HEAD_CLASS = \"h-auto py-2 px-4 text-xs font-medium text-foreground whitespace-nowrap text-left\";\nexport const CELL_CLASS = \"p-4 text-sm font-normal text-foreground align-top min-w-[150px] text-left\";\n\n/**\n * Row tint matches the artifact card's frosted-glass scheme. The custom `border-b-brown-30`\n * overrides shadcn's row-default border (which inherits `--color-border` = brown-40) with the\n * lighter brown-30. Hover lifts to `bg-secondary` (opaque brown-20) for strong feedback against\n * the translucent base.\n */\nexport const ROW_CLASSES = \"border-b-brown-30 bg-background/70 hover:bg-secondary\";\n\n/**\n * Mount-time fade-in for data rows so the shimmer-to-data transition feels smooth (300ms ease-in\n * over `opacity: 0 → 1`). Shimmer rows keep `ROW_CLASSES` (no animate-in) so they remain in their\n * loading stillness while the pulse animation runs. `animate-in fade-in duration-300` is provided\n * by `tw-animate-css`.\n */\nexport const DATA_ROW_CLASSES = `${ROW_CLASSES} animate-in fade-in duration-300`;\n\n/** Layered drop-shadow for the scroll-lift effect on the sticky header. */\nexport const SCROLL_SHADOW = \"0 1px 2px rgb(0 0 0 / 0.01), 0 6px 12px -2px rgb(0 0 0 / 0.03)\";\n","import { type ReactNode } from \"react\";\n\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, useScrollShadow } from \"@/components/table\";\nimport type { TableColumn, TableRow as TableRowData } from \"@/components/artifacts/types\";\nimport { StatusMessage } from \"./table-artifact-styles\";\nimport type { ArtifactTableProps, TableArtifactContentProps } from \"./table-artifact-content.types\";\nimport { TABLE_STATUS } from \"./table-artifact-content.constants\";\nimport {\n CELL_CLASS,\n DATA_ROW_CLASSES,\n formatCell,\n HEAD_CLASS,\n ROW_CLASSES,\n SCROLL_SHADOW,\n} from \"./table-artifact-content.utils\";\n\n/**\n * Bridges artifact data-states → shadcn's compound `Table` primitives.\n *\n * The four states render differently:\n *\n * - **loading w/ knownRowCount** → renders a sticky-header table with N shimmer rows so the\n * layout doesn't jump.\n * - **loading w/o knownRowCount** → renders the inline \"Loading table…\" status message.\n * - **error / unavailable** → renders an inline status message.\n * - **ready** → renders the full table with data rows and the scroll-lift\n * shadow on the sticky header.\n *\n * The shadcn primitives are composed directly here — no `Table` wrapper component sits in between.\n * Each row variant (header, data, shimmer, empty) is a small inline component below.\n */\nexport function TableArtifactContent({\n columns,\n data,\n knownRowCount,\n maxShimmerRows,\n maxBodyHeight,\n unavailableMessage,\n}: TableArtifactContentProps): ReactNode {\n if (data.status === TABLE_STATUS.ERROR) {\n // No retry hook today — copy intentionally drops the \"Please try again.\" that has nowhere\n // to land. Wire an `onRetry` callback into `ArtifactService` to re-mint a fresh\n // presigned URL before re-introducing the retry framing.\n return <StatusMessage $tone=\"error\">Couldn't load table data.</StatusMessage>;\n }\n if (data.status === TABLE_STATUS.UNAVAILABLE) {\n return <StatusMessage $tone=\"info\">{unavailableMessage}</StatusMessage>;\n }\n if (data.status === TABLE_STATUS.LOADING) {\n if (typeof knownRowCount === \"number\" && knownRowCount > 0) {\n const shimmerCount = Math.min(knownRowCount, maxShimmerRows);\n return (\n <ArtifactTable columns={columns} maxBodyHeight={maxBodyHeight}>\n {renderShimmerRows(columns, shimmerCount)}\n </ArtifactTable>\n );\n }\n return <StatusMessage $tone=\"info\">Loading table…</StatusMessage>;\n }\n // data.status === TABLE_STATUS.READY\n return (\n <ArtifactTable columns={columns} maxBodyHeight={maxBodyHeight}>\n {data.rows.length === 0 ? renderEmptyRow(columns.length) : renderDataRows(columns, data.rows)}\n </ArtifactTable>\n );\n}\n\n/**\n * Compound-table chrome shared between the loading-shimmer branch and the data/empty branch:\n * scroll container, sticky header, and the body slot. Caller passes the body rows.\n */\nfunction ArtifactTable({ columns, maxBodyHeight, children }: ArtifactTableProps): ReactNode {\n const { targetRef, isScrolled } = useScrollShadow();\n return (\n <div ref={targetRef} className=\"overscroll-none\" style={{ maxHeight: maxBodyHeight, overflowY: \"auto\" }}>\n <Table containerClassName=\"overflow-visible\">\n <TableHeader\n data-scrolled={isScrolled ? \"true\" : undefined}\n className=\"sticky top-0 z-10 bg-background/70 backdrop-blur-lg transition-shadow\"\n style={isScrolled ? { boxShadow: SCROLL_SHADOW } : undefined}\n >\n <TableRow className=\"hover:bg-transparent\">\n {columns.map((column) => (\n <TableHead key={column.key} scope=\"col\" className={HEAD_CLASS}>\n {column.label}\n </TableHead>\n ))}\n </TableRow>\n </TableHeader>\n <TableBody>{children}</TableBody>\n </Table>\n </div>\n );\n}\n\nfunction renderShimmerRows(columns: TableColumn[], count: number): ReactNode {\n return Array.from({ length: count }).map((_, index) => (\n <TableRow key={`shimmer-${index}`} className={ROW_CLASSES} aria-hidden=\"true\">\n {columns.map((column) => (\n <TableCell key={column.key} className={CELL_CLASS}>\n <span className=\"block h-3 w-3/4 animate-pulse rounded bg-muted-foreground/20\" />\n </TableCell>\n ))}\n </TableRow>\n ));\n}\n\nfunction renderDataRows(columns: TableColumn[], rows: TableRowData[]): ReactNode {\n // `key={index}` is safe today because `rows` is a static fetch result — no sort, filter, or\n // streaming insertion. The moment row order can change (e.g. client-side sort feature), this\n // must switch to a stable per-row identity or React will reconcile incorrectly (inputs lose\n // focus, animations glitch). The data hook will need to surface a row-id at that point.\n return rows.map((row, index) => (\n <TableRow key={index} className={DATA_ROW_CLASSES}>\n {columns.map((column) => (\n <TableCell key={column.key} className={CELL_CLASS}>\n {formatCell(row, column)}\n </TableCell>\n ))}\n </TableRow>\n ));\n}\n\nfunction renderEmptyRow(colSpan: number): ReactNode {\n return (\n <TableRow className=\"hover:bg-transparent\">\n <TableCell colSpan={colSpan} className=\"py-6 text-center text-sm text-muted-foreground\">\n No rows to display.\n </TableCell>\n </TableRow>\n );\n}\n","import { useEffect, useMemo, useState } from \"react\";\n\nimport type { TableColumn, TableRow } from \"@/components/artifacts/types\";\nimport { parseCsv } from \"./parse-csv\";\n\n/**\n * Discriminator for the result returned by `useTableArtifactData`.\n *\n * - `loading` — fetch is in flight (or about to be).\n * - `ready` — payload fetched and parsed successfully.\n * - `error` — fetch or parse failed at runtime; user can retry.\n * - `unavailable` — the artifact has no presigned URL at all (permanent server-side state). Distinct\n * from `error` so the renderer can surface \"data is unavailable\" instead of a misleading \"try again\".\n */\nexport type TableArtifactDataState =\n | { status: \"loading\"; rows: null; error: null }\n | { status: \"ready\"; rows: TableRow[]; error: null }\n | { status: \"error\"; rows: null; error: Error }\n | { status: \"unavailable\"; rows: null; error: null };\n\nconst LOADING: TableArtifactDataState = { status: \"loading\", rows: null, error: null };\nconst UNAVAILABLE: TableArtifactDataState = { status: \"unavailable\", rows: null, error: null };\n\ninterface InternalState {\n /** The cache key the current `data` was fetched for; used to ignore stale data when inputs change. */\n cacheKey: string | null;\n /** The fetch result for `cacheKey`. */\n data: TableArtifactDataState;\n}\n\nconst INITIAL_INTERNAL: InternalState = { cacheKey: null, data: LOADING };\n\n/**\n * Builds a stable fingerprint string for a columns array so the effect only re-runs when the\n * column definitions actually change, not just when the array reference is replaced.\n */\nfunction columnsFingerprint(columns: TableColumn[]): string {\n return columns.map((c) => `${c.key}:${c.type ?? \"string\"}`).join(\"|\");\n}\n\n/**\n * Fetches a table artifact's data payload from a presigned URL and parses it as CSV.\n *\n * The server writes `text/csv` to the presigned URL (io-server PR #2096). This hook fetches with\n * `Accept: text/csv`, reads the body as text, and delegates to `parseCsv` for RFC 4180 parsing\n * and per-column type coercion (CSV strings → typed values per `column.type`).\n *\n * Returns `loading` while the request is in flight, `unavailable` synchronously when no URL is\n * supplied, `ready` on success, or `error` on a runtime failure (HTTP non-2xx, network, or parse\n * error). Parse errors are surfaced as `error` state — they are never thrown.\n *\n * In-flight requests are cancelled via `AbortController` when the URL or columns change, or the\n * consumer unmounts, so abandoned table loads don't keep consuming bandwidth.\n *\n * @param presignedUrl S3 presigned URL for the artifact's CSV file, or `null`/`undefined` when absent.\n * @param columns Column definitions from `TableConfig.columns` — used for per-cell type coercion.\n */\nexport function useTableArtifactData(\n presignedUrl: string | null | undefined,\n columns: TableColumn[]\n): TableArtifactDataState {\n // Stable fingerprint so the effect doesn't re-fire on referentially-new but content-equal column arrays.\n const colsKey = useMemo(() => columnsFingerprint(columns), [columns]);\n\n const cacheKey = presignedUrl ? `${presignedUrl}::${colsKey}` : null;\n\n const [state, setState] = useState<InternalState>(INITIAL_INTERNAL);\n\n useEffect(() => {\n if (!presignedUrl) return;\n\n const controller = new AbortController();\n\n fetch(presignedUrl, {\n signal: controller.signal,\n headers: { Accept: \"text/csv\" },\n // Presigned URLs are cross-origin S3 in production and don't need credentials. Explicit\n // omit so a same-origin URL (compromised payload, local dev) can't accidentally receive\n // session cookies or auth headers.\n credentials: \"omit\",\n })\n .then(async (response) => {\n if (!response.ok) throw new Error(`Failed to load table data (${response.status})`);\n return response.text();\n })\n .then((text) => {\n if (controller.signal.aborted) return;\n try {\n const rows = parseCsv(text, columns);\n setState({ cacheKey: `${presignedUrl}::${colsKey}`, data: { status: \"ready\", rows, error: null } });\n } catch (parseError: unknown) {\n console.error(\"[TableArtifact] CSV parse failed\", parseError);\n const err = parseError instanceof Error ? parseError : new Error(String(parseError));\n setState({ cacheKey: `${presignedUrl}::${colsKey}`, data: { status: \"error\", rows: null, error: err } });\n }\n })\n .catch((error: unknown) => {\n // Per the Fetch spec, `signal.aborted` is set before the promise rejects on abort, so this\n // guard catches every abort case driven by our `controller.abort()` cleanup.\n if (controller.signal.aborted) return;\n console.error(\"[TableArtifact] Fetch failed\", error);\n const err = error instanceof Error ? error : new Error(String(error));\n setState({ cacheKey: `${presignedUrl}::${colsKey}`, data: { status: \"error\", rows: null, error: err } });\n });\n\n return () => {\n controller.abort();\n };\n // `columns` is intentionally omitted from the dep array: `colsKey` is its stable fingerprint\n // (covers every observable change), and `columns` is validated config from a static payload\n // that cannot mutate between effect invocation and fetch resolution. If `columns` ever becomes\n // dynamic (e.g. a future column-reorder UI), this assumption breaks and the suppression must\n // be removed in favour of including `columns` directly.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [presignedUrl, colsKey]);\n\n if (!presignedUrl) return UNAVAILABLE;\n // While the in-flight URL/columns change, cached data belongs to a stale key — return loading until\n // the new fetch resolves. Avoids a synchronous setState() in the effect body (lint forbids that).\n if (state.cacheKey !== cacheKey) return LOADING;\n return state.data;\n}\n","import Papa from \"papaparse\";\n\nimport type { TableColumn, TableRow } from \"@/components/artifacts/types\";\n\n/**\n * Parses a CSV text payload fetched from a presigned URL into `TableRow[]`.\n *\n * Uses `Papa.parse` with `header: true` (first row is the header) and `skipEmptyLines: true`.\n * Every cell arrives as a string — the renderer NEVER coerces values to JS numbers / booleans /\n * dates. Format conversion is a server concern: if a column needs to be `\"Yes/No\"` or\n * `\"$1,234\"`, the server emits it that way in the CSV.\n *\n * Column projection rules:\n * - CSV header columns NOT in `columns[].key` are silently dropped.\n * - `columns[].key` values missing from the CSV header are silently omitted from row output —\n * client-side reconciliation warnings would let the client second-guess the server's contract.\n * Trust the CSV.\n *\n * Empty cells (`\"\"`) are returned as `null` so the renderer can distinguish \"missing value\"\n * from \"empty string\" downstream.\n *\n * @param text Raw CSV text (may start with a UTF-8 BOM which Papa strips automatically).\n * @param columns Column definitions from `TableConfig.columns`.\n * @returns Rows in source order, projected to the configured columns.\n */\nexport function parseCsv(text: string, columns: TableColumn[]): TableRow[] {\n const result = Papa.parse<Record<string, string>>(text, {\n header: true,\n skipEmptyLines: true,\n dynamicTyping: false,\n });\n\n const csvHeaders = new Set(result.meta?.fields ?? []);\n const presentColumns = columns.filter((col) => csvHeaders.has(col.key));\n\n return result.data.map((rawRow) => {\n const row: TableRow = {};\n for (const column of presentColumns) {\n const value = rawRow[column.key];\n row[column.key] = value === undefined || value === \"\" ? null : value;\n }\n return row;\n });\n}\n","import type { TableColumn, TableConfig } from \"@/components/artifacts/types\";\n\n/**\n * Returns true iff `config` carries the minimum-viable shape for rendering: a non-empty array\n * of columns where each has a non-empty `key` and a string `label`.\n *\n * Anything else is trusted to the server. The deprecated `type` / `align` wire fields are NOT\n * validated — clay doesn't act on them, so rejecting unknown values would punish servers\n * shipping fields clay was about to ignore anyway.\n */\nexport function isValidTableConfig(config: unknown): config is TableConfig {\n if (!config || typeof config !== \"object\") return false;\n const candidate = config as { columns?: unknown };\n if (!Array.isArray(candidate.columns)) return false;\n if (candidate.columns.length === 0) return false;\n return candidate.columns.every(isValidTableColumn);\n}\n\n/** Minimum-viable column shape: non-empty string `key` + string `label`. */\nfunction isValidTableColumn(column: unknown): column is TableColumn {\n if (!column || typeof column !== \"object\") return false;\n const candidate = column as Record<string, unknown>;\n if (typeof candidate.key !== \"string\" || candidate.key.length === 0) return false;\n if (typeof candidate.label !== \"string\") return false;\n return true;\n}\n","import type { TableArtifactRecord } from \"@/components/artifacts/types\";\n\n/**\n * Produces a plain-text clipboard representation of a table artifact.\n *\n * Returns the artifact title as plain text so that pasting into non-markdown-aware targets\n * (plain-text editors, terminal, spreadsheets) does not expose raw markdown syntax. This\n * matches the contract of `TextBlockService.toClipboardText`, which also strips markdown —\n * `useCopyToClipboard` writes the aggregated string verbatim, so every block type must\n * independently normalise to plain text.\n *\n * The presigned URL is intentionally omitted from the clipboard value: presigned URLs expire\n * quickly (typically 15 min–1 h) and are not useful when pasted as bare text. The Download\n * button in the artifact chrome is the canonical way to obtain the file.\n */\nexport function tableArtifactToClipboardText(artifact: TableArtifactRecord): string {\n const trimmedTitle = artifact.title?.trim();\n return trimmedTitle || \"Table\";\n}\n","import type { ArtifactService, TableArtifactRecord } from \"../types\";\nimport { artifactTypes } from \"../types\";\nimport { TableArtifact } from \"../table-artifact/table-artifact\";\nimport { tableArtifactToClipboardText } from \"../table-artifact/to-clipboard-text\";\n\nexport const TableArtifactService: ArtifactService<TableArtifactRecord> = {\n type: artifactTypes.TABLE,\n Component: TableArtifact,\n toClipboardText: tableArtifactToClipboardText,\n};\n","import type { ArtifactRecord, ArtifactService, ArtifactType } from \"../types\";\nimport { artifactTypes } from \"../types\";\nimport { TableArtifactService } from \"./table-artifact-service\";\n\n// `ArtifactService<TSpecific>` is invariant on `TSpecific` via React's `ComponentType`\n// (props are contravariant). Each service overlaps structurally with the base `ArtifactService`\n// enough for a direct `as ArtifactService` cast. The registry dispatches only by runtime\n// discriminator — `ArtifactServices[artifact.type]` always resolves to the matching concrete service.\n/**\n * Map of artifact services keyed by `artifact.type`.\n *\n * Adding a new artifact type = create a `*-service.ts` file (mirroring `block-services/`), then\n * add one entry here. The block-level dispatcher (`ArtifactRefBlock`) consumes this map to\n * render the concrete component; `artifactToClipboardText` consumes it for the clipboard contract.\n */\nexport const ArtifactServices: Record<ArtifactType, ArtifactService> = {\n [artifactTypes.TABLE]: TableArtifactService as ArtifactService,\n};\n\n/**\n * Returns a clipboard-friendly string for an artifact, delegating to the registered service's\n * `toClipboardText`. Falls back to `[Artifact: <title>]` when the artifact type has no registered\n * service (unknown type) so copy never silently produces an empty string.\n */\nexport function artifactToClipboardText(artifact: ArtifactRecord): string {\n const entry = ArtifactServices[artifact.type];\n if (!entry) {\n return `[Artifact: ${artifact.title ?? artifact.type}]`;\n }\n return entry.toClipboardText(artifact);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeO,IAAM,gBAAgB;AAAA,EAC3B,OAAO;A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6CAAC,iBAAc,WAAW,eAAgB,mBAAS,OAAM,IAAmB,6CAAC,UAAK;AAAA,QACpG,6CAAC,mBACC,uDAAC,0BAAuB,MAAM,gBAAgB,IAAI,GACpD;AAAA,SACF;AAAA,MACA,6CAAC,mBAAgB,WAAU,wBAAuB,OAAO,EAAE,WAAW,OAAO,GAC3E;AAAA,QAAC;AAAA;AAAA,UACC,SAAS;AAAA,UACT;AAAA,UACA,eAAe,SAAS,OAAO,OAAO;AAAA,UACtC,gBAAgB;AAAA,UAChB,eAAe;AAAA,UACf,oBAAoB;AAAA;AAAA,MACtB,GACF;AAAA,OACF;AAAA;AAEJ;;;AsBvFO,SAAS,6BAA6B,UAAuC;AAClF,QAAM,eAAe,SAAS,OAAO,KAAK;AAC1C,SAAO,gBAAgB;AACzB;;;ACbO,IAAM,uBAA6D;AAAA,EACxE,MAAM,cAAc;AAAA,EACpB,WAAW;AAAA,EACX,iBAAiB;AACnB;;;ACMO,IAAM,mBAA0D;AAAA,EACrE,CAAC,cAAc,KAAK,GAAG;AACzB;AAOO,SAAS,wBAAwB,UAAkC;AACxE,QAAM,QAAQ,iBAAiB,SAAS,IAAI;AAC5C,MAAI,CAAC,OAAO;AACV,WAAO,cAAc,SAAS,SAAS,SAAS,IAAI;AAAA,EACtD;AACA,SAAO,MAAM,gBAAgB,QAAQ;AACvC;","names":["import_react","import_react","import_react","styled","import_jsx_runtime","Icon","import_styled_components","styled","import_jsx_runtime","IconButton","import_jsx_runtime","import_jsx_runtime","React","import_jsx_runtime","import_react","import_react","import_jsx_runtime","import_react","Papa","import_jsx_runtime"]}
1
+ {"version":3,"sources":["../src/components/artifacts/index.ts","../src/components/artifacts/artifact-base.ts","../src/components/artifacts/chart-artifact/types.ts","../src/components/artifacts/table-artifact/types.ts","../src/components/artifacts/chart-artifact/chart-artifact.tsx","../src/lib/utils.ts","../src/components/ai-elements/artifact.tsx","../node_modules/@tabler/icons-react/src/defaultAttributes.ts","../node_modules/@tabler/icons-react/src/createReactComponent.ts","../node_modules/@tabler/icons-react/src/icons/IconDownload.ts","../src/components/icon-button/icon-button.tsx","../src/components/icon/icon.tsx","../src/components/icon/icon-styles.ts","../src/components/icon-button/icon-button-styles.ts","../src/tokens/colors.ts","../src/components/ui/tooltip.tsx","../src/components/artifacts/artifact-download-button/artifact-download-button.tsx","../src/components/artifacts/status-message.tsx","../src/components/chart/bar-chart/bar-chart.tsx","../src/components/chart/chart-container.tsx","../src/components/chart/chart-legend-content.tsx","../src/components/chart/chart-tooltip-content.tsx","../src/components/chart/chart-palette.ts","../src/components/chart/chart-styles.ts","../src/components/chart/chart-tick-utils.ts","../src/components/chart/coerce-numeric.ts","../src/components/artifacts/chart-artifact/chart-variant-services/constants.ts","../src/components/artifacts/chart-artifact/chart-variant-services/bar-chart-variant-component.tsx","../src/components/artifacts/chart-artifact/chart-variant-services/shared-column-keys.ts","../src/components/artifacts/chart-artifact/chart-variant-services/shared-validators.ts","../src/components/artifacts/chart-artifact/chart-variant-services/bar-chart-variant-service.tsx","../src/components/chart/line-chart/line-chart.tsx","../src/components/artifacts/chart-artifact/chart-variant-services/line-chart-variant-component.tsx","../src/components/artifacts/chart-artifact/chart-variant-services/line-chart-variant-service.tsx","../src/components/chart/pie-chart/pie-chart.tsx","../src/components/artifacts/chart-artifact/chart-variant-services/pie-chart-variant-component.tsx","../src/components/artifacts/chart-artifact/chart-variant-services/pie-chart-variant-service.tsx","../src/components/artifacts/chart-artifact/chart-variant-services/index.ts","../src/components/artifacts/chart-artifact/chart-artifact-content.tsx","../src/components/artifacts/parse-csv.ts","../src/components/artifacts/use-rows-artifact-data.ts","../src/components/artifacts/chart-artifact/use-chart-artifact-data.ts","../src/components/artifacts/chart-artifact/validate.ts","../src/components/artifacts/chart-artifact/to-clipboard-text.ts","../src/components/artifacts/artifact-services/chart-artifact-service.ts","../src/components/artifacts/table-artifact/table-artifact.tsx","../src/components/ui/table.tsx","../src/components/table/use-scroll-shadow.ts","../src/components/artifacts/table-artifact/table-artifact-content.constants.ts","../src/components/artifacts/table-artifact/table-artifact-content.utils.ts","../src/components/artifacts/table-artifact/table-artifact-content.tsx","../src/components/artifacts/table-artifact/use-table-artifact-data.ts","../src/components/artifacts/table-artifact/validate.ts","../src/components/artifacts/table-artifact/to-clipboard-text.ts","../src/components/artifacts/artifact-services/table-artifact-service.ts","../src/components/artifacts/artifact-services/index.ts"],"sourcesContent":["/**\n * Public surface for `@shapesos/clay/artifacts`.\n *\n * Two layers are exposed:\n *\n * 1. **Domain types** — wire-protocol shapes for the artifact union (`ArtifactRecord`,\n * `TableArtifactRecord`, `TableConfig`, etc.). Consumers use these to type their server\n * payloads and to guard branches in their own logic.\n * 2. **Components** — concrete per-type components (`TableArtifact`), the shared download utility\n * (`ArtifactDownloadButton`), and the artifact services map (`ArtifactServices` +\n * `artifactToClipboardText`) so consumers can render artifacts outside the chat block path.\n *\n * Each per-type component composes the ai-elements primitives (`Artifact`, `ArtifactHeader`,\n * `ArtifactTitle`, `ArtifactActions`, `ArtifactContent`) directly — there is no mandatory wrapper\n * shell. `ArtifactDownloadButton` is the one shared utility: it guards against unsafe URL schemes\n * and can be dropped into any per-type `<ArtifactActions>`.\n *\n * The block layer (`@shapesos/clay/blocks`) imports from here to wire `ARTIFACT_REF` blocks; the\n * separation lets a future surface render an artifact directly without touching the block layer.\n */\n\nexport { DEFAULT_CHART_ARTIFACT_LABELS, DEFAULT_TABLE_ARTIFACT_LABELS, artifactTypes } from \"./types\";\nexport type {\n ArtifactDataRow,\n ArtifactLabelsMap,\n ArtifactRecord,\n ArtifactType,\n BarChartConfig,\n ChartArtifactLabels,\n ChartArtifactRecord,\n ChartConfig,\n ChartSeries,\n ChartStats,\n ChartVariant,\n LineChartConfig,\n PieChartConfig,\n TableArtifactLabels,\n TableArtifactRecord,\n TableColumn,\n TableConfig,\n TableRow,\n TableStats,\n} from \"./types\";\n\nexport { ArtifactServices, artifactToClipboardText } from \"./artifact-services\";\nexport type { ArtifactService, ArtifactServiceProps } from \"./types\";\n\nexport { ArtifactDownloadButton, isSafeDownloadUrl } from \"./artifact-download-button/artifact-download-button\";\nexport type { ArtifactDownloadButtonProps } from \"./artifact-download-button/artifact-download-button\";\n\nexport { TableArtifact } from \"./table-artifact/table-artifact\";\nexport { ChartArtifact } from \"./chart-artifact/chart-artifact\";\n","/**\n * Shared artifact primitives — the discriminator constant and the cross-variant `ArtifactBase`\n * shape that every concrete artifact record extends.\n *\n * Pulled into its own file so the per-type `types.ts` files (`table-artifact/types.ts`,\n * `chart-artifact/types.ts`) and the union assembler (`artifacts/types.ts`) can all depend on\n * one canonical source without creating a circular module graph between them.\n */\n\n/**\n * Artifact-type discriminator constants. Uppercase to match the server-side `artifactTypes`\n * constant — io-server stores `artifact.type === \"TABLE\"` (aligned with the GraphQL enum).\n */\nexport const artifactTypes = {\n TABLE: \"TABLE\",\n CHART: \"CHART\",\n} as const;\n\n/** Discriminator for artifact types. Additive — new types extend this union. */\nexport type ArtifactType = (typeof artifactTypes)[keyof typeof artifactTypes];\n\n/** Common shape every artifact record carries. Discriminated by `type`. */\nexport interface ArtifactBase<TType extends ArtifactType, TConfig> {\n /** Artifact-type discriminator. */\n type: TType;\n /** Human-readable label. Nullable when the artifact has no title. */\n title: string | null;\n /** Rendering config — shape varies per artifact type. */\n config: TConfig;\n /** Protected-asset metadata pointing to the underlying data payload. Null while the asset is unavailable. */\n protectedAsset: {\n /** Time-limited URL the renderer fetches the artifact's data from. */\n presignedUrl: string;\n } | null;\n}\n\n/**\n * A row inside an artifact's parsed CSV. Every cell is the raw string from the CSV (or `null`\n * for the empty string). Used by every artifact kind whose data wire is a CSV (`TABLE`, `CHART`).\n * The renderer never coerces — type-aware formatting is a server concern (the CSV's contents\n * are what the user sees).\n */\nexport type ArtifactDataRow = Record<string, string | null>;\n","import type { ChartSeries } from \"@/components/chart/types\";\nimport { artifactTypes, type ArtifactBase } from \"../artifact-base\";\nimport type { ChartConfig } from \"./chart-variant-services\";\n\nexport type { ChartConfig } from \"./chart-variant-services\";\nexport type { LineChartConfig, BarChartConfig, PieChartConfig } from \"./chart-variant-services\";\n\n/**\n * Optional stats embedded in `ChartConfig` so clients can pre-render UI before fetching the\n * actual CSV (e.g. a skeleton sized to the eventual row count). Mirrors `TableStats`.\n */\nexport interface ChartStats {\n /** Total number of rows in the materialised CSV. */\n rowCount: number;\n}\n\n/**\n * Cross-variant base for `ChartConfig`. Carries the fields every variant shares — series\n * descriptors and optional stats. Per-variant config interfaces (in `chart-variant-services/`)\n * extend this with their own required fields.\n *\n * Note: `series` is always present on the wire (matching the GraphQL `[ChartSeries!]!` shape)\n * even for PIE — PIE just receives an empty array. Keeping it on the base mirrors the wire shape\n * exactly and avoids TS object-literal freshness errors for callers that explicitly set\n * `series: []` on a pie config.\n */\nexport interface ChartConfigBase {\n /** Series descriptors in render order. LINE/BAR consume these; PIE ignores in favour of `categoryKey`+`valueKey`. */\n series: ChartSeries[];\n /** Optional metadata describing the underlying data — used for loading-state UI. */\n stats?: ChartStats;\n}\n\n/** Concrete chart artifact record. */\nexport type ChartArtifactRecord = ArtifactBase<typeof artifactTypes.CHART, ChartConfig>;\n\n/**\n * Localized labels for the `CHART` artifact's user-facing strings. Covers action buttons AND\n * status messages — see `TableArtifactLabels` for the same shape philosophy. Extends as the\n * chart artifact grows its action set (e.g. future `copyAsPng`); optional keys document\n * anticipated additions without forcing every consumer to provide them today.\n */\nexport interface ChartArtifactLabels {\n /** Tooltip + aria-label on the Download CSV button in the chart artifact header. */\n download: string;\n /** Status message shown when no presigned URL is available or the chart config is malformed. */\n unavailable: string;\n /** Status message shown when the fetch / parse fails at runtime. */\n loadError: string;\n /** Status message shown while the CSV is being fetched. */\n loading: string;\n /** Status message shown when the fetched CSV has zero data rows. */\n empty: string;\n /**\n * Category labels treated as the \"Others\" bucket in pie charts (case-insensitive). Matching\n * slices are pinned to the end of the sweep and rendered in neutral grey. The agent writes a\n * translated bucket name in non-English UIs (e.g. \"אחרים\", \"Otros\") — consumer passes the\n * localized list here so clay can detect the bucket regardless of language. English fallback\n * is `[\"Others\", \"Other\"]`. Pass `[]` to disable Others detection (every slice from the palette).\n */\n othersCategoryLabels: readonly string[];\n}\n\n/** English fallback for `ChartArtifactLabels`. Used when the consumer hasn't passed `labels`. */\nexport const DEFAULT_CHART_ARTIFACT_LABELS: ChartArtifactLabels = {\n download: \"Download CSV\",\n unavailable: \"Chart data is unavailable.\",\n loadError: \"Couldn't load chart data.\",\n loading: \"Loading chart…\",\n empty: \"No data to chart.\",\n othersCategoryLabels: [\"Others\", \"Other\"],\n};\n\n/**\n * Consumer-supplied side-effect callbacks for actions on the chart artifact. Mirrors\n * `ChartArtifactLabels`'s shape philosophy: one entry per action this artifact exposes\n * (download today; future \"Copy as PNG\" etc.). Every callback is optional — consumers wire\n * only the actions they care about. The artifact passes its own `ChartArtifactRecord` as the\n * only argument so consumers can derive analytics context (title, config.variant, etc.) without\n * a per-block closure at every render site.\n *\n * The callback fires alongside the default browser behaviour (e.g. `onDownload` does not\n * prevent the anchor's download navigation) — it's purely for analytics / observability hooks.\n */\nexport interface ChartArtifactCallbacks {\n /** Fires when the Download CSV button is clicked. Browser-native download still happens. */\n onDownload?: (artifact: ChartArtifactRecord) => void;\n}\n","import { artifactTypes, type ArtifactBase, type ArtifactDataRow } from \"../artifact-base\";\n\n/**\n * A single column descriptor for a `TableArtifact`. Carries the ORDER and LABEL for the\n * rendered table — `key` selects a column from the CSV header; `label` overrides the rendered\n * header text. The CSV is always the source of truth for the data shape; clay never coerces,\n * reformats, or interprets cell values.\n */\nexport interface TableColumn {\n /** Matches a header in the CSV. Required. Used to project + order the CSV's columns. */\n key: string;\n /** Human-readable header text. Required. */\n label: string;\n /**\n * Accepted in the wire payload but not consulted by the renderer — every cell is rendered as\n * the raw CSV string (or empty for null). Format conversion is a server concern; if a column\n * needs to be \"Yes/No\" instead of \"true/false\", the server should emit it that way in the CSV.\n * Kept in the interface so callers that pass `type` (e.g. io-client) don't get a type error.\n */\n type?: \"string\" | \"number\" | \"date\" | \"boolean\";\n /**\n * Accepted in the wire payload but not consulted by the renderer — every column is left-aligned\n * by design. Kept in the interface for forward-compat; restore per-column alignment by editing\n * `table-artifact-content.tsx` if a future use case justifies it.\n */\n align?: \"left\" | \"center\" | \"right\";\n}\n\n/**\n * Optional stats embedded in `TableConfig` so clients can pre-render UI before fetching the\n * actual data payload (e.g. N loading shimmers sized to the eventual row count).\n *\n * Backward-compat: optional everywhere — older artifacts persisted before this field shipped\n * still validate. The renderer falls back to a single status-message line when `stats` is absent.\n */\nexport interface TableStats {\n /** Total number of rows in the materialised CSV. Lets the loading branch render shimmers. */\n rowCount: number;\n}\n\n/** Rendering config for a table artifact, stored at `artifact.config` (JSONB on the server). */\nexport interface TableConfig {\n /** Column descriptors in render order. */\n columns: TableColumn[];\n /** Optional metadata describing the underlying data — used for loading-state UI. */\n stats?: TableStats;\n}\n\n/** Alias retained for callers typed against the table-specific name. */\nexport type TableRow = ArtifactDataRow;\n\n/** Concrete table artifact record. */\nexport type TableArtifactRecord = ArtifactBase<typeof artifactTypes.TABLE, TableConfig>;\n\n/**\n * Localized labels for the `TABLE` artifact's user-facing strings. Covers both action buttons\n * (download today; future \"Copy as CSV\", etc.) AND status messages (loading / error / empty /\n * unavailable). Consumer passes the bag from their i18n layer; clay falls back to English\n * defaults when omitted (per-key Partial merge).\n */\nexport interface TableArtifactLabels {\n /** Tooltip + aria-label on the Download CSV button in the table artifact header. */\n download: string;\n /**\n * Status message shown when no presigned URL is available (permanent server-side absence) or\n * the artifact config is malformed. Both states reduce to \"the underlying file isn't usable\".\n */\n unavailable: string;\n /** Status message shown when the fetch / parse fails at runtime (transient). */\n loadError: string;\n /** Status message shown while the CSV is being fetched and `stats.rowCount` is not known. */\n loading: string;\n /** Empty-state row inside the table body when the fetched CSV has zero data rows. */\n empty: string;\n}\n\n/** English fallback for `TableArtifactLabels`. Used when the consumer hasn't passed `labels`. */\nexport const DEFAULT_TABLE_ARTIFACT_LABELS: TableArtifactLabels = {\n download: \"Download CSV\",\n unavailable: \"Table data is unavailable.\",\n loadError: \"Couldn't load table data.\",\n loading: \"Loading table…\",\n empty: \"No rows to display.\",\n};\n\n/**\n * Consumer-supplied side-effect callbacks for actions on the table artifact. Mirrors\n * `ChartArtifactCallbacks` — see that interface for the shape philosophy. Every callback is\n * optional; the artifact passes its own `TableArtifactRecord` as the only argument so consumers\n * can derive analytics context without a per-block closure at every render site.\n */\nexport interface TableArtifactCallbacks {\n /** Fires when the Download CSV button is clicked. Browser-native download still happens. */\n onDownload?: (artifact: TableArtifactRecord) => void;\n}\n","import { useEffect, useMemo, type ReactNode } from \"react\";\n\nimport {\n Artifact,\n ArtifactActions,\n ArtifactContent,\n ArtifactHeader,\n ArtifactTitle,\n} from \"@/components/ai-elements/artifact\";\nimport { ArtifactDownloadButton } from \"@/components/artifacts/artifact-download-button/artifact-download-button\";\nimport {\n DEFAULT_CHART_ARTIFACT_LABELS,\n type ArtifactServiceProps,\n type ChartArtifactLabels,\n type ChartArtifactRecord,\n} from \"@/components/artifacts/types\";\nimport { artifactTypes } from \"@/components/artifacts/artifact-base\";\nimport { StatusMessage } from \"../status-message\";\nimport { ChartArtifactContent } from \"./chart-artifact-content\";\nimport { useChartArtifactData } from \"./use-chart-artifact-data\";\nimport { isValidChartConfig } from \"./validate\";\n\nconst TITLE_CLASSES = \"text-sm font-semibold text-foreground\";\n\n/**\n * Chart height. Picks a single sensible size for all three variants so chat layout stays\n * predictable — mirrors `TableArtifact`'s `TABLE_MAX_BODY_HEIGHT` approach. Width is fluid via\n * recharts' `ResponsiveContainer`.\n */\nconst CHART_HEIGHT = 320;\n\n/**\n * Orchestrator for the `CHART`-typed artifact.\n *\n * Composes the ai-elements chrome primitives (`Artifact`, `ArtifactHeader`, `ArtifactTitle`,\n * `ArtifactActions`, `ArtifactContent`) directly around the chart body (`ChartArtifactContent`),\n * matching `TableArtifact`'s shape. Loading / error / unavailable / empty states render an inline\n * `StatusMessage`; the ready state delegates to per-variant recharts trees inside\n * `ChartArtifactContent`.\n *\n * The renderer is variant-agnostic at this level — it doesn't know about LINE vs BAR vs PIE.\n * Variant dispatch lives inside `ChartArtifactContent` so the orchestrator can focus on the\n * data lifecycle and the chrome.\n *\n * Labels for action buttons (download, future copy-as-PNG) are pulled from the optional `labels`\n * prop with per-key fallback to `DEFAULT_CHART_ARTIFACT_LABELS`. Consumers translate via their\n * own i18n layer and pass the bag; non-i18n consumers omit it and get English defaults.\n */\nexport function ChartArtifact({ artifact, labels, callbacks }: ArtifactServiceProps<ChartArtifactRecord>): ReactNode {\n const validConfig = isValidChartConfig(artifact.config);\n\n useEffect(() => {\n if (validConfig) return;\n console.warn(\"[clay] ChartArtifact: malformed `config` — skipping render.\");\n }, [validConfig]);\n\n const presignedUrl = artifact.protectedAsset?.presignedUrl ?? null;\n\n // Read this artifact type's slice out of the union labels bag, then merge it over the English\n // defaults. Per-key Partial merge means a consumer can translate `download` and leave future\n // keys to fall back. Memoised so resolved labels are referentially stable across renders.\n const resolvedLabels = useMemo<ChartArtifactLabels>(\n () => ({ ...DEFAULT_CHART_ARTIFACT_LABELS, ...(labels?.[artifactTypes.CHART] ?? {}) }),\n [labels]\n );\n\n // Hook is always called (Rules of Hooks). Pass null URL when config is invalid so the hook\n // short-circuits at its `if (!presignedUrl) return UNAVAILABLE` path — no network fetch fires\n // for an artifact whose config shape can't be rendered.\n const data = useChartArtifactData(\n validConfig ? presignedUrl : null,\n validConfig ? artifact.config : { variant: \"LINE\", series: [], xKey: \"x\" }\n );\n\n // Bridge the consumer's `onDownload` callback into the download button. Wrapped to capture\n // `artifact` so the callback receives analytics context. `undefined` (rather than a no-op)\n // when no callback is wired — keeps the button free of a redundant click listener.\n const onDownload = callbacks?.[artifactTypes.CHART]?.onDownload;\n const handleDownloadClick = onDownload ? () => onDownload(artifact) : undefined;\n\n return (\n <Artifact className=\"shadow-none w-full rounded-2xl bg-background/70\">\n <ArtifactHeader className=\"bg-background/70\">\n {artifact.title ? <ArtifactTitle className={TITLE_CLASSES}>{artifact.title}</ArtifactTitle> : <span />}\n {presignedUrl ? (\n <ArtifactActions>\n <ArtifactDownloadButton href={presignedUrl} label={resolvedLabels.download} onClick={handleDownloadClick} />\n </ArtifactActions>\n ) : null}\n </ArtifactHeader>\n {/*\n `flex-none` overrides ai-elements' default `flex-1`. In a column flex container\n `flex: 1 1 0%` sets `flex-basis: 0%` which beats the inline `height` per CSS flex spec —\n leaving the chart's `ResponsiveContainer` 0px tall with no visible SVG.\n `flex items-center justify-center` vertically + horizontally centres status messages\n (loading / error / unavailable / empty) in the 320px area; the chart itself fills the\n whole box because its `<ChartContainer>` sets `width:100% height:100%`.\n */}\n <ArtifactContent\n className=\"p-4 overflow-visible flex flex-none items-center justify-center\"\n style={{ height: CHART_HEIGHT }}\n >\n {renderBody(validConfig, artifact, data, resolvedLabels)}\n </ArtifactContent>\n </Artifact>\n );\n}\n\n/** Splits the body branches out so the orchestrator's JSX stays readable. Labels are pre-merged\n * by the caller, so each branch reads a single field on a complete object. */\nfunction renderBody(\n validConfig: boolean,\n artifact: ChartArtifactRecord,\n data: ReturnType<typeof useChartArtifactData>,\n labels: ChartArtifactLabels\n): ReactNode {\n if (!validConfig) {\n return <StatusMessage $tone=\"info\">{labels.unavailable}</StatusMessage>;\n }\n if (data.status === \"error\") {\n // No retry hook today — mirrors `TableArtifact`. Wire `onRetry` into `ArtifactService` when\n // a fresh-presigned-URL mint flow exists.\n return <StatusMessage $tone=\"error\">{labels.loadError}</StatusMessage>;\n }\n if (data.status === \"unavailable\") {\n return <StatusMessage $tone=\"info\">{labels.unavailable}</StatusMessage>;\n }\n if (data.status === \"loading\") {\n return <StatusMessage $tone=\"info\">{labels.loading}</StatusMessage>;\n }\n // data.status === \"ready\"\n if (data.rows.length === 0) {\n return <StatusMessage $tone=\"info\">{labels.empty}</StatusMessage>;\n }\n return <ChartArtifactContent config={artifact.config} rows={data.rows} labels={labels} />;\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\n/**\n * Combines class names using clsx and tailwind-merge — the standard shadcn/ui helper.\n * Tailwind classes that conflict (e.g. `p-2 p-4`) get merged so the last one wins.\n */\nexport function cn(...inputs: ClassValue[]): string {\n return twMerge(clsx(inputs));\n}\n","import type { HTMLAttributes } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------------------------------\n * Originally vendored from `@vercel/ai-elements`'s `artifact` registry entry — see\n * https://elements.ai-sdk.dev/api/registry/artifact.json. Slimmed to the chrome primitives clay\n * actually composes (`Artifact`, `ArtifactHeader`, `ArtifactTitle`, `ArtifactActions`,\n * `ArtifactContent`). The original entry also shipped `ArtifactClose`, `ArtifactDescription`, and\n * `ArtifactAction` — all dependent on the shadcn `Button` primitive, none of which clay consumes.\n * Action buttons inside the artifact header use clay's `IconButton` (see `TableArtifact`'s\n * `ExportCsvButton`) instead of a generic shadcn Button, so the design system stays single-sourced.\n *\n * If a future ai-elements re-scaffold needs one of the dropped primitives back, re-add only the\n * piece consumers need and route its inner button through clay's `Button` / `IconButton` rather\n * than re-introducing the shadcn Button file.\n * ------------------------------------------------------------------------------------------------ */\n\nexport type ArtifactProps = HTMLAttributes<HTMLDivElement>;\n\nexport const Artifact = ({ className, ...props }: ArtifactProps) => (\n <div\n className={cn(\"flex flex-col overflow-hidden rounded-lg border bg-background shadow-sm\", className)}\n {...props}\n />\n);\n\nexport type ArtifactHeaderProps = HTMLAttributes<HTMLDivElement>;\n\nexport const ArtifactHeader = ({ className, ...props }: ArtifactHeaderProps) => (\n <div className={cn(\"flex items-center justify-between border-b bg-muted/50 px-4 py-3\", className)} {...props} />\n);\n\nexport type ArtifactTitleProps = HTMLAttributes<HTMLParagraphElement>;\n\nexport const ArtifactTitle = ({ className, ...props }: ArtifactTitleProps) => (\n <p className={cn(\"font-medium text-foreground text-sm\", className)} {...props} />\n);\n\nexport type ArtifactActionsProps = HTMLAttributes<HTMLDivElement>;\n\nexport const ArtifactActions = ({ className, ...props }: ArtifactActionsProps) => (\n <div className={cn(\"flex items-center gap-1\", className)} {...props} />\n);\n\nexport type ArtifactContentProps = HTMLAttributes<HTMLDivElement>;\n\nexport const ArtifactContent = ({ className, ...props }: ArtifactContentProps) => (\n <div className={cn(\"flex-1 overflow-auto p-4\", className)} {...props} />\n);\n","export default {\n outline: {\n xmlns: 'http://www.w3.org/2000/svg',\n width: 24,\n height: 24,\n viewBox: '0 0 24 24',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 2,\n strokeLinecap: 'round',\n strokeLinejoin: 'round',\n },\n filled: {\n xmlns: 'http://www.w3.org/2000/svg',\n width: 24,\n height: 24,\n viewBox: '0 0 24 24',\n fill: 'currentColor',\n stroke: 'none',\n },\n};\n","import { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes';\nimport type { IconNode, IconProps, Icon } from './types';\n\nconst createReactComponent = (\n type: 'outline' | 'filled',\n iconName: string,\n iconNamePascal: string,\n iconNode: IconNode,\n) => {\n const Component = forwardRef<SVGSVGElement, IconProps>(\n (\n { color = 'currentColor', size = 24, stroke = 2, title, className, children, ...rest }: IconProps,\n ref,\n ) =>\n createElement(\n 'svg',\n {\n ref,\n ...defaultAttributes[type],\n width: size,\n height: size,\n className: [`tabler-icon`, `tabler-icon-${iconName}`, className].join(' '),\n ...(type === 'filled'\n ? {\n fill: color,\n }\n : {\n strokeWidth: stroke,\n stroke: color,\n }),\n ...rest,\n },\n [\n title && createElement('title', { key: 'svg-title' }, title),\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...(Array.isArray(children) ? children : [children]),\n ],\n ),\n );\n\n Component.displayName = `${iconNamePascal}`;\n\n return Component;\n};\n\nexport default createReactComponent;\n","import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M7 11l5 5l5 -5\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M12 4l0 12\",\"key\":\"svg-2\"}]]\n\nconst IconDownload = createReactComponent('outline', 'download', 'Download', __iconNode);\n\nexport default IconDownload;","import { forwardRef } from \"react\";\n\nimport { Icon } from \"../icon/icon\";\nimport { Button } from \"./icon-button-styles\";\nimport type { IconButtonProps, IconButtonSize } from \"./types\";\n\nconst ICON_SIZE_BY_BUTTON_SIZE: Record<IconButtonSize, number> = {\n small: 16,\n medium: 20,\n};\n\n/** Ghost-style icon button. `forwardRef` + the rest-props spread so Radix `Slot`-based wrappers\n * (Tooltip, Popover, DropdownMenu) can attach refs and event handlers via `asChild`. */\nexport const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton(\n {\n icon,\n size = \"small\",\n variant = \"short\",\n isSelected = false,\n disabled = false,\n onClick,\n className,\n id,\n as,\n \"aria-label\": ariaLabel,\n ...rest\n },\n ref\n) {\n // Only set `type=\"button\"` when rendering as a native button. Anchors (`as=\"a\"`) treat the\n // `type` attribute as a content-type hint for the linked resource — `type=\"button\"` on an\n // anchor is semantically wrong and shows up as an a11y / HTML-validation noise warning.\n const isNativeButton = as === undefined || as === \"button\";\n return (\n <Button\n ref={ref}\n className={className}\n id={id}\n as={as}\n $size={size}\n $variant={variant}\n $isSelected={isSelected}\n disabled={disabled}\n onClick={disabled ? undefined : onClick}\n aria-label={ariaLabel}\n {...(isNativeButton ? { type: \"button\" as const } : {})}\n {...rest}\n >\n <Icon icon={icon} size={ICON_SIZE_BY_BUTTON_SIZE[size]} />\n </Button>\n );\n});\n","import { forwardRef } from \"react\";\n\nimport { IconWrapper, getStrokeWidth } from \"./icon-styles\";\nimport type { IconProps } from \"./types\";\n\nconst DEFAULT_SIZE = 16;\n\nexport const Icon = forwardRef<HTMLSpanElement, IconProps>(function Icon(\n { icon: IconComponent, size = DEFAULT_SIZE, color, className, \"aria-label\": ariaLabel },\n ref\n) {\n return (\n <IconWrapper\n ref={ref}\n className={className}\n $color={color}\n aria-label={ariaLabel}\n role={ariaLabel ? \"img\" : undefined}\n >\n <IconComponent width={size} height={size} strokeWidth={getStrokeWidth(size)} />\n </IconWrapper>\n );\n});\n","import styled from \"styled-components\";\n\nexport const STROKE_WIDTH_BY_SIZE: Record<number, number> = {\n 12: 1.4,\n 14: 1.4,\n 16: 1.8,\n 18: 1.8,\n 20: 1.8,\n 24: 1.8,\n};\n\nexport const DEFAULT_STROKE_WIDTH = 1.8;\n\nexport function getStrokeWidth(size: number): number {\n return STROKE_WIDTH_BY_SIZE[size] ?? DEFAULT_STROKE_WIDTH;\n}\n\nexport const IconWrapper = styled.span<{ $color?: string }>`\n display: inline-flex;\n align-items: center;\n justify-content: center;\n color: ${({ $color }) => $color ?? \"currentColor\"};\n flex-shrink: 0;\n`;\n","import styled from \"styled-components\";\n\nimport { colors } from \"../../tokens/colors\";\nimport type { IconButtonSize, IconButtonVariant } from \"./types\";\n\nconst PADDING: Record<IconButtonVariant, Record<IconButtonSize, string>> = {\n short: {\n small: \"4px\",\n medium: \"6px\",\n },\n long: {\n small: \"4px 6px\",\n medium: \"6px 10px\",\n },\n};\n\nconst BORDER_RADIUS: Record<IconButtonSize, number> = {\n small: 6,\n medium: 10,\n};\n\nexport const Button = styled.button<{\n $size: IconButtonSize;\n $variant: IconButtonVariant;\n $isSelected: boolean;\n}>`\n display: inline-flex;\n align-items: center;\n justify-content: center;\n padding: ${({ $size, $variant }) => PADDING[$variant][$size]};\n border: none;\n border-radius: ${({ $size }) => BORDER_RADIUS[$size]}px;\n background: ${({ $isSelected }) => ($isSelected ? colors[\"brown-40\"] : \"transparent\")};\n color: ${colors[\"brown-100\"]};\n cursor: pointer;\n transition: background-color 100ms ease;\n\n &:hover {\n background: ${({ $isSelected }) => ($isSelected ? colors[\"brown-40\"] : colors[\"brown-20\"])};\n }\n\n &:active {\n background: ${colors[\"brown-40\"]};\n }\n\n &:disabled {\n color: ${colors[\"brown-50\"]};\n background: transparent;\n cursor: not-allowed;\n }\n`;\n","export const colors = {\n // White\n white: \"#FFFFFF\",\n \"white-alpha-85\": \"rgba(255, 255, 255, 0.85)\",\n \"white-alpha-40\": \"rgba(255, 255, 255, 0.40)\",\n\n // Brown\n \"brown-10\": \"#FAF9F8\",\n \"brown-20\": \"#F5F3F0\",\n \"brown-30\": \"#EEEBE5\",\n \"brown-40\": \"#E6E2DA\",\n \"brown-50\": \"#CFCBC4\",\n \"brown-60\": \"#A19E99\",\n \"brown-70\": \"#73716D\",\n \"brown-80\": \"#5C5A57\",\n \"brown-90\": \"#2E2D2C\",\n \"brown-100\": \"#171716\",\n \"brown-alpha-12\": \"rgba(23, 23, 22, 0.12)\",\n \"brown-alpha-20\": \"rgba(23, 23, 22, 0.20)\",\n \"brown-alpha-55\": \"rgba(23, 23, 22, 0.55)\",\n \"brown-alpha-70\": \"rgba(23, 23, 22, 0.70)\",\n \"brown-alpha-80\": \"rgba(23, 23, 22, 0.80)\",\n \"brown-alpha-90\": \"rgba(23, 23, 22, 0.90)\",\n\n // Fuchsia\n \"fuchsia-50\": \"#FAF5FF\",\n \"fuchsia-300\": \"#F0ABFC\",\n \"fuchsia-500\": \"#D946EF\",\n \"fuchsia-600\": \"#C026D3\",\n \"fuchsia-800\": \"#86198F\",\n\n // Pink\n \"pink-50\": \"#FDF2F8\",\n \"pink-400\": \"#F472B6\",\n \"pink-600\": \"#DB2777\",\n \"pink-800\": \"#9D174D\",\n\n // Violet\n \"violet-50\": \"#F5F3FF\",\n \"violet-400\": \"#A78BFA\",\n \"violet-600\": \"#7C3AED\",\n \"violet-800\": \"#5B21B6\",\n\n // Indigo\n \"indigo-50\": \"#EEF2FF\",\n \"indigo-400\": \"#818CF8\",\n \"indigo-500\": \"#6366F1\",\n \"indigo-600\": \"#4F46E5\",\n \"indigo-800\": \"#3730A3\",\n\n // Cyan\n \"cyan-50\": \"#E7FEFF\",\n \"cyan-300\": \"#67E8F9\",\n \"cyan-600\": \"#0891B2\",\n \"cyan-900\": \"#164E63\",\n\n // Teal\n \"teal-50\": \"#EBFDF9\",\n \"teal-300\": \"#5EEAD4\",\n \"teal-600\": \"#0D9488\",\n\n // Rose\n \"rose-400\": \"#FB7185\",\n\n // Purple\n \"purple-400\": \"#C084FC\",\n\n // Blue\n \"blue-50\": \"#EFF6FF\",\n \"blue-100\": \"#DBEAFE\",\n \"blue-300\": \"#93C5FD\",\n \"blue-400\": \"#60A5FA\",\n \"blue-600\": \"#2563EB\",\n \"blue-800\": \"#1E40AF\",\n\n // Sky\n \"sky-300\": \"#7DD3FC\",\n\n // Green\n \"green-50\": \"#ECF9F0\",\n \"green-100\": \"#D4F1D9\",\n \"green-400\": \"#3DC269\",\n \"green-700\": \"#277C43\",\n \"green-800\": \"#1C5930\",\n\n // Orange\n \"orange-50\": \"#FFF7ED\",\n \"orange-100\": \"#FFEDD5\",\n \"orange-200\": \"#FED7AA\",\n \"orange-500\": \"#F97316\",\n \"orange-600\": \"#EA580C\",\n\n // Red\n \"red-50\": \"#FEF2F2\",\n \"red-100\": \"#FEE2E2\",\n \"red-200\": \"#FECACA\",\n \"red-400\": \"#F7776C\",\n \"red-500\": \"#EF4444\",\n \"red-600\": \"#DC2626\",\n} as const;\n\nexport type ColorToken = keyof typeof colors;\n","import * as React from \"react\";\nimport * as TooltipPrimitive from \"@radix-ui/react-tooltip\";\n\nimport { cn } from \"@/lib/utils\";\n\nconst TooltipProvider = TooltipPrimitive.Provider;\n\nconst Tooltip = TooltipPrimitive.Root;\n\nconst TooltipTrigger = TooltipPrimitive.Trigger;\n\nconst TooltipContent = React.forwardRef<\n React.ElementRef<typeof TooltipPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>\n>(({ className, sideOffset = 4, ...props }, ref) => (\n <TooltipPrimitive.Content\n ref={ref}\n sideOffset={sideOffset}\n className={cn(\n \"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]\",\n className\n )}\n {...props}\n />\n));\nTooltipContent.displayName = TooltipPrimitive.Content.displayName;\n\nexport { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };\n","import { IconDownload } from \"@tabler/icons-react\";\nimport type { ReactNode } from \"react\";\n\nimport { IconButton } from \"@/components/icon-button/icon-button\";\nimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from \"@/components/ui/tooltip\";\n\n/** English fallback label. Each per-type artifact passes a localized label in via the\n * `labels` prop; this default keeps the button usable for any consumer rendering it standalone. */\nconst DEFAULT_LABEL = \"Download CSV\";\n\n/** Props for `ArtifactDownloadButton`. */\nexport interface ArtifactDownloadButtonProps {\n /**\n * URL to download the artifact's underlying bytes. The button is an `<a href download>` so the\n * browser uses whatever filename the server supplies via `Content-Disposition`. No client-side\n * filename invention.\n *\n * Renders nothing when the URL is not a safe `http(s):` scheme — guards against `javascript:` or\n * `data:` URIs smuggled into `presignedUrl`.\n */\n href: string;\n /**\n * Tooltip text + `aria-label` for the button. Optional — defaults to `\"Download CSV\"` so direct\n * consumers don't have to pass anything for the common case. Per-type artifact orchestrators\n * (`<ChartArtifact>`, `<TableArtifact>`) pass a translated value via their own `labels` prop so\n * the button reads in the user's language.\n */\n label?: string;\n /**\n * Optional callback fired on click — runs alongside the browser's native download navigation\n * (no `preventDefault`). Used for analytics / observability hooks; per-type artifact\n * orchestrators wire this from their `callbacks` prop.\n */\n onClick?: () => void;\n}\n\n/**\n * Reusable download button for artifact headers. Anchor-based so the browser handles the download\n * natively (respects `Content-Disposition`, falls back to URL basename). `rel=\"noopener noreferrer\"`\n * defends against `window.opener` leakage if the browser opens the URL instead of downloading.\n *\n * Drop this inside `<ArtifactActions>` in any per-type artifact orchestrator.\n */\nexport function ArtifactDownloadButton({\n href,\n label = DEFAULT_LABEL,\n onClick,\n}: ArtifactDownloadButtonProps): ReactNode {\n if (!isSafeDownloadUrl(href)) return null;\n return (\n <TooltipProvider>\n <Tooltip>\n <TooltipTrigger asChild>\n <IconButton\n as=\"a\"\n href={href}\n download\n rel=\"noopener noreferrer\"\n onClick={onClick}\n icon={IconDownload}\n size=\"small\"\n aria-label={label}\n />\n </TooltipTrigger>\n <TooltipContent>{label}</TooltipContent>\n </Tooltip>\n </TooltipProvider>\n );\n}\n\n/**\n * Returns `true` only for `http:` and `https:` URLs. Rejects `javascript:`, `data:`, and any\n * other scheme that could execute code on click.\n */\nexport function isSafeDownloadUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n return parsed.protocol === \"https:\" || parsed.protocol === \"http:\";\n } catch {\n return false;\n }\n}\n","import type { ReactNode } from \"react\";\n\nimport { createElement } from \"react\";\n\ninterface StatusMessageProps {\n /** Visual tone: \"error\" renders red copy, \"info\" renders muted brown copy. */\n $tone?: \"info\" | \"error\";\n children: ReactNode;\n}\n\n/**\n * Centred status copy rendered inside an artifact when there is nothing to show — loading\n * without a known size, error, or unavailable. Shared across every artifact kind that needs\n * an inline status surface; Tailwind-styled so it stays consistent with the artifact chrome.\n */\nexport function StatusMessage({ $tone, children }: StatusMessageProps): ReactNode {\n return createElement(\n \"div\",\n {\n className: `py-6 px-2 text-center text-sm font-medium leading-5 ${\n $tone === \"error\" ? \"text-red-600\" : \"text-brown-70\"\n }`,\n },\n children\n );\n}\n","import { type ReactNode, useMemo } from \"react\";\nimport { Bar, BarChart as RechartsBarChart, CartesianGrid, LabelList, Legend, Tooltip, XAxis, YAxis } from \"recharts\";\n\nimport { ChartContainer } from \"../chart-container\";\nimport { ChartLegendContent } from \"../chart-legend-content\";\nimport { ChartTooltipContent } from \"../chart-tooltip-content\";\nimport { CHART_PALETTE, colorForSeriesIndex } from \"../chart-palette\";\nimport {\n BAR_TOOLTIP_CURSOR_FILL,\n CHART_AXIS_PROPS,\n CHART_GRID_PROPS,\n CHART_MARGIN,\n CHART_VALUE_LABEL_STYLE,\n} from \"../chart-styles\";\nimport { defaultBarTickFormatter } from \"../chart-tick-utils\";\nimport { coerceNumericColumns } from \"../coerce-numeric\";\nimport type { ChartSeries } from \"../types\";\n\nexport interface BarChartProps {\n /** Rows to plot. Each row should carry the `xKey` column and one column per `series[].key`. */\n data: ReadonlyArray<Record<string, unknown>>;\n /** CSV/data column to use for the categorical x-axis (e.g. `\"month\"`, `\"quarter\"`). */\n xKey: string;\n /** One descriptor per bar series. Length 1 = single-series chart; 2+ = grouped or stacked. */\n series: ChartSeries[];\n /**\n * When true, all series stack on one stack-id (vertical sum). When false (default), bars\n * group side-by-side per x-tick.\n */\n stacked?: boolean;\n /** Container height. Number = px, string = any CSS length. Default 320. */\n height?: number | string;\n /** Container width. Default `\"100%\"`. */\n width?: number | string;\n /** Optional className on the outer container. */\n className?: string;\n /** Override the default palette (`CHART_PALETTE`). Colors are assigned by series index. */\n palette?: readonly string[];\n /** Show the tooltip on hover. Default true. */\n showTooltip?: boolean;\n /**\n * Show the legend at the top. **Default behavior**: auto-hidden for single-series charts\n * (the legend would just label the one and only color, which is noise). Pass `true` to force\n * the legend even with one series; pass `false` to suppress for multi-series.\n */\n showLegend?: boolean;\n /** Show horizontal dashed grid lines. Default true. */\n showGrid?: boolean;\n /** Show the x-axis. Default true. */\n showXAxis?: boolean;\n /** Show the y-axis. Default true. */\n showYAxis?: boolean;\n /**\n * Show numeric value labels above each bar. **Default behavior**: auto-on for single\n * non-stacked series (labels stay readable); auto-off for stacked or multi-series bars\n * (labels overlap and clutter). Pass explicitly to override.\n */\n showValueLabels?: boolean;\n /**\n * Recharts XAxis tick `interval`. Default `0` — every category gets a label (no info loss\n * from auto-skipping). Use `\"preserveStartEnd\"` to let recharts drop colliding labels but\n * keep the first and last. For long category names, prefer `xAxisAngle` to rotate the labels\n * rather than dropping them.\n */\n xAxisInterval?: number | \"preserveStart\" | \"preserveEnd\" | \"preserveStartEnd\";\n /**\n * Rotate x-axis tick labels by this many degrees. **Default**: auto — `0` (horizontal) for\n * ≤7 categories; `-30` for 8+ categories so longer labels fit diagonally without overlapping\n * their neighbours. Pass `0` explicitly to force horizontal labels even at high counts; pass\n * any other number to set a custom angle.\n *\n * When the resolved angle is non-zero the chart auto-bumps its bottom margin and right-\n * anchors the labels so they don't run off the axis. The container `height` budget should\n * accommodate the angled labels (~40-60px more).\n */\n xAxisAngle?: number;\n /**\n * Custom formatter for x-axis tick labels. **Default**: clay auto-truncates labels based on\n * the number of categories so no labels overlap (see `getDefaultTickFormatter`). Pass an\n * explicit formatter to override — e.g. for word-boundary truncation, locale-aware\n * abbreviations, or to opt out of truncation entirely with `(v) => String(v)`.\n *\n * The tooltip continues to show the full unformatted value on hover regardless.\n */\n xAxisTickFormatter?: (value: unknown) => string;\n}\n\n/**\n * Pre-composed bar chart. Single-call usage for the common case; for custom recharts trees\n * compose `<ChartContainer>` + recharts primitives directly.\n *\n * ```tsx\n * <BarChart\n * data={[{ month: \"Jan\", us: 120, uk: 60 }, { month: \"Feb\", us: 132, uk: 64 }]}\n * xKey=\"month\"\n * series={[\n * { key: \"us\", label: \"US\" },\n * { key: \"uk\", label: \"UK\" },\n * ]}\n * stacked\n * />\n * ```\n *\n * **Smart defaults**: legend auto-hides for single-series charts; value labels auto-show for\n * single non-stacked series; all x-axis ticks are shown by default (no recharts auto-skip).\n * Override any of these via the named props.\n *\n * Numeric coercion: `data` rows may carry string values for the series columns (e.g. when\n * derived from CSV) — recharts needs numbers, so we coerce in-place. Already-numeric data\n * passes through unchanged.\n */\nexport function BarChart({\n data,\n xKey,\n series,\n stacked = false,\n height = 320,\n width = \"100%\",\n className,\n palette = CHART_PALETTE,\n showTooltip = true,\n showLegend,\n showGrid = true,\n showXAxis = true,\n showYAxis = true,\n showValueLabels,\n xAxisInterval = 0,\n xAxisAngle,\n xAxisTickFormatter,\n}: BarChartProps): ReactNode {\n const seriesKeys = useMemo(() => series.map((s) => s.key), [series]);\n // Memoised so non-artifact consumers passing inline `data` arrays don't re-allocate the\n // coerced copy on every parent render. For the artifact path `data` is already stable from\n // `useRowsArtifactData`, so this is a no-op there.\n const coercedData = useMemo(\n () => coerceNumericColumns(data as ReadonlyArray<Record<string, unknown>>, seriesKeys),\n [data, seriesKeys]\n );\n\n // Smart defaults — see prop JSDoc for rationale.\n const resolvedShowLegend = showLegend ?? series.length > 1;\n const resolvedShowValueLabels = showValueLabels ?? (!stacked && series.length === 1);\n // Auto-angle for dense bar charts: at 8+ categories the horizontal slot per label is too\n // narrow for full-text labels to fit. Rotating to -30° lets labels extend diagonally below\n // the axis without overlapping their neighbours. Consumer can override with `xAxisAngle={0}`.\n const resolvedAngle = xAxisAngle ?? (coercedData.length >= 8 ? -30 : 0);\n // Auto-truncating tick formatter — keeps every bar labeled while preventing overlap. The\n // tooltip shows the full unformatted value on hover, so no information is lost. Consumer\n // can opt out with `(v) => String(v)`.\n const resolvedTickFormatter = useMemo(\n () => xAxisTickFormatter ?? defaultBarTickFormatter(coercedData.length),\n [xAxisTickFormatter, coercedData.length]\n );\n\n // Angled labels need extra bottom margin so they don't clip the chart. ~0.7px per degree\n // covers up to -45° comfortably; we cap to avoid runaway when callers pass aggressive angles.\n const angledLabelPad = resolvedAngle === 0 ? 0 : Math.min(Math.abs(resolvedAngle) * 0.7, 40);\n const chartMargin = { ...CHART_MARGIN, bottom: CHART_MARGIN.bottom + angledLabelPad };\n\n return (\n <ChartContainer height={height} width={width} className={className}>\n <RechartsBarChart data={coercedData} margin={chartMargin} barCategoryGap=\"22%\">\n {showGrid ? <CartesianGrid {...CHART_GRID_PROPS} /> : null}\n {showXAxis ? (\n <XAxis\n dataKey={xKey}\n {...CHART_AXIS_PROPS}\n interval={xAxisInterval}\n angle={resolvedAngle}\n // Right-anchor angled labels so the end of each label aligns with its tick, rather\n // than the centre running off the axis. Middle-anchor for horizontal labels.\n textAnchor={resolvedAngle !== 0 ? \"end\" : \"middle\"}\n tickMargin={resolvedAngle === 0 ? 8 : 12}\n height={resolvedAngle !== 0 ? 60 : undefined}\n tickFormatter={resolvedTickFormatter}\n />\n ) : null}\n {showYAxis ? <YAxis {...CHART_AXIS_PROPS} width={40} /> : null}\n {showTooltip ? <Tooltip cursor={{ fill: BAR_TOOLTIP_CURSOR_FILL }} content={<ChartTooltipContent />} /> : null}\n {resolvedShowLegend ? (\n <Legend\n verticalAlign=\"top\"\n align=\"center\"\n // Pin the absolutely-positioned wrapper flush to the chart's top edge. Recharts'\n // default `top` for a top-aligned legend leaves a gap above the swatches; we'd\n // rather let `CHART_MARGIN.top` control the breathing room below the legend.\n wrapperStyle={{ top: 0 }}\n // Recharts 3.x defaults `itemSorter` to `'value'`, which alphabetically sorts legend\n // entries by label. The tooltip, the stack, and our chart's series colours all follow\n // declaration order — sorting the legend silently breaks correspondence (an \"Others\"\n // series declared last ends up mid-legend alphabetically). `null` disables the sort.\n itemSorter={null}\n content={<ChartLegendContent iconType=\"square\" />}\n />\n ) : null}\n {series.map((s, i) => (\n <Bar\n key={s.key}\n dataKey={s.key}\n name={s.label}\n fill={colorForSeriesIndex(i, palette)}\n stackId={stacked ? \"default\" : s.key}\n radius={barRadius(stacked, i, series.length)}\n >\n {resolvedShowValueLabels ? (\n <LabelList dataKey={s.key} position=\"top\" style={CHART_VALUE_LABEL_STYLE} />\n ) : null}\n </Bar>\n ))}\n </RechartsBarChart>\n </ChartContainer>\n );\n}\n\n/**\n * Per-corner border radius for a bar at position `seriesIndex` in `seriesCount` total series.\n *\n * - **Grouped (non-stacked)** — every series rounded at the top (`[6, 6, 0, 0]`). Bottom sits\n * on the X-axis, so flat bottom looks correct.\n * - **Stacked** — only the top-most segment gets `[6, 6, 0, 0]`; bottom + middle segments are\n * squared so the rect joins look seamless. Bottom segment is flat too because the chart's\n * X-axis is its base.\n */\nfunction barRadius(stacked: boolean, seriesIndex: number, seriesCount: number): [number, number, number, number] {\n if (!stacked) return [6, 6, 0, 0];\n const isTopSegment = seriesIndex === seriesCount - 1;\n return isTopSegment ? [6, 6, 0, 0] : [0, 0, 0, 0];\n}\n","import { type CSSProperties, type ReactElement, type ReactNode } from \"react\";\nimport { ResponsiveContainer } from \"recharts\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport interface ChartContainerProps {\n /** A single recharts chart element — `<LineChart>`, `<BarChart>`, `<PieChart>`, etc. */\n children: ReactElement;\n /**\n * Container height. Recharts' `ResponsiveContainer` measures its parent, so we need a\n * concrete value here (not \"auto\"). Accepts a number (px) or any CSS length string.\n * Defaults to `320` — a sensible mid-density chart height.\n */\n height?: number | string;\n /**\n * Container width. Defaults to `\"100%\"` so the chart flexes to its parent. Pass a fixed\n * number when embedding in a layout that doesn't have a definite width (e.g. an auto-sized\n * flex column).\n */\n width?: number | string;\n /** Optional className spread on the outer wrapper. */\n className?: string;\n /** Optional inline style merged into the outer wrapper. `width`/`height` here take precedence. */\n style?: CSSProperties;\n}\n\n/**\n * The composable foundation for every clay chart. Wraps recharts' `ResponsiveContainer` in a\n * sized `<div>` so the chart has a definite parent box to measure against — without this, charts\n * silently collapse to 0×0 inside flex containers (see the `flex-basis` gotcha documented in\n * the chart-artifact orchestrator).\n *\n * Use directly when composing a chart from recharts primitives:\n *\n * ```tsx\n * <ChartContainer height={320}>\n * <LineChart data={data} margin={{ top: 8, right: 16, left: 0, bottom: 4 }}>\n * <CartesianGrid {...CHART_GRID_PROPS} />\n * <XAxis dataKey=\"month\" {...CHART_AXIS_PROPS} />\n * <YAxis {...CHART_AXIS_PROPS} />\n * <Tooltip content={<ChartTooltipContent />} />\n * <Legend content={<ChartLegendContent />} />\n * <Line dataKey=\"value\" stroke={CHART_PALETTE[0]} />\n * </LineChart>\n * </ChartContainer>\n * ```\n *\n * For common shapes, prefer the pre-composed `<BarChart>` / `<LineChart>` / `<PieChart>` —\n * they call `ChartContainer` under the hood with sensible defaults.\n */\nexport function ChartContainer({\n children,\n height = 320,\n width = \"100%\",\n className,\n style,\n}: ChartContainerProps): ReactNode {\n return (\n <div className={cn(\"text-xs text-foreground\", className)} style={{ width, height, ...style }}>\n <ResponsiveContainer width=\"100%\" height=\"100%\">\n {children}\n </ResponsiveContainer>\n </div>\n );\n}\n","import { type ReactNode } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/**\n * Single entry in recharts' legend payload — one per series. Typed locally because recharts'\n * `LegendProps['payload']` is overly tagged-generic.\n */\ninterface LegendPayloadEntry {\n value?: string | number;\n color?: string;\n dataKey?: string | number;\n type?: string;\n}\n\n/**\n * Recharts injects `payload` at runtime when this component is used as the `content` slot on\n * `<Legend>`. Consumer-facing props (`className`, `iconType`) survive the cloneElement merge.\n */\nexport interface ChartLegendContentProps {\n /** Set by recharts at runtime — one entry per series. */\n payload?: LegendPayloadEntry[];\n /** Optional className merged onto the legend list. */\n className?: string;\n /** Visual indicator next to each label. `square` for bars/pies; `line` for line/area. Default `square`. */\n iconType?: \"square\" | \"line\";\n}\n\n/**\n * The default legend body for clay charts. Drop into any recharts `<Legend>`:\n *\n * ```tsx\n * <Legend content={<ChartLegendContent iconType=\"square\" />} />\n * <Legend content={<ChartLegendContent iconType=\"line\" />} />\n * ```\n *\n * Recharts also accepts `verticalAlign` / `align` on `<Legend>` itself for positioning —\n * `<ChartLegendContent>` is just the body. Style stays consistent regardless of position.\n */\nexport function ChartLegendContent({ payload, className, iconType = \"square\" }: ChartLegendContentProps): ReactNode {\n if (!payload || payload.length === 0) return null;\n\n return (\n <ul\n // No padding on this `<ul>`. Recharts wraps it in a `.recharts-legend-wrapper` div that's\n // positioned `absolute` with an inline `top` — padding here doesn't shift the wrapper's\n // anchor point, it only inflates the wrapper's height. The \"gap above the legend\" must be\n // controlled by the wrapper's inline `top`, set via each chart's `<Legend wrapperStyle>`.\n className={cn(\"flex flex-wrap items-center justify-center gap-x-4 gap-y-2 text-xs text-brown-80\", className)}\n >\n {payload.map((entry: LegendPayloadEntry, i: number) => {\n const swatchColor = typeof entry.color === \"string\" ? entry.color : \"transparent\";\n const label = entry.value !== undefined ? String(entry.value) : \"\";\n return (\n <li key={`${label}-${i}`} className=\"flex items-center gap-1.5\">\n {iconType === \"square\" ? (\n <span className=\"inline-block h-2.5 w-2.5 shrink-0 rounded-sm\" style={{ background: swatchColor }} />\n ) : (\n <span className=\"inline-block h-[3px] w-4 shrink-0 rounded-full\" style={{ background: swatchColor }} />\n )}\n <span>{label}</span>\n </li>\n );\n })}\n </ul>\n );\n}\n","import { type ReactNode } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/**\n * Single entry in recharts' tooltip payload — one per series at the hovered x-tick.\n * Typed locally because recharts' `TooltipProps['payload']` is overly tagged-generic for this use.\n */\ninterface TooltipPayloadEntry {\n name?: string | number;\n value?: number | string;\n color?: string;\n dataKey?: string | number;\n}\n\n/**\n * Recharts injects `active`, `payload`, and `label` at runtime when this component is used as\n * the `content` slot on `<Tooltip>`. Consumer-facing props (`className`, `showLabel`,\n * `formatValue`) survive the cloneElement merge.\n */\nexport interface ChartTooltipContentProps {\n /** Set by recharts at runtime — true when the tooltip is hovered open. */\n active?: boolean;\n /** Set by recharts at runtime — one entry per series. */\n payload?: TooltipPayloadEntry[];\n /** Set by recharts at runtime — the x-tick label for the hovered column. */\n label?: string | number;\n /** Optional className merged onto the tooltip card. */\n className?: string;\n /** When false, the row label (typically the x-tick value) is hidden. Default true. */\n showLabel?: boolean;\n /** Override the formatter used on each entry's value. Defaults to `String(value)`. */\n formatValue?: (value: number | string | undefined, name: string | undefined) => string;\n}\n\n/**\n * The default tooltip card for clay charts. Drop into any recharts `<Tooltip>`:\n *\n * ```tsx\n * <Tooltip content={<ChartTooltipContent />} />\n * <Tooltip content={<ChartTooltipContent formatValue={(v) => `$${v}`} />} />\n * ```\n *\n * Renders a soft brown card with one row per series, swatch left, name center, value right.\n * Returns `null` when recharts says the tooltip is inactive — recharts mounts the content\n * component unconditionally and toggles it via the `active` prop.\n */\nexport function ChartTooltipContent({\n active,\n payload,\n label,\n className,\n showLabel = true,\n formatValue,\n}: ChartTooltipContentProps): ReactNode {\n if (!active || !payload || payload.length === 0) return null;\n\n return (\n <div\n className={cn(\n \"rounded-lg border border-brown-40 bg-brown-10 px-3 py-2 text-xs shadow-sm\",\n \"min-w-32 text-foreground\",\n className\n )}\n >\n {showLabel && label !== undefined && label !== null ? (\n <div className=\"mb-1.5 font-medium text-brown-90\">{String(label)}</div>\n ) : null}\n <ul className=\"space-y-1\">\n {payload.map((entry: TooltipPayloadEntry, i: number) => {\n const name = entry.name !== undefined ? String(entry.name) : \"\";\n const rawValue = entry.value;\n const display = formatValue ? formatValue(rawValue, name) : rawValue === undefined ? \"\" : String(rawValue);\n const swatch = typeof entry.color === \"string\" ? entry.color : \"transparent\";\n return (\n <li key={`${name}-${i}`} className=\"flex items-center gap-2\">\n <span className=\"inline-block h-2.5 w-2.5 shrink-0 rounded-sm\" style={{ background: swatch }} />\n <span className=\"text-brown-70\">{name}</span>\n <span className=\"ml-auto font-semibold tabular-nums text-brown-90\">{display}</span>\n </li>\n );\n })}\n </ul>\n </div>\n );\n}\n","import { colors } from \"@/tokens\";\n\n/**\n * Single ordered color palette shared by every chart variant (`BarChart`, `LineChart`,\n * `PieChart`). A graduated walk down the blue family (`blue-600` → `blue-400` → `blue-300` →\n * `blue-100`), pivot into the indigo family (`indigo-400` → `indigo-500` → `indigo-600` →\n * `indigo-800`), and close on the deepest blue (`blue-800`).\n *\n * Design intent: every chart in the product sits in the same cool blue / indigo family so\n * adjacent charts on a dashboard read as a unified system rather than a kaleidoscope. The\n * deliberately narrow hue range (blue + indigo only — no warm accents) is the point: it\n * forecloses on rainbow-coded multi-series charts where the visual noise outweighs the\n * series-distinction it tries to provide.\n *\n * **Same palette for pie too**: pie slices read as parts of a whole, but they also share a\n * dashboard with bar/line charts — keeping one palette across every variant means a single\n * chat surface containing all three variants looks like one design system, not three.\n *\n * Nine entries — the v1 series cap. The palette cycles modulo its length for series counts\n * past nine via `colorForSeriesIndex`.\n */\nexport const CHART_PALETTE = [\n colors[\"blue-600\"], // #2563EB — primary\n colors[\"blue-400\"], // #60A5FA — mid\n colors[\"blue-300\"], // #93C5FD — light\n colors[\"blue-100\"], // #DBEAFE — very light\n colors[\"indigo-400\"], // #818CF8\n colors[\"indigo-500\"], // #6366F1\n colors[\"indigo-600\"], // #4F46E5\n colors[\"indigo-800\"], // #3730A3\n colors[\"blue-800\"], // #1E40AF — deepest\n] as const;\n\n/**\n * Slice color reserved for the \"Others\" bucket in pie charts. Neutral warm grey so it reads as\n * \"leftover / unattributed\" rather than a peer category. Pinning to a constant (rather than the\n * tail of `CHART_PALETTE`) means an Others slice always renders identically regardless of how\n * many named categories the data carries before it.\n */\nexport const OTHERS_SLICE_COLOR = colors[\"brown-60\"];\n\n/**\n * English fallback labels treated as the \"Others\" bucket — case-insensitive match.\n *\n * Consumers should pass their own localized list to `<PieChart>` via the `othersCategoryLabels`\n * prop (or via the artifact's `labels.othersCategoryLabels`) — in non-English UIs the agent\n * writes a translated bucket name (e.g. \"אחרים\", \"Otros\", \"Anderen\") and the consumer's i18n\n * layer is the only place that knows which strings to map to grey/last.\n */\nexport const DEFAULT_OTHERS_CATEGORY_LABELS: readonly string[] = [\"others\", \"other\"];\n\n/**\n * True when `value` matches one of `labels` (case-insensitive, trims whitespace). `labels` is\n * required — consumers pass either `DEFAULT_OTHERS_CATEGORY_LABELS` (English fallback) or their\n * own translated list. Pass an empty array to disable Others detection entirely.\n */\nexport function isOthersCategory(value: unknown, labels: readonly string[]): boolean {\n if (value === null || value === undefined) return false;\n if (labels.length === 0) return false;\n const normalized = String(value).trim().toLowerCase();\n for (const label of labels) {\n if (normalized === label.toLowerCase()) return true;\n }\n return false;\n}\n\n/**\n * Resolves the color for a series at `index`. Cycles deterministically past the palette length\n * so configurations with more series than colors still render rather than throwing. Pass an\n * alternate `palette` (e.g. a brand-specific override) to use something other than the default\n * `CHART_PALETTE`.\n */\nexport function colorForSeriesIndex(index: number, palette: readonly string[] = CHART_PALETTE): string {\n return palette[index % palette.length] ?? CHART_PALETTE[0];\n}\n","import { colors } from \"@/tokens\";\n\n/**\n * Shared visual constants for every chart variant. Two flavours of export:\n *\n * 1. Raw constants (`GRID_STROKE`, `AXIS_STROKE`, …) — for one-off uses or custom recharts trees.\n * 2. Preset prop bundles (`CHART_AXIS_PROPS`, `CHART_GRID_PROPS`) — spreadable into recharts\n * primitives so consumers can build composable charts without restating defaults:\n *\n * ```tsx\n * <CartesianGrid {...CHART_GRID_PROPS} />\n * <XAxis dataKey=\"x\" {...CHART_AXIS_PROPS} tickMargin={8} />\n * ```\n *\n * Recharts primitives must be inlined inside the chart tree — recharts identifies its slot\n * children by component reference (`child.type === XAxis`), so wrapping them in a custom React\n * component breaks dispatch. Constants and preset props are the right shape to share.\n */\n\n// ── raw color constants ──────────────────────────────────────────────────────────────────────\n\n/** Horizontal grid line color — kept soft so the data dominates the visual hierarchy. */\nexport const GRID_STROKE = colors[\"brown-40\"];\n\n/** Axis-line + axis-tick color. Lighter than the tick text so the axis frames rather than competes. */\nexport const AXIS_STROKE = colors[\"brown-50\"];\n\n/** Axis tick label text style. */\nexport const AXIS_TICK_STYLE = {\n fill: colors[\"brown-70\"],\n fontSize: 12,\n fontWeight: 500,\n} as const;\n\n/**\n * Text style for data-point value labels — bars (`<LabelList position=\"top\">`), line\n * data-point labels, and pie slice value labels all use this so labels read as one visual\n * family regardless of chart variant. Matches `AXIS_TICK_STYLE` for color/weight/size so\n * every secondary text element in a chart sits at the same hierarchy level.\n */\nexport const CHART_VALUE_LABEL_STYLE = {\n fill: colors[\"brown-70\"],\n fontSize: 12,\n fontWeight: 500,\n} as const;\n\n/** Cursor (hover guide) fill for bar tooltips. */\nexport const BAR_TOOLTIP_CURSOR_FILL = colors[\"brown-alpha-12\"];\n\n/** Active-dot ring fill on hovered line points — matches the chart background so the dot reads raised. */\nexport const LINE_ACTIVE_DOT_STROKE = colors[\"brown-10\"];\n\n/** Default recharts margin — leaves room for axis ticks/labels and the bottom legend. */\nexport const CHART_MARGIN = { top: 8, right: 16, left: 0, bottom: 4 } as const;\n\n/** Pie-specific margin — extra horizontal room to absorb outside slice labels. */\nexport const PIE_CHART_MARGIN = { top: 0, right: 24, left: 24, bottom: 4 } as const;\n\n// ── preset prop bundles ──────────────────────────────────────────────────────────────────────\n\n/**\n * Spreadable defaults for `<XAxis>` and `<YAxis>` — no axis line, no tick line, soft brown ticks.\n * Pass `dataKey` explicitly on `<XAxis>`; leave it off `<YAxis>`. Override anything per-instance.\n */\nexport const CHART_AXIS_PROPS = {\n stroke: AXIS_STROKE,\n tick: AXIS_TICK_STYLE,\n tickLine: false,\n axisLine: false,\n} as const;\n\n/**\n * Spreadable defaults for `<CartesianGrid>` — horizontal dashed lines only.\n */\nexport const CHART_GRID_PROPS = {\n stroke: GRID_STROKE,\n strokeDasharray: \"3 3\",\n vertical: false,\n} as const;\n","/**\n * Shared x-axis tick helpers used by both `BarChart` and `LineChart`. Pulled into one module so\n * the truncation thresholds and the truncation algorithm itself stay in one place — otherwise\n * each variant evolves its own slightly-different heuristic and the charts read inconsistently\n * side-by-side.\n *\n * Bar uses `defaultBarTickFormatter` (label per category, truncated when dense).\n * Line uses `defaultLineChartTickFormatter` (label only at evenly-distributed indices).\n * Both share the `maxTickCharsByCategoryCount` ladder and the `truncateLabel` ellipsis logic.\n */\n\n/**\n * Max characters per x-axis tick label, keyed by category count. The thresholds approximate the\n * available pixel slot per tick on a typical chat-card-width chart (~700px plot area) at the\n * default 12px tick font size. Sparse charts get no truncation; dense charts get aggressive\n * trimming so labels stop overlapping.\n *\n * Consumers can override the entire formatting via `xAxisTickFormatter` on either chart.\n */\nexport function maxTickCharsByCategoryCount(n: number): number {\n if (n <= 5) return 24; // effectively no truncation\n if (n <= 8) return 14;\n if (n <= 12) return 10;\n if (n <= 16) return 7;\n return 5;\n}\n\n/**\n * Truncates one label per the per-count cap. Trailing whitespace before the ellipsis is trimmed\n * so \"Human Resources\" with cap=7 becomes \"Human…\" not \"Human …\" (reads cleaner).\n */\nexport function truncateLabel(value: unknown, maxChars: number): string {\n const s = String(value ?? \"\");\n if (s.length <= maxChars) return s;\n return s.slice(0, Math.max(1, maxChars - 1)).trimEnd() + \"…\";\n}\n\n/**\n * Returns the set of data-point indices whose label should be visible. First and last always\n * included; the remaining (target - 2) are evenly distributed across the interior. Avoids the\n * \"cluster in the middle\" failure mode of recharts' built-in `preserveStartEnd`.\n *\n * Example for N=12, target=5: visible indices are {0, 3, 5, 8, 11} — 5 evenly-spaced labels.\n * Used by `LineChart` to thin x-axis labels at high data-point counts while keeping every data\n * point drawn.\n */\nexport function evenlyDistributedVisibleIndices(n: number, target: number): Set<number> {\n if (n <= target) {\n return new Set(Array.from({ length: n }, (_, i) => i));\n }\n const set = new Set<number>();\n const step = (n - 1) / (target - 1);\n for (let i = 0; i < target; i++) {\n set.add(Math.round(i * step));\n }\n return set;\n}\n\n/**\n * Per-category truncating formatter used as `BarChart`'s default `tickFormatter`. Every category\n * gets a label (no info loss from auto-skipping) but long labels get truncated by the\n * `maxTickCharsByCategoryCount` ladder so dense charts don't overlap.\n */\nexport function defaultBarTickFormatter(categoryCount: number): (value: unknown) => string {\n const max = maxTickCharsByCategoryCount(categoryCount);\n return (value) => truncateLabel(value, max);\n}\n\n/**\n * Per-index truncating formatter used as `LineChart`'s default `tickFormatter`. Returns the\n * (truncated) label only for indices in `visibleIndices`; the rest return `\"\"` so recharts\n * renders no text there. The data point itself still draws.\n *\n * Truncation is keyed by the *visible* tick count, not the total data-point count: LINE thins\n * its labels via `visibleIndices` (typically 5-7 visible ticks even at N=100+ data points), so\n * each rendered label has plenty of pixel room. Using `categoryCount` here would cap labels\n * like \"Dec 2022\" to 5 characters on a 50-month chart and clip them to \"Dec…\" even though only\n * ~5 ticks actually render. `BarChart` keeps using `categoryCount` because every category gets\n * a tick there — density really is data-point count.\n */\nexport function defaultLineChartTickFormatter(\n categoryCount: number,\n visibleIndices: Set<number>\n): (value: unknown, index: number) => string {\n const max = maxTickCharsByCategoryCount(visibleIndices.size || categoryCount);\n return (value, index) => {\n if (!visibleIndices.has(index)) return \"\";\n return truncateLabel(value, max);\n };\n}\n","/**\n * Returns a shallow copy of `rows` with the `numericKeys` columns coerced to `number`.\n * Cells that can't be parsed become `NaN`; `null` / `undefined` cells pass through untouched;\n * columns NOT in `numericKeys` pass through unchanged.\n *\n * Recharts needs `number` on `dataKey` resolution for `<Line>` / `<Bar>` / `<Pie>` — already-\n * numeric data is a no-op. The function exists for the CSV-derived case where values arrive\n * as strings. `NaN` propagates to recharts as a missing data point (zero-height bar, gap in\n * line, zero-area slice).\n */\nexport function coerceNumericColumns(\n rows: ReadonlyArray<Record<string, unknown>>,\n numericKeys: ReadonlyArray<string>\n): Array<Record<string, unknown>> {\n return rows.map((row) => {\n const out: Record<string, unknown> = { ...row };\n for (const k of numericKeys) {\n const v = out[k];\n if (v == null) continue;\n const n = Number(v);\n out[k] = Number.isFinite(n) ? n : NaN;\n }\n return out;\n });\n}\n","/**\n * Shared constants used by every chart variant's render Component.\n *\n * Pulled into one module so a future tweak (e.g. changing the variants to render at a fixed\n * pixel height) is a one-line edit here instead of N matching edits across variant files.\n */\n\n/**\n * Height passed to every variant's chart-library component. `\"100%\"` flexes the chart inside\n * the artifact's content area — the orchestrator (`ChartArtifact`) owns the actual pixel\n * budget (via its own `CHART_HEIGHT`); the variant Components just fill the parent.\n */\nexport const VARIANT_CHART_HEIGHT = \"100%\" as const;\n","import { type ReactNode } from \"react\";\n\nimport { BarChart } from \"@/components/chart/bar-chart/bar-chart\";\nimport type { BarChartConfig } from \"./bar-chart-variant-service\";\nimport { VARIANT_CHART_HEIGHT } from \"./constants\";\nimport type { ChartVariantComponentProps } from \"./types\";\n\n/**\n * Render Component for the `BAR` chart variant. Maps the artifact's wire-shaped\n * `BarChartConfig` onto props for the high-level `<BarChart>` from `@shapesos/clay/chart`.\n *\n * Split out from `bar-chart-variant-service.ts` so the service file stays a pure declarative\n * registration (discriminator + validator + column keys + Component reference) — the React\n * tree lives here.\n */\nexport function BarChartVariantComponent({ config, rows }: ChartVariantComponentProps<BarChartConfig>): ReactNode {\n return (\n <BarChart\n data={rows}\n xKey={config.xKey}\n series={config.series}\n stacked={config.stacked}\n height={VARIANT_CHART_HEIGHT}\n />\n );\n}\n","import type { ChartSeries } from \"@/components/chart/types\";\nimport type { BarChartConfig } from \"./bar-chart-variant-service\";\nimport type { LineChartConfig } from \"./line-chart-variant-service\";\nimport type { PieChartConfig } from \"./pie-chart-variant-service\";\n\n/**\n * CSV-column-projection helpers — one per chart variant. Pulled into this shared module so each\n * variant service file stays focused on the service definition (variant discriminator,\n * isValidConfig, Component) and the column-key extraction lives next to its siblings.\n *\n * Line + Bar share the same shape (`xKey + series.key`) and use the same helper. Pie has its\n * own shape (`categoryKey + valueKey`).\n *\n * Used by each variant service's `columnKeys` field to drive `useChartArtifactData`'s CSV\n * projection (matches the table-artifact projection contract — keep only the columns the chart\n * actually reads, drop the rest).\n */\n\n/** Column keys for LINE / BAR variants: the x-axis column plus every series's data column. */\nexport function seriesBasedColumnKeys(config: LineChartConfig | BarChartConfig): string[] {\n return [config.xKey, ...config.series.map((s: ChartSeries) => s.key)];\n}\n\n/** Column keys for the PIE variant: the slice-label column plus the slice-value column. */\nexport function pieColumnKeys(config: PieChartConfig): string[] {\n return [config.categoryKey, config.valueKey];\n}\n","import type { ChartSeries } from \"@/components/chart/types\";\n\n/**\n * Minimum-viable series shape for LINE / BAR variants: non-empty string `key` + string `label`.\n * Pulled into a shared file so every variant service that consumes `series` reuses one definition.\n */\nexport function isValidChartSeries(series: unknown): series is ChartSeries {\n if (!series || typeof series !== \"object\") return false;\n const candidate = series as Record<string, unknown>;\n if (typeof candidate.key !== \"string\" || candidate.key.length === 0) return false;\n if (typeof candidate.label !== \"string\") return false;\n return true;\n}\n","import type { ChartConfigBase } from \"../types\";\nimport { BarChartVariantComponent } from \"./bar-chart-variant-component\";\nimport { seriesBasedColumnKeys } from \"./shared-column-keys\";\nimport { isValidChartSeries } from \"./shared-validators\";\nimport type { ChartVariantService } from \"./types\";\n\n/**\n * Rendering config for a `BAR` chart. `xKey` selects the categorical axis; each series\n * contributes one `<Bar>`. `stacked` collapses all series onto a single stack-id (so they sum\n * vertically); when false / omitted bars are grouped side-by-side per x-tick.\n */\nexport interface BarChartConfig extends ChartConfigBase {\n variant: \"BAR\";\n /** CSV column key used as the x-axis. */\n xKey: string;\n /** When true, stack all series on one stack-id. When false / omitted, group bars side-by-side. */\n stacked?: boolean;\n}\n\nfunction isValidBarChartConfig(config: unknown): config is BarChartConfig {\n if (!config || typeof config !== \"object\") return false;\n const candidate = config as Record<string, unknown>;\n if (candidate.variant !== \"BAR\") return false;\n if (typeof candidate.xKey !== \"string\" || candidate.xKey.length === 0) return false;\n if (!Array.isArray(candidate.series) || candidate.series.length === 0) return false;\n if (!candidate.series.every(isValidChartSeries)) return false;\n return true;\n}\n\nexport const BarChartVariantService: ChartVariantService<\"BAR\", BarChartConfig> = {\n variant: \"BAR\",\n isValidConfig: isValidBarChartConfig,\n columnKeys: seriesBasedColumnKeys,\n Component: BarChartVariantComponent,\n};\n","import { type ReactNode, useMemo } from \"react\";\nimport {\n CartesianGrid,\n LabelList,\n Legend,\n Line,\n LineChart as RechartsLineChart,\n Tooltip,\n XAxis,\n YAxis,\n} from \"recharts\";\n\nimport { ChartContainer } from \"../chart-container\";\nimport { ChartLegendContent } from \"../chart-legend-content\";\nimport { ChartTooltipContent } from \"../chart-tooltip-content\";\nimport { CHART_PALETTE, colorForSeriesIndex } from \"../chart-palette\";\nimport {\n CHART_AXIS_PROPS,\n CHART_GRID_PROPS,\n CHART_MARGIN,\n CHART_VALUE_LABEL_STYLE,\n LINE_ACTIVE_DOT_STROKE,\n} from \"../chart-styles\";\nimport { defaultLineChartTickFormatter, evenlyDistributedVisibleIndices } from \"../chart-tick-utils\";\nimport { coerceNumericColumns } from \"../coerce-numeric\";\nimport type { ChartSeries } from \"../types\";\n\nexport interface LineChartProps {\n /** Rows to plot. Each row should carry the `xKey` column and one column per `series[].key`. */\n data: ReadonlyArray<Record<string, unknown>>;\n /** Data column for the categorical/temporal x-axis. */\n xKey: string;\n /** One descriptor per line series. */\n series: ChartSeries[];\n /** Render monotone-curve lines instead of straight segments. **Default true** — smooth\n * curves look cleaner for typical chat / dashboard usage. Pass `false` for true linear\n * interpolation (e.g. step-like data where the literal value at each point matters). */\n smooth?: boolean;\n /** Show data-point dots. **Default true** — dots anchor each bin of the line so the viewer\n * can read individual values at a glance. Pass `false` for a pure trend line (dense data sets\n * where dots would crowd, or styling preference for unembellished strokes). */\n showDots?: boolean;\n /** Line stroke width in px. Default 2. */\n strokeWidth?: number;\n /** Container height. Default 320. */\n height?: number | string;\n /** Container width. Default `\"100%\"`. */\n width?: number | string;\n /** Optional className on the outer container. */\n className?: string;\n /** Override the default palette. Colors are assigned by series index. */\n palette?: readonly string[];\n /** Show the tooltip on hover. Default true. */\n showTooltip?: boolean;\n /**\n * Show the legend at the top. **Default behavior**: auto-hidden for single-series charts\n * (the legend would just label the one and only color, which is noise). Pass `true` to force\n * the legend even with one series; pass `false` to suppress for multi-series.\n */\n showLegend?: boolean;\n /** Show horizontal dashed grid lines. Default true. */\n showGrid?: boolean;\n /** Show the x-axis. Default true. */\n showXAxis?: boolean;\n /** Show the y-axis. Default true. */\n showYAxis?: boolean;\n /**\n * Show numeric value labels next to each data point. **Default off** — for line charts with\n * many data points (12+ months × N series) labels overlap quickly. Set `true` for single-series\n * charts with sparse data (e.g. ≤8 points) where the labels stay readable.\n */\n showValueLabels?: boolean;\n /**\n * Recharts XAxis tick `interval`. **Default**: `0` (every tick rendered) — clay's tick\n * formatter blanks out non-key labels so the visible labels stay evenly distributed.\n * Override to a fixed number to force \"every Nth label\", or to a recharts string preset\n * like `\"preserveStartEnd\"` to let recharts pick.\n */\n xAxisInterval?: number | \"preserveStart\" | \"preserveEnd\" | \"preserveStartEnd\";\n /**\n * Rotate x-axis tick labels by this many degrees. Negative values tilt up-and-right (e.g.\n * `-30`). Default `0`. When non-zero, the chart auto-bumps its bottom margin.\n */\n xAxisAngle?: number;\n /**\n * Custom formatter for x-axis tick labels. **Default**: clay shows only ~5 evenly-distributed\n * labels (first + last + ~3 middle), and auto-truncates each shown label so dense datasets\n * stay readable. Pass an explicit formatter to override the per-label rendering — to also\n * change which labels are visible, pass `xAxisInterval` and a formatter that returns the\n * value for every index.\n *\n * The tooltip continues to show the full unformatted value on hover regardless.\n */\n xAxisTickFormatter?: (value: unknown) => string;\n}\n\n/**\n * Target visible x-axis label count for line charts. Recharts' built-in `preserveStartEnd`\n * picks labels by collision detection, which produces uneven clusters when label widths vary.\n * Picking a fixed target and distributing evenly gives a cleaner result and the same value at\n * any chart width (the chart still shows every data point as a dot — only labels thin out).\n */\nconst TARGET_VISIBLE_LABELS = 5;\n\n/**\n * Pre-composed line chart. Single-call usage for the common case; for custom recharts trees\n * compose `<ChartContainer>` + recharts primitives directly.\n *\n * ```tsx\n * <LineChart\n * data={[{ month: \"Jan\", value: 120 }, { month: \"Feb\", value: 132 }]}\n * xKey=\"month\"\n * series={[{ key: \"value\", label: \"Headcount\" }]}\n * smooth\n * />\n * ```\n *\n * **Smart defaults**: legend auto-hides for single-series; value labels default off (turn on\n * for sparse single-series charts); x-axis shows every tick by default.\n */\nexport function LineChart({\n data,\n xKey,\n series,\n smooth = true,\n showDots = true,\n strokeWidth = 2,\n height = 320,\n width = \"100%\",\n className,\n palette = CHART_PALETTE,\n showTooltip = true,\n showLegend,\n showGrid = true,\n showXAxis = true,\n showYAxis = true,\n showValueLabels = false,\n xAxisInterval = 0,\n xAxisAngle = 0,\n xAxisTickFormatter,\n}: LineChartProps): ReactNode {\n const seriesKeys = useMemo(() => series.map((s) => s.key), [series]);\n // Memoised so non-artifact consumers passing inline `data` arrays don't re-allocate the\n // coerced copy on every parent render.\n const coercedData = useMemo(\n () => coerceNumericColumns(data as ReadonlyArray<Record<string, unknown>>, seriesKeys),\n [data, seriesKeys]\n );\n const lineType = smooth ? \"monotone\" : \"linear\";\n\n const resolvedShowLegend = showLegend ?? series.length > 1;\n // Default: only ~5 evenly distributed labels are visible (first + last + middle), each\n // truncated to fit. Consumer can override with `xAxisTickFormatter` (their formatter is\n // applied to every label without thinning). See `defaultLineChartTickFormatter`.\n const resolvedTickFormatter = useMemo(() => {\n if (xAxisTickFormatter) return xAxisTickFormatter;\n const visible = evenlyDistributedVisibleIndices(coercedData.length, TARGET_VISIBLE_LABELS);\n return defaultLineChartTickFormatter(coercedData.length, visible);\n }, [xAxisTickFormatter, coercedData.length]);\n const angledLabelPad = xAxisAngle === 0 ? 0 : Math.min(Math.abs(xAxisAngle) * 0.7, 40);\n // Extra right margin so the rightmost x-axis tick label has room to render its right half\n // without getting clipped at the chart edge. Recharts centres tick labels under their tick;\n // without padding, ~half of the last label spills past the plot area.\n const chartMargin = { ...CHART_MARGIN, right: CHART_MARGIN.right + 16, bottom: CHART_MARGIN.bottom + angledLabelPad };\n\n return (\n <ChartContainer height={height} width={width} className={className}>\n <RechartsLineChart data={coercedData} margin={chartMargin}>\n {showGrid ? <CartesianGrid {...CHART_GRID_PROPS} /> : null}\n {showXAxis ? (\n <XAxis\n dataKey={xKey}\n {...CHART_AXIS_PROPS}\n interval={xAxisInterval}\n angle={xAxisAngle}\n textAnchor={xAxisAngle !== 0 ? \"end\" : \"middle\"}\n tickMargin={xAxisAngle === 0 ? 8 : 12}\n height={xAxisAngle !== 0 ? 60 : undefined}\n tickFormatter={resolvedTickFormatter}\n />\n ) : null}\n {showYAxis ? <YAxis {...CHART_AXIS_PROPS} width={40} /> : null}\n {showTooltip ? <Tooltip content={<ChartTooltipContent />} /> : null}\n {resolvedShowLegend ? (\n <Legend\n verticalAlign=\"top\"\n align=\"center\"\n // Pin the absolutely-positioned wrapper flush to the chart's top edge — see `BarChart`\n // for the rationale.\n wrapperStyle={{ top: 0 }}\n // Preserve declaration order; disable recharts 3.x's `'value'` alphabetical sort.\n // See `BarChart` for the rationale.\n itemSorter={null}\n content={<ChartLegendContent iconType=\"line\" />}\n />\n ) : null}\n {series.map((s, i) => {\n const color = colorForSeriesIndex(i, palette);\n return (\n <Line\n key={s.key}\n type={lineType}\n dataKey={s.key}\n name={s.label}\n stroke={color}\n strokeWidth={strokeWidth}\n // Filled dot matching the line color — recharts default is hollow (white fill +\n // colored stroke), which reads as \"annotation\" rather than \"data point\".\n dot={showDots ? { r: 3, fill: color, stroke: color, strokeWidth: 0 } : false}\n activeDot={{ r: 5, fill: color, stroke: LINE_ACTIVE_DOT_STROKE, strokeWidth: 2 }}\n >\n {showValueLabels ? <LabelList dataKey={s.key} position=\"top\" style={CHART_VALUE_LABEL_STYLE} /> : null}\n </Line>\n );\n })}\n </RechartsLineChart>\n </ChartContainer>\n );\n}\n","import { type ReactNode } from \"react\";\n\nimport { LineChart } from \"@/components/chart/line-chart/line-chart\";\nimport { VARIANT_CHART_HEIGHT } from \"./constants\";\nimport type { LineChartConfig } from \"./line-chart-variant-service\";\nimport type { ChartVariantComponentProps } from \"./types\";\n\n/**\n * Render Component for the `LINE` chart variant. Maps the artifact's wire-shaped\n * `LineChartConfig` onto props for the high-level `<LineChart>` from `@shapesos/clay/chart`.\n *\n * Split out from `line-chart-variant-service.ts` so the service file stays a pure declarative\n * registration — see `bar-chart-variant-component.tsx` for the rationale.\n */\nexport function LineChartVariantComponent({ config, rows }: ChartVariantComponentProps<LineChartConfig>): ReactNode {\n return <LineChart data={rows} xKey={config.xKey} series={config.series} height={VARIANT_CHART_HEIGHT} />;\n}\n","import type { ChartConfigBase } from \"../types\";\nimport { LineChartVariantComponent } from \"./line-chart-variant-component\";\nimport { seriesBasedColumnKeys } from \"./shared-column-keys\";\nimport { isValidChartSeries } from \"./shared-validators\";\nimport type { ChartVariantService } from \"./types\";\n\n/**\n * Rendering config for a `LINE` chart. `xKey` selects the categorical/temporal axis from the\n * CSV; each series contributes one `<Line>` overlaid against that axis.\n */\nexport interface LineChartConfig extends ChartConfigBase {\n variant: \"LINE\";\n /** CSV column key used as the x-axis. */\n xKey: string;\n}\n\nfunction isValidLineChartConfig(config: unknown): config is LineChartConfig {\n if (!config || typeof config !== \"object\") return false;\n const candidate = config as Record<string, unknown>;\n if (candidate.variant !== \"LINE\") return false;\n if (typeof candidate.xKey !== \"string\" || candidate.xKey.length === 0) return false;\n if (!Array.isArray(candidate.series) || candidate.series.length === 0) return false;\n if (!candidate.series.every(isValidChartSeries)) return false;\n return true;\n}\n\nexport const LineChartVariantService: ChartVariantService<\"LINE\", LineChartConfig> = {\n variant: \"LINE\",\n isValidConfig: isValidLineChartConfig,\n columnKeys: seriesBasedColumnKeys,\n Component: LineChartVariantComponent,\n};\n","import { type ReactNode, useMemo } from \"react\";\nimport { Cell, Legend, Pie, PieChart as RechartsPieChart, Tooltip } from \"recharts\";\n\nimport { ChartContainer } from \"../chart-container\";\nimport { ChartLegendContent } from \"../chart-legend-content\";\nimport { ChartTooltipContent } from \"../chart-tooltip-content\";\nimport {\n CHART_PALETTE,\n DEFAULT_OTHERS_CATEGORY_LABELS,\n OTHERS_SLICE_COLOR,\n colorForSeriesIndex,\n isOthersCategory,\n} from \"../chart-palette\";\nimport { CHART_VALUE_LABEL_STYLE, PIE_CHART_MARGIN } from \"../chart-styles\";\nimport { coerceNumericColumns } from \"../coerce-numeric\";\n\n/**\n * Recharts injects geometric position props onto label render functions. Typed locally because\n * recharts' `PieLabelProps` is overly tagged-generic.\n */\ninterface PieLabelRenderProps {\n /** Computed x coordinate for the label (outside the slice). */\n x?: number;\n /** Computed y coordinate for the label. */\n y?: number;\n /** \"start\" / \"middle\" / \"end\" / \"inherit\" — pre-computed for legibility outside the slice. */\n textAnchor?: \"start\" | \"middle\" | \"end\" | \"inherit\";\n /** The slice's numeric value (the value of `valueKey` on the row). */\n value?: unknown;\n}\n\nexport interface PieChartProps {\n /** Rows to plot. Each row maps to one slice. */\n data: ReadonlyArray<Record<string, unknown>>;\n /** Data column used as the slice label / legend entry. */\n categoryKey: string;\n /** Data column used as the slice numeric value. */\n valueKey: string;\n /** Container height. Default 320. */\n height?: number | string;\n /** Container width. Default `\"100%\"`. */\n width?: number | string;\n /** Optional className on the outer container. */\n className?: string;\n /** Override the default palette. Default `CHART_PALETTE` — the shared blue + indigo graduated\n * palette every chart variant uses. Override per-instance for brand-specific colours. */\n palette?: readonly string[];\n /** Show value labels next to each slice. Default true. */\n showLabels?: boolean;\n /** Show the tooltip on hover. Default true. */\n showTooltip?: boolean;\n /** Show the legend (category names). Default true. Position controlled by `legendPosition`. */\n showLegend?: boolean;\n /** Inner radius — `0` (default) for a pie; `>0` (e.g. `\"40%\"`) for a donut. */\n innerRadius?: number | string;\n /** Outer radius. Default `\"68%\"` — leaves room for outside value labels. */\n outerRadius?: number | string;\n /**\n * Category labels treated as the \"Others\" bucket (case-insensitive match). Matching slices are\n * pinned to the end of the sweep regardless of value and rendered in neutral grey\n * (`OTHERS_SLICE_COLOR`).\n *\n * **Default**: `DEFAULT_OTHERS_CATEGORY_LABELS` (English \"Others\" / \"Other\"). Pass a localized\n * list in non-English UIs — e.g. `[\"אחרים\"]` for Hebrew or `[\"Otros\", \"Otro\"]` for Spanish.\n * Pass `[]` to disable Others detection entirely (every slice colored from the palette).\n */\n othersCategoryLabels?: readonly string[];\n}\n\n/**\n * Pre-composed pie chart. One slice per row, colored by row index from the palette. Outside\n * value labels (no connector line); legend at the top. Set `innerRadius` to make a donut.\n *\n * **Sweep**: starts at 12 o'clock and proceeds clockwise (`startAngle={90}` / `endAngle={-270}`).\n * Recharts' default starts at 3 o'clock counter-clockwise, which feels arbitrary for a\n * data-first composition.\n *\n * **\"Others\" bucket**: any slice whose category label matches \"Others\" / \"Other\"\n * (case-insensitive — see `isOthersCategory`) is pinned to the end of the sweep regardless of\n * value, and rendered in neutral grey (`OTHERS_SLICE_COLOR`) so it reads as \"unattributed\n * leftover\" rather than a peer category. Other slices retain their incoming order.\n *\n * ```tsx\n * <PieChart\n * data={[\n * { department: \"Engineering\", headcount: 42 },\n * { department: \"Sales\", headcount: 18 },\n * { department: \"Others\", headcount: 5 },\n * ]}\n * categoryKey=\"department\"\n * valueKey=\"headcount\"\n * />\n *\n * // Donut variant\n * <PieChart data={...} categoryKey=\"...\" valueKey=\"...\" innerRadius=\"40%\" />\n * ```\n */\nexport function PieChart({\n data,\n categoryKey,\n valueKey,\n height = 320,\n width = \"100%\",\n className,\n palette = CHART_PALETTE,\n showLabels = true,\n showTooltip = true,\n showLegend = true,\n innerRadius = 0,\n outerRadius = \"68%\",\n othersCategoryLabels = DEFAULT_OTHERS_CATEGORY_LABELS,\n}: PieChartProps): ReactNode {\n // Memoised so non-artifact consumers passing inline `data` arrays don't re-allocate the\n // coerced + reordered copy on every parent render. Three steps:\n // 1. Coerce the `valueKey` column to numeric (CSV-derived rows arrive as strings).\n // 2. Stable-partition: keep non-Others slices in their original order, then append any\n // Others slices at the tail — preserves the agent's intended ordering for the named\n // categories while guaranteeing \"Others\" sits at the end of the sweep regardless of size.\n // 3. Compute per-slice colors keyed by the **named-slice index** (not the position in the\n // reordered array). Without this, an Others row added or removed in the middle of the\n // data would visibly shift the palette colors of every named slice that came after it.\n // Indexing by \"Nth named slice\" keeps each named category's color stable across data\n // edits / `othersCategoryLabels` updates.\n const { orderedData, sliceColors } = useMemo(() => {\n const coerced = coerceNumericColumns(data as ReadonlyArray<Record<string, unknown>>, [valueKey]);\n const namedRows: Record<string, unknown>[] = [];\n const namedColors: string[] = [];\n const othersRows: Record<string, unknown>[] = [];\n const othersColors: string[] = [];\n for (const row of coerced) {\n if (isOthersCategory(row[categoryKey], othersCategoryLabels)) {\n othersRows.push(row);\n othersColors.push(OTHERS_SLICE_COLOR);\n } else {\n namedRows.push(row);\n namedColors.push(colorForSeriesIndex(namedRows.length - 1, palette));\n }\n }\n return {\n orderedData: [...namedRows, ...othersRows],\n sliceColors: [...namedColors, ...othersColors],\n };\n }, [data, valueKey, categoryKey, othersCategoryLabels, palette]);\n\n return (\n <ChartContainer height={height} width={width} className={className}>\n <RechartsPieChart margin={PIE_CHART_MARGIN}>\n {showTooltip ? <Tooltip content={<ChartTooltipContent />} /> : null}\n {showLegend ? (\n <Legend\n verticalAlign=\"top\"\n align=\"center\"\n // Pin the absolutely-positioned wrapper flush to the chart's top edge — see `BarChart`\n // for the rationale.\n wrapperStyle={{ top: 0 }}\n // Preserve slice order; disable recharts 3.x's `'value'` alphabetical sort. Critical\n // for pie because the Others bucket is intentionally pinned to the end of the sweep\n // — sorting alphabetically would break that contract.\n itemSorter={null}\n content={<ChartLegendContent iconType=\"square\" />}\n />\n ) : null}\n <Pie\n data={orderedData}\n dataKey={valueKey}\n nameKey={categoryKey}\n cx=\"50%\"\n cy=\"52%\"\n // Start at 12 o'clock and sweep clockwise. Recharts' default (`0` / `360`) starts at\n // 3 o'clock counter-clockwise. The +90 / -270 pair preserves the full 360° arc length.\n startAngle={90}\n endAngle={-270}\n innerRadius={innerRadius}\n outerRadius={outerRadius}\n label={\n showLabels\n ? (entry: PieLabelRenderProps) => {\n const v = entry.value;\n if (v === undefined || v === null) return null;\n // Render the label as a `<text>` so we can pin its `fill` to the shared\n // `CHART_VALUE_LABEL_STYLE` instead of letting recharts auto-color it to\n // the slice's fill (which on light-blue slices becomes near-invisible).\n // Recharts passes the computed `x`/`y`/`textAnchor` so positioning is\n // unchanged.\n return (\n <text\n x={entry.x}\n y={entry.y}\n fill={CHART_VALUE_LABEL_STYLE.fill}\n fontSize={CHART_VALUE_LABEL_STYLE.fontSize}\n fontWeight={CHART_VALUE_LABEL_STYLE.fontWeight}\n textAnchor={entry.textAnchor}\n dominantBaseline=\"central\"\n >\n {String(v)}\n </text>\n );\n }\n : false\n }\n // No connector line — outside labels sit clean next to their slice. The thin\n // brown line between slice and label adds visual noise without information gain.\n labelLine={false}\n // No stroke between slices — gradient palette + adjacent contiguous segments read\n // as one continuous wheel rather than discrete cards with cream gaps between them.\n stroke=\"none\"\n strokeWidth={0}\n >\n {orderedData.map((_row, i) => (\n <Cell key={i} fill={sliceColors[i]} />\n ))}\n </Pie>\n </RechartsPieChart>\n </ChartContainer>\n );\n}\n","import { type ReactNode } from \"react\";\n\nimport { PieChart } from \"@/components/chart/pie-chart/pie-chart\";\nimport { VARIANT_CHART_HEIGHT } from \"./constants\";\nimport type { PieChartConfig } from \"./pie-chart-variant-service\";\nimport type { ChartVariantComponentProps } from \"./types\";\n\n/**\n * Render Component for the `PIE` chart variant. Maps the artifact's wire-shaped\n * `PieChartConfig` onto props for the high-level `<PieChart>` from `@shapesos/clay/chart`,\n * threading the localized `othersCategoryLabels` from the resolved labels bag so non-English\n * UIs can auto-pin their translated \"Others\" bucket to the end of the sweep.\n *\n * Split out from `pie-chart-variant-service.ts` so the service file stays a pure declarative\n * registration — see `bar-chart-variant-component.tsx` for the rationale.\n */\nexport function PieChartVariantComponent({\n config,\n rows,\n labels,\n}: ChartVariantComponentProps<PieChartConfig>): ReactNode {\n return (\n <PieChart\n data={rows}\n categoryKey={config.categoryKey}\n valueKey={config.valueKey}\n othersCategoryLabels={labels.othersCategoryLabels}\n height={VARIANT_CHART_HEIGHT}\n />\n );\n}\n","import type { ChartConfigBase } from \"../types\";\nimport { PieChartVariantComponent } from \"./pie-chart-variant-component\";\nimport { pieColumnKeys } from \"./shared-column-keys\";\nimport type { ChartVariantService } from \"./types\";\n\n/**\n * Rendering config for a `PIE` chart. `categoryKey` names the slice; `valueKey` carries the\n * slice's numeric magnitude. One row of CSV becomes one slice. The base's `series` array is\n * always empty for pie — colors are resolved by row index from the palette.\n */\nexport interface PieChartConfig extends ChartConfigBase {\n variant: \"PIE\";\n /** CSV column key used as the slice label. */\n categoryKey: string;\n /** CSV column key used as the slice numeric value. */\n valueKey: string;\n}\n\nfunction isValidPieChartConfig(config: unknown): config is PieChartConfig {\n if (!config || typeof config !== \"object\") return false;\n const candidate = config as Record<string, unknown>;\n if (candidate.variant !== \"PIE\") return false;\n if (typeof candidate.categoryKey !== \"string\" || candidate.categoryKey.length === 0) return false;\n if (typeof candidate.valueKey !== \"string\" || candidate.valueKey.length === 0) return false;\n if (!Array.isArray(candidate.series)) return false;\n return true;\n}\n\nexport const PieChartVariantService: ChartVariantService<\"PIE\", PieChartConfig> = {\n variant: \"PIE\",\n isValidConfig: isValidPieChartConfig,\n columnKeys: pieColumnKeys,\n Component: PieChartVariantComponent,\n};\n","import type { ChartVariant } from \"@/components/chart/types\";\nimport { BarChartVariantService, type BarChartConfig } from \"./bar-chart-variant-service\";\nimport { LineChartVariantService, type LineChartConfig } from \"./line-chart-variant-service\";\nimport { PieChartVariantService, type PieChartConfig } from \"./pie-chart-variant-service\";\nimport type { ChartVariantService } from \"./types\";\n\n/**\n * Discriminated union of all supported chart variant configs. Assembled here (not in the parent\n * `types.ts`) because the union depends on each variant service file as its single source of\n * truth for that variant's config type.\n *\n * Extension pattern: add a new variant by creating one `*-chart-variant-service.ts` file and\n * extending this union + the `ChartVariantServices` map below. No edits to the dispatcher.\n */\nexport type ChartConfig = LineChartConfig | BarChartConfig | PieChartConfig;\n\nexport { type LineChartConfig, type BarChartConfig, type PieChartConfig };\nexport { LineChartVariantService, BarChartVariantService, PieChartVariantService };\nexport type { ChartVariantComponentProps, ChartVariantService } from \"./types\";\n\n/**\n * Map of chart-variant services keyed by `config.variant`. Mirrors the artifact / block service\n * registries. The chart-artifact dispatcher looks up `ChartVariantServices[config.variant]` at\n * runtime to resolve validation, column projection, and the render Component for the variant.\n *\n * `ChartVariantService<TVariant, TConfig>` is invariant in `TConfig` (props on the Component are\n * contravariant). Each concrete service overlaps structurally with the base `ChartVariantService`\n * enough for a direct `as ChartVariantService` cast at registration time — the dispatch only ever\n * pulls the matching variant out by runtime discriminator, so this is sound.\n */\nexport const ChartVariantServices: Record<ChartVariant, ChartVariantService> = {\n LINE: LineChartVariantService as ChartVariantService,\n BAR: BarChartVariantService as ChartVariantService,\n PIE: PieChartVariantService as ChartVariantService,\n};\n","import { type ReactNode } from \"react\";\n\nimport type { ArtifactDataRow } from \"@/components/artifacts/types\";\nimport { StatusMessage } from \"../status-message\";\nimport { ChartVariantServices } from \"./chart-variant-services\";\nimport type { ChartConfig, ChartArtifactLabels } from \"./types\";\n\n/**\n * Props for the chart-artifact variant dispatcher. Internal to the artifact path — the\n * orchestrator (`chart-artifact.tsx`) is the only caller. By the time these props are\n * constructed, `config` has been narrowed by `isValidChartConfig` and `rows` has resolved to\n * the `\"ready\"` state of the data hook.\n */\nexport interface ChartArtifactContentProps {\n /** Validated chart config — narrowed by `variant` for per-variant component selection. */\n config: ChartConfig;\n /** Parsed CSV rows. Caller guards `rows.length > 0` before rendering this. */\n rows: ArtifactDataRow[];\n /** Fully-resolved labels bag — supplies the fallback message when the variant is unsupported. */\n labels: ChartArtifactLabels;\n}\n\n/**\n * Variant dispatcher for `ChartArtifact`. Looks up the matching per-variant service in the\n * `ChartVariantServices` registry and renders its Component. Each variant service owns its own\n * config type, validation, column projection, and renderer — see `chart-variant-services/`.\n *\n * Unknown variants fall back to a status message (rather than throwing) so an older clay client\n * encountering a future variant degrades gracefully instead of crashing the chat.\n */\nexport function ChartArtifactContent({ config, rows, labels }: ChartArtifactContentProps): ReactNode {\n const service = ChartVariantServices[config.variant];\n if (!service) {\n return <StatusMessage $tone=\"info\">{labels.unavailable}</StatusMessage>;\n }\n // Registry guarantees the runtime variant matches the service's TConfig; loose at the type\n // boundary here is sound — see `ChartVariantServices` cast doc.\n const Component = service.Component as React.ComponentType<{\n config: ChartConfig;\n rows: ArtifactDataRow[];\n labels: ChartArtifactLabels;\n }>;\n return <Component config={config} rows={rows} labels={labels} />;\n}\n","import Papa from \"papaparse\";\n\nimport type { ArtifactDataRow } from \"./types\";\nimport type { ArtifactColumnLike } from \"./use-rows-artifact-data\";\n\n/**\n * Parses a CSV text payload fetched from a presigned URL into `ArtifactDataRow[]`.\n *\n * Shared across artifact kinds whose data wire is a CSV (`TABLE`, `CHART`). Uses `Papa.parse`\n * with `header: true` (first row is the header) and `skipEmptyLines: true`. Every cell arrives\n * as a string — the renderer NEVER coerces values to JS numbers / booleans / dates. Format\n * conversion is a server concern: if a column needs to be `\"Yes/No\"` or `\"$1,234\"`, the server\n * emits it that way in the CSV.\n *\n * Column projection rules:\n * - CSV header columns NOT in `columns[].key` are silently dropped.\n * - `columns[].key` values missing from the CSV header are silently omitted from row output —\n * client-side reconciliation warnings would let the client second-guess the server's contract.\n * Trust the CSV.\n *\n * Empty cells (`\"\"`) are returned as `null` so the renderer can distinguish \"missing value\"\n * from \"empty string\" downstream.\n *\n * Generic over the column shape so callers carrying richer column metadata (`TableColumn` with\n * `label` and the deprecated `type`/`align`) get back their own type rather than `unknown`.\n *\n * @param text Raw CSV text (may start with a UTF-8 BOM which Papa strips automatically).\n * @param columns Column descriptors — only `key` is consulted for projection.\n * @returns Rows in source order, projected to the configured columns.\n */\nexport function parseCsv<TColumn extends ArtifactColumnLike>(text: string, columns: TColumn[]): ArtifactDataRow[] {\n const result = Papa.parse<Record<string, string>>(text, {\n header: true,\n skipEmptyLines: true,\n dynamicTyping: false,\n });\n\n const csvHeaders = new Set(result.meta?.fields ?? []);\n const presentColumns = columns.filter((col) => csvHeaders.has(col.key));\n\n // No overlap between requested columns and CSV headers — return [] (treat as \"no data\")\n // rather than `result.data.length` rows of `{}`. The latter has positive length so the chart's\n // empty-state check (`data.rows.length === 0`) would miss it, and the chart would render\n // blank (no plottable fields) instead of the empty status message.\n if (presentColumns.length === 0) return [];\n\n return result.data.map((rawRow) => {\n const row: ArtifactDataRow = {};\n for (const column of presentColumns) {\n const value = rawRow[column.key];\n row[column.key] = value === undefined || value === \"\" ? null : value;\n }\n return row;\n });\n}\n","import { useEffect, useMemo, useState } from \"react\";\n\nimport { isSafeDownloadUrl } from \"./artifact-download-button/artifact-download-button\";\nimport type { ArtifactDataRow } from \"./types\";\n\n/**\n * Discriminator for the result returned by `useRowsArtifactData`.\n *\n * - `loading` — fetch is in flight (or about to be).\n * - `ready` — payload fetched and parsed successfully.\n * - `error` — fetch or parse failed at runtime; user can retry.\n * - `unavailable` — the artifact has no presigned URL at all (permanent server-side state). Distinct\n * from `error` so the renderer can surface \"data is unavailable\" instead of a misleading \"try again\".\n */\nexport type RowsArtifactDataState =\n | { status: \"loading\"; rows: null; error: null }\n | { status: \"ready\"; rows: ArtifactDataRow[]; error: null }\n | { status: \"error\"; rows: null; error: Error }\n | { status: \"unavailable\"; rows: null; error: null };\n\nconst LOADING: RowsArtifactDataState = { status: \"loading\", rows: null, error: null };\nconst UNAVAILABLE: RowsArtifactDataState = { status: \"unavailable\", rows: null, error: null };\n\ninterface InternalState {\n /** The cache key the current `data` was fetched for; used to ignore stale data when inputs change. */\n cacheKey: string | null;\n /** The fetch result for `cacheKey`. */\n data: RowsArtifactDataState;\n}\n\nconst INITIAL_INTERNAL: InternalState = { cacheKey: null, data: LOADING };\n\n/** Minimum shape a column descriptor must carry for CSV projection. `TableColumn` and the\n * shapes derived from `ChartConfig` both satisfy this. */\nexport interface ArtifactColumnLike {\n key: string;\n}\n\n/** Builds a stable fingerprint for a columns array so the effect only re-runs on real changes. */\nfunction columnsFingerprint(columns: ArtifactColumnLike[]): string {\n return columns.map((c) => c.key).join(\"|\");\n}\n\n/**\n * Strips any query parameters from a URL before logging. Presigned URLs carry the AWS signature\n * in the query string, which is a time-limited bearer credential. Logging it to an observability\n * platform (Logfire/Datadog/etc.) is a credential leak.\n */\nfunction scrubUrl(url: string): string {\n const q = url.indexOf(\"?\");\n return q === -1 ? url : `${url.slice(0, q)}?<redacted>`;\n}\n\n/**\n * Fetches an artifact's CSV payload from a presigned URL and parses it via the caller-supplied\n * `parse` function. Shared core for every artifact kind whose data wire is a CSV file\n * (`TABLE`, `CHART`, …). The two type-specific renderers wrap this with a default `parse`.\n *\n * Returns `loading` while the request is in flight, `unavailable` synchronously when no URL is\n * supplied (or the URL fails the safe-scheme guard), `ready` on success, or `error` on a runtime\n * failure (HTTP non-2xx, network, or parse error). Parse errors are surfaced as `error` state —\n * they are never thrown.\n *\n * In-flight requests are cancelled via `AbortController` when the URL or columns change, or the\n * consumer unmounts, so abandoned loads don't keep consuming bandwidth.\n *\n * @param presignedUrl S3 presigned URL for the artifact's CSV file, or `null`/`undefined` when absent.\n * Validated against `isSafeDownloadUrl` before fetch — any non-http(s) scheme\n * (e.g. `file:`, `data:`, `javascript:`) is treated as `unavailable`. The same\n * guard backs `ArtifactDownloadButton`; both code paths share one check.\n * @param columns Column descriptors — used for the cache-key fingerprint AND passed verbatim to `parse`.\n * @param parse CSV-text → rows parser. **MUST be a stable (module-scope or memoised)\n * function reference** — it is intentionally omitted from the effect's dep\n * array. Passing an inline arrow function will silently skip re-parsing on\n * change. Both current call sites (`useTableArtifactData`, `useChartArtifactData`)\n * pass the module-scope `parseCsv`.\n */\nexport function useRowsArtifactData<TColumn extends ArtifactColumnLike>(\n presignedUrl: string | null | undefined,\n columns: TColumn[],\n parse: (text: string, columns: TColumn[]) => ArtifactDataRow[]\n): RowsArtifactDataState {\n // Stable fingerprint so the effect doesn't re-fire on referentially-new but content-equal column arrays.\n const colsKey = useMemo(() => columnsFingerprint(columns), [columns]);\n\n const safeUrl = presignedUrl && isSafeDownloadUrl(presignedUrl) ? presignedUrl : null;\n const cacheKey = safeUrl ? `${safeUrl}::${colsKey}` : null;\n\n const [state, setState] = useState<InternalState>(INITIAL_INTERNAL);\n\n useEffect(() => {\n if (!safeUrl) return;\n\n const controller = new AbortController();\n\n fetch(safeUrl, {\n signal: controller.signal,\n headers: { Accept: \"text/csv\" },\n // Presigned URLs are cross-origin S3 in production and don't need credentials. Explicit\n // omit so a same-origin URL (compromised payload, local dev) can't accidentally receive\n // session cookies or auth headers.\n credentials: \"omit\",\n })\n .then(async (response) => {\n if (!response.ok) throw new Error(`Failed to load artifact data (${response.status})`);\n return response.text();\n })\n .then((text) => {\n if (controller.signal.aborted) return;\n try {\n const rows = parse(text, columns);\n setState({ cacheKey: `${safeUrl}::${colsKey}`, data: { status: \"ready\", rows, error: null } });\n } catch (parseError: unknown) {\n const err = parseError instanceof Error ? parseError : new Error(String(parseError));\n console.error(\"[ArtifactData] CSV parse failed:\", err.message);\n setState({ cacheKey: `${safeUrl}::${colsKey}`, data: { status: \"error\", rows: null, error: err } });\n }\n })\n .catch((error: unknown) => {\n // Per the Fetch spec, `signal.aborted` is set before the promise rejects on abort, so this\n // guard catches every abort case driven by our `controller.abort()` cleanup.\n if (controller.signal.aborted) return;\n const err = error instanceof Error ? error : new Error(String(error));\n // Log only `err.message`, not the full Error — some browsers include the full URL (with\n // AWS signature query params) in `TypeError.message` on network errors. Belt-and-suspenders:\n // scrub query params from the URL when we log the cache key for debugging.\n console.error(`[ArtifactData] Fetch failed [${scrubUrl(safeUrl)}]:`, err.message);\n setState({ cacheKey: `${safeUrl}::${colsKey}`, data: { status: \"error\", rows: null, error: err } });\n });\n\n return () => {\n controller.abort();\n };\n // `columns` and `parse` are intentionally omitted from the dep array: `colsKey` is the stable\n // fingerprint covering every observable column change, and `parse` is required to be a stable\n // module-scope or memoised reference (see JSDoc on the `parse` param). If either becomes\n // dynamic, this assumption breaks and the suppression must be removed.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [safeUrl, colsKey]);\n\n if (!safeUrl) return UNAVAILABLE;\n // While the in-flight URL/columns change, cached data belongs to a stale key — return loading until\n // the new fetch resolves. Avoids a synchronous setState() in the effect body (lint forbids that).\n if (state.cacheKey !== cacheKey) return LOADING;\n return state.data;\n}\n","import type { ChartVariant } from \"@/components/chart/types\";\nimport { parseCsv } from \"../parse-csv\";\nimport { useRowsArtifactData, type RowsArtifactDataState } from \"../use-rows-artifact-data\";\nimport { ChartVariantServices } from \"./chart-variant-services\";\nimport type { ChartConfig } from \"./types\";\n\n/**\n * Fetches a chart artifact's data payload from a presigned URL and parses it as CSV.\n *\n * Thin wrapper over the shared `useRowsArtifactData` core. Derives the column-key list from\n * `config` by delegating to the matching variant service's `columnKeys` method — each variant\n * owns its own CSV-column projection. The keys drive `parseCsv`'s per-row projection (matches\n * the table-artifact projection contract).\n *\n * @param presignedUrl S3 presigned URL for the artifact's CSV file, or `null`/`undefined` when absent.\n * @param config Validated chart config — used to derive the projection columns.\n */\nexport function useChartArtifactData(\n presignedUrl: string | null | undefined,\n config: ChartConfig\n): RowsArtifactDataState {\n const service = ChartVariantServices[config.variant as ChartVariant];\n // `isValidChartConfig` is the caller-side guard — service should always exist here, but\n // fall back to an empty projection rather than crashing if a future invariant slips.\n const keys = service ? service.columnKeys(config) : [];\n const columns = keys.map((key) => ({ key }));\n return useRowsArtifactData(presignedUrl, columns, parseCsv);\n}\n","import type { ChartVariant } from \"@/components/chart/types\";\nimport { ChartVariantServices } from \"./chart-variant-services\";\nimport type { ChartConfig } from \"./types\";\n\n/**\n * Returns true iff `config` carries the minimum-viable shape for rendering its `variant`.\n *\n * Thin dispatcher: validates the variant discriminator is one we know, then delegates to the\n * variant service's own `isValidConfig`. Each variant owns its own validation rules — see\n * `chart-variant-services/<variant>-chart-variant-service.ts`.\n *\n * The server-side `normaliseConfig` is the authoritative validator; this predicate exists so a\n * malformed payload renders the unavailable-state instead of crashing.\n */\nexport function isValidChartConfig(config: unknown): config is ChartConfig {\n if (!config || typeof config !== \"object\") return false;\n const variant = (config as Record<string, unknown>).variant;\n if (typeof variant !== \"string\") return false;\n const service = ChartVariantServices[variant as ChartVariant];\n if (!service) return false;\n return service.isValidConfig(config);\n}\n","import type { ChartArtifactRecord } from \"@/components/artifacts/types\";\n\n/**\n * Produces a plain-text clipboard representation of a chart artifact.\n *\n * Returns the artifact title as plain text so pasting into non-markdown-aware targets\n * (plain-text editors, terminal, spreadsheets) does not expose raw markdown syntax. Mirrors\n * `tableArtifactToClipboardText`'s contract — every block-aggregating consumer\n * (`ArtifactRefBlockService.toClipboardText`) writes the aggregated string verbatim.\n *\n * The presigned URL is intentionally omitted: presigned URLs expire quickly and are not useful\n * when pasted as bare text. The Download button in the artifact chrome is the canonical way\n * to obtain the underlying file.\n */\nexport function chartArtifactToClipboardText(artifact: ChartArtifactRecord): string {\n const trimmedTitle = artifact.title?.trim();\n return trimmedTitle || \"Chart\";\n}\n","import type { ArtifactService, ChartArtifactRecord } from \"../types\";\nimport { artifactTypes } from \"../types\";\nimport { ChartArtifact } from \"../chart-artifact/chart-artifact\";\nimport { chartArtifactToClipboardText } from \"../chart-artifact/to-clipboard-text\";\n\nexport const ChartArtifactService: ArtifactService<ChartArtifactRecord> = {\n type: artifactTypes.CHART,\n Component: ChartArtifact,\n toClipboardText: chartArtifactToClipboardText,\n};\n","import { useEffect, useMemo, type ReactNode } from \"react\";\n\nimport {\n Artifact,\n ArtifactActions,\n ArtifactContent,\n ArtifactHeader,\n ArtifactTitle,\n} from \"@/components/ai-elements/artifact\";\nimport { ArtifactDownloadButton } from \"@/components/artifacts/artifact-download-button/artifact-download-button\";\nimport {\n DEFAULT_TABLE_ARTIFACT_LABELS,\n type ArtifactServiceProps,\n type TableArtifactLabels,\n type TableArtifactRecord,\n} from \"@/components/artifacts/types\";\nimport { artifactTypes } from \"@/components/artifacts/artifact-base\";\nimport { TableArtifactContent } from \"./table-artifact-content\";\nimport { StatusMessage } from \"../status-message\";\nimport { useTableArtifactData } from \"./use-table-artifact-data\";\nimport { isValidTableConfig } from \"./validate\";\n\nconst TITLE_CLASSES = \"text-sm font-semibold text-foreground\";\n\n/**\n * Cap the body at ~10 rows × 48px (~480px). Long lists scroll inside the artifact so they\n * don't stretch the chat surface. Each artifact type declares its own sensible cap.\n */\nconst TABLE_MAX_BODY_HEIGHT = 480;\n\n/**\n * Cap on shimmer rows during loading. Approximates the visible viewport (`TABLE_MAX_BODY_HEIGHT`\n * ÷ 48px per row) so we don't render hundreds of placeholder DOM nodes for very large tables.\n */\nconst MAX_SHIMMER_ROWS = 10;\n\n/**\n * Orchestrator for the `table`-typed artifact.\n *\n * Composes the ai-elements chrome primitives (`Artifact`, `ArtifactHeader`, `ArtifactTitle`,\n * `ArtifactActions`, `ArtifactContent`) directly around the table body (`TableArtifactContent`).\n * Download is handled via `ArtifactDownloadButton` — a shared utility component that applies the\n * safe-URL guard and renders nothing for non-http(s) schemes.\n */\nexport function TableArtifact({ artifact, labels, callbacks }: ArtifactServiceProps<TableArtifactRecord>): ReactNode {\n const validConfig = isValidTableConfig(artifact.config);\n const validColumns = validConfig ? artifact.config.columns : null;\n\n useEffect(() => {\n if (validConfig) return;\n console.warn(\"[clay] TableArtifact: malformed `config` — skipping render.\");\n }, [validConfig]);\n\n // Read this artifact type's slice out of the union labels bag, then merge over the English\n // defaults. See `ChartArtifact` for rationale.\n const resolvedLabels = useMemo<TableArtifactLabels>(\n () => ({ ...DEFAULT_TABLE_ARTIFACT_LABELS, ...(labels?.[artifactTypes.TABLE] ?? {}) }),\n [labels]\n );\n\n // Hook is always called (Rules of Hooks). Pass null URL when config is invalid so the hook\n // short-circuits at its `if (!presignedUrl) return UNAVAILABLE` path — no network fetch fires\n // for an artifact whose config shape can't be rendered.\n const data = useTableArtifactData(\n validConfig ? artifact.protectedAsset?.presignedUrl ?? null : null,\n validColumns ?? []\n );\n\n const presignedUrl = artifact.protectedAsset?.presignedUrl ?? null;\n\n // Bridge the consumer's `onDownload` callback into the download button. Wrapped to capture\n // `artifact` so the callback receives analytics context without a per-block closure on the\n // consumer side. `undefined` (rather than a no-op) when no callback wired — keeps the button\n // free of a redundant click listener.\n const onDownload = callbacks?.[artifactTypes.TABLE]?.onDownload;\n const handleDownloadClick = onDownload ? () => onDownload(artifact) : undefined;\n\n if (!validConfig || !validColumns) {\n return (\n <Artifact className=\"shadow-none w-full rounded-2xl bg-background/70\">\n <ArtifactHeader className=\"bg-background/70\">\n {artifact.title ? <ArtifactTitle className={TITLE_CLASSES}>{artifact.title}</ArtifactTitle> : <span />}\n {presignedUrl ? (\n <ArtifactActions>\n <ArtifactDownloadButton\n href={presignedUrl}\n label={resolvedLabels.download}\n onClick={handleDownloadClick}\n />\n </ArtifactActions>\n ) : null}\n </ArtifactHeader>\n <ArtifactContent className=\"p-0 overflow-auto\" style={{ maxHeight: TABLE_MAX_BODY_HEIGHT }}>\n <StatusMessage $tone=\"info\">{resolvedLabels.unavailable}</StatusMessage>\n </ArtifactContent>\n </Artifact>\n );\n }\n\n return (\n // The table body owns its own scroll container (`ArtifactTable` inside `TableArtifactContent`).\n // Disable the outer overflow container so only one scroll context exists — this prevents\n // double-scroll nesting and lets `useScrollShadow` find the correct scroll ancestor.\n <Artifact className=\"shadow-none w-full rounded-2xl bg-background/70\">\n <ArtifactHeader className=\"bg-background/70\">\n {artifact.title ? <ArtifactTitle className={TITLE_CLASSES}>{artifact.title}</ArtifactTitle> : <span />}\n <ArtifactActions>\n <ArtifactDownloadButton\n href={presignedUrl ?? \"\"}\n label={resolvedLabels.download}\n onClick={handleDownloadClick}\n />\n </ArtifactActions>\n </ArtifactHeader>\n <ArtifactContent className=\"p-0 overflow-visible\" style={{ maxHeight: \"none\" }}>\n <TableArtifactContent\n columns={validColumns}\n data={data}\n knownRowCount={artifact.config.stats?.rowCount}\n maxShimmerRows={MAX_SHIMMER_ROWS}\n maxBodyHeight={TABLE_MAX_BODY_HEIGHT}\n labels={resolvedLabels}\n />\n </ArtifactContent>\n </Artifact>\n );\n}\n","import * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/** Extension of shadcn's `Table` registry component: exposes `containerClassName` so callers can\n * override the wrapping `<div>`'s default `overflow-auto`. We need this for sticky-header support\n * (sticky uses the nearest overflow ancestor as its containing block — when the actual scroll\n * container is one level out, the inner overflow-auto needs to be neutralised with\n * `overflow-visible` so sticky aligns with the real scrolling parent). */\nconst Table = React.forwardRef<\n HTMLTableElement,\n React.HTMLAttributes<HTMLTableElement> & { containerClassName?: string }\n>(({ className, containerClassName, ...props }, ref) => (\n <div className={cn(\"relative w-full overflow-auto\", containerClassName)}>\n <table ref={ref} className={cn(\"w-full caption-bottom text-sm\", className)} {...props} />\n </div>\n));\nTable.displayName = \"Table\";\n\nconst TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(\n ({ className, ...props }, ref) => <thead ref={ref} className={cn(\"[&_tr]:border-b\", className)} {...props} />\n);\nTableHeader.displayName = \"TableHeader\";\n\nconst TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(\n ({ className, ...props }, ref) => (\n <tbody ref={ref} className={cn(\"[&_tr:last-child]:border-0\", className)} {...props} />\n )\n);\nTableBody.displayName = \"TableBody\";\n\nconst TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(\n ({ className, ...props }, ref) => (\n <tfoot ref={ref} className={cn(\"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0\", className)} {...props} />\n )\n);\nTableFooter.displayName = \"TableFooter\";\n\nconst TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(\n ({ className, ...props }, ref) => (\n <tr\n ref={ref}\n className={cn(\"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted\", className)}\n {...props}\n />\n )\n);\nTableRow.displayName = \"TableRow\";\n\nconst TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(\n ({ className, ...props }, ref) => (\n <th\n ref={ref}\n className={cn(\n \"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0\",\n className\n )}\n {...props}\n />\n )\n);\nTableHead.displayName = \"TableHead\";\n\nconst TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(\n ({ className, ...props }, ref) => (\n <td ref={ref} className={cn(\"p-4 align-middle [&:has([role=checkbox])]:pr-0\", className)} {...props} />\n )\n);\nTableCell.displayName = \"TableCell\";\n\nconst TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>(\n ({ className, ...props }, ref) => (\n <caption ref={ref} className={cn(\"mt-4 text-sm text-muted-foreground\", className)} {...props} />\n )\n);\nTableCaption.displayName = \"TableCaption\";\n\nexport { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };\n","import { useEffect, useRef, useState, type RefObject } from \"react\";\n\n/**\n * Tracks whether a scroll container has scrolled past its top edge, for sticky-header shadow effects.\n *\n * Returns `targetRef` (attach to the scroll container itself or any element inside it) and\n * `isScrolled` (true once the container's `scrollTop > 0`). On mount the hook walks up the DOM\n * from the target to find the nearest overflow ancestor (or uses the target itself if it already\n * has `overflowY: auto | scroll`), then listens to its `scroll` event.\n *\n * Used to surface a subtle \"scroll lift\" shadow under sticky headers so users know there is\n * content hidden above.\n *\n * **Why a scroll listener and not a sentinel + IntersectionObserver:** an earlier version used a\n * 1px sentinel as the first child of the scroll container. The sentinel's height pushed the thead\n * down by one pixel in normal flow, and as soon as the user scrolled the thead snapped up to its\n * sticky position — a visible 1px jitter. A scroll listener has no layout footprint.\n *\n * `passive: true` so the listener doesn't block native scroll smoothness; we never call\n * `preventDefault`.\n */\nexport function useScrollShadow(): {\n targetRef: RefObject<HTMLDivElement | null>;\n isScrolled: boolean;\n} {\n const targetRef = useRef<HTMLDivElement>(null);\n const [isScrolled, setIsScrolled] = useState(false);\n\n useEffect(() => {\n const target = targetRef.current;\n if (!target) return;\n\n let scrollContainer: HTMLElement | null = target;\n while (scrollContainer) {\n const overflowY = getComputedStyle(scrollContainer).overflowY;\n if (overflowY === \"auto\" || overflowY === \"scroll\") break;\n scrollContainer = scrollContainer.parentElement;\n }\n if (!scrollContainer) return;\n\n setIsScrolled(scrollContainer.scrollTop > 0);\n\n const handleScroll = () => {\n if (!scrollContainer) return;\n setIsScrolled(scrollContainer.scrollTop > 0);\n };\n scrollContainer.addEventListener(\"scroll\", handleScroll, { passive: true });\n return () => scrollContainer.removeEventListener(\"scroll\", handleScroll);\n }, []);\n\n return { targetRef, isScrolled };\n}\n","/**\n * Discriminant constants for `TableArtifactDataState.status`.\n *\n * Use these instead of inline string literals so a typo is a compile-time error rather than a\n * silent wrong-branch at runtime.\n */\nexport const TABLE_STATUS = {\n LOADING: \"loading\",\n READY: \"ready\",\n ERROR: \"error\",\n UNAVAILABLE: \"unavailable\",\n} as const;\n","import type { TableColumn, TableRow as TableRowData } from \"@/components/artifacts/types\";\n\n/**\n * Returns a cell's rendered string. The CSV is the source of truth — clay never coerces or\n * reformats values. `null` / missing keys render as the empty cell. The value comes out as it\n * went in (whatever the server wrote into the CSV).\n */\nexport function formatCell(row: TableRowData, column: TableColumn): string {\n return row[column.key] ?? \"\";\n}\n\n/**\n * Header + body cell class strings. Alignment is uniformly left in chat-embedded artifact tables\n * by design (mixing right-aligned numerics with left-aligned text reads inconsistently); the\n * wire-type `column.align` is preserved for forward-compat but ignored at render time. See\n * `TableColumn.align` doc in `@/components/artifacts/types`.\n */\nexport const HEAD_CLASS = \"h-auto py-2 px-4 text-xs font-medium text-foreground whitespace-nowrap text-left\";\nexport const CELL_CLASS = \"p-4 text-sm font-normal text-foreground align-top min-w-[150px] text-left\";\n\n/**\n * Row tint matches the artifact card's frosted-glass scheme. The custom `border-b-brown-30`\n * overrides shadcn's row-default border (which inherits `--color-border` = brown-40) with the\n * lighter brown-30. Hover lifts to `bg-secondary` (opaque brown-20) for strong feedback against\n * the translucent base.\n */\nexport const ROW_CLASSES = \"border-b-brown-30 bg-background/70 hover:bg-secondary\";\n\n/**\n * Mount-time fade-in for data rows so the shimmer-to-data transition feels smooth (300ms ease-in\n * over `opacity: 0 → 1`). Shimmer rows keep `ROW_CLASSES` (no animate-in) so they remain in their\n * loading stillness while the pulse animation runs. `animate-in fade-in duration-300` is provided\n * by `tw-animate-css`.\n */\nexport const DATA_ROW_CLASSES = `${ROW_CLASSES} animate-in fade-in duration-300`;\n\n/** Layered drop-shadow for the scroll-lift effect on the sticky header. */\nexport const SCROLL_SHADOW = \"0 1px 2px rgb(0 0 0 / 0.01), 0 6px 12px -2px rgb(0 0 0 / 0.03)\";\n","import { type ReactNode } from \"react\";\n\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, useScrollShadow } from \"@/components/table\";\nimport type { TableColumn, TableRow as TableRowData } from \"@/components/artifacts/types\";\nimport { StatusMessage } from \"../status-message\";\nimport type { ArtifactTableProps, TableArtifactContentProps } from \"./table-artifact-content.types\";\nimport { TABLE_STATUS } from \"./table-artifact-content.constants\";\nimport {\n CELL_CLASS,\n DATA_ROW_CLASSES,\n formatCell,\n HEAD_CLASS,\n ROW_CLASSES,\n SCROLL_SHADOW,\n} from \"./table-artifact-content.utils\";\n\n/**\n * Bridges artifact data-states → shadcn's compound `Table` primitives.\n *\n * The four states render differently:\n *\n * - **loading w/ knownRowCount** → renders a sticky-header table with N shimmer rows so the\n * layout doesn't jump.\n * - **loading w/o knownRowCount** → renders the inline \"Loading table…\" status message.\n * - **error / unavailable** → renders an inline status message.\n * - **ready** → renders the full table with data rows and the scroll-lift\n * shadow on the sticky header.\n *\n * The shadcn primitives are composed directly here — no `Table` wrapper component sits in between.\n * Each row variant (header, data, shimmer, empty) is a small inline component below.\n */\nexport function TableArtifactContent({\n columns,\n data,\n knownRowCount,\n maxShimmerRows,\n maxBodyHeight,\n labels,\n}: TableArtifactContentProps): ReactNode {\n if (data.status === TABLE_STATUS.ERROR) {\n // No retry hook today — copy intentionally drops the \"Please try again.\" that has nowhere\n // to land. Wire an `onRetry` callback into `ArtifactService` to re-mint a fresh\n // presigned URL before re-introducing the retry framing.\n return <StatusMessage $tone=\"error\">{labels.loadError}</StatusMessage>;\n }\n if (data.status === TABLE_STATUS.UNAVAILABLE) {\n return <StatusMessage $tone=\"info\">{labels.unavailable}</StatusMessage>;\n }\n if (data.status === TABLE_STATUS.LOADING) {\n if (typeof knownRowCount === \"number\" && knownRowCount > 0) {\n const shimmerCount = Math.min(knownRowCount, maxShimmerRows);\n return (\n <ArtifactTable columns={columns} maxBodyHeight={maxBodyHeight}>\n {renderShimmerRows(columns, shimmerCount)}\n </ArtifactTable>\n );\n }\n return <StatusMessage $tone=\"info\">{labels.loading}</StatusMessage>;\n }\n // data.status === TABLE_STATUS.READY\n return (\n <ArtifactTable columns={columns} maxBodyHeight={maxBodyHeight}>\n {data.rows.length === 0 ? renderEmptyRow(columns.length, labels.empty) : renderDataRows(columns, data.rows)}\n </ArtifactTable>\n );\n}\n\n/**\n * Compound-table chrome shared between the loading-shimmer branch and the data/empty branch:\n * scroll container, sticky header, and the body slot. Caller passes the body rows.\n */\nfunction ArtifactTable({ columns, maxBodyHeight, children }: ArtifactTableProps): ReactNode {\n const { targetRef, isScrolled } = useScrollShadow();\n return (\n <div ref={targetRef} className=\"overscroll-none\" style={{ maxHeight: maxBodyHeight, overflowY: \"auto\" }}>\n <Table containerClassName=\"overflow-visible\">\n <TableHeader\n data-scrolled={isScrolled ? \"true\" : undefined}\n className=\"sticky top-0 z-10 bg-background/70 backdrop-blur-lg transition-shadow\"\n style={isScrolled ? { boxShadow: SCROLL_SHADOW } : undefined}\n >\n <TableRow className=\"hover:bg-transparent\">\n {columns.map((column) => (\n <TableHead key={column.key} scope=\"col\" className={HEAD_CLASS}>\n {column.label}\n </TableHead>\n ))}\n </TableRow>\n </TableHeader>\n <TableBody>{children}</TableBody>\n </Table>\n </div>\n );\n}\n\nfunction renderShimmerRows(columns: TableColumn[], count: number): ReactNode {\n return Array.from({ length: count }).map((_, index) => (\n <TableRow key={`shimmer-${index}`} className={ROW_CLASSES} aria-hidden=\"true\">\n {columns.map((column) => (\n <TableCell key={column.key} className={CELL_CLASS}>\n <span className=\"block h-3 w-3/4 animate-pulse rounded bg-muted-foreground/20\" />\n </TableCell>\n ))}\n </TableRow>\n ));\n}\n\nfunction renderDataRows(columns: TableColumn[], rows: TableRowData[]): ReactNode {\n // `key={index}` is safe today because `rows` is a static fetch result — no sort, filter, or\n // streaming insertion. The moment row order can change (e.g. client-side sort feature), this\n // must switch to a stable per-row identity or React will reconcile incorrectly (inputs lose\n // focus, animations glitch). The data hook will need to surface a row-id at that point.\n return rows.map((row, index) => (\n <TableRow key={index} className={DATA_ROW_CLASSES}>\n {columns.map((column) => (\n <TableCell key={column.key} className={CELL_CLASS}>\n {formatCell(row, column)}\n </TableCell>\n ))}\n </TableRow>\n ));\n}\n\nfunction renderEmptyRow(colSpan: number, emptyMessage: string): ReactNode {\n return (\n <TableRow className=\"hover:bg-transparent\">\n <TableCell colSpan={colSpan} className=\"py-6 text-center text-sm text-muted-foreground\">\n {emptyMessage}\n </TableCell>\n </TableRow>\n );\n}\n","import type { TableColumn } from \"@/components/artifacts/types\";\nimport { useRowsArtifactData, type RowsArtifactDataState } from \"../use-rows-artifact-data\";\nimport { parseCsv } from \"../parse-csv\";\n\n/**\n * Per-table data state. Re-exported from the shared rows-state union so callers that imported\n * the original `TableArtifactDataState` name still resolve. `TableRow` is itself an alias for\n * `ArtifactDataRow`, so `rows: TableRow[]` and `rows: ArtifactDataRow[]` are the same type.\n */\nexport type TableArtifactDataState = RowsArtifactDataState;\n\n/**\n * Fetches a table artifact's data payload from a presigned URL and parses it as CSV.\n *\n * Thin wrapper over `useRowsArtifactData` — the shared core for every artifact kind whose data\n * wire is a CSV file. Supplies `parseCsv` as the parser (per-column projection from CSV headers,\n * empty cells coerced to `null`).\n *\n * @param presignedUrl S3 presigned URL for the artifact's CSV file, or `null`/`undefined` when absent.\n * @param columns Column definitions from `TableConfig.columns` — used for projection.\n */\nexport function useTableArtifactData(\n presignedUrl: string | null | undefined,\n columns: TableColumn[]\n): RowsArtifactDataState {\n return useRowsArtifactData(presignedUrl, columns, parseCsv);\n}\n","import type { TableColumn, TableConfig } from \"@/components/artifacts/types\";\n\n/**\n * Returns true iff `config` carries the minimum-viable shape for rendering: a non-empty array\n * of columns where each has a non-empty `key` and a string `label`.\n *\n * Anything else is trusted to the server. The deprecated `type` / `align` wire fields are NOT\n * validated — clay doesn't act on them, so rejecting unknown values would punish servers\n * shipping fields clay was about to ignore anyway.\n */\nexport function isValidTableConfig(config: unknown): config is TableConfig {\n if (!config || typeof config !== \"object\") return false;\n const candidate = config as { columns?: unknown };\n if (!Array.isArray(candidate.columns)) return false;\n if (candidate.columns.length === 0) return false;\n return candidate.columns.every(isValidTableColumn);\n}\n\n/** Minimum-viable column shape: non-empty string `key` + string `label`. */\nfunction isValidTableColumn(column: unknown): column is TableColumn {\n if (!column || typeof column !== \"object\") return false;\n const candidate = column as Record<string, unknown>;\n if (typeof candidate.key !== \"string\" || candidate.key.length === 0) return false;\n if (typeof candidate.label !== \"string\") return false;\n return true;\n}\n","import type { TableArtifactRecord } from \"@/components/artifacts/types\";\n\n/**\n * Produces a plain-text clipboard representation of a table artifact.\n *\n * Returns the artifact title as plain text so that pasting into non-markdown-aware targets\n * (plain-text editors, terminal, spreadsheets) does not expose raw markdown syntax. This\n * matches the contract of `TextBlockService.toClipboardText`, which also strips markdown —\n * `useCopyToClipboard` writes the aggregated string verbatim, so every block type must\n * independently normalise to plain text.\n *\n * The presigned URL is intentionally omitted from the clipboard value: presigned URLs expire\n * quickly (typically 15 min–1 h) and are not useful when pasted as bare text. The Download\n * button in the artifact chrome is the canonical way to obtain the file.\n */\nexport function tableArtifactToClipboardText(artifact: TableArtifactRecord): string {\n const trimmedTitle = artifact.title?.trim();\n return trimmedTitle || \"Table\";\n}\n","import type { ArtifactService, TableArtifactRecord } from \"../types\";\nimport { artifactTypes } from \"../types\";\nimport { TableArtifact } from \"../table-artifact/table-artifact\";\nimport { tableArtifactToClipboardText } from \"../table-artifact/to-clipboard-text\";\n\nexport const TableArtifactService: ArtifactService<TableArtifactRecord> = {\n type: artifactTypes.TABLE,\n Component: TableArtifact,\n toClipboardText: tableArtifactToClipboardText,\n};\n","import type { ArtifactRecord, ArtifactService, ArtifactType } from \"../types\";\nimport { artifactTypes } from \"../types\";\nimport { ChartArtifactService } from \"./chart-artifact-service\";\nimport { TableArtifactService } from \"./table-artifact-service\";\n\n// `ArtifactService<TSpecific>` is invariant on `TSpecific` via React's `ComponentType`\n// (props are contravariant). Each service overlaps structurally with the base `ArtifactService`\n// enough for a direct `as ArtifactService` cast. The registry dispatches only by runtime\n// discriminator — `ArtifactServices[artifact.type]` always resolves to the matching concrete service.\n/**\n * Map of artifact services keyed by `artifact.type`.\n *\n * Adding a new artifact type = create a `*-service.ts` file (mirroring `block-services/`), then\n * add one entry here. The block-level dispatcher (`ArtifactRefBlock`) consumes this map to\n * render the concrete component; `artifactToClipboardText` consumes it for the clipboard contract.\n */\nexport const ArtifactServices: Record<ArtifactType, ArtifactService> = {\n [artifactTypes.TABLE]: TableArtifactService as ArtifactService,\n [artifactTypes.CHART]: ChartArtifactService as ArtifactService,\n};\n\n/**\n * Returns a clipboard-friendly string for an artifact, delegating to the registered service's\n * `toClipboardText`. Falls back to `[Artifact: <title>]` when the artifact type has no registered\n * service (unknown type) so copy never silently produces an empty string.\n */\nexport function artifactToClipboardText(artifact: ArtifactRecord): string {\n const entry = ArtifactServices[artifact.type];\n if (!entry) {\n return `[Artifact: ${artifact.title ?? artifact.type}]`;\n }\n return entry.toClipboardText(artifact);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,gBAAgB;AAAA,EAC3B,OAAO;AAAA,EACP,OAAO;AACT;;;ACgDO,IAAM,gCAAqD;AAAA,EAChE,UAAU;AAAA,EACV,aAAa;AAAA,EACb,WAAW;AAAA,EACX,SAAS;AAAA,EACT,OAAO;AAAA,EACP,sBAAsB,CAAC,UAAU,OAAO;AAC1C;;;ACMO,IAAM,gCAAqD;AAAA,EAChE,UAAU;AAAA,EACV,aAAa;AAAA,EACb,WAAW;AAAA,EACX,SAAS;AAAA,EACT,OAAO;AACT;;;ACnFA,IAAAA,gBAAmD;;;ACAnD,kBAAsC;AACtC,4BAAwB;AAMjB,SAAS,MAAM,QAA8B;AAClD,aAAO,mCAAQ,kBAAK,MAAM,CAAC;AAC7B;;;ACYE;AADK,IAAM,WAAW,CAAC,EAAE,WAAW,GAAG,MAAM,MAC7C;AAAA,EAAC;AAAA;AAAA,IACC,WAAW,GAAG,2EAA2E,SAAS;AAAA,IACjG,GAAG;AAAA;AACN;AAKK,IAAM,iBAAiB,CAAC,EAAE,WAAW,GAAG,MAAM,MACnD,4CAAC,SAA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AAAA,UACtC,gBAAgB;AAAA,UAChB,eAAe;AAAA,UACf,QAAQ;AAAA;AAAA,MACV,GACF;AAAA,OACF;AAAA;AAEJ;;;AQ/GO,SAAS,6BAA6B,UAAuC;AAClF,QAAM,eAAe,SAAS,OAAO,KAAK;AAC1C,SAAO,gBAAgB;AACzB;;;ACbO,IAAM,uBAA6D;AAAA,EACxE,MAAM,cAAc;AAAA,EACpB,WAAW;AAAA,EACX,iBAAiB;AACnB;;;ACOO,IAAM,mBAA0D;AAAA,EACrE,CAAC,cAAc,KAAK,GAAG;AAAA,EACvB,CAAC,cAAc,KAAK,GAAG;AACzB;AAOO,SAAS,wBAAwB,UAAkC;AACxE,QAAM,QAAQ,iBAAiB,SAAS,IAAI;AAC5C,MAAI,CAAC,OAAO;AACV,WAAO,cAAc,SAAS,SAAS,SAAS,IAAI;AAAA,EACtD;AACA,SAAO,MAAM,gBAAgB,QAAQ;AACvC;","names":["import_react","import_react","import_react","styled","import_jsx_runtime","Icon","import_styled_components","styled","import_jsx_runtime","IconButton","import_jsx_runtime","import_jsx_runtime","import_react","import_react","import_recharts","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","RechartsBarChart","import_jsx_runtime","import_react","import_recharts","import_jsx_runtime","RechartsLineChart","import_jsx_runtime","import_react","import_recharts","import_jsx_runtime","RechartsPieChart","import_jsx_runtime","import_jsx_runtime","Papa","import_react","import_jsx_runtime","import_react","React","import_jsx_runtime","import_react","import_jsx_runtime","import_jsx_runtime","TITLE_CLASSES"]}