Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore(design-sync): sync the design system to Claude Design (#18966)

Mark Salpeter9179a3eb7d1e
diff --git a/.design-sync/NOTES.md b/.design-sync/NOTES.md
new file mode 100644
index 0000000000..5254e44543
--- /dev/null
+++ b/.design-sync/NOTES.md
@@ -0,0 +1,76 @@
+# design-sync notes
+
+- Scope (user choice, 2026-10-16): `web/src/components/design-system` stories (primitives + table + charts) plus the shared app components with stories elsewhere under `web/src/components` (widened the same day). Exclude `web/src/features`, `web/src/ee` and `.storybook/docs`.
+- Shared components are exported by name from an explicit list in `gen-entry.sh` (their modules also export shadcn primitives that clash with DS names) - add a line there when a new shared component gets stories. Shared components a single DS component already covers stay out (user choice, 2026-10-16), so the design agent reaches for the DS one: ui `Button` and ui `dropdown-menu` (-> Button/DropdownMenu; Playground/Button stories are skipped by id under Button, `titleMap {"dropdown-menu": null}`), `InfoTooltip` (-> Tooltip), `TextChip` (-> Badge/Tag), `TextActionButton` (-> Button `variant="text"`), `ActionButton` (-> Button; its extras are access/entitlement/tracking logic), `ActionButtonCountBadge` (-> Badge). `DataTable` was first left out (-> Table), then added on 2026-10-18 (user choice): `Table` has no pagination, row selection, pinned columns, custom row heights, grouped headers, `renderRow`, peek or footer, and both are used about equally in the app (~34 vs ~32 importers). Kept: domain wrappers built on DS parts (ScoreTag, ScoreBadge, EnvLabelBadge, ...) and components with no DS counterpart (Drawer, StatusBadge, AIAssistedInput, MarkdownView, table chrome, nav). Kebab-case story titles (`mobile-page-actions-content`, `drawer`, ...) and `MarkdownViewer` -> `MarkdownView` pair via `cfg.titleMap`.
+
+- **Every sync: re-evaluate `Table` vs `DataTable`** (user ask, 2026-10-18). Diff `TableProps` (`design-system/table/Table.tsx`) against `DataTable`'s props (`components/table/data-table.tsx`) and compare their stories. Once `Table` covers everything `DataTable` does (pagination, selection, pinning, row heights, grouped headers, `renderRow`/folder rows, peek, footer), drop `DataTable` from gen-entry.sh, its config override and conventions.md, and tell the user. Until then, report the remaining gap in the sync summary.
+
+## Setup / prerequisites
+
+- Env: build Storybook with the committed `.env.dev.example` (`npx dotenv -e ../.env.dev.example`), never the main checkout's `.env` (may hold secrets). `gen-entry.sh` mirrors its `NEXT_PUBLIC_*` values into `process-shim.js`.
+- Build `@langfuse/shared` first (`pnpm --filter=@langfuse/shared exec prisma generate && pnpm --filter=@langfuse/shared build`) - the bundle resolves its `dist/`; missing dist = WORKSPACE_SIBLING failures.
+- `.design-sync/node_modules` must be a symlink to `../.ds-sync/node_modules` (gitignored; recreate per clone) - `overrides/dts.mjs` needs ts-morph from there.
+- The design system has no `dist/`: `.design-sync/ds-package/` is a shim package. `gen-entry.sh` regenerates `index.ts` (one `export *` per public module, `process-shim.js` imported first) - rerun it when components are added/removed (buildCmd does).
+
+## Build fixes (why each file exists)
+
+- `ds-package/tsconfig.json`: maps node builtins `fs`/`stream`/`zlib` -> `node-stubs/empty.js` (Next's bloom-filter pulls gzip-size on a dev-only branch) + `"jsx": "react-jsx"`, and `next/router` -> `next-router.ts` (see Router). Gotchas: the converter's comment stripper breaks on a `"//"` JSON key - no comments/"//" keys; do NOT map `@/*` there (the paths plugin's existsSync matches directories and breaks directory imports) - esbuild handles `@/` via web/tsconfig.json natively.
+- `process-shim.js` (generated): Next/next-auth/env.mjs read `process.env` at module scope -> "process is not defined" without it.
+- `ds-package/copy-css.sh`: Tailwind v4 CSS only exists compiled inside the Storybook build; copies the stylesheet `sb-reference/iframe.html` links to `ds-package/storybook-compiled.css` (cfg.cssEntry, gitignored). Also injects IBM Plex Mono `@font-face` into `sb-reference/iframe.html` (see Fonts).
+- `ds-package/LangfuseProvider.tsx` (cfg.provider): the decorator auto-bundle fails (`Could not resolve tailwindcss`), so the preview.tsx decorator chain is distilled here: RouterContext(stub) > LayerProvider > ThemeProvider(light, class) > `#__next` bg/text > SessionProvider(null) > TooltipProvider.
+- Router: Storybook's nextjs-vite framework mocks the Pages router; table code (`data-table.tsx` rows, `peek.tsx`, `ValueCell.tsx`) calls `useRouter()` from `next/router` and threw "NextRouter was not mounted" (blank Table previews). LangfuseProvider mounts an inert stub router. Each `_preview/<Name>.js` bundles its OWN copy of non-DS code (web/src/components/table, next), so a context from the bundle alone never reaches it: tsconfig maps `next/router` -> `ds-package/next-router.ts`, whose `useRouter` reads the RouterContext LangfuseProvider publishes on `globalThis.__dsRouterContext`. tsconfig is not grade-keyed, so this carried grades.
+- `#__next` height: Storybook gives `div#__next` `height: 100vh` in canvas view so globals.css' `#__next, #__next > div {height:100%}` chain resolves (IOTableCell panels, truncation footers). LangfuseProvider's `fullHeight` prop mirrors it, defaulting on only for `?story=` captures (grid cards and designs stay `auto`; designs can pass `fullHeight`).
+- Public assets: LangfuseIcon/LangfuseLogo load `${NEXT_PUBLIC_BASE_PATH ?? ""}/icon.svg|wordart-*.svg` from web/public. The bundle ships no loose files (the build wipes ds-bundle/), so `gen-entry.sh` discovers those paths in DS sources and generates `public-assets.js` (data URLs + an `<img src>` remap via `setAttribute`/`src` setter), imported right after process-shim.js. The reference was broken too - `.ds-sync/storybook/http-serve.mjs` serves `.svg` as octet-stream - so copy-css.sh injects the same script into `sb-reference/iframe.html` (`data-ds-sync-assets`, replaced each run). Run gen-entry.sh before copy-css.sh.
+- `ds-package/csf-factories-preview.tsx` + `overrides/story-imports.mjs`: stories use CSF factories (`preview.meta().story()`), which need Storybook's runtime ("definePreview is not a function"). The fork redirects `web/.storybook/preview.*` to the shim, which flattens factory stories to CSF3 and maps `globals.theme === "dark"` to a `.dark` wrapper div. It also runs meta + story `beforeEach` hooks once before first render (cleanup on unmount): AppSidebar's Launch Week stories pin `Date.now` there, and without it the frozen capture clock expired those notifications.
+- `overrides/dts.mjs`: ts-morph `.d.ts` extraction for TS source (baseUrl web + `@/*`, @types/react from web/node_modules, resolveSourceFileDependencies). Two forks for the shared components: `pkgDir` is `web/src` (not the design-system dir), so their own `on*` callbacks survive the DOM-noise filter; and `propsBodyFor` looks up `<Name>Props` in the component's own file first, because with the wider `pkgDir` another file's `InputProps` was winning.
+- `cfg.storyImports.shim` lists the shared modules whose filename doesn't match the export (`ai-assisted-input.tsx`, `drawer.tsx`, `MarkdownViewer.tsx`, `grouped-score-badge.tsx`) plus `ui/sidebar.tsx`. Without the shim the preview bundles a second source copy, which loses LangfuseProvider's contexts ("`Tooltip` must be used within `TooltipProvider`", "useSidebar must be used within a Sidebar"). `score-tag.tsx` and `mobile-page-actions-content.tsx` stay unshimmed: their stories import non-exported names (`SCORE_LEVEL_LABELS`, ui `Popover`).
+- `SidebarProvider` + `SidebarInset` are exported because `AppSidebar` can't render outside them.
+
+## Fonts
+
+- Sans = system stack by design (globals.css `--font-sans`), nothing to ship.
+- Mono = IBM Plex Mono, self-hosted at `web/public/fonts/*.woff2` and loaded in the app by `next/font/local` (`web/src/styles/fonts.ts`, var `--font-plex-mono`). Outside Next the var is unset and `font-mono` falls back to the literal "IBM Plex Mono" family, so `ds-package/plex-mono.css` (cfg.extraFonts) declares that family; copy-css.sh injects the same faces into the reference iframe so compare verifies with the real font. Keep both in sync with fonts.ts weights (400, 600).
+
+## Preview / grading decisions
+
+- `[PORTAL?]` fires on EVERY component - false positive: LayerProvider always mounts `div[data-overlay-root]` with empty layer divs as a body child. Judge overlay bleed from the images; apply cardMode "single" only where overlay content visibly escapes.
+- `play()` stories: Storybook runs a story's `play` before capture; static previews never do. Stories whose post-play state differs visibly (opened dialog/menu/tooltip, toggled format) are skipped via `cfg.overrides.<Name>.skip` - they're interaction tests, not design variants. `(Test)` stories whose play leaves the initial render unchanged stay and are graded. Skips live in `cfg.overrides.<Name>.skip` (overlays: every (Test) story that opens a menu/hover card/tooltip/dialog; charts: (Test) stories whose play opens a tooltip or toggles a series; Dialog/Avatar/Codeblock interaction tests; GroupedScoreBadges "(Test) With Overflow", KeyValueFilterBuilder "(Test) Observed Key Suggestion Preserves Value", MarkdownView "(Test) Reveals Header Controls On Focus"). A play() that only leaves a focus ring (Accordion/Alert/Callout dismiss tests, chart legend buttons, IconButton/Toggle clicks, form-input (Test) stories, Table actions trigger, AIAssistedInput retrigger) is graded match - focus residue is not a design difference.
+- Button absorbs 7 `Playground/Button` stories from `src/components/ui/Button.stories.tsx` (out of scope) - skipped by id.
+- Table absorbs ~88 `Table/Columns/create*TableColumn` stories (titleParts match "Table"; titleMap can't exclude) - kept under Table with cardMode single, primaryStory Default.
+- Avatar: owned `previews/Avatar.tsx` - Default story's `src: "/apple-touch-icon.png"` is a Storybook staticDirs path; the owned preview imports the file (esbuild dataurl) instead.
+- Dark-theme stories (StatusMessage Dark*): Storybook paints the whole canvas dark, the preview only wraps the component - framing only, graded match.
+- `layout: "fullscreen"` stories (charts, Dialog, Table, PaginationBar, IOTableCell): the card html keeps `body{padding:24px}` on `?story=` captures, so `h-dvh` story roots overflowed the 900x700 capture and lost the x-axis/legend band. `csf-factories-preview.tsx` appends a `FullscreenFrame` decorator to fullscreen stories that zeroes body padding on `?story=` captures only (grid/column cards keep padding).
+- Grade-key gotcha: grade keys hash `overrides/*.mjs` fork bytes (any fork edit re-grades EVERY component) but NOT `ds-package/` sources. After editing the shim/provider, delete `.design-sync/.cache/compare/<Name>.grade.json` for the components whose render actually changes.
+- Table name collisions: Table absorbs ~22 column-story files whose names repeat (19x "Default", 19x "Loading", 16x "Empty Value", ...). grade.json is keyed by story NAME, so one verdict covers every same-named story - judge each pair, record the worst verdict per name.
+- Screenshot lifetime: package-build wipes `ds-bundle/_screenshots/compare/`, and EVERY compare run (scoped or not) replaces that folder with only its own captures. Finish all grading of one capture pass before the next build/compare; grades in `.cache/compare/*.grade.json` survive either way.
+- Story caps: compare defaults to 20 stories per component - run Table with `--max-stories 120` and Tabs with `--max-stories 24` or tail stories stay ungraded.
+- PaginationBar: its only offset-mode story "(Test) Navigates pages" (id `...--default`) is play-state and skipped, so offset-mode chrome is unverified; only the cursor-mode story is graded.
+- Padded-layout framing: sb captures crop to the 868px story root at 0,0; ds captures are 900px with the card's 24px body inset, so full-width content is 16px narrower in ds. Framing only - graded match everywhere (Tabs, CodeSection, Button, Table columns, ...).
+- Meta decorators apply twice (fixed, 2026-10-18): `makeStory` in `csf-factories-preview.tsx` merges meta decorators into `story.decorators`, and the preview generator (`preview-gen-storybook.mjs:60`) concatenates `meta.decorators` again, which doubled the `p-4` inset on DataTable and the 8 charts. `preview.meta` now omits `decorators` from the meta fields it returns. The 9 components were regraded after the fix and are pixel-identical apart from play() focus residue. The shim is not grade-keyed, so any later shim edit needs the affected grade.json files deleted by hand.
+- Table Actor/Button column stories don't set `layout: "fullscreen"`, so the preview keeps the 24px card inset storybook lacks - framing only, graded match.
+- ChartTooltip (`internal/charts`) is excluded (`cfg.titleMap {ChartTooltip: null}` + not exported by gen-entry.sh): all 10 stories render the tooltip only after play() hover/focus; charts render it internally.
+- ConfirmationDialogController: the converter pairs stories to exports by display name first, so stories "Standard"/"Type to confirm" (exports `StandardExample`/`TypeToConfirmExample`) render the `(Test)` exports `Standard`/`TypeToConfirm` - identical args, so harmless; both `(Test)` stories are skipped. Revisit if their args diverge.
+- OrganizationDropdownMenu/ProjectDropdownMenu: no story opens the menu (render-prop trigger, no `open`/play), so compare verifies only the trigger; the menu content is unverified.
+- MediaTag "Wikimedia File Page Fallback" loads a commons.wikimedia.org URL, which the capture sandbox blocks - both panels show "Failed to load media", so that story is unverified. Re-capture unsandboxed (`compare.mjs --components MediaTag --force`) to verify it.
+- Drawer Compact: the sb shot crops 16px into the fixed full-width sheet (hides its left padding/rounded corner) - framing only, graded match.
+- Grading triage: `md5 -q` on each raw `__sb.png`/`__ds.png` pair separates byte-identical pairs from ones needing a careful look (still open one pair per story file to rule out both-blank) - a triage aid, never the verdict.
+- HoverCard "(Test) Delayed" matches only because both captures land before its 700ms openDelay - skip it if a capture ever shows the card open.
+
+## Known validate warnings (expected)
+
+- `[TOKENS_MISSING]` 7 vars (`--col-scoreName-size`, `--emoji-hover-color`, `--sdm-tbg`, `--peek-max-width`, `--tw`, `--streamdown-caret`, `--radix-accordion-content-height`): all set at runtime by inline styles/JS or vendored libs - ignorable. Any other warning is new.
+
+## Re-sync risks (check these first when a re-sync diverges)
+
+- Order: `@langfuse/shared` build -> Storybook build under `.env.dev.example` -> `gen-entry.sh` -> `copy-css.sh` (re-injects fonts + public assets into `sb-reference/iframe.html`; a fresh Storybook build drops both) -> package-build.
+- `ds-package/` sources (LangfuseProvider, next-router.ts, csf-factories-preview.tsx incl. FullscreenFrame, process-shim/public-assets generation, tsconfig) are NOT grade-keyed: after editing them, delete the affected `.cache/compare/<Name>.grade.json` by hand.
+- `overrides/story-imports.mjs` IS keyed: any byte change re-grades all 80 components.
+- process-shim.js mirrors `.env.dev.example` NEXT_PUBLIC_* values; if a value there starts gating a component's render, the preview follows the dev example, not prod.
+- New web/public assets referenced via `NEXT_PUBLIC_BASE_PATH ?? ""}/...` are picked up by gen-entry.sh automatically; other static paths (e.g. Avatar's `/apple-touch-icon.png`) need an owned preview.
+- Shared app components: a new kebab-named (or otherwise export-mismatched) module a story imports must join `cfg.storyImports.shim`, or its preview bundles a second copy and loses provider contexts. New shared components also need a line in gen-entry.sh's heredoc. MediaTag's Wikimedia story stays unverified while capture runs sandboxed.
+- Owned preview: `previews/Avatar.tsx` shadows the generated one - re-check it when Avatar stories change.
+- Story `beforeEach` runs in the preview shim (see Build fixes); a story relying on Storybook loaders, `mount`, or async `beforeEach` work will still diverge.
+- Play-state skips are by story id; renamed stories silently lose their skip (compare then shows the post-play delta - re-skip).
+- Story caps (Table 120, Tabs 24), Table name collisions, ConfirmationDialogController pairing and HoverCard "(Test) Delayed" timing (see above).
+- A new Storybook framework mock (router, image, font) is invisible to the bundle - a blank or throwing preview usually means one is missing from LangfuseProvider.
+- Previews compile with esbuild `charset: 'utf8'`, so a `"\uFFFD"` string constant anywhere in the import graph lands as a raw U+FFFD and claude.ai flags the file as having unreadable characters. Check with `perl -CSD -ne 'print "$ARGV\n" if /\x{FFFD}/' ds-bundle/_preview/*.js`; fix at the source (e.g. `String.fromCharCode(0xfffd)`, as in `packages/shared/src/domain/auditLogs.ts`).
diff --git a/.design-sync/config.json b/.design-sync/config.json
new file mode 100644
index 0000000000..992fb59fd8
--- /dev/null
+++ b/.design-sync/config.json
@@ -0,0 +1,326 @@
+{
+ "projectId": "31adc942-7274-47d3-8b86-cc9a1ec5e652",
+ "shape": "storybook",
+ "storybookConfigDir": "web/.storybook",
+ "pkg": "@langfuse/design-system",
+ "globalName": "LangfuseDS",
+ "entry": ".design-sync/ds-package/index.ts",
+ "tsconfig": "tsconfig.json",
+ "storybookStatic": ".design-sync/sb-reference",
+ "buildCmd": ".design-sync/ds-package/gen-entry.sh && (cd web && npx dotenv -e ../.env.dev.example -- npx storybook build -c .storybook -o \"$(git rev-parse --show-toplevel)/.design-sync/sb-reference\") && .design-sync/ds-package/copy-css.sh",
+ "libOverrides": {
+ "dts.mjs": "DS ships TS source (no dist/): resolve web @/* paths, @types/react from web/node_modules, in-package = web/src/components/design-system/",
+ "story-imports.mjs": "Storybook 10 CSF factories: redirect web/.storybook/preview imports to ds-package/csf-factories-preview.tsx (flattens preview.meta().story() to CSF3)"
+ },
+ "cssEntry": "storybook-compiled.css",
+ "provider": {
+ "component": "LangfuseProvider"
+ },
+ "overrides": {
+ "Table": {
+ "cardMode": "single",
+ "primaryStory": "Default",
+ "skip": [
+ "design-components-table--sorting",
+ "design-components-table--resize-columns"
+ ]
+ },
+ "Button": {
+ "skip": [
+ "playground-button--default",
+ "playground-button--disabled",
+ "playground-button--keyboard-focus",
+ "playground-button--loading",
+ "playground-button--loading-with-text",
+ "playground-button--variant-matrix",
+ "playground-button--with-icon"
+ ]
+ },
+ "Alert": {
+ "cardMode": "column"
+ },
+ "AreaChart": {
+ "cardMode": "column",
+ "skip": [
+ "design-components-areachart--highlight-legend",
+ "design-components-areachart--stacked-areas"
+ ]
+ },
+ "BarChart": {
+ "cardMode": "column"
+ },
+ "GroupedBarChart": {
+ "cardMode": "column",
+ "skip": [
+ "design-components-groupedbarchart--side-by-side"
+ ]
+ },
+ "HistogramChart": {
+ "cardMode": "column"
+ },
+ "HorizontalBarChart": {
+ "cardMode": "column",
+ "skip": [
+ "design-components-horizontalbarchart--category-colors",
+ "design-components-horizontalbarchart--long-and-duplicate-labels",
+ "design-components-horizontalbarchart--many-rows",
+ "design-components-horizontalbarchart--side-tooltip"
+ ]
+ },
+ "LineChart": {
+ "cardMode": "column",
+ "skip": [
+ "design-components-linechart--many-legend-entries"
+ ]
+ },
+ "LinkBadge": {
+ "cardMode": "column"
+ },
+ "MultiSelectTagInput": {
+ "cardMode": "column",
+ "skip": [
+ "design-components-multiselecttaginput--test-selects-option"
+ ]
+ },
+ "SelectInput": {
+ "cardMode": "column",
+ "skip": [
+ "design-components-selectinput--searchable-with-badges",
+ "design-components-selectinput--empty",
+ "design-components-selectinput--test-forwards-trigger-props",
+ "design-components-selectinput--test-keeps-badged-label-readable",
+ "design-components-selectinput--test-keeps-badged-label-readable-without-search"
+ ]
+ },
+ "StackedBarChart": {
+ "cardMode": "column",
+ "skip": [
+ "design-components-stackedbarchart--legend-toggle",
+ "design-components-stackedbarchart--single-series-initially-hidden"
+ ]
+ },
+ "Tabs": {
+ "cardMode": "column",
+ "skip": [
+ "design-components-tabs--switches-tab",
+ "design-components-tabs--selects-hidden-tab-from-overflow-menu",
+ "design-components-tabs--focuses-tab-selected-from-overflow-menu",
+ "design-components-tabs--tracks-trigger-resize"
+ ]
+ },
+ "ControlledHoverCard": {
+ "cardMode": "single",
+ "skip": [
+ "design-components-controlledhovercard--controlled",
+ "design-components-controlledhovercard--popover-layer"
+ ]
+ },
+ "DialogController": {
+ "cardMode": "single",
+ "skip": [
+ "design-components-dialogcontroller--close-veto",
+ "design-components-dialogcontroller--fresh-content-on-open",
+ "design-components-dialogcontroller--initial-state"
+ ]
+ },
+ "Dialog": {
+ "skip": [
+ "design-components-dialog--autofocus",
+ "design-components-dialog--destructive-autofocus",
+ "design-components-dialog--destructive-only-autofocus"
+ ]
+ },
+ "Avatar": {
+ "skip": [
+ "design-components-avatar--test-hover-name-and-email"
+ ]
+ },
+ "Codeblock": {
+ "skip": [
+ "design-components-codeblock--json",
+ "design-components-codeblock--large-json",
+ "design-components-codeblock--lossless-json",
+ "design-components-codeblock--invalid-json"
+ ]
+ },
+ "ConfirmationDialogController": {
+ "skip": [
+ "design-components-confirmationdialogcontroller--standard",
+ "design-components-confirmationdialogcontroller--type-to-confirm"
+ ]
+ },
+ "DropdownMenu": {
+ "skip": [
+ "design-components-dropdownmenu--test-actions-remain-independent",
+ "design-components-dropdownmenu--test-checkbox-and-submenu",
+ "design-components-dropdownmenu--test-click-actions",
+ "design-components-dropdownmenu--test-disabled-action",
+ "design-components-dropdownmenu--test-disabled-link",
+ "design-components-dropdownmenu--test-keyboard-activation",
+ "design-components-dropdownmenu--test-nested-menus-stay-within-viewport",
+ "design-components-dropdownmenu--test-search-behavior",
+ "design-components-dropdownmenu--test-secondary-action-layout",
+ "design-components-dropdownmenu--test-trigger-and-items"
+ ]
+ },
+ "HoverCard": {
+ "skip": [
+ "design-components-hovercard--default-surface",
+ "design-components-hovercard--disabled",
+ "design-components-hovercard--hoverable-content",
+ "design-components-hovercard--keyboard-navigation",
+ "design-components-hovercard--trigger-ref-and-click-handler",
+ "design-components-hovercard--trigger-ref-cleanup"
+ ]
+ },
+ "HoverCardController": {
+ "skip": [
+ "design-components-hovercardcontroller--custom-surface"
+ ]
+ },
+ "PieChart": {
+ "skip": [
+ "design-components-piechart--center-text-fits",
+ "design-components-piechart--combined-small-slices",
+ "design-components-piechart--keyboard-focus",
+ "design-components-piechart--oversized-center-text-hidden"
+ ]
+ },
+ "Tooltip": {
+ "skip": [
+ "design-components-tooltip--test-hover-and-focus",
+ "design-components-tooltip--test-pointer-transparent-content",
+ "design-components-tooltip--test-shortcut-renders-keycap"
+ ]
+ },
+ "Input": {
+ "skip": [
+ "design-components-input--test-accepts-text"
+ ]
+ },
+ "SearchInput": {
+ "skip": [
+ "design-components-searchinput--test-submits-on-enter",
+ "design-components-searchinput--test-opens-dropdown"
+ ]
+ },
+ "SwitchInput": {
+ "skip": [
+ "design-components-switchinput--changes-value"
+ ]
+ },
+ "RadioGroup": {
+ "skip": [
+ "design-components-radiogroup--test-selects-option"
+ ]
+ },
+ "Form": {
+ "skip": [
+ "design-components-form--submits"
+ ]
+ },
+ "SelectDropdown": {
+ "skip": [
+ "design-components-selectdropdown--compact-trigger",
+ "design-components-selectdropdown--wrapped-trigger",
+ "design-components-selectdropdown--grouped-disabled-options"
+ ]
+ },
+ "MultiSelectInput": {
+ "skip": [
+ "design-components-multiselectinput--test-selects-multiple-options",
+ "design-components-multiselectinput--test-hides-select-all-while-searching",
+ "design-components-multiselectinput--test-keeps-wheel-inside-popover",
+ "design-components-multiselectinput--test-keeps-overlapping-labels-distinct"
+ ]
+ },
+ "PaginationBar": {
+ "skip": [
+ "design-components-paginationbar--default"
+ ]
+ },
+ "CodeSection": {
+ "skip": [
+ "design-components-codesection--toggles-collapse"
+ ]
+ },
+ "Drawer": {
+ "cardMode": "single",
+ "primaryStory": "Compact"
+ },
+ "ItemBadge": {
+ "cardMode": "column"
+ },
+ "KeyValueFilterBuilder": {
+ "cardMode": "column",
+ "skip": [
+ "playground-keyvaluefilterbuilder--test-observed-key-suggestion-preserves-value"
+ ]
+ },
+ "MediaTag": {
+ "cardMode": "single",
+ "primaryStory": "AllKinds"
+ },
+ "MobilePageActionsContent": {
+ "cardMode": "single",
+ "primaryStory": "MixedPageControls"
+ },
+ "OverviewSelectionBar": {
+ "cardMode": "single",
+ "primaryStory": "Default"
+ },
+ "StatusBadge": {
+ "cardMode": "column"
+ },
+ "AppSidebar": {
+ "cardMode": "single",
+ "primaryStory": "Default"
+ },
+ "GroupedScoreBadges": {
+ "skip": [
+ "playground-groupedscorebadges--with-overflow"
+ ]
+ },
+ "MarkdownView": {
+ "skip": [
+ "playground-markdownviewer--header-controls-on-focus"
+ ]
+ },
+ "DataTable": {
+ "cardMode": "single",
+ "primaryStory": "Default",
+ "skip": [
+ "playground-datatable--pixel-resize-keeps-cells-mounted",
+ "playground-datatable--medium-boundary-updates-only-resized-row",
+ "playground-datatable--equivalent-refresh-keeps-resize-active",
+ "playground-datatable--membership-changes-cancel-resize",
+ "playground-datatable--canceled-pointers-restore-row-height",
+ "playground-datatable--overlapping-pointers-keep-first-resize",
+ "playground-datatable--removed-lower-handle-releases-pending-resize",
+ "playground-datatable--removed-lower-handle-rolls-back-preview",
+ "playground-datatable--removed-keyboard-handle-cancels-resize"
+ ]
+ }
+ },
+ "extraFonts": [
+ "plex-mono.css"
+ ],
+ "titleMap": {
+ "ChartTooltip": null,
+ "dropdown-menu": null,
+ "mobile-page-actions-content": "MobilePageActionsContent",
+ "MarkdownViewer": "MarkdownView",
+ "ai-assisted-input": "AIAssistedInput",
+ "drawer": "Drawer"
+ },
+ "readmeHeader": ".design-sync/conventions.md",
+ "storyImports": {
+ "shim": [
+ "/components/ui/ai-assisted-input.tsx",
+ "/components/ui/sidebar.tsx",
+ "/components/ui/drawer.tsx",
+ "/components/ui/MarkdownViewer.tsx",
+ "/components/grouped-score-badge.tsx"
+ ]
+ }
+}
diff --git a/.design-sync/conventions.md b/.design-sync/conventions.md
new file mode 100644
index 0000000000..ecf3797a03
--- /dev/null
+++ b/.design-sync/conventions.md
@@ -0,0 +1,67 @@
+# Langfuse design system - how to build with it
+
+Components are on `window.LangfuseDS` (e.g. `const { Button, Alert, Tabs, Badge } = window.LangfuseDS;`). Each component's `<Name>.d.ts` is its API contract and `<Name>.prompt.md` shows real usage - read both before using a component.
+
+## Wrap everything in `LangfuseProvider`
+
+Render your whole app inside `LangfuseDS.LangfuseProvider` exactly once, at the root. It sets the light theme class, the `bg-background text-foreground` page surface, the overlay layer root that dialogs/menus/tooltips portal into, and the tooltip/session context. Without it, overlays have nowhere to mount and tooltips throw.
+
+```jsx
+const { LangfuseProvider } = window.LangfuseDS;
+root.render(<LangfuseProvider><App /></LangfuseProvider>);
+```
+
+Dark mode: pass `theme="dark"` - `<LangfuseProvider theme="dark">` - so the `dark` class lands on `<html>` and portalled dialogs, menus, tooltips and code highlighting switch too. A `<div className="dark bg-background text-foreground">` wrapper only flips inline content inside it, never overlays.
+
+## Component API idiom
+
+- Components take **no `className`/`style`** - style comes from enum props (`variant`, `size`), never Tailwind strings. Use only the values the `.d.ts` lists.
+- Labels are props, not children, where the API says so: `<Button text="Save" variant="primary" />`, `<Badge text="beta" />`.
+- Compound components hang off the parent: `Alert.Title`/`Alert.Description`, `Tabs.List`/`Tabs.Trigger`/`Tabs.Content`.
+- Booleans are `is*`/`should*` or plain (`loading`, `disabled`); components never carry outer margin - spacing is the parent's job.
+- Prefer a library component over hand-rolled markup: `Button`, `IconButton`, `TextLink`, `Input`, `SearchInput`, `SelectInput`, `Checkbox`, `Switch`, `Tabs`, `Dialog` + `DialogController`, `Tooltip`, `Badge`, `Tag`, `Alert`, `Callout`, `StatusMessage`, `Codeblock`, `Table`, charts (`LineChart`, `BarChart`, `AreaChart`, `PieChart`, ...).
+- Icons are lucide-react components on `window.LangfuseDS.LucideIcons` (the app's only icon set): `const { Plus, Trash2 } = window.LangfuseDS.LucideIcons;` then `<IconButton icon={Trash2} ... />` / `<Button icon={Plus} ... />`. Never draw inline SVGs or use emoji.
+
+## App components (Playground group)
+
+The `playground` group holds Langfuse app components built for specific screens: `AppSidebar`, `OrganizationDropdownMenu`/`ProjectDropdownMenu`, `Drawer`, `MarkdownView`, `StatusBadge`, `ItemBadge`, `ScoreBadge`/`ScoreTag`/`GroupedScoreBadges`, `EnvLabelBadge`, `MediaTag`/`MediaFileCard`, `AIAssistedInput`, `CrashModal`, `EvaluatorsOnboardingView`, `DataTable`, and table chrome (`FacetHeader`, `KeyValueFilterBuilder`, `OverviewSelectionBar`, `TableViewPresetsButton`, `ColumnVisibilityHeader`). Use them when a design shows that exact piece of the app. They predate the design-system rules above, so follow each one's `.d.ts` rather than the idiom - and for generic UI always reach for the design-system component first (`Table` for simple lists, `Tooltip` for help text, `Badge`/`Tag` for chips, `Button` for actions). Tables: use `Table` for simple lists (sorting, resizing, column visibility, a row actions menu, `rowHeight`). Use `DataTable` for explorer screens such as traces, observations and evals. It adds pagination with totals, row selection, pinned columns, density and custom row heights, grouped headers and folder rows that `Table` lacks. Build `DataTable` columns with the same `create*TableColumn` helpers. `AppSidebar` only renders inside `SidebarProvider`, with the page body in a sibling `SidebarInset`: `<SidebarProvider open><AppSidebar ... /><SidebarInset>...</SidebarInset></SidebarProvider>`.
+
+## Layout glue: Tailwind v4 utilities with Langfuse tokens
+
+Your own layout markup uses Tailwind classes - but only ones present in the shipped `_ds_bundle.css` (it is precompiled; classes it doesn't contain do nothing). Safe vocabulary:
+
+| Family | Classes |
+|---|---|
+| Surfaces | `bg-background` `bg-card` `bg-muted` `bg-secondary` `bg-surface-sunken` `bg-primary` |
+| Text | `text-foreground` `text-foreground-secondary` `text-foreground-tertiary` `text-muted-foreground` `text-primary` `text-primary-foreground` `text-link` `text-destructive` |
+| Status | `bg-light-red`/`text-dark-red`, `bg-light-yellow`/`text-dark-yellow`, `bg-light-green`/`text-dark-green` |
+| Borders | `border` `border-border` `divide-y` `rounded-md` `rounded-lg` `shadow-sm` |
+| Type | `text-2xs` `text-xs` `text-sm` `text-base` `text-lg` `text-xl` `text-2xl`, `font-bold` (the only bold weight), `font-mono` (IBM Plex Mono) |
+| Layout | `flex` `flex-col` `grid` `grid-cols-2` `grid-cols-3` `items-center` `justify-between` `gap-1..6` `p-2..6` `px-4` `py-3` `space-y-2` `space-y-4` `w-full` `h-full` `max-w-md` `max-w-lg` `truncate` `overflow-auto` |
+
+Never use hex colors or raw px; `font-medium`/`font-semibold` compile but are off-system drift - use `font-bold` or nothing. The token source is `styles.css` -> `_ds_bundle.css` (`--color-*`, `--radius`, `--text-*`).
+
+## Example
+
+```jsx
+const { LangfuseProvider, Alert, Button, Badge } = window.LangfuseDS;
+
+function Panel() {
+ return (
+ <div className="flex flex-col gap-4 p-6 max-w-lg">
+ <div className="flex items-center justify-between">
+ <h2 className="text-lg font-bold text-foreground">Evaluators</h2>
+ <Badge text="beta" />
+ </div>
+ <Alert variant="warning">
+ <Alert.Title>Quota almost reached</Alert.Title>
+ <Alert.Description>90% of this month's evaluations are used.</Alert.Description>
+ </Alert>
+ <div className="flex gap-2">
+ <Button text="Cancel" variant="secondary" />
+ <Button text="Upgrade" variant="primary" />
+ </div>
+ </div>
+ );
+}
+```
diff --git a/.design-sync/ds-package/LangfuseProvider.tsx b/.design-sync/ds-package/LangfuseProvider.tsx
new file mode 100644
index 0000000000..07c25597c2
--- /dev/null
+++ b/.design-sync/ds-package/LangfuseProvider.tsx
@@ -0,0 +1,94 @@
+// The app-level context every Langfuse design-system component expects, distilled
+// from web/.storybook/preview.tsx's decorator (which mirrors _app.tsx/_document.tsx):
+// next-themes ThemeProvider (class strategy), the `div#__next > div` DOM scaffold
+// that globals.css scopes layout rules to, a null next-auth session (feature flags
+// resolve to false), the Radix TooltipProvider, and the LayerProvider z-index stack.
+// It also mounts an inert pages-router stub (Storybook's nextjs framework mocks the
+// router; table rows call `useRouter()` from next/router and throw without one).
+import { type ReactNode } from "react";
+import { SessionProvider } from "next-auth/react";
+import { type NextRouter } from "next/router";
+import { RouterContext } from "next/dist/shared/lib/router-context.shared-runtime";
+import { TooltipProvider } from "../../web/src/components/ui/tooltip";
+import { LayerProvider } from "../../web/src/context/LayerContext/LayerContext";
+import { ThemeProvider } from "../../web/src/features/theming/ThemeProvider";
+
+/** stubRouter is an inert pages router whose navigation calls resolve without effect */
+const stubRouter: NextRouter = {
+ route: "/",
+ pathname: "/",
+ query: {},
+ asPath: "/",
+ basePath: "",
+ isLocaleDomain: false,
+ isReady: true,
+ isFallback: false,
+ isPreview: false,
+ push: () => Promise.resolve(true),
+ replace: () => Promise.resolve(true),
+ reload: () => {},
+ back: () => {},
+ forward: () => {},
+ prefetch: () => Promise.resolve(),
+ beforePopState: () => {},
+ events: { on: () => {}, off: () => {}, emit: () => {} },
+};
+
+(
+ globalThis as { __dsRouterContext?: typeof RouterContext }
+).__dsRouterContext ??= RouterContext; // read by next-router.ts in every preview's bundled copy
+
+export function LangfuseProvider({
+ children,
+ theme = "light",
+ fullHeight = isSingleStoryCapture(),
+}: LangfuseProviderProps) {
+ return (
+ <RouterContext.Provider value={stubRouter}>
+ <LayerProvider>
+ <ThemeProvider
+ attribute="class"
+ forcedTheme={theme}
+ enableSystem={false}
+ disableTransitionOnChange
+ >
+ <div
+ id="__next"
+ className="bg-background text-foreground"
+ style={{ height: nextHeight(fullHeight) }}
+ >
+ <div>
+ <SessionProvider session={null}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </SessionProvider>
+ </div>
+ </div>
+ </ThemeProvider>
+ </LayerProvider>
+ </RouterContext.Provider>
+ );
+}
+
+/** nextHeight mirrors Storybook's `#__next` height for canvas vs. inline renders */
+function nextHeight(fullHeight: boolean): string {
+ if (fullHeight) return "100vh";
+ return "auto";
+}
+
+/** isSingleStoryCapture reports whether the page renders one story via `?story=` */
+function isSingleStoryCapture(): boolean {
+ try {
+ return new URLSearchParams(window.location.search).has("story");
+ } catch {
+ return false;
+ }
+}
+
+/** LangfuseProviderProps configures the app-level context LangfuseProvider mounts */
+type LangfuseProviderProps = {
+ children?: ReactNode;
+ /** Forced color theme; toggles the `dark` class on <html>. */
+ theme?: "light" | "dark";
+ /** Gives `#__next` a 100vh height so `h-full` chains resolve; on for `?story=` captures. */
+ fullHeight?: boolean;
+};
diff --git a/.design-sync/ds-package/copy-css.sh b/.design-sync/ds-package/copy-css.sh
new file mode 100755
index 0000000000..d703796b36
--- /dev/null
+++ b/.design-sync/ds-package/copy-css.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+# Copies Storybook's compiled Tailwind v4 stylesheet (the one iframe.html links)
+# into the shim package so cfg.cssEntry can append it to _ds_bundle.css.
+set -euo pipefail
+ROOT="$(git rev-parse --show-toplevel)"
+SB="$ROOT/.design-sync/sb-reference"
+HREF="$(grep -o '<link rel="stylesheet"[^>]*href="[^"]*"' "$SB/iframe.html" | sed -E 's/.*href="\.?\/?([^"]*)".*/\1/' | head -1)"
+cp "$SB/$HREF" "$ROOT/.design-sync/ds-package/storybook-compiled.css"
+echo "copied $HREF -> .design-sync/ds-package/storybook-compiled.css"
+# Storybook (like the bundle) has no next/font, so --font-plex-mono is unset and
+# font-mono falls back to the literal "IBM Plex Mono" family. Give the reference
+# the same @font-face the bundle ships (cfg.extraFonts plex-mono.css) so the
+# compare oracle verifies with the real font. Fonts are served from staticDirs.
+if ! grep -q 'data-ds-sync-fonts' "$SB/iframe.html"; then
+ FACES='<style data-ds-sync-fonts>@font-face{font-family:"IBM Plex Mono";src:url("./fonts/IBMPlexMono-Regular.woff2") format("woff2");font-weight:400;font-style:normal}@font-face{font-family:"IBM Plex Mono";src:url("./fonts/IBMPlexMono-Bold.woff2") format("woff2");font-weight:600;font-style:normal}</style>'
+ FACES="$FACES" perl -0pi -e 's|</head>|$ENV{FACES}</head>|' "$SB/iframe.html"
+ echo "injected IBM Plex Mono @font-face into sb-reference/iframe.html"
+fi
+# The reference server has no svg MIME type, so web/public images break there
+# too; inject gen-entry.sh's public-assets.js (refreshed on every run).
+ASSETS_JS="$(cat "$ROOT/.design-sync/ds-package/public-assets.js")"
+ASSETS_JS="$ASSETS_JS" perl -0pi -e 's|<script data-ds-sync-assets>.*?</script>||s; s|</head>|<script data-ds-sync-assets>$ENV{ASSETS_JS}</script></head>|' "$SB/iframe.html"
+echo "injected public-assets.js into sb-reference/iframe.html"
diff --git a/.design-sync/ds-package/csf-factories-preview.tsx b/.design-sync/ds-package/csf-factories-preview.tsx
new file mode 100644
index 0000000000..b667d11e51
--- /dev/null
+++ b/.design-sync/ds-package/csf-factories-preview.tsx
@@ -0,0 +1,116 @@
+// Stand-in for web/.storybook/preview.tsx when design-sync compiles story files
+// into previews (wired by .design-sync/overrides/story-imports.mjs). The stories
+// use Storybook 10 CSF factories - `preview.meta({...}).story({...})` and
+// `story.extend({...})` - which the converter's inert @storybook stubs can't run.
+// This flattens each factory story into a plain CSF3 object (args/argTypes/
+// parameters/decorators merged meta-first, render/component inherited), which is
+// what the preview generator composes. The real preview's decorator chain is
+// supplied separately by cfg.provider (LangfuseProvider); story-level
+// `globals.theme: "dark"` is honored with a `.dark` wrapper, since globals.css
+// scopes the dark tokens and the `dark:` variant to `.dark` / `.dark *`.
+// `parameters.layout: "fullscreen"` drops the card's body padding on `?story=`
+// captures, matching Storybook's unpadded fullscreen canvas.
+import * as React from "react";
+
+const arr = (d: unknown): any[] => (d == null ? [] : ([] as any[]).concat(d));
+
+const preview = {
+ meta(metaInput: Input) {
+ // makeStory already folds these into each story; the generator would apply them again
+ const { decorators: _decorators, ...metaFields } = metaInput;
+ return {
+ input: metaInput,
+ ...metaFields,
+ story: (input: Input = {}) =>
+ makeStory(
+ metaInput,
+ typeof input === "function" ? { render: input } : input,
+ ),
+ };
+ },
+};
+
+export default preview;
+
+/** FullscreenFrame drops the card's body padding while a single `?story=` capture renders */
+function FullscreenFrame(Story: React.ComponentType) {
+ React.useLayoutEffect(() => {
+ if (!isSingleStoryCapture()) return;
+ const body = document.body;
+ const prev = body.style.padding;
+ body.style.padding = "0";
+ return () => {
+ body.style.padding = prev;
+ };
+ }, []);
+ return <Story />;
+}
+
+const darkDecorator = (Story: any) => (
+ <div className="dark bg-background text-foreground">
+ <Story />
+ </div>
+);
+
+function makeStory(meta: Input, input: Input): any {
+ const m = mergeInput(meta, input);
+ const story: any = {
+ ...m,
+ render: input.render ?? meta.render,
+ component: input.component ?? meta.component,
+ decorators: storyDecorators(m),
+ input,
+ extend: (more: Input) => makeStory(meta, mergeInput(input, more)),
+ };
+ story.composed = story;
+ return story;
+}
+
+function mergeInput(base: Input, more: Input): Input {
+ return {
+ ...base,
+ ...more,
+ args: { ...(base.args ?? {}), ...(more.args ?? {}) },
+ argTypes: { ...(base.argTypes ?? {}), ...(more.argTypes ?? {}) },
+ parameters: { ...(base.parameters ?? {}), ...(more.parameters ?? {}) },
+ globals: { ...(base.globals ?? {}), ...(more.globals ?? {}) },
+ // Storybook composes extended decorators innermost-last; base first here
+ // because the generator applies the list inner -> outer.
+ decorators: [...arr(more.decorators), ...arr(base.decorators)],
+ beforeEach: [...arr(base.beforeEach), ...arr(more.beforeEach)],
+ };
+}
+
+/** storyDecorators appends the dark-theme, fullscreen and beforeEach wrappers a story asks for */
+function storyDecorators(m: Input): any[] {
+ const decorators = [...m.decorators];
+ if (m.globals?.theme === "dark") decorators.push(darkDecorator);
+ if (m.parameters?.layout === "fullscreen") decorators.push(FullscreenFrame);
+ if (m.beforeEach.length > 0)
+ decorators.push(beforeEachDecorator(m.beforeEach));
+ return decorators;
+}
+
+/** beforeEachDecorator runs the meta and story `beforeEach` hooks once before the story first renders */
+function beforeEachDecorator(hooks: Array<() => unknown>) {
+ return function BeforeEach(Story: React.ComponentType) {
+ const [cleanups] = React.useState(() => hooks.map((hook) => hook()));
+ React.useEffect(() => () => cleanups.forEach(runCleanup), [cleanups]);
+ return <Story />;
+ };
+}
+
+/** runCleanup calls a `beforeEach` return value when it is a cleanup function */
+function runCleanup(cleanup: unknown) {
+ if (typeof cleanup === "function") cleanup();
+}
+
+function isSingleStoryCapture(): boolean {
+ try {
+ return new URLSearchParams(window.location.search).has("story");
+ } catch {
+ return false;
+ }
+}
+
+type Input = Record<string, any>;
diff --git a/.design-sync/ds-package/gen-entry.sh b/.design-sync/ds-package/gen-entry.sh
new file mode 100755
index 0000000000..2ca22fed4c
--- /dev/null
+++ b/.design-sync/ds-package/gen-entry.sh
@@ -0,0 +1,105 @@
+#!/usr/bin/env bash
+# Regenerates index.ts: one `export *` per public design-system module
+# (everything under web/src/components/design-system except stories, tests,
+# and internal/), plus the chart constants and the internal ChartLegend
+# (it has its own stories). Run from anywhere.
+set -euo pipefail
+cd "$(dirname "$0")"
+D=../../web/src/components/design-system
+# Browser `process` shim: Next/next-auth/env.mjs read process.env at module
+# scope. NEXT_PUBLIC_* values mirror what the Storybook build inlines (it runs
+# under ../../.env.dev.example), so previews match the reference render.
+{
+ echo '// GENERATED by gen-entry.sh - do not hand-edit.'
+ printf 'var env = { NODE_ENV: "development"'
+ grep -E '^NEXT_PUBLIC_[A-Z0-9_]+=' ../../.env.dev.example | sed -E 's/^([A-Z0-9_]+)="?([^"]*)"?$/, \1: "\2"/' | tr -d '\n'
+ echo ' };'
+ echo 'if (typeof globalThis.process === "undefined") globalThis.process = { env: env, browser: true, platform: "browser", version: "", versions: {}, cwd: function () { return "/"; }, nextTick: function (f) { var a = [].slice.call(arguments, 1); Promise.resolve().then(function () { f.apply(null, a); }); } };'
+ echo 'else globalThis.process.env = Object.assign({}, env, globalThis.process.env);'
+} > process-shim.js
+# Public assets: DS components load web/public files via
+# `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/<file>`. The bundle ships no loose files,
+# so embed each as a data URL and remap matching <img src> values at runtime.
+# copy-css.sh injects the same script into the reference iframe.html.
+ASSETS="$(cd "$D" && grep -rhoE 'NEXT_PUBLIC_BASE_PATH \?\? ""\}/[A-Za-z0-9._/-]+' --include='*.tsx' --exclude='*.stories.tsx' . \
+ | sed -E 's|.*\}/||' | LC_ALL=C sort -u)"
+# shellcheck disable=SC2086
+node - ../../web/public $ASSETS > public-assets.js <<'JS'
+const fs = require("fs");
+const path = require("path");
+const [dir, ...files] = process.argv.slice(2);
+const mime = { ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".webp": "image/webp", ".ico": "image/x-icon" };
+const assets = Object.fromEntries(files.map((f) => [
+ "/" + f,
+ `data:${mime[path.extname(f)] || "application/octet-stream"};base64,` + fs.readFileSync(path.join(dir, f)).toString("base64"),
+]));
+process.stdout.write(`// GENERATED by gen-entry.sh - do not hand-edit.
+(function () {
+ if (typeof window === "undefined" || window.__dsPublicAssets) return;
+ var assets = ${JSON.stringify(assets)};
+ window.__dsPublicAssets = assets;
+ function remap(value) {
+ if (typeof value !== "string") return value;
+ var p = globalThis.process, base = (p && p.env && p.env.NEXT_PUBLIC_BASE_PATH) || "";
+ var key = base && value.indexOf(base) === 0 ? value.slice(base.length) : value;
+ return Object.prototype.hasOwnProperty.call(assets, key) ? assets[key] : value;
+ }
+ var setAttribute = Element.prototype.setAttribute;
+ Element.prototype.setAttribute = function (name, value) {
+ if (this.tagName === "IMG" && String(name).toLowerCase() === "src") value = remap(value);
+ return setAttribute.call(this, name, value);
+ };
+ var src = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "src");
+ Object.defineProperty(HTMLImageElement.prototype, "src", {
+ configurable: true, enumerable: src.enumerable, get: src.get,
+ set: function (value) { src.set.call(this, remap(value)); },
+ });
+})();
+`);
+JS
+{
+ echo '// GENERATED by gen-entry.sh - the design-sync "package entry" for the'
+ echo '// Langfuse design system (which has no dist/ build). Do not hand-edit.'
+ echo 'import "./process-shim.js"; // must stay first - see gen-entry.sh'
+ echo 'import "./public-assets.js";'
+ (cd "$D" && find . -name '*.tsx' ! -name '*.stories.tsx' ! -name '*.test.tsx' ! -name '*.clienttest.tsx' \
+ ! -path './internal/*' ! -path './charts/ChartLegend.tsx' | LC_ALL=C sort) \
+ | sed 's|^\./||; s|\.tsx$||' | while read -r p; do echo "export * from \"$D/$p\";"; done
+ echo "export * from \"$D/charts/constants\";"
+ echo "export { ChartLegend } from \"$D/internal/charts/ChartLegend\";"
+ # Shared app components (web/src/components outside design-system) that have
+ # stories. Named exports, not `export *`: their modules also export helpers
+ # and shadcn primitives whose names clash with DS components. Components a
+ # DS component already covers are left out (see NOTES.md "Scope").
+ S=../../web/src/components
+ while read -r mod names; do echo "export { $names } from \"$S/$mod\";"; done <<'EOF'
+CrashModal/CrashModal CrashModal
+EnvLabelBadge EnvLabelBadge
+grouped-score-badge GroupedScoreBadges
+ItemBadge ItemBadge, ItemTypeIcon
+MediaFileCard/MediaFileCard MediaFileCard
+MediaTag/MediaTag MediaTag
+OrganizationDropdownMenu/OrganizationDropdownMenu OrganizationDropdownMenu
+ProjectDropdownMenu/ProjectDropdownMenu ProjectDropdownMenu
+ScoreBadge/ScoreBadge ScoreBadge
+score-tag ScoreTag
+layouts/mobile-page-actions-content MobilePageActionsContent
+nav/AppSidebar/AppSidebar AppSidebar
+onboarding/components/EvaluatorsOnboardingView/EvaluatorsOnboardingView EvaluatorsOnboardingView
+table/ColumnVisibilityHeader ColumnVisibilityHeader
+table/data-table DataTable
+table/FacetHeader FacetHeader
+table/KeyValueFilterBuilder KeyValueFilterBuilder
+table/OverviewSelectionBar/OverviewSelectionBar OverviewSelectionBar
+table/table-view-presets/components/TableViewPresetsButton TableViewPresetsButton
+ui/MarkdownViewer MarkdownView
+ui/StatusBadge/StatusBadge StatusBadge
+ui/ai-assisted-input AIAssistedInput
+ui/drawer Drawer, DrawerController, DrawerTrigger, DrawerClose, DrawerContent, DrawerHeader, DrawerTitle, DrawerDescription
+ui/sidebar SidebarProvider, SidebarInset
+EOF
+ echo "export { LangfuseProvider } from \"./LangfuseProvider\";"
+ # Icon props (Button/IconButton `icon`, ...) take lucide components; the
+ # namespace export avoids clashes with DS names like Table/Tag.
+ echo "export * as LucideIcons from \"lucide-react\";"
+} > index.ts
diff --git a/.design-sync/ds-package/next-router.ts b/.design-sync/ds-package/next-router.ts
new file mode 100644
index 0000000000..116f633e12
--- /dev/null
+++ b/.design-sync/ds-package/next-router.ts
@@ -0,0 +1,26 @@
+// tsconfig `paths` maps every `next/router` import here - in the bundle and in
+// each preview IIFE, which bundles its own copy of non-DS code like
+// web/src/components/table. useRouter reads the one RouterContext that
+// LangfuseProvider publishes, so its stub router reaches those copies too.
+import { useContext } from "react";
+import { type NextRouter } from "next/dist/client/router";
+import { RouterContext } from "next/dist/shared/lib/router-context.shared-runtime";
+
+export * from "next/dist/client/router";
+export { default } from "next/dist/client/router";
+
+/** useRouter returns the router mounted by the nearest shared RouterContext */
+export function useRouter(): NextRouter {
+ const router = useContext(sharedRouterContext());
+ if (!router) throw new Error("NextRouter was not mounted.");
+ return router;
+}
+
+/** sharedRouterContext returns the published bundle RouterContext, else this copy's own */
+function sharedRouterContext(): typeof RouterContext {
+ const published = (globalThis as SharedRouterGlobal).__dsRouterContext;
+ if (published) return published;
+ return RouterContext;
+}
+
+type SharedRouterGlobal = { __dsRouterContext?: typeof RouterContext };
diff --git a/.design-sync/ds-package/node-stubs/empty.js b/.design-sync/ds-package/node-stubs/empty.js
new file mode 100644
index 0000000000..f053ebf797
--- /dev/null
+++ b/.design-sync/ds-package/node-stubs/empty.js
@@ -0,0 +1 @@
+module.exports = {};
diff --git a/.design-sync/ds-package/package.json b/.design-sync/ds-package/package.json
new file mode 100644
index 0000000000..c0f9ce1a3f
--- /dev/null
+++ b/.design-sync/ds-package/package.json
@@ -0,0 +1,8 @@
+{
+ "name": "@langfuse/design-system",
+ "version": "0.0.0",
+ "private": true,
+ "description": "design-sync shim package: points the converter at the source barrel of web/src/components/design-system",
+ "module": "index.ts",
+ "types": "index.ts"
+}
diff --git a/.design-sync/ds-package/plex-mono.css b/.design-sync/ds-package/plex-mono.css
new file mode 100644
index 0000000000..05be2c0525
--- /dev/null
+++ b/.design-sync/ds-package/plex-mono.css
@@ -0,0 +1,17 @@
+/* IBM Plex Mono, mirroring web/src/styles/fonts.ts (next/font/local). The app
+ exposes it as var(--font-plex-mono); globals.css falls back to the literal
+ "IBM Plex Mono" family, which these faces satisfy outside Next. */
+@font-face {
+ font-family: "IBM Plex Mono";
+ src: url("../../web/public/fonts/IBMPlexMono-Regular.woff2") format("woff2");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+@font-face {
+ font-family: "IBM Plex Mono";
+ src: url("../../web/public/fonts/IBMPlexMono-Bold.woff2") format("woff2");
+ font-weight: 600;
+ font-style: normal;
+ font-display: swap;
+}
diff --git a/.design-sync/ds-package/tsconfig.json b/.design-sync/ds-package/tsconfig.json
new file mode 100644
index 0000000000..5db7b78e27
--- /dev/null
+++ b/.design-sync/ds-package/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "baseUrl": ".",
+ "paths": {
+ "fs": [
+ "./node-stubs/empty.js"
+ ],
+ "stream": [
+ "./node-stubs/empty.js"
+ ],
+ "zlib": [
+ "./node-stubs/empty.js"
+ ],
+ "next/router": [
+ "./next-router.ts"
+ ]
+ },
+ "jsx": "react-jsx"
+ }
+}
diff --git a/.design-sync/overrides/dts.mjs b/.design-sync/overrides/dts.mjs
new file mode 100644
index 0000000000..6719cdc46d
--- /dev/null
+++ b/.design-sync/overrides/dts.mjs
@@ -0,0 +1,571 @@
+// forked from design-sync lib/dts.mjs - DS ships TS source (no dist/): resolve web's `@/*` tsconfig paths, find @types/react under web/node_modules, and treat web/src/ (the DS plus the shared app components it ships) as the in-package dir.
+// .d.ts extraction via ts-morph (real TS checker). Resolves the apparent
+// structural type of each <Name>Props - unwraps Omit/Pick, follows extends
+// chains and intersections, resolves `(typeof X)[number]` / mapped types to
+// literal unions.
+
+import { existsSync, readFileSync, readdirSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { Project, Node, ts } from 'ts-morph';
+
+export function findTypesRoot(pkgDir, pkgJson) {
+ // Workspace/monorepo packages often point dev `types` at src/*.ts (no .d.ts
+ // tree there); publishConfig carries the published .d.ts entry - prefer it
+ // when it exists on disk.
+ const pubTypes = pkgJson.publishConfig?.types;
+ if (pubTypes && existsSync(join(pkgDir, pubTypes))) return dirname(join(pkgDir, pubTypes));
+ const t = pkgJson.types || pkgJson.typings;
+ if (t) return dirname(join(pkgDir, t));
+ const hasDts = (d) => { try { return readdirSync(d).some((f) => f.endsWith('.d.ts')); } catch { return false; } };
+ for (const c of ['build/ts', 'dist/types', 'types', 'lib', 'dist']) {
+ const p = join(pkgDir, c);
+ if (existsSync(p) && (c !== 'dist' || hasDts(p))) return p;
+ }
+ return pkgDir;
+}
+
+// *Props are prop interfaces; ALL-CAPS are object constants; *Manager /
+// *Placements / *Context are utility singletons; use* are hooks - none
+// renderable. (dts.nonComponents also catches React.Context by symbol kind;
+// the suffix check is belt-and-suspenders for DSes where that misses.)
+export const isComponentName = (n) => !n.endsWith('Props') && !/^[A-Z][A-Z0-9_]+$/.test(n)
+ && !/(?:Manager|Placements|Context)$/.test(n) && !/^use[A-Z]/.test(n);
+
+// Partition into roots and subcomponents. A name is a subcomponent ONLY when
+// another name is a PascalCase prefix of it AND the suffix is an actual
+// namespace member of that prefix per the `compounds` map (i.e. Table.Row
+// exists, so top-level TableRow is the same subpart). Name shape alone
+// can't distinguish TableRow (only renders inside Table) from ButtonGroup
+// (standalone) - the compounds membership is the reliable signal. For DSes
+// that export subparts top-level only (no `Table.Row` namespace), this
+// conservatively does nothing.
+export function partitionSubcomponents(names, compounds) {
+ const set = new Set(names);
+ const parentOf = new Map();
+ for (const n of names) {
+ const parts = n.match(/[A-Z][a-z0-9]*/g) ?? [];
+ // Try longest prefix first, keep trying shorter ones - `ListItemText`
+ // with compounds {List: ['ItemText']} must reach `List` even if
+ // `ListItem` is itself a top-level name.
+ for (let i = parts.length - 1; i >= 1; i--) {
+ const prefix = parts.slice(0, i).join('');
+ if (!set.has(prefix)) continue;
+ const suffix = parts.slice(i).join('');
+ if ((compounds?.get(prefix) ?? []).includes(suffix)) { parentOf.set(n, prefix); break; }
+ }
+ }
+ // Flatten transitively - TableRowCell -> TableRow -> Table becomes
+ // TableRowCell -> Table, so the caller's per-root bucketing doesn't lose
+ // subs whose immediate parent is itself a sub. Terminates: each parent has
+ // strictly fewer PascalCase parts than its child.
+ for (const [n] of parentOf) {
+ let p = parentOf.get(n);
+ while (parentOf.has(p)) p = parentOf.get(p);
+ parentOf.set(n, p);
+ }
+ return { parentOf };
+}
+
+// One Project per package - loadDts/exportedNames share it.
+const projects = new Map();
+
+function projectFor(pkgDir, typesRoot) {
+ if (projects.has(pkgDir)) return projects.get(pkgDir);
+ // Derive node_modules for cross-package resolution (React, peer deps).
+ // Normalize separators - pkgDir may have backslashes on Windows.
+ const posix = pkgDir.split('\\').join('/');
+ const i = posix.lastIndexOf('/node_modules/');
+ let nodeModules = i >= 0 ? join(pkgDir.slice(0, i), 'node_modules') : join(pkgDir, '..');
+ // Workspace packages live outside node_modules - walk up to the hoisted
+ // root node_modules so @types/react resolves (otherwise React utility types
+ // collapse to `any` and inherited props drop out of the emitted bodies).
+ if (!existsSync(join(nodeModules, '@types', 'react'))) {
+ for (let d = pkgDir; ; d = dirname(d)) {
+ if (existsSync(join(d, 'node_modules', '@types', 'react'))) { nodeModules = join(d, 'node_modules'); break; }
+ if (dirname(d) === d) break;
+ }
+ }
+ // [fork] pnpm doesn't hoist @types/react to the root - use web's.
+ const WEB = resolve(pkgDir, '../../web');
+ if (!existsSync(join(nodeModules, '@types', 'react'))) nodeModules = join(WEB, 'node_modules');
+ const pj = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8'));
+ // Same publishConfig preference as findTypesRoot - keep the two in sync.
+ const pubEntry = pj.publishConfig?.types;
+ const entry = join(pkgDir, (pubEntry && existsSync(join(pkgDir, pubEntry)) ? pubEntry : null) || pj.types || pj.typings || 'index.d.ts');
+ const project = new Project({
+ skipAddingFilesFromTsConfig: true,
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2020,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ jsx: ts.JsxEmit.ReactJSX,
+ skipLibCheck: true,
+ strict: false,
+ // [fork] web/tsconfig.json paths
+ baseUrl: WEB,
+ paths: { '@/*': ['./*'] },
+ },
+ });
+ // Add the package's own .d.ts tree plus @types/react (otherwise
+ // `ComponentPropsWithoutRef<...>` is `any` and intersection types collapse).
+ const reactTypes = join(nodeModules, '@types', 'react', 'index.d.ts');
+ // The negation must be absolute-scoped to match the positive pattern -
+ // ts-morph's fast-glob ignores bare `!**/node_modules/**` otherwise.
+ const root = typesRoot ?? dirname(entry);
+ project.addSourceFilesAtPaths([`${root}/**/*.d.ts`, `!${root}/**/node_modules/**`]);
+ console.error(` [DTS] parsed ${project.getSourceFiles().length} .d.ts files from ${root}`);
+ // ts-morph StandardizedFilePath is always forward-slash; normalize pkgDir
+ // once so fp.startsWith(pkgDir) in isOwnProp/propsBodyFor works on Windows.
+ // Trailing slash so a sibling node_modules package whose name is a prefix of
+ // this one (foo vs foo-icons) isn't mis-classified as in-package.
+ const pkgDirStd = pkgDir.split('\\').join('/').replace(/\/?$/, '/');
+ if (existsSync(reactTypes)) project.addSourceFileAtPath(reactTypes);
+ else console.error(
+ '\n[DTS_REACT] \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n' +
+ '[DTS_REACT] @types/react not found in node_modules. React utility types\n' +
+ '[DTS_REACT] (ComponentPropsWithoutRef, FC, \u2026) will resolve to `any`, so\n' +
+ '[DTS_REACT] components whose props extend them will emit EMPTY bodies.\n' +
+ '[DTS_REACT] Fix: `npm i -D @types/react` then rebuild.\n' +
+ '[DTS_REACT] \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n',
+ );
+ if (existsSync(entry)) project.addSourceFileAtPath(entry);
+ // [fork] pull the TS source graph in, and scope 'in-package' to the app source dir.
+ project.resolveSourceFileDependencies();
+ const srcDir = join(WEB, 'src').split('\\').join('/') + '/';
+ const ctx = { project, entry, pkgDir: srcDir };
+ projects.set(pkgDir, ctx);
+ return ctx;
+}
+
+// Keep a prop unless its declaration lives in React/DOM types or a CSS-in-JS
+// style-system base (hundreds of token-typed style props from the component
+// library's styled-props layer). The small KEEP_PROP set passes regardless so
+// structural props survive when inherited from React. ts-morph's getFilePath()
+// returns StandardizedFilePath (forward-slash), so the substring checks are
+// cross-platform.
+const KEEP_PROP = /^(children|className|style|as|asChild|ref|id)$/;
+// Style-system bases are detected by SHAPE, two-tier (canonical contract -
+// the call sites point here):
+// - EXTERNAL packages: >STYLE_SYSTEM_THRESHOLD CSS/token-named props,
+// counted per package directory (the node_modules/<pkg>/ boundary), so a
+// style system split across small per-category .d.ts files still crosses
+// the bar in aggregate. Paths with no node_modules/ segment fall back to
+// per-file counting at the in-package bar.
+// - IN-PACKAGE files: >IN_PACKAGE_FILE_THRESHOLD CSS-named props in ONE
+// file. Hand-written API layers (tens of CSS-named props) are the DS's
+// own API and are never filtered; only a generated style system crosses
+// this bar. Left unfiltered, printing hundreds of token-typed unions per
+// component costs minutes of build time and tens of GB of retained
+// checker cache, and bloats every emitted .d.ts.
+// All props declared in a flagged file/package are filtered (KEEP_PROP
+// passes regardless). ASSUMPTION: when inherited shorthands are real API,
+// override per component with cfg.dtsPropsFor.<Name>.
+const CSS_PROP_NAME =
+ /^(m[tblrxy]?$|p[tblrxy]?$|margin|padding|bg|background|color|border|width|height|flex|grid|gap|font|text|display|position|top|left|right|bottom|z|opacity|overflow|shadow|rounded|space)/;
+const STYLE_SYSTEM_THRESHOLD = 15;
+const IN_PACKAGE_FILE_THRESHOLD = 100;
+// The package that owns a path: its deepest node_modules/<pkg>/ boundary
+// (trailing slash), or null for workspace paths. Identity comparison against
+// ownerOf(pkgDir) is the single in-package/external discriminator.
+function ownerOf(p) {
+ const m = /^(.*\/node_modules\/(?:@[^/]+\/)?[^/]+)\//.exec(p);
+ return m ? m[1] + '/' : null;
+}
+function detectStyleSystemDirs(props, pkgDir, declFile) {
+ const pkgOwner = ownerOf(pkgDir);
+ const cssByDir = new Map();
+ for (const p of props) {
+ if (!CSS_PROP_NAME.test(p.getName())) continue;
+ const d = p.getDeclarations()[0];
+ if (!d) continue;
+ const fp = d.getSourceFile().getFilePath();
+ // Key shape encodes the tier (see the canonical contract above
+ // CSS_PROP_NAME): external packages -> node_modules/<pkg>/ prefix key
+ // (trailing slash); in-package declarations -> exact FILE key. The
+ // DEEPEST node_modules boundary decides: a dep nested under the
+ // package's own node_modules (un-hoisted version conflict) is external.
+ // One principle, no orientation cases: a declaration is IN-PACKAGE iff
+ // the package that OWNS its file is the package being synced.
+ // ownerOf() = deepest node_modules package boundary, null for
+ // workspace paths. This derives every layout - nested dep under the
+ // package's own node_modules (different owner -> external), dual-publish
+ // nested manifest (same owner -> in-package even though pkgDir sits
+ // below the boundary), DS synced from inside a host package's
+ // node_modules (host files have a shallower owner -> external).
+ // In-package files key per-FILE; external files key per owning package.
+ // Ownerless externals (sibling workspace packages) key per-file at the
+ // in-package bar - the documented out-of-scope fallback in the
+ // canonical block above.
+ const owner = ownerOf(fp);
+ const inPackage = owner === pkgOwner && (owner !== null || fp.startsWith(pkgDir));
+ const key = inPackage ? fp : (owner ?? fp);
+ // Never flag the file that declares the component's own Props: in a
+ // rolled-up single-file .d.ts the generated style layer co-lives with
+ // the API interfaces, and a per-FILE flag would drop the component's
+ // own props. Separate generated files still filter; rollups fall back
+ // to unfiltered (slow but correct). External dir keys are unaffected.
+ if (key === declFile) continue;
+ cssByDir.set(key, (cssByDir.get(key) ?? 0) + 1);
+ }
+ // Per-tier bars - rationale in the canonical block above CSS_PROP_NAME.
+ const keys = [];
+ for (const [k, n] of cssByDir) {
+ const bar = k.endsWith('/') ? STYLE_SYSTEM_THRESHOLD : IN_PACKAGE_FILE_THRESHOLD;
+ if (n > bar) keys.push(k);
+ }
+ return keys;
+}
+function isOwnProp(p, pkgDir, styleSystemDirs) {
+ const name = p.getName();
+ if (KEEP_PROP.test(name)) return true;
+ const d = p.getDeclarations()[0];
+ if (!d) return true;
+ const fp = d.getSourceFile().getFilePath();
+ // Same owner-identity discriminator as detectStyleSystemDirs, same order
+ // of authority: a flagged in-package FILE drops first (exact match); then
+ // owner-equality keeps the DS's own API - checked BEFORE dir keys because
+ // a flagged dir key can be an ANCESTOR of pkgDir (DS synced from inside a
+ // host package's node_modules) and must not swallow in-package files;
+ // then flagged external packages drop by prefix.
+ if (styleSystemDirs.some((k) => !k.endsWith('/') && fp === k)) return false;
+ const owner = ownerOf(fp);
+ if (owner === ownerOf(pkgDir) && (owner !== null || fp.startsWith(pkgDir))) return true;
+ if (styleSystemDirs.some((k) => k.endsWith('/') && fp.startsWith(k))) return false;
+ if (fp.includes('/@types/react/') || fp.includes('/typescript/lib/')) return false;
+ // DOM-noise name filters apply only to props inherited from other packages.
+ if (/^(on[A-Z]|aria-)/.test(name)) return false;
+ return true;
+}
+
+// [fork] Keys a Props declaration names in `Pick<T, K>` are deliberate API,
+// even when T is a React DOM attribute type that isOwnProp would filter.
+function pickedKeysOf(at) {
+ const keys = new Set();
+ for (const ref of at.getDescendantsOfKind(ts.SyntaxKind.TypeReference)) {
+ if (ref.getTypeName().getText() !== 'Pick') continue;
+ const k = ref.getTypeArguments()[1]?.getType();
+ if (!k) continue;
+ for (const u of k.isUnion() ? k.getUnionTypes() : [k]) {
+ if (u.isStringLiteral()) keys.add(u.getLiteralValue());
+ }
+ }
+ return keys;
+}
+
+// Keep well-known aliases as-written instead of expanding to their full union.
+const KEEP_ALIAS = /^(ReactNode|ReactElement|CSSProperties|JSX\.Element|Key|Ref|RefObject)$/;
+
+function typeText(t, at) {
+ const alias = t.getAliasSymbol()?.getName();
+ if (alias && KEEP_ALIAS.test(alias)) return `React.${alias}`;
+ if (t.isBoolean()) return 'boolean';
+ let s;
+ if (t.isUnion()) {
+ // Render each member so ReactNode/boolean collapse while literal unions
+ // stay expanded; dedup, drop `undefined` (optionality is the `?`).
+ const parts = t.getUnionTypes().map((u) => typeText(u, at)).filter((p) => p !== 'undefined');
+ let uniq = [...new Set(parts)];
+ if (uniq.length === 2 && uniq.includes('true') && uniq.includes('false')) return 'boolean';
+ // Collapse the structural expansion of React.ReactNode (string | number |
+ // ReactElement<...> | Iterable<ReactNode> | ReactPortal | Promise<...>) back to
+ // the alias - when the alias symbol is lost, the expansion blows past the
+ // length cap below and would truncate into invalid TS.
+ if (uniq.includes('ReactPortal') && uniq.some((u) => u.startsWith('Iterable<ReactNode>'))) {
+ const RN_MEMBER = /^(string|number|bigint|boolean|ReactPortal|Iterable<ReactNode>.*|ReactElement<.*|Promise<.*)$/;
+ uniq = [...new Set([...uniq.filter((u) => !RN_MEMBER.test(u)), 'React.ReactNode'])];
+ }
+ // Function-type members are invalid un-parenthesized inside a union
+ // (`string | (x) => void` doesn't parse) - wrap them.
+ if (uniq.length > 1) uniq = uniq.map((u) => (u.includes('=>') ? `(${u})` : u));
+ // Cap very wide unions (icon-name sets can be 600+ members).
+ if (uniq.length > 24) uniq = [...uniq.slice(0, 16), `(string & {}) /* +${uniq.length - 16} more */`];
+ s = uniq.join(' | ').replace(/\bfalse \| true\b/, 'boolean');
+ } else {
+ s = t.getText(at, ts.TypeFormatFlags.NoTruncation).replace(/import\("[^"]*"\)\./g, '');
+ }
+ // Never hard-slice an over-long type - a cut generic/object literal is
+ // invalid TS and fails the validator's [DTS_PARSE] check (and the app's
+ // API-contract parse). Fall back to a safe wide type instead; the JSDoc
+ // line above the prop carries the human-readable detail.
+ return s.length > 240 ? 'unknown' : s;
+}
+
+// PascalCase value exports from the entry module. The checker knows value vs
+// type, so type-only exports never enter the set.
+export function exportedNames(pkgDir, pkgJson) {
+ const { project, entry } = projectFor(pkgDir, findTypesRoot(pkgDir, pkgJson));
+ const sf = project.getSourceFile(entry);
+ const names = new Set();
+ if (!sf) return names;
+ for (const [name, decls] of sf.getExportedDeclarations()) {
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(name)) continue;
+ const hasValue = decls.some((d) =>
+ Node.isVariableDeclaration(d) || Node.isFunctionDeclaration(d) ||
+ Node.isClassDeclaration(d) || Node.isSourceFile(d));
+ if (hasValue) names.add(name);
+ }
+ return names;
+}
+
+// Builds the context propsBodyFor/jsdocFor read from. `nonComponents` /
+// `compounds` are derived from the checker's symbol kinds.
+export function loadDts(typesRoot) {
+ // typesRoot is always under <nm>/<pkg>/... - walk up to the real package
+ // root: the nearest package.json with a `name` field, skipping stubs
+ // (`{"type":"module"}` in esm/ or dist/). dirname-fixed-point is the
+ // cross-platform root test (`/` vs `C:\`).
+ let walk = typesRoot;
+ for (; walk !== dirname(walk); walk = dirname(walk)) {
+ const pj = join(walk, 'package.json');
+ if (existsSync(pj)) {
+ try { if (JSON.parse(readFileSync(pj, 'utf8')).name) break; } catch {}
+ }
+ }
+ // projectFor normalizes pkgDir to forward-slashes (ts-morph's
+ // StandardizedFilePath) - use that for every fp.startsWith() downstream.
+ const { project, entry, pkgDir } = projectFor(walk, typesRoot);
+ const sf = project.getSourceFile(entry);
+ const nonComponents = new Set();
+ const compounds = new Map();
+ if (sf) for (const [name, decls] of sf.getExportedDeclarations()) {
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(name)) continue;
+ // Declaration-merged names (`interface Button {}` + `const Button: ...`)
+ // return both decls - prefer the value decl so the merge isn't
+ // misclassified as type-only by whichever the checker listed first.
+ const d = decls.find((x) =>
+ Node.isVariableDeclaration(x) || Node.isFunctionDeclaration(x) ||
+ Node.isClassDeclaration(x) || Node.isSourceFile(x)) ?? decls[0];
+ // Namespace export (`export * as X`) -> compound with its own value members.
+ if (Node.isSourceFile(d)) {
+ const members = [...d.getExportedDeclarations().entries()]
+ .filter(([n, ds]) => /^[A-Z][a-z]/.test(n) && ds.some((x) => !Node.isInterfaceDeclaration(x) && !Node.isTypeAliasDeclaration(x)))
+ .map(([n]) => n);
+ if (members.length) compounds.set(name, members);
+ else nonComponents.add(name);
+ continue;
+ }
+ // Type-only / enum / Context / abstract-class are not components.
+ if (Node.isInterfaceDeclaration(d) || Node.isTypeAliasDeclaration(d) || Node.isEnumDeclaration(d)) {
+ nonComponents.add(name);
+ continue;
+ }
+ if (Node.isClassDeclaration(d) && d.isAbstract()) { nonComponents.add(name); continue; }
+ if (Node.isClassDeclaration(d)) continue; // always renderable; compounds via statics aren't handled here
+ if (!Node.isVariableDeclaration(d) && !Node.isFunctionDeclaration(d)) continue;
+ // `const X: FC<...> & { Sub: ... }` (possibly through an alias/Omit) -
+ // PascalCase callable properties declared in-package are compound members
+ // (React.Component lifecycle names have underscores / fail the full match).
+ const t = d.getType();
+ const members = [];
+ // PascalCase props can't be style-system CSS-shorthands, so the empty
+ // list is correct here - detectStyleSystemDirs would contribute nothing.
+ const noStyle = [];
+ for (const p of t.getProperties()) {
+ const pn = p.getName();
+ if (!/^[A-Z][a-zA-Z0-9]*$/.test(pn) || !isOwnProp(p, pkgDir, noStyle)) continue;
+ if (p.getTypeAtLocation(d).getCallSignatures().length) members.push(pn);
+ }
+ if (members.length) compounds.set(name, members);
+ // Only provably-not-renderable consts are filtered: a plain object/record
+ // type whose every property is a primitive (token/enum
+ // objects like Colors or Sizes). Anything with a call signature, construct signature, or a
+ // non-primitive property stays - class components and forwardRef wrappers
+ // without call sigs on the instance type must not be dropped here.
+ if (t.isObject() && !t.getCallSignatures().length && !t.getConstructSignatures().length && !members.length && !t.isAny()) {
+ const props = t.getProperties();
+ if (props.length && props.every((p) => {
+ const pt = p.getTypeAtLocation(d);
+ return pt.isString() || pt.isNumber() || pt.isStringLiteral() || pt.isNumberLiteral();
+ })) nonComponents.add(name);
+ }
+ }
+ return { project, entry, pkgDir, nonComponents, compounds };
+}
+
+// Returns { body, generics, extendsClause, prelude } for emit.mjs. Types are
+// fully resolved into `body`, so extendsClause/prelude stay empty.
+export function propsBodyFor(name, ctx) {
+ if (ctx.dtsPropsFor?.[name]) {
+ return { body: ctx.dtsPropsFor[name], generics: '', extendsClause: '', prelude: '' };
+ }
+ const { project, entry, pkgDir } = ctx;
+ // Find <Name>Props across the package's own files (not @types/react).
+ // Skip deprecated/legacy/experimental dirs so a stale copy doesn't shadow
+ // the live one.
+ let decl = null;
+ // [fork] pkgDir spans all of web/src, where `<Name>Props` repeats (ui/input
+ // has its own InputProps) - check the component's declaring file first.
+ const ownFile = project.getSourceFile(entry)?.getExportedDeclarations().get(name)?.[0]?.getSourceFile();
+ for (const sf of [ownFile, ...project.getSourceFiles()].filter(Boolean)) {
+ const fp = sf.getFilePath();
+ if (!fp.startsWith(pkgDir)) continue;
+ if (/\/(deprecated|legacy|experimental)\//i.test(fp)) continue;
+ decl = sf.getInterface(`${name}Props`) ?? sf.getTypeAlias(`${name}Props`);
+ if (decl) break;
+ }
+ // Fallback: derive from the component symbol's first call signature.
+ // Prefer the value decl (declaration-merging - see loadDts).
+ if (!decl) {
+ const decls = project.getSourceFile(entry)?.getExportedDeclarations().get(name) ?? [];
+ const exp = decls.find((d) =>
+ Node.isVariableDeclaration(d) || Node.isFunctionDeclaration(d) || Node.isClassDeclaration(d)) ?? decls[0];
+ if (!exp || Node.isSourceFile(exp)) return null;
+ const sig = exp.getType().getCallSignatures()[0];
+ const p0 = sig?.getParameters()[0];
+ if (!p0) return null;
+ return emitBody(p0.getTypeAtLocation(exp), exp, '', pkgDir);
+ }
+ const generics = decl.getTypeParameters?.().length
+ ? `<${decl.getTypeParameters().map((p) => p.getText()).join(', ')}>`
+ : '';
+ return emitBody(decl.getType(), decl, generics, pkgDir);
+}
+
+let loggedStyleSystemDirs;
+function emitBody(type, at, generics, pkgDir) {
+ const lines = [];
+ const props = type.getApparentType().getProperties();
+ // `at` is the component's own Props declaration site - its file is exempt
+ // from per-FILE flagging (see detectStyleSystemDirs).
+ const styleSystemDirs = detectStyleSystemDirs(props, pkgDir, at.getSourceFile().getFilePath());
+ // Surface a one-shot [DTS_STYLE_SYSTEM] line per flagged package so the
+ // self-heal loop routes to cfg.dtsPropsFor when the heuristic guesses
+ // wrong. ASSUMPTION: props from the named packages are token-typed
+ // style shorthands; override a component's contract with cfg.dtsPropsFor.
+ loggedStyleSystemDirs ??= new Set();
+ for (const dir of styleSystemDirs) {
+ if (loggedStyleSystemDirs.has(dir)) continue;
+ loggedStyleSystemDirs.add(dir);
+ const isDirKey = dir.endsWith('/');
+ const pkg = /\/node_modules\/((?:@[^/]+\/)?[^/]+)\/$/.exec(dir)?.[1]
+ ?? (dir.startsWith(pkgDir) ? dir.slice(pkgDir.length) : dir);
+ const bar = isDirKey ? STYLE_SYSTEM_THRESHOLD : IN_PACKAGE_FILE_THRESHOLD;
+ console.error(
+ `[DTS_STYLE_SYSTEM] filtering ${pkg} props (>${bar} CSS-shorthand-named props) \u2014 override a component with cfg.dtsPropsFor.<Name> if these are real API`,
+ );
+ }
+ const picked = pickedKeysOf(at);
+ for (const p of props) {
+ if (!picked.has(p.getName()) && !isOwnProp(p, pkgDir, styleSystemDirs)) continue;
+ const optional = p.hasFlags(ts.SymbolFlags.Optional) ? '?' : '';
+ const pt = p.getTypeAtLocation(at);
+ let tt = typeText(pt, at);
+ // Structural hint when the type text hides the shape (aliased functions /
+ // arrays) - smartDefaultProps reads these to pick the right required-stub.
+ const members = pt.isUnion() ? pt.getUnionTypes() : [pt];
+ if (members.some((u) => u.getCallSignatures().length)) tt += ' /* @fn */';
+ // Tuples are not @arr - `[]` has the wrong length and `[0]` access crashes
+ // either way; optional tuples are safer left unset.
+ else if (members.some((u) => u.isArray())) tt += ' /* @arr */';
+ // Leading JSDoc on the prop declaration, if any.
+ const d = p.getDeclarations()[0];
+ const doc = d?.getJsDocs?.()?.[0]?.getDescription()?.trim();
+ if (doc) lines.push(` /** ${doc.replace(/\s+/g, ' ').slice(0, 120)} */`);
+ const pn = p.getName();
+ // Hyphenated/index-signature names (`data-*`, `aria-*`) must be quoted.
+ const key = /^[a-zA-Z_$][\w$]*$/.test(pn) ? pn : JSON.stringify(pn);
+ lines.push(` ${key}${optional}: ${tt};`);
+ }
+ if (!lines.length) return null;
+ return { body: lines.join('\n'), generics, extendsClause: '', prelude: '' };
+}
+
+// Scaffold-preview defaults from the resolved props body. Conservative: fill
+// only what's needed for a meaningful first render (children + variant axis +
+// visibility toggles + required arrays). Optional string/number/Date props are
+// left unset - filling them with placeholder values crashes more than it
+// helps.
+//
+// Void-element-ish components - a string `children` would throw at render.
+const VOID_LIKE = /^(Text|Number|Search|Password|File|Masked)?Input$|^(TextField|TextArea|Textarea|Img|Image|Avatar|Hr|Br|Spacer|Divider|Separator|Slider|Progress|ProgressBar)$/;
+// Ordered preference for the variant axis - earlier wins. `type` is last so
+// the HTML `type` attr ("button"|"submit"|"reset") doesn't beat `variant`.
+const VARIANT_RANK = ['variant', 'intent', 'kind', 'appearance', 'tone', 'status', 'size', 'color', 'type'];
+export function smartDefaultProps(name, pb) {
+ const body = pb?.body ?? '';
+ const props = {};
+ let variants = null;
+ // Matches the 2-space indent emitBody writes - keep the two in sync.
+ // `.+` (not `[^;]+`) so object-param types with inner semicolons still match.
+ for (const m of body.matchAll(/^ {2}([a-zA-Z_$][\w$]*)(\??)\s*:\s*(.+);$/gm)) {
+ const [, prop, q, t] = m;
+ if (prop in props) continue;
+ const req = !q;
+ // Union of string literals, optionally with a `string & {}` escape-hatch
+ // member (the "autocomplete these, accept any string" TS pattern).
+ if (/^(?:(?:"[^"]*"|\(?string\s*&\s*\{\}\)?)\s*\|?\s*)+$/.test(t)) {
+ const lits = [...t.matchAll(/"([^"]*)"/g)].map((l) => l[1]).filter(Boolean);
+ if (lits.length >= 2) {
+ const rank = VARIANT_RANK.indexOf(prop.toLowerCase());
+ // Displace on strictly better rank (prop names are unique, so no ties).
+ if (!variants || (rank >= 0 && (variants.rank < 0 || rank < variants.rank))) {
+ variants = { prop, values: lits.slice(0, 4), rank };
+ }
+ if (req) props[prop] = lits[0];
+ continue;
+ }
+ }
+ // Structural hints (/* @fn */, /* @arr */) from emitBody are authoritative
+ // over the text regexes - `(() => void)[]` has @arr, so the `=>` in the
+ // element type must not flip it to isFn. The text regexes cover
+ // cfg.dtsPropsFor overrides with no hints.
+ const hasFn = t.includes('/* @fn */'), hasArr = t.includes('/* @arr */');
+ const isFn = hasFn || (!hasArr && /=>|\)\s*:/.test(t));
+ const isArr = !isFn && (hasArr || /\[\]|Array</.test(t));
+ if (prop === 'children' && /React\.ReactNode|ReactElement/.test(t) && !isFn && !VOID_LIKE.test(name)) props.children = name;
+ // Visibility toggles - an overlay/dialog with open=false renders nothing.
+ else if (/^(open|isOpen|visible|show|defaultOpen|expanded|checked|active|selected)$/.test(prop) && t === 'boolean') props[prop] = true;
+ // Callable (required or optional) - optional stays unset (DSes guard
+ // optional callbacks); required gets a noop.
+ else if (isFn) { if (req) props[prop] = { $raw: '()=>null' }; }
+ // Arrays (required or optional). `[]` is crash-safe but renders nothing.
+ // Props that look like data/option lists get a small sample so the
+ // preview has visible rows; element shape is best-effort from the type
+ // text (string[] -> strings; otherwise {id,label,value}).
+ else if (isArr) {
+ const isList = /^(items|options|tabs|rows|columns|data|actions|fields|links|steps|choices|values)$/i.test(prop);
+ const elT = t.replace(/\/\*.*?\*\//g, '').trim();
+ const elIsString = /^(?:readonly\s+)?string\[\]|^ReadonlyArray<string>|^Array<string>/.test(elT);
+ // Over-provision keys - extra ones are ignored, and this covers the
+ // common {id|key} + {label|text|name|title} + value conventions.
+ props[prop] = isList
+ ? elIsString
+ ? ['Item 1', 'Item 2', 'Item 3']
+ : [1, 2, 3].map((i) => {
+ const s = String(i), l = `Item ${i}`;
+ return { id: s, key: s, value: s, label: l, text: l, name: l, title: l };
+ })
+ : [];
+ }
+ // Optional everything-else stays unset - the component's own defaults are
+ // safer than a placeholder.
+ else if (!req) continue;
+ // Required props get a type-appropriate stub so the render doesn't crash
+ // on `undefined....` / `undefined()`. `$raw` values are emitted verbatim by
+ // scaffoldPropsExpr (not JSON-stringified).
+ else if (/\bDate\b/.test(t)) props[prop] = { $raw: 'new Date()' };
+ else if (/ElementType|ComponentType|JSXElementConstructor/.test(t)) props[prop] = 'div';
+ else if (/React\.ReactNode|ReactElement/.test(t)) props[prop] = name;
+ else if (/^string\b/.test(t)) props[prop] = name;
+ else if (/^number\b/.test(t)) props[prop] = 0;
+ else if (/^boolean\b/.test(t)) props[prop] = false;
+ else if (/^\{/.test(t) || /Record<|Partial<|Pick<|Omit</.test(t)) props[prop] = {};
+ // Fallback: required prop of unrecognized shape - `{}` is the least likely
+ // to crash `.foo` access.
+ else props[prop] = {};
+ }
+ return { props, variants };
+}
+
+// One-line JSDoc from the component's own declaration.
+export function jsdocFor(name, ctx) {
+ const decls = ctx.project?.getSourceFile(ctx.entry)?.getExportedDeclarations().get(name) ?? [];
+ const exp = decls.find((d) =>
+ Node.isVariableDeclaration(d) || Node.isFunctionDeclaration(d) || Node.isClassDeclaration(d)) ?? decls[0];
+ if (!exp || Node.isSourceFile(exp)) return '';
+ const doc = exp.getJsDocs?.()?.[0]?.getDescription()
+ ?? exp.getSymbol?.()?.compilerSymbol.getDocumentationComment?.(undefined)?.[0]?.text;
+ if (!doc) return '';
+ return doc.split('\n').find((l) => l.trim() && !l.trim().startsWith('@'))
+ ?.trim().replace(/\s+/g, ' ').replace(/[^\w\s.,()'/:+-]/g, '').slice(0, 140) ?? '';
+}
diff --git a/.design-sync/overrides/story-imports.mjs b/.design-sync/overrides/story-imports.mjs
new file mode 100644
index 0000000000..25b8d4d07d
--- /dev/null
+++ b/.design-sync/overrides/story-imports.mjs
@@ -0,0 +1,264 @@
+// forked from design-sync lib/story-imports.mjs - stories use Storybook 10 CSF factories (`import preview from ".storybook/preview"; preview.meta().story()`); redirect that import to .design-sync/ds-package/csf-factories-preview.tsx, which flattens factory stories to CSF3 objects.
+// How story modules resolve at preview-compile time. Small on purpose and
+// FORKABLE: copy to .design-sync/overrides/story-imports.mjs (declare in
+// cfg.libOverrides) when a repo's layout needs different rules - this seam
+// owns ALL resolution policy, so a fork never touches generation or build
+// orchestration. Lighter tweaks need no fork: cfg.storyImports.shim /
+// cfg.storyImports.bundle are substring patterns matched against resolved
+// paths (any import style - relative, tsconfig alias, bare workspace name)
+// that force a module to the bundle global / to source bundling, and
+// cfg.storyImports.loaders merges over STORY_LOADERS.
+//
+// Rules:
+// 1. Package + extraEntries imports -> `window.<GLOBAL>` (the shipped bundle).
+// Subpaths whose last segment is an exported component (`<pkg>/Button`)
+// shim with that export as the default; every other subpath
+// (`<pkg>/locales/en.json`, `<pkg>/utils`) bundles normally - a wrong
+// shim is silent, a missing module is loud (and the fix is named:
+// cfg.extraEntries merges a subpath's exports onto the global).
+// 2. ANY import that RESOLVES to an EXPORTED component's module ->
+// `window.<GLOBAL>` too, however it was spelled (relative `../Button` -
+// the dominant story convention - tsconfig alias, or monorepo path). This
+// keeps previews rendering the SHIPPED bundle instead of a duplicate
+// source copy - which breaks React context identity (consumers throw
+// their missing-provider errors) and drops co-located styles. Story files
+// themselves and anything under node_modules are never redirected.
+// Default imports get the matched export as `default` (default-importing
+// the component is a common story convention; a bare namespace shim
+// renders "Element type is invalid" in every such cell).
+// 3. Every other import (fixtures, helpers, internal contexts) bundles from
+// source; component imports INSIDE those modules recurse through rule 2.
+// The honest residue: a story needing a component-PRIVATE context that
+// must share identity with the global component renders a cell error and
+// falls to grading/hand-fix - no shim can fix that, by construction.
+// 4. @storybook/* runtime -> functional stubs. manager/preview/client-api get
+// real no-op hooks (useGlobals/useArgs/addons - module-scope
+// `addons.register()` or a decorator calling `useGlobals()` on an empty
+// stub takes the whole module down); everything else gets an inert
+// callable proxy so the canonical CSF idiom - `args: { onClick: fn() }`,
+// `action('click')` at module scope - evaluates instead of throwing.
+// 5. Styles/assets -> LOADERS below (styles ship via _ds_bundle.css/styles.css;
+// images inline as data URLs so fixtures keep working offline). Exception:
+// `.module.css` falls through to esbuild's local-css default - class names
+// resolve and the compiled stylesheet lands at _preview/<Name>.css, which
+// the emitted html links when present.
+
+import { existsSync, realpathSync } from 'node:fs';
+import { relative, resolve } from 'node:path';
+
+// Storybook's preview-api also re-exports React-compatible hooks for use in
+// render functions - those delegate to the page's React (an inert stub there
+// is a guaranteed render crash: destructuring a non-iterable).
+const MANAGER_API_STUB =
+ 'const noopChannel={on(){},off(){},once(){},emit(){},removeListener(){}};' +
+ 'const addons={register(){},add(){},getChannel(){return noopChannel},setConfig(){},getConfig(){return{}}};' +
+ 'const R=function(){return window.React||{}};' +
+ 'module.exports={addons,types:{},useGlobals(){return[{},function(){}]},useArgs(){return[{},function(){},function(){}]},useParameter(){},useStorybookApi(){return{}},' +
+ 'useState(){return R().useState.apply(null,arguments)},useCallback(){return R().useCallback.apply(null,arguments)},useRef(){return R().useRef.apply(null,arguments)},' +
+ 'useMemo(){return R().useMemo.apply(null,arguments)},useEffect(){return R().useEffect.apply(null,arguments)},useReducer(){return R().useReducer.apply(null,arguments)},' +
+ 'useChannel(){return function(){}}};';
+
+// Inert callable proxy: every member access yields another inert callable, so
+// `fn()`, `action("x")`, `expect.anything()`, `userEvent.click(...)` all
+// evaluate to harmless values at module scope. Named imports are copied by
+// esbuild's CJS interop from own enumerable props, so the common API surface
+// is materialized explicitly (Object.assign keeps them as own props of the
+// callable default - do not change the proxy target's own-property shape);
+// everything else resolves through the get trap. The DEFAULT export is a
+// children-passthrough component: stories render addon defaults as JSX
+// (@storybook/addon-links `<LinkTo>...</LinkTo>`), and an object default
+// throws "Element type is invalid" the instant React mounts it. Both traps
+// hand back the REAL `prototype` - React's shouldConstruct() probes
+// `.prototype.isReactComponent`, and a truthy proxy answer classifies the
+// stub as a CLASS component, silently swallowing the children.
+const INERT_STUB =
+ 'var inert=new Proxy(function(){},{' +
+ 'get:function(t,k){if(k==="then")return void 0;if(k==="prototype")return t.prototype;if(k==="valueOf"||k==="toString"||k===Symbol.toPrimitive)return function(){return""};return inert},' +
+ 'apply:function(){return inert},construct:function(){return{}}});' +
+ 'var m={};"fn action actions expect userEvent within waitFor screen fireEvent spyOn mocked jest vi configureActions decorateAction setupWorker http HttpResponse graphql rest".split(" ").forEach(function(k){m[k]=inert});' +
+ 'var def=function(p){return p&&p.children!==void 0?p.children:null};Object.assign(def,m);' +
+ 'module.exports=new Proxy(def,{get:function(t,k){if(k==="then")return void 0;if(k==="prototype")return t.prototype;return k in m?m[k]:k==="__esModule"?void 0:inert}});';
+
+export const STORY_FILE_RE = /\.stor(?:y|ies)\.[cm]?[jt]sx?$/;
+
+export const STORY_LOADERS = {
+ // jsx is a strict syntax superset of js - JSX-in-.js story files are a
+ // common convention and plain .js parses identically.
+ '.js': 'jsx',
+ '.css': 'empty', '.scss': 'empty', '.sass': 'empty', '.less': 'empty', '.styl': 'empty',
+ '.png': 'dataurl', '.jpg': 'dataurl', '.jpeg': 'dataurl', '.gif': 'dataurl',
+ '.webp': 'dataurl', '.avif': 'dataurl', '.svg': 'dataurl', '.ico': 'dataurl',
+ '.woff': 'dataurl', '.woff2': 'dataurl', '.ttf': 'dataurl', '.eot': 'empty',
+ '.md': 'text', '.mdx': 'empty', '.mp4': 'empty', '.webm': 'empty', '.mov': 'empty',
+};
+
+// Which exported component (if any) does a resolved file path look like the
+// source module of? Matches `<...>/Button/Button.tsx`, `<...>/Button/index.ts`,
+// and bare `<...>/Button.tsx`; returns the export name or null. A helper
+// coincidentally named like an export (`utils/Text.ts`) would false-positive -
+// that's what cfg.storyImports.bundle is for; over-shimming surfaces
+// immediately as undefined-component cell errors, never as silent wrong
+// renders.
+function exportedComponentFor(p, exported) {
+ const segs = p.replace(/\\/g, '/').split('/');
+ const file = (segs[segs.length - 1] ?? '').replace(/\.[cm]?[jt]sx?$/, '');
+ const dir = segs[segs.length - 2] ?? '';
+ if (exported.has(file)) return file;
+ if ((file === 'index' || file === dir) && exported.has(dir)) return dir;
+ return null;
+}
+
+// The @storybook/* stub plugin alone - also used by the decorator bundler.
+export function storybookStubPlugin() {
+ return {
+ name: 'sb-stub',
+ setup(b) {
+ b.onResolve({ filter: /^(@storybook\/|storybook(\/|$)|msw(\/|$)|@mswjs\/)/ }, (a) => ({ path: a.path, namespace: 'sb-stub' }));
+ b.onLoad({ filter: /.*/, namespace: 'sb-stub' }, (a) => ({
+ contents: /(^|\/)(manager|preview|client)-api$/.test(a.path) ? MANAGER_API_STUB : INERT_STUB,
+ loader: 'js',
+ }));
+ },
+ };
+}
+
+// Build the esbuild plugin set for compiling preview .tsx files (generated
+// story-module wrappers AND hand-authored previews - same rules for both).
+// IMPORTANT for callers: any tsconfig-paths plugin must be registered AFTER
+// these (buildPreviews does this) - the policy plugin resolves aliases via
+// b.resolve, so a paths plugin registered first would bypass rule 2.
+export function storyImportPlugins({ PKG, GLOBAL, extraEntries = [], exported, cfg, pkgDir }) {
+ // Path-form entries (./, ../, absolute) are repo files bundled by path -
+ // they must never enter import-SPECIFIER matching below, where a story's
+ // relative import could coincidentally equal the config string and get
+ // wrongly shimmed to the global. Bare package specifiers only.
+ extraEntries = extraEntries.filter((e) => !/^(\.\.?\/|\/|[A-Za-z]:[\\/])/.test(e));
+ const escRx = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const pkgRx = new RegExp(`^(?:${[PKG, ...extraEntries].map(escRx).join('|')})(?:/.*)?$`);
+ const force = cfg?.storyImports ?? {};
+ const matches = (p, pats) => Array.isArray(pats) && pats.some((s) => typeof s === 'string' && p.includes(s));
+ // ESM facade shim, NOT CJS: in a `"type":"module"` repo esbuild applies
+ // node's ESM-CJS interop to the importing file - `default` becomes the
+ // whole exports object and `__esModule` is ignored - which breaks every
+ // `import Button from '<pkg>/Button'` (the style most docs examples use).
+ // An ESM module binds `default` explicitly under BOTH interop modes; the
+ // star re-export of the raw CJS global keeps dynamic named access working
+ // (hooks, constants - anything on the global beyond the component list).
+ const shimFor = (name) =>
+ `export * from "__ds_raw__";var g=window.${GLOBAL};export default ${
+ name ? `g[${JSON.stringify(name)}]!==void 0?g[${JSON.stringify(name)}]:g` : `"default" in g?g.default:g`
+ };`;
+ const shimResult = (name) => ({ path: name ? `ds:${name}` : 'ds', namespace: 'ds-shim' });
+
+ const dsShim = {
+ name: 'ds-global',
+ setup(b) {
+ const entryNames = new Set([PKG, ...extraEntries]);
+ b.onResolve({ filter: pkgRx }, (a) => {
+ if (matches(a.path, force.bundle)) return null; // explicit bundle wins
+ if (!entryNames.has(a.path)) {
+ // Subpath import: a named component shims default-aware; anything
+ // else bundles normally - a wrong root-namespace shim is silent
+ // (undefined members), a missing module is loud, and the loud
+ // path's fix is named (cfg.extraEntries / node_modules symlink in
+ // the package's own source repo).
+ const name = (a.path.split('/').pop() ?? '').replace(/\.[cm]?[jt]sx?$/, '');
+ return exported.has(name) ? shimResult(name) : null;
+ }
+ return shimResult(null);
+ });
+ b.onLoad({ filter: /.*/, namespace: 'ds-shim' }, (a) => ({
+ contents: shimFor(a.path.startsWith('ds:') ? a.path.slice(3) : null),
+ loader: 'js',
+ }));
+ // Location-independent story imports emitted by the preview generator:
+ // `@ds-stories/<repo-root-relative path>` resolves against cwd, so the
+ // same wrapper compiles from the generated cache or from
+ // .design-sync/previews/ after a promote. Extensionless - esbuild
+ // appends its resolve extensions.
+ b.onResolve({ filter: /^@ds-stories\// }, (a) => {
+ const base = resolve(process.cwd(), a.path.slice('@ds-stories/'.length));
+ for (const ext of ['', '.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs', '.mdx']) {
+ if (existsSync(base + ext)) return { path: base + ext };
+ }
+ return { errors: [{ text: `@ds-stories path not found: ${a.path} (resolved against ${process.cwd()})` }] };
+ });
+ // The raw CJS module the ESM facade star-re-exports - dynamic names
+ // (everything on the global) without a static export list.
+ b.onResolve({ filter: /^__ds_raw__$/ }, () => ({ path: '__ds_raw__', namespace: 'ds-raw' }));
+ b.onLoad({ filter: /.*/, namespace: 'ds-raw' }, () => ({
+ contents: `module.exports=window.${GLOBAL};`,
+ loader: 'js',
+ }));
+ },
+ };
+
+ // Rule 2: resolve every remaining import and shim the ones that land on an
+ // exported component's module - regardless of how the import was spelled.
+ // Returning the b.resolve result (instead of null) keeps resolution single-pass.
+ // The package's own source BARREL (src/index.* under the build cwd OR under
+ // the package dir - monorepos build from the repo root while the barrel
+ // lives at packages/<x>/src/) shims to the root namespace: `import { X }
+ // from "../src"` would otherwise bundle a second copy of the whole library
+ // with its own React contexts.
+ const CWD = process.cwd().replace(/\\/g, '/');
+ // realpath both roots - esbuild's resolver returns symlink-resolved paths,
+ // and a merely-resolve()'d root (symlinked tmpdir, symlinked package dir)
+ // would never prefix-match them.
+ const real = (p) => { try { return realpathSync(p).replace(/\\/g, '/'); } catch { return null; } };
+ const barrelRoots = [...new Set([CWD, real(process.cwd()), pkgDir && resolve(pkgDir).replace(/\\/g, '/'), pkgDir && real(pkgDir)].filter(Boolean))];
+ const policyRedirect = {
+ name: 'ds-import-policy',
+ setup(b) {
+ b.onResolve({ filter: /.*/ }, async (a) => {
+ if (a.pluginData === 'ds-resolving') return null; // our own re-entry
+ if (a.kind === 'entry-point' || (a.namespace && a.namespace !== 'file')) return null;
+ const r = await b.resolve(a.path, {
+ kind: a.kind, resolveDir: a.resolveDir, importer: a.importer,
+ pluginData: 'ds-resolving',
+ });
+ if (r.errors.length > 0 || !r.path) return null;
+ if (r.namespace && r.namespace !== 'file') return r; // claimed by another plugin
+ const p = r.path.replace(/\\/g, '/');
+ // [fork] CSF-factories preview -> flattening stand-in (see header).
+ if (/\/web\/\.storybook\/preview\.[cm]?[jt]sx?$/.test(p)) {
+ return { path: resolve(process.cwd(), '.design-sync/ds-package/csf-factories-preview.tsx') };
+ }
+ if (STORY_FILE_RE.test(p)) return r; // never the story itself
+ if (matches(p, force.bundle)) return r; // explicit bundle wins
+ if (matches(p, force.shim)) return shimResult(exportedComponentFor(p, exported));
+ if (p.includes('/node_modules/')) return r; // third-party stays put
+ // relative() instead of a startsWith prefix - case-insensitive on
+ // win32, where the pkgDir roots carry user-typed casing (a lowercase
+ // d:\ drive from --node-modules) while p carries cwd casing, and JS
+ // realpathSync never canonicalizes case. Outside-root ('../') and
+ // cross-drive (absolute) remainders can never match the anchor.
+ // Known limit: darwin's default case-insensitive APFS still compares
+ // case-sensitively here (path.posix.relative) - a blanket lowercase
+ // compare would be wrong on case-SENSITIVE volumes, so mis-cased
+ // --node-modules on mac remains the user's to fix.
+ if (barrelRoots.some((root) => /^src\/index\.[cm]?[jt]sx?$/.test(relative(root, p).replace(/\\/g, '/')))) {
+ return shimResult(null); // package source barrel
+ }
+ const name = exportedComponentFor(p, exported);
+ return name ? shimResult(name) : r;
+ });
+ },
+ };
+
+ // Bare `import console from "console"` (and node:console) appears in real
+ // story files; node builtins can't bundle for the browser, but this one has
+ // an exact page-global equivalent.
+ const consoleStub = {
+ name: 'node-console-stub',
+ setup(b) {
+ b.onResolve({ filter: /^(node:)?console$/ }, () => ({ path: 'console', namespace: 'node-console' }));
+ b.onLoad({ filter: /.*/, namespace: 'node-console' }, () => ({ contents: 'module.exports=console;', loader: 'js' }));
+ },
+ };
+
+ return {
+ plugins: [dsShim, storybookStubPlugin(), consoleStub, policyRedirect],
+ loaders: { ...STORY_LOADERS, ...(force.loaders ?? {}) },
+ };
+}
diff --git a/.design-sync/previews/Avatar.tsx b/.design-sync/previews/Avatar.tsx
new file mode 100644
index 0000000000..358b164df6
--- /dev/null
+++ b/.design-sync/previews/Avatar.tsx
@@ -0,0 +1,75 @@
+import * as React from "react";
+import * as S from "@ds-stories/web/src/components/design-system/Avatar/Avatar.stories";
+import appleTouchIcon from "../../web/public/apple-touch-icon.png";
+
+function compose(S: any, key: string) {
+ const meta: any = S.default ?? {};
+ const st: any = S[key];
+ const args: any = { ...(meta.args ?? {}), ...(st && st.args ? st.args : {}) };
+ // Storybook resolves argTypes.mapping (control value -> real arg) before
+ // rendering; mirror that so mapped args don't render raw.
+ const at: any = {
+ ...(meta.argTypes ?? {}),
+ ...(st && st.argTypes ? st.argTypes : {}),
+ };
+ for (const k of Object.keys(args)) {
+ const m = at[k] && at[k].mapping;
+ if (m && typeof m === "object" && args[k] in m) args[k] = m[args[k]];
+ }
+ const title: string = typeof meta.title === "string" ? meta.title : "";
+ const ctx: any = {
+ args,
+ name: key,
+ title,
+ kind: title,
+ id: "",
+ componentId: "",
+ globals: {},
+ viewMode: "story",
+ parameters: (st && st.parameters) ?? meta.parameters ?? {},
+ };
+ let render: (() => any) | null = null;
+ if (st && typeof st.render === "function")
+ render = () => st.render(args, ctx);
+ else if (typeof st === "function") render = () => st(args, ctx);
+ else if (typeof meta.render === "function")
+ render = () => meta.render(args, ctx);
+ else {
+ const C = (st && st.component) || meta.component;
+ if (C) render = () => React.createElement(C, args);
+ }
+ if (!render) return () => null;
+ // [].concat: a single function is legal CSF decorator shorthand. A
+ // decorator returning undefined (stubbed addon) falls through to the inner
+ // render — otherwise one unrecognized addon blanks the cell silently.
+ const decorators: any[] = ([] as any[])
+ .concat((st && st.decorators) ?? [])
+ .concat(meta.decorators ?? []);
+ return decorators.reduce(
+ (inner: any, dec: any) => () => {
+ const out = dec(inner, ctx);
+ return out === undefined ? inner() : out;
+ },
+ render,
+ );
+}
+
+// Default: the story uses src "/apple-touch-icon.png", served only by
+// storybook staticDirs (web/public). Import the same file (bundled as a data
+// URL) so the preview shows the real image instead of the fallback initial.
+const DefaultStory = compose(
+ {
+ ...S,
+ Default: {
+ ...(S as any).Default,
+ args: { ...(S as any).Default.args, src: appleTouchIcon },
+ },
+ },
+ "Default",
+);
+export const Default = /* Default */ DefaultStory;
+export const Fallback = /* Fallback */ compose(S, "Fallback");
+export const WithEmail = /* With Email */ compose(S, "WithEmail");
+export const VariantMatrix = /* Variant Matrix */ compose(S, "VariantMatrix");
+export const TestHoverNameAndEmail =
+ /* (Test) Hover shows name and email */ compose(S, "TestHoverNameAndEmail");
diff --git a/.gitignore b/.gitignore
index b1ccc4ad40..89b1dac23d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -118,3 +118,18 @@ web/test-results/*
# Superset config
.superset/
+
+# design-sync (claude.ai/design) - build artifacts and machine-local state
+.design-sync/sb-reference/
+.design-sync/learnings/
+.design-sync/.cache/
+.design-sync/node_modules
+.design-sync/*.log
+.ds-sync/
+ds-bundle/
+.design-sync/ds-package/storybook-compiled.css
+.design-sync/ds-package/index.ts
+.design-sync/ds-package/process-shim.js
+.design-sync/ds-package/public-assets.js
+.design-sync/upload-*.txt
+.design-sync/chunk-*.json
diff --git a/.semgrepignore b/.semgrepignore
index f91738c127..f38940aa52 100644
--- a/.semgrepignore
+++ b/.semgrepignore
@@ -18,3 +18,8 @@ scripts/code-eval-runners/
# explicit-unescape XSS rule does not apply.
ai-gateway/about.hbs
packages/native/about.hbs
+
+# claude.ai/design sync build tooling, run locally by /design-sync and never
+# deployed. story-imports.mjs builds its package-matching regex from
+# escaped config values, which trips detect-non-literal-regexp.
+.design-sync/
diff --git a/knip.jsonc b/knip.jsonc
index 34cc44d5af..f4fc1843b3 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -2,6 +2,8 @@
"ignore": [
".agents/skills/**",
"scripts/**",
+ // claude.ai/design sync build inputs, loaded by the design-sync converter rather than imported.
+ ".design-sync/**",
"vitest.workspace.ts",
// Generated by `napi build`: the loader probes optional per-platform
// packages and a WASI fallback that this workspace never publishes.
diff --git a/packages/shared/src/domain/auditLogs.ts b/packages/shared/src/domain/auditLogs.ts
index 98194e5007..9e72088b4d 100644
--- a/packages/shared/src/domain/auditLogs.ts
+++ b/packages/shared/src/domain/auditLogs.ts
@@ -170,7 +170,10 @@ const serializedJson = z
// `before`, `after` and `params` are already escaped by JSON.stringify.
const toJsonbSafeStrings = (value: unknown): unknown => {
if (typeof value === "string") {
- return value.replaceAll("\u0000", "\uFFFD").toWellFormed();
+ // not a "\uFFFD" literal: utf8 bundlers inline it as a raw replacement char
+ return value
+ .replaceAll("\u0000", String.fromCharCode(0xfffd))
+ .toWellFormed();
}
if (Array.isArray(value)) return value.map(toJsonbSafeStrings);
if (typeof value === "object" && value !== null) {