Skip to content

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

10.6 KB
Raw Blame
import type { StorybookConfig } from "@storybook/nextjs-vite";

import { dirname, resolve } from "path";

import { fileURLToPath } from "url";
import {
  flatStoryTitlesPlugin,
  flattenStoryIndexTitles,
  type StoryTitleGroup,
} from "./storybook-flat-story-titles";

const STORY_EXTENSIONS = "@(js|jsx|mjs|ts|tsx)";
// Design-system reference pages that sit directly under Design (not
// Design/Components): the token reference, one single-leaf page per element.
// Directories that get their own sidebar section instead of the flat
// Playground default. This is not a `stories` entry with a `titlePrefix`
// because story titles are injected into each meta — see StoryTitleGroup.
// Only stories inside a configured directory can appear under its feature;
// explicit story titles are rejected by the title plugin.
const STORY_TITLE_GROUPS: StoryTitleGroup[] = [
  {
    directory: "src/components/design-system/table/columns",
    titlePrefix: "Design/Components/Table/Columns",
  },
  {
    directory: "src/components/design-system/table/components",
    titlePrefix: "Design/Components/Table/Cells",
  },
  {
    directory: "src/features/ai-gateway/components",
    titlePrefix: "Features/AI Gateway",
  },
  {
    directory: "src/features/evals/v2/components",
    titlePrefix: "Features/Evaluations",
  },
  {
    directory: "src/features/in-app-agent/components",
    titlePrefix: "Features/In-App Agent",
  },
  {
    directory: "src/features/monitors/automations",
    titlePrefix: "Features/Monitors",
  },
  {
    directory: "src/features/traces/components",
    titlePrefix: "Features/Traces",
  },
];
const DESIGN_REFERENCE_STORIES = [
  "ThemeTokens/Color",
  "ThemeTokens/Typography",
  "ThemeTokens/Layout",
  "ThemeTokens/Charts",
] as const;

/**
 * This function is used to resolve the absolute path of a package.
 * It is needed in projects that use Yarn PnP or are set up within a monorepo.
 */
function getAbsolutePath(value: string) {
  return dirname(fileURLToPath(import.meta.resolve(`${value}/package.json`)));
}

const config: StorybookConfig = {
  stories: [
    // Curated design-system documentation shown under Design.
    {
      directory: "./docs",
      files: "**/*.mdx",
      titlePrefix: "Design",
    },
    // Technical MDX documents colocated with implementation code.
    {
      directory: "../src",
      files: "**/*.mdx",
      titlePrefix: "Playground/Docs",
    },
    // Components in the design-system are automatically shown under Design.
    {
      directory: "../src/components/design-system",
      files: `**/*.stories.${STORY_EXTENSIONS}`,
      titlePrefix: "Design/Components",
    },
    // Design-system reference pages shown directly under Design.
    ...DESIGN_REFERENCE_STORIES.map((storyPath) => ({
      directory: "./docs",
      files: `${storyPath}.stories.${STORY_EXTENSIONS}`,
      titlePrefix: "Design",
    })),
    // All other component stories belong to the flat Playground by default.
    // Outside components/design-system the exclusion is by path, so a generic
    // basename like Charts.stories.tsx elsewhere still reaches the Playground;
    // the design-system directory is excluded in full. Disjoint globs because
    // !(...)
    // matches a single path segment — which also means
    // `!(dir)/**` requires at least one leading segment, so files sitting
    // directly in the entry's directory need their own `*.stories` entry
    // (hence the depth-one entries below).
    {
      directory: "../src",
      files: `*.stories.${STORY_EXTENSIONS}`,
      titlePrefix: "Playground",
    },
    {
      directory: "../src",
      files: `!(components)/**/*.stories.${STORY_EXTENSIONS}`,
      titlePrefix: "Playground",
    },
    {
      directory: "../src/components",
      files: `*.stories.${STORY_EXTENSIONS}`,
      titlePrefix: "Playground",
    },
    {
      directory: "../src/components",
      files: `!(design-system)/**/*.stories.${STORY_EXTENSIONS}`,
      titlePrefix: "Playground",
    },
  ],
  experimental_indexers: flattenStoryIndexTitles(STORY_TITLE_GROUPS),
  features: {
    changeDetection: true,
  },
  addons: [
    getAbsolutePath("@storybook/addon-a11y"),
    getAbsolutePath("@storybook/addon-docs"),
    getAbsolutePath("@storybook/addon-vitest"),
  ],
  framework: getAbsolutePath("@storybook/nextjs-vite"),
  staticDirs: ["../public", "./public"],
  // Resolve `@langfuse/shared` to its TypeScript source, mirroring the app's
  // own alias (next.config.mjs: webpack alias + turbopack.resolveAlias both map
  // "@langfuse/shared" -> "./packages/shared/src"). The package's published
  // entry is a CommonJS bundle whose deeply transitive `export *` re-export
  // chains (e.g. MediaReferenceStringSchema, re-exported through
  // utils/IORepresentation/chatML) are not statically resolvable by Rollup's /
  // Vite's CJS named-export lexer, so a Storybook build (and the dev server)
  // fails with "X is not exported by packages/shared/dist/src/index.js" for any
  // story whose dependency graph touches such an export (e.g. LangfuseMediaView,
  // pulled in transitively by the table stories). Pointing at the source makes
  // Storybook resolve named exports exactly like the app does.
  viteFinal: async (viteConfig) => {
    // Linked workspace packages are not prebundled by default. Bundle the icon
    // barrels so each browser worker does not request thousands of modules.
    viteConfig.optimizeDeps = {
      ...viteConfig.optimizeDeps,
      include: [
        ...(viteConfig.optimizeDeps?.include ?? []),
        "@langfuse/icons",
        "@langfuse/icons/si",
        "@langfuse/icons/tb",
      ],
    };
    viteConfig.plugins = [
      flatStoryTitlesPlugin(STORY_TITLE_GROUPS),
      {
        // The Next.js framework aliases `react-dom` by prefix, which turns this
        // subpath (imported by @react-email/render in email template stories)
        // into `react-dom/index.js/server.browser`. Its aliases are merged
        // after viteFinal, so this rule has to be prepended once resolved.
        name: "react-dom-server-browser-alias",
        configResolved({ resolve }) {
          resolve.alias.unshift({
            find: /^react-dom\/server\.browser$/,
            replacement: fileURLToPath(
              import.meta
                .resolve("next/dist/compiled/react-dom/server.browser.js"),
            ),
          });
        },
      },
      ...(viteConfig.plugins ?? []),
      {
        name: "exclude-generated-icons-from-docgen",
        configResolved({ plugins }) {
          const docgen = plugins.find(
            (plugin) => plugin.name === "storybook:react-docgen-plugin",
          );
          if (!docgen?.transform) return;

          const transform =
            typeof docgen.transform === "function"
              ? docgen.transform
              : docgen.transform.handler;
          docgen.transform = {
            ...(typeof docgen.transform === "object" ? docgen.transform : {}),
            handler(code, id, options) {
              // Linked generated dependencies bypass docgen's node_modules
              // exclusion; resolving their icon catalogs dominates build time.
              if (id.replaceAll("\\", "/").includes("/packages/icons/dist/")) {
                return null;
              }
              return transform.call(this, code, id, options);
            },
          };
        },
      },
    ];

    const sharedSrc = resolve(
      dirname(fileURLToPath(import.meta.url)),
      "../../packages/shared/src",
    );
    const prismaBrowserStub = resolve(
      dirname(fileURLToPath(import.meta.url)),
      "./prisma-browser-stub.cjs",
    );
    viteConfig.resolve = viteConfig.resolve ?? {};
    // Use the array form with regex `find`s for *exact* matching. The object
    // form is treated by Vite/Rollup as a literal prefix replacement, so an
    // import like `@langfuse/shared/src/db` would become `.../src/src/db`
    // (double `src`) and fail to resolve. The bare specifier and the
    // `@langfuse/shared/src/...` subpaths (which the package's `exports` map
    // under `src/`) are handled by two distinct, anchored rules — matching how
    // the app aliases the package (next.config.mjs: transpilePackages +
    // turbopack.resolveAlias "@langfuse/shared" -> "./packages/shared/src").
    const existingAlias = viteConfig.resolve.alias ?? {};
    const aliasArray = Array.isArray(existingAlias)
      ? existingAlias
      : Object.entries(existingAlias).map(([find, replacement]) => ({
          find,
          replacement: replacement as string,
        }));
    viteConfig.resolve.alias = [
      // Story importers are excluded from the production tsconfig.
      {
        find: /^@\//,
        replacement: fileURLToPath(new URL("../", import.meta.url)),
      },
      // The package also exposes a few named subpath exports (e.g.
      // `@langfuse/shared/query`, imported transitively via the chart-library's
      // PivotTable → widgets/utils). Those aren't under `src/`, so the two rules
      // below miss them and they fall through to the CJS dist bundle, whose
      // re-exported names (e.g. `getViewDeclaration`) Vite's lexer can't resolve
      // — the same failure the bare-specifier rule fixes. Map the source-safe
      // subpaths to source too. (`query/index.ts` only re-exports client-safe
      // dataModel/types/validateQuery.)
      {
        find: /^@langfuse\/shared\/query$/,
        replacement: `${sharedSrc}/features/query`,
      },
      // Client-safe role catalog, imported by the RBAC role-select UI and its
      // stories. No `/rbac/server` rule: a story pulling server-only code
      // should fail the build, not silently resolve.
      {
        find: /^@langfuse\/shared\/rbac$/,
        replacement: `${sharedSrc}/features/rbac`,
      },
      // Client-safe entry of the in-app-agent module (imported by the agent
      // window components and their stories). Deliberately no rule for the
      // `/server` subpaths: a story that pulls server code should fail the
      // build, not silently resolve.
      {
        find: /^@langfuse\/shared\/in-app-agent$/,
        replacement: `${sharedSrc}/in-app-agent`,
      },
      // Client-safe Topics schemas and constants; no rule for
      // `/topics/server`, for the same reason.
      {
        find: /^@langfuse\/shared\/topics$/,
        replacement: `${sharedSrc}/topics`,
      },
      {
        find: /^\.prisma\/client\/index-browser$/,
        replacement: prismaBrowserStub,
      },
      {
        find: /^@langfuse\/shared\/src\/(.*)$/,
        replacement: `${sharedSrc}/$1`,
      },
      { find: /^@langfuse\/shared$/, replacement: sharedSrc },
      ...aliasArray,
    ];
    return viteConfig;
  },
};

export default config;