// @bun
import{CodeBlock as fe,InstallCommand as Ze}from"@contractspec/lib.design-system";import he from"@contractspec/lib.ui-link";import{ChevronRight as Xe}from"lucide-react";import{jsx as c,jsxs as g}from"react/jsx-runtime";function $e(){return g("div",{className:"space-y-8",children:[g("div",{className:"space-y-4",children:[c("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.accessibility"}),c("p",{className:"text-muted-foreground",children:"Stable exports of accessibility primitives for LSSM web apps, ensuring WCAG compliance and inclusive design."})]}),g("div",{className:"space-y-4",children:[c("h2",{className:"font-bold text-2xl",children:"Installation"}),c(Ze,{package:"@contractspec/lib.accessibility"})]}),g("div",{className:"space-y-4",children:[c("h2",{className:"font-bold text-2xl",children:"Exports"}),g("ul",{className:"space-y-2 text-muted-foreground",children:[g("li",{children:[c("code",{className:"rounded bg-background/50 px-2 py-1",children:"SkipLink"}),": A link to skip navigation, visible on focus"]}),g("li",{children:[c("code",{className:"rounded bg-background/50 px-2 py-1",children:"VisuallyHidden"}),": Hide content visually but keep it for screen readers"]}),g("li",{children:[c("code",{className:"rounded bg-background/50 px-2 py-1",children:"SRLiveRegionProvider"}),","," ",c("code",{className:"rounded bg-background/50 px-2 py-1",children:"useSRLiveRegion"}),": Manage live region announcements"]}),g("li",{children:[c("code",{className:"rounded bg-background/50 px-2 py-1",children:"RouteAnnouncer"}),": Announce page title/path changes on navigation"]}),g("li",{children:[c("code",{className:"rounded bg-background/50 px-2 py-1",children:"FocusOnRouteChange"}),": Reset focus to body or main content on navigation"]}),g("li",{children:[c("code",{className:"rounded bg-background/50 px-2 py-1",children:"useReducedMotion"}),": Detect if the user prefers reduced motion"]})]})]}),g("div",{className:"space-y-4",children:[c("h2",{className:"font-bold text-2xl",children:"Example: App Setup"}),c(fe,{language:"tsx",code:`import {
  SRLiveRegionProvider,
  RouteAnnouncer,
  SkipLink
} from '@contractspec/lib.accessibility';

export function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <SRLiveRegionProvider>
          <SkipLink />
          <RouteAnnouncer />
          <main id="main-content">
            {children}
          </main>
        </SRLiveRegionProvider>
      </body>
    </html>
  );
}`})]}),g("div",{className:"space-y-4",children:[c("h2",{className:"font-bold text-2xl",children:"Example: Live Announcements"}),c(fe,{language:"tsx",code:`import { useSRLiveRegion } from '@contractspec/lib.accessibility';

export function TodoList() {
  const { announce } = useSRLiveRegion();

  const addTodo = () => {
    // ... add logic
    announce('Todo added successfully', 'polite');
  };

  return <button onClick={addTodo}>Add Todo</button>;
}`})]}),g("div",{className:"space-y-4",children:[c("h2",{className:"font-bold text-2xl",children:"WCAG Compliance"}),g("p",{className:"text-muted-foreground",children:["These components map directly to WCAG 2.1 Level AA requirements documented in ",c("code",{children:"docs/accessibility_wcag_compliance_specs.md"}),":"]}),g("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[c("li",{children:"2.4.1 Bypass Blocks (SkipLink)"}),c("li",{children:"4.1.3 Status Messages (LiveRegion)"}),c("li",{children:"2.4.3 Focus Order (FocusOnRouteChange)"}),c("li",{children:"2.3.3 Animation from Interactions (useReducedMotion)"})]})]}),g("div",{className:"flex items-center gap-4 pt-4",children:[c(he,{href:"/docs/libraries/design-system",className:"btn-ghost",children:"Previous: Design System"}),g(he,{href:"/docs/libraries",className:"btn-primary",children:["Back to Libraries ",c(Xe,{size:16})]})]})]})}import{CodeBlock as be,InstallCommand as Ye}from"@contractspec/lib.design-system";import ve from"@contractspec/lib.ui-link";import{ChevronRight as xe}from"lucide-react";import{jsx as f,jsxs as M}from"react/jsx-runtime";function je(){return M("div",{className:"space-y-8",children:[M("div",{className:"space-y-4",children:[f("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.ai-agent"}),f("p",{className:"text-lg text-muted-foreground",children:"Define AI agents in TypeScript, run them with deterministic tool calling, capture working memory, and route low-confidence decisions to human reviewers."})]}),M("div",{className:"space-y-4",children:[f("h2",{className:"font-bold text-2xl",children:"Installation"}),f(Ye,{package:"@contractspec/lib.ai-agent"})]}),M("div",{className:"space-y-3",children:[f("h2",{className:"font-bold text-2xl",children:"Define & register"}),f(be,{language:"typescript",code:`import { defineAgent, AgentRegistry } from '@contractspec/lib.contracts-spec/agent';

const SupportBot = defineAgent({
  meta: {
    key: 'support.bot',
    version: '1.0.0',
    description: 'Resolve tickets and escalate low-confidence decisions.',
    owners: ['support'],
    tags: ['support'],
    stability: 'experimental',
  },
  instructions: 'Resolve tickets. Escalate when confidence < 0.75.',
  tools: [{ name: 'support_resolve_ticket' }],
  policy: {
    confidence: { min: 0.7, default: 0.6 },
    escalation: { confidenceThreshold: 0.75 },
  },
});

const registry = new AgentRegistry().register(SupportBot);`})]}),M("div",{className:"space-y-3",children:[f("h2",{className:"font-bold text-2xl",children:"Run with approvals"}),f(be,{language:"typescript",code:`import { createUnifiedAgent, ApprovalWorkflow } from '@contractspec/lib.ai-agent';

const approvals = new ApprovalWorkflow();
const agent = createUnifiedAgent(SupportBot, {
  backend: 'ai-sdk',
  tools: new Map([['support_resolve_ticket', async (input) => resolveTicket(input)]]),
});

const result = await agent.run(ticket.body);
// Route low-confidence or manual-review flows through approvals when needed.
`})]}),M("div",{className:"space-y-3",children:[f("h2",{className:"font-bold text-2xl",children:"What's inside"}),M("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[M("li",{children:[f("code",{children:"createUnifiedAgent"}),", ",f("code",{children:"ContractSpecAgent"}),","," ",f("code",{children:"UnifiedAgent"})]}),f("li",{children:"MCP, operation-backed, memory, and subagent tool adapters"}),M("li",{children:[f("code",{children:"InMemoryAgentMemory"})," plus interfaces for custom stores"]}),M("li",{children:[f("code",{children:"ApprovalWorkflow"})," + ",f("code",{children:"ApprovalStore"})," for human-in-the-loop reviews"]})]})]}),M("div",{className:"flex items-center gap-4 pt-4",children:[f(ve,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),M(ve,{href:"/docs/libraries/support-bot",className:"btn-primary",children:["Next: Support Bot ",f(xe,{size:16})]})]})]})}import{CodeBlock as re,InstallCommand as et}from"@contractspec/lib.design-system";import{jsx as F,jsxs as ae}from"react/jsx-runtime";function tt(){return ae("div",{className:"space-y-8",children:[ae("div",{className:"space-y-4",children:[F("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.analytics"}),F("p",{className:"text-lg text-muted-foreground",children:"Work directly with telemetry events to understand conversion, retention, churn, and growth opportunities."})]}),ae("div",{className:"space-y-4",children:[F("h2",{className:"font-bold text-2xl",children:"Installation"}),F(et,{package:"@contractspec/lib.analytics"})]}),ae("div",{className:"space-y-3",children:[F("h2",{className:"font-bold text-2xl",children:"Funnels in memory"}),F(re,{language:"typescript",code:`import { FunnelAnalyzer } from '@contractspec/lib.analytics/funnel';

const analyzer = new FunnelAnalyzer();
const report = analyzer.analyze(events, {
  name: 'signup',
  steps: [
    { id: 'view', eventName: 'page.view', match: (e) => e.properties?.slug === '/signup' },
    { id: 'submit', eventName: 'signup.submit' },
    { id: 'verified', eventName: 'account.verified' },
  ],
});`})]}),ae("div",{className:"space-y-3",children:[F("h2",{className:"font-bold text-2xl",children:"Cohorts & churn"}),F(re,{language:"typescript",code:`import { CohortTracker } from '@contractspec/lib.analytics/cohort';
import { ChurnPredictor } from '@contractspec/lib.analytics/churn';

const cohorts = new CohortTracker().analyze(events, { bucket: 'week', periods: 8 });
const churn = new ChurnPredictor().score(events);`})]}),ae("div",{className:"space-y-3",children:[F("h2",{className:"font-bold text-2xl",children:"Growth hypotheses"}),F(re,{language:"typescript",code:`import { GrowthHypothesisGenerator } from '@contractspec/lib.analytics/growth';

const ideas = new GrowthHypothesisGenerator().generate([
  { name: 'Activation rate', current: 0.42, previous: 0.55, target: 0.6 },
  { name: 'Expansion ARPU', current: 1.2, previous: 0.9 },
]);`})]})]})}import{CodeBlock as at,InstallCommand as ot}from"@contractspec/lib.design-system";import ye from"@contractspec/lib.ui-link";import{ChevronRight as it}from"lucide-react";import{jsx as A,jsxs as $}from"react/jsx-runtime";function rt(){return $("div",{className:"space-y-8",children:[$("div",{className:"space-y-4",children:[A("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.content-gen"}),A("p",{className:"text-lg text-muted-foreground",children:"Feed a single ContentBrief and produce cohesive marketing assets without touching a CMS."})]}),$("div",{className:"space-y-4",children:[A("h2",{className:"font-bold text-2xl",children:"Installation"}),A(ot,{package:"@contractspec/lib.content-gen"})]}),$("div",{className:"space-y-3",children:[A("h2",{className:"font-bold text-2xl",children:"One brief, many assets"}),A(at,{language:"typescript",code:`import {
  BlogGenerator,
  LandingPageGenerator,
  EmailCampaignGenerator,
  SocialPostGenerator,
} from '@contractspec/lib.content-gen/generators';
import { SeoOptimizer } from '@contractspec/lib.content-gen/seo';

const brief = {
  title: 'AI Ops Copilot',
  summary: 'Automates support + growth.',
  problems: ['Support queues pile up', 'Growth teams lack experiments'],
  solutions: ['AI agents', 'Approval queue', 'Analytics'],
  audience: { role: 'COO', industry: 'Fintech' },
};

const blog = await new BlogGenerator().generate(brief);
const landing = await new LandingPageGenerator().generate(brief);
const email = await new EmailCampaignGenerator().generate({ brief, variant: 'announcement' });
const social = await new SocialPostGenerator().generate(brief);
const seo = new SeoOptimizer().optimize(brief);`})]}),$("div",{className:"space-y-3",children:[A("h2",{className:"font-bold text-2xl",children:"When to use"}),$("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[A("li",{children:"Ship landing page refreshes whenever specs change."}),A("li",{children:"Automate release emails + nurture sequences per vertical."}),A("li",{children:"Create social snippets that stay on-message with the same brief."}),A("li",{children:"Generate SEO metadata + Schema.org markup alongside content."})]})]}),$("div",{className:"flex items-center gap-4 pt-4",children:[A(ye,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),$(ye,{href:"/docs/libraries/support-bot",className:"btn-primary",children:["Next: Support Bot ",A(it,{size:16})]})]})]})}import{CodeBlock as nt,InstallCommand as ct}from"@contractspec/lib.design-system";import ne from"@contractspec/lib.ui-link";import{ChevronRight as lt}from"lucide-react";import{jsx as a,jsxs as o}from"react/jsx-runtime";var st=`import { defineDataView } from '@contractspec/lib.contracts-spec/data-views';
import { ListDataGridShowcaseRowsQuery } from '@contractspec/example.data-grid-showcase/contracts/data-grid-showcase.operation';

export const DataGridShowcaseDataView = defineDataView({
  meta: {
    key: 'examples.data-grid-showcase.table',
    version: '1.0.0',
    entity: 'account',
    title: 'Data Grid Showcase Table',
    description:
      'Declarative DataViewSpec for the ContractSpec table showcase.',
    domain: 'examples',
    owners: ['@platform.core'],
    tags: ['examples', 'table', 'data-grid'],
    stability: 'experimental',
  },
  source: {
    primary: {
      key: ListDataGridShowcaseRowsQuery.meta.key,
      version: ListDataGridShowcaseRowsQuery.meta.version,
    },
  },
  view: {
    kind: 'table',
    executionMode: 'client',
    selection: 'multiple',
    columnVisibility: true,
    columnResizing: true,
    columnPinning: true,
    rowExpansion: {
      fields: ['notes', 'renewalDate', 'lastActivityAt'],
    },
    initialState: {
      pageSize: 4,
      hiddenColumns: ['notes'],
      pinnedColumns: {
        left: ['account'],
      },
      sorting: [{ field: 'arr', desc: true }],
    },
    fields: [
      { key: 'account', label: 'Account', dataPath: 'account', sortable: true },
      { key: 'owner', label: 'Owner', dataPath: 'owner', sortable: true },
      { key: 'status', label: 'Status', dataPath: 'status', sortable: true },
      { key: 'notes', label: 'Notes', dataPath: 'notes' },
    ],
  },
});`;function dt(){return o("div",{className:"space-y-8",children:[o("div",{className:"space-y-4",children:[a("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.contracts-spec"}),a("p",{className:"text-lg text-muted-foreground",children:"The core library for defining what your application can do. Unified specifications for Operations, Events, Presentations, and Features."})]}),o("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Installation"}),a(ct,{package:["@contractspec/lib.contracts-spec","@contractspec/lib.schema"]})]}),o("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"What lives where"}),o("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[o("li",{children:[a("strong",{children:"@contractspec/lib.contracts-spec"})," (root): The core contracts definitions (OperationSpec, PresentationSpec, Registry)."]}),o("li",{children:[a("strong",{children:"@contractspec/lib.contracts-runtime-client-react"}),": Browser-safe helpers (React renderers, client SDK). Import this for web/React Native."]}),o("li",{children:[a("strong",{children:"@contractspec/lib.contracts-runtime-server-rest"}),": HTTP/MCP adapters, registries, integrations (Node-only)."]}),o("li",{children:[a("strong",{children:"@contractspec/lib.schema"}),": Schema dictionary (SchemaModel, FieldType) for I/O definitions."]})]})]}),o("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Data table contract example"}),o("p",{className:"text-muted-foreground",children:["The canonical account-grid example starts here in"," ",a("code",{children:"@contractspec/lib.contracts-spec"}),". The contract declares table execution mode, selection, pinning, resizing, row expansion, and initial state before any renderer is chosen."]}),a(nt,{language:"typescript",code:st}),o("p",{className:"text-muted-foreground text-sm",children:["See the live version in"," ",a(ne,{href:"/docs/examples/data-grid-showcase",className:"text-[color:var(--rust)] underline underline-offset-4",children:"/docs/examples/data-grid-showcase"}),"."]})]}),o("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Core Concepts"}),o("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[o("li",{children:[a("strong",{children:"OperationSpec"}),": Immutable description of an operation (Command or Query). Defines I/O, policy, and metadata."]}),o("li",{children:[a("strong",{children:"OperationSpecRegistry"}),": Registry of specs + handlers. Use ",a("code",{className:"font-mono text-xs",children:"installOp"})," ","to attach a handler."]}),o("li",{children:[a("strong",{children:"CapabilitySpec"}),": Canonical capability declaration (requires/provides)."]}),o("li",{children:[a("strong",{children:"PolicySpec"}),": Declarative policy rules (ABAC/ReBAC, rate limits)."]}),o("li",{children:[a("strong",{children:"TelemetrySpec"}),": Analytics definitions and privacy levels."]}),o("li",{children:[a("strong",{children:"PresentationSpec (V2)"}),": Describes how data is rendered (Web Components, Markdown, Data)."]}),o("li",{children:[a("strong",{children:"DataViewSpec"}),": Declarative list, table, grid, and detail contracts that the table showcase uses as its canonical account-grid example."]})]})]}),o("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Lifecycle"}),o("ol",{className:"list-inside list-decimal space-y-2 text-muted-foreground",children:[o("li",{children:[a("strong",{children:"Define"})," the spec (I/O via SchemaModel or Zod)."]}),o("li",{children:[a("strong",{children:"Register"})," it:"," ",a("code",{className:"font-mono text-xs",children:"installOp(registry, spec, handler)"}),"."]}),o("li",{children:[a("strong",{children:"Expose"})," it via an adapter (REST, GraphQL, MCP)."]}),o("li",{children:[a("strong",{children:"Validate"})," at runtime automatically."]})]})]}),o("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Adapters"}),o("ul",{className:"space-y-2 text-muted-foreground",children:[o("li",{children:[a("code",{className:"rounded bg-background/50 px-2 py-1",children:"server/rest-next-app"}),": Next.js App Router adapter"]}),o("li",{children:[a("code",{className:"rounded bg-background/50 px-2 py-1",children:"server/provider-mcp"}),": Model Context Protocol (MCP) for AI agents"]}),o("li",{children:[a("code",{className:"rounded bg-background/50 px-2 py-1",children:"server/graphql-pothos"}),": GraphQL schema generator"]})]})]}),o("div",{className:"flex items-center gap-4 pt-4",children:[o(ne,{href:"/docs/libraries/schema",className:"btn-primary",children:["Next: Schema ",a(lt,{size:16})]}),a(ne,{href:"/docs/specs/capabilities",className:"btn-ghost",children:"Core Concepts"})]})]})}import{CodeBlock as Ne,InstallCommand as pt}from"@contractspec/lib.design-system";import we from"@contractspec/lib.ui-link";import{ChevronRight as mt}from"lucide-react";import{jsx as z,jsxs as _}from"react/jsx-runtime";function ut(){return _("div",{className:"space-y-8",children:[_("div",{className:"space-y-4",children:[z("h1",{className:"font-bold text-4xl",children:"Cost Tracking Library"}),_("p",{className:"text-lg text-muted-foreground",children:[z("code",{children:"@contractspec/lib.cost-tracking"})," transforms raw telemetry into dollars: DB/API/compute costs per operation, budget alerts per tenant, and actionable optimization tips."]})]}),_("div",{className:"space-y-4",children:[z("h2",{className:"font-bold text-2xl",children:"Installation"}),z(pt,{package:"@contractspec/lib.cost-tracking"})]}),_("div",{className:"space-y-4",children:[z("h2",{className:"font-bold text-2xl",children:"Record Samples"}),z(Ne,{language:"typescript",code:`const tracker = new CostTracker();
tracker.recordSample({
  operation: 'orders.list',
  tenantId: 'acme',
  dbReads: 1200,
  dbWrites: 4,
  computeMs: 180,
  externalCalls: [{ provider: 'stripe', cost: 0.02 }],
});`})]}),_("div",{className:"space-y-4",children:[z("h2",{className:"font-bold text-2xl",children:"Budget Alerts"}),z(Ne,{language:"typescript",code:`const budgets = new BudgetAlertManager({
  budgets: [{ tenantId: 'acme', monthlyLimit: 150 }],
  onAlert: ({ tenantId, total }) => notifyFinance(tenantId, total),
});

tracker.getTotals({ tenantId: 'acme' }).forEach((summary) => budgets.track(summary));`})]}),_("div",{className:"space-y-4",children:[z("h2",{className:"font-bold text-2xl",children:"Optimization Suggestions"}),_("p",{className:"text-muted-foreground text-sm",children:["Feed summaries into ",z("code",{children:"OptimizationRecommender"})," to surface N+1 queries, compute-heavy steps, or expensive external calls. Store the generated suggestions in the new Prisma model to power Ops playbooks."]})]}),_("div",{className:"flex items-center gap-4 pt-4",children:[z(we,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),_(we,{href:"/docs/libraries/slo",className:"btn-primary",children:["Next: SLO ",z(mt,{size:16})]})]})]})}import{CodeBlock as gt}from"@contractspec/lib.design-system";import ke from"@contractspec/lib.ui-link";import{ChevronRight as ft}from"lucide-react";import{jsx as h,jsxs as b}from"react/jsx-runtime";function ht(){return b("div",{className:"space-y-8",children:[b("div",{className:"space-y-4",children:[h("h1",{className:"font-bold text-4xl",children:"Data & Backend"}),h("p",{className:"text-muted-foreground",children:"A collection of robust, platform-agnostic libraries for building the backend infrastructure of your LSSM applications."})]}),b("div",{className:"space-y-4",children:[h("h2",{className:"font-bold text-2xl",children:"Libraries"}),b("div",{className:"space-y-6",children:[b("div",{className:"card-subtle p-6",children:[h("h3",{className:"font-bold text-lg",children:"@contractspec/app.cli-database"}),b("p",{className:"mt-2 text-muted-foreground text-sm",children:[h("strong",{children:"Prisma Wrapper & CLI"}),". Provides a unified way to manage database schemas, migrations, and clients. Includes seeders and factory patterns for testing."]})]}),b("div",{className:"card-subtle p-6",children:[h("h3",{className:"font-bold text-lg",children:"@contractspec/lib.bus"}),b("p",{className:"mt-2 text-muted-foreground text-sm",children:[h("strong",{children:"Type-Safe Event Bus"}),". Decouple your architecture with typed events. Supports in-memory dispatch for monoliths and can be extended for distributed message queues (Redis, SQS)."]})]}),b("div",{className:"card-subtle p-6",children:[h("h3",{className:"font-bold text-lg",children:"@contractspec/lib.logger"}),b("p",{className:"mt-2 text-muted-foreground text-sm",children:[h("strong",{children:"High-Performance Logging"}),". Optimized for Bun and structured JSON output. Includes plugins for ElysiaJS to log HTTP requests automatically."]})]}),b("div",{className:"card-subtle p-6",children:[h("h3",{className:"font-bold text-lg",children:"@contractspec/lib.error"}),b("p",{className:"mt-2 text-muted-foreground text-sm",children:[h("strong",{children:"Standardized Errors"}),". Use `AppError` with standard codes (NOT_FOUND, UNAUTHORIZED) to ensure consistent HTTP responses and error handling across services."]})]}),b("div",{className:"card-subtle p-6",children:[h("h3",{className:"font-bold text-lg",children:"@contractspec/lib.exporter"}),b("p",{className:"mt-2 text-muted-foreground text-sm",children:[h("strong",{children:"Data Export"}),". Generate CSV and XML files from your data. Platform-agnostic and streaming-friendly."]})]})]})]}),b("div",{className:"space-y-4",children:[h("h2",{className:"font-bold text-2xl",children:"Example: Unified Backend Flow"}),h(gt,{language:"typescript",code:`import { logger } from '@contractspec/lib.logger';
import { AppError } from '@contractspec/lib.error';
import { db } from '@contractspec/app.cli-database';
import { EventBus } from '@contractspec/lib.bus';

export async function createUser(email: string) {
  logger.info({ email }, 'Creating user');

  const existing = await db.user.findUnique({ where: { email } });
  if (existing) {
    throw new AppError('User already exists', 'CONFLICT');
  }

  const user = await db.user.create({ data: { email } });
  
  await EventBus.publish('user.created', { userId: user.id });
  
  return user;
}`})]}),b("div",{className:"flex items-center gap-4 pt-4",children:[b(ke,{href:"/docs/libraries/runtime",className:"btn-primary",children:["Next: Runtime ",h(ft,{size:16})]}),h(ke,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"})]})]})}import{CodeBlock as Se,InstallCommand as bt}from"@contractspec/lib.design-system";import Ce from"@contractspec/lib.ui-link";import{ChevronRight as vt}from"lucide-react";import{jsx as l,jsxs as v}from"react/jsx-runtime";function yt(){return v("div",{className:"space-y-8",children:[v("div",{className:"space-y-4",children:[l("h1",{className:"font-bold text-4xl",children:"DataViews Runtime Library"}),v("p",{className:"text-lg text-muted-foreground",children:["The ",l("code",{children:"@contractspec/lib.contracts-spec/data-views"})," and"," ",l("code",{children:"@contractspec/lib.design-system"})," libraries provide the runtime logic and UI components to render DataViews in your application."]})]}),v("div",{className:"space-y-4",children:[l("h2",{className:"font-bold text-2xl",children:"Installation"}),l(bt,{package:["@contractspec/lib.contracts-spec","@contractspec/lib.design-system"]})]}),v("div",{className:"space-y-4",children:[l("h2",{className:"font-bold text-2xl",children:"DataViewRenderer"}),l("p",{className:"text-muted-foreground",children:"The primary component for rendering any DataView. It automatically selects the correct layout (List, Table, Grid, Detail) based on the spec."}),l(Se,{language:"tsx",code:`import { DataViewRenderer } from '@contractspec/lib.design-system';
import { MyUserList } from './specs/users.data-view';

export function UserPage() {
  return (
    <DataViewRenderer
      spec={MyUserList}
      items={users}
      pagination={{ page: 1, pageSize: 20, total: 100 }}
      onPageChange={(page) => fetchPage(page)}
    />
  );
}`}),l("h3",{className:"font-semibold text-xl",children:"Props"}),v("ul",{className:"list-disc space-y-2 pl-6 text-muted-foreground",children:[v("li",{children:[l("code",{children:"spec"}),": The DataViewSpec definition."]}),v("li",{children:[l("code",{children:"items"}),": Array of data items to render."]}),v("li",{children:[l("code",{children:"filters"}),": Current filter state object."]}),v("li",{children:[l("code",{children:"onFilterChange"}),": Callback when filters change."]}),v("li",{children:[l("code",{children:"pagination"}),": Object with ",l("code",{children:"page"}),","," ",l("code",{children:"pageSize"}),", ",l("code",{children:"total"}),"."]}),v("li",{children:[l("code",{children:"onPageChange"}),": Callback when page changes."]})]})]}),v("div",{className:"space-y-4",children:[l("h2",{className:"font-bold text-2xl",children:"Query Generation"}),v("p",{className:"text-muted-foreground",children:["The ",l("code",{children:"DataViewQueryGenerator"})," utility helps translate DataView parameters (filters, sorting, pagination) into query arguments for your backend."]}),l(Se,{language:"typescript",code:`import { DataViewQueryGenerator } from '@contractspec/lib.contracts-spec/data-views/query-generator';

const generator = new DataViewQueryGenerator(MyUserList);
const query = generator.generate({
  pagination: { page: 1, pageSize: 20 },
  filters: { role: 'admin' }
});

// query.input contains { skip: 0, take: 20, role: 'admin' }`})]}),v("div",{className:"flex items-center gap-4 pt-4",children:[l(Ce,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),v(Ce,{href:"/docs/libraries/data-backend",className:"btn-primary",children:["Next: Data & Backend ",l(vt,{size:16})]})]})]})}import{CodeBlock as Nt,InstallCommand as wt}from"@contractspec/lib.design-system";import ce from"@contractspec/lib.ui-link";import{ChevronRight as kt}from"lucide-react";import{jsx as t,jsxs as n}from"react/jsx-runtime";var St=`import { Button, DataTable } from '@contractspec/lib.design-system';
import { useContractTable } from '@contractspec/lib.presentation-runtime-react';

import { SHOWCASE_ROWS } from '@contractspec/example.data-grid-showcase/ui/data-grid-showcase.data';
import { useShowcaseColumns } from '@contractspec/example.data-grid-showcase/ui/data-grid-showcase.columns';
import {
  ExpandedRowContent,
  ShowcaseToolbar,
} from '@contractspec/example.data-grid-showcase/ui/data-grid-showcase.parts';

export function AccountHealthTable() {
  const columns = useShowcaseColumns();

  const controller = useContractTable({
    data: SHOWCASE_ROWS,
    columns,
    selectionMode: 'multiple',
    initialState: {
      sorting: [{ id: 'arr', desc: true }],
      pagination: { pageIndex: 0, pageSize: 4 },
      columnVisibility: { notes: false },
      columnPinning: { left: ['account'], right: [] },
    },
    renderExpandedContent: (row) => <ExpandedRowContent row={row} />,
    getCanExpand: () => true,
  });

  return (
    <DataTable
      controller={controller}
      title="Account health"
      description="Composed table surface for the canonical account grid."
      headerActions={<Button variant="outline">Reset</Button>}
      toolbar={
        <ShowcaseToolbar
          controller={controller}
          label="Client mode"
          primaryColumnId="account"
          toggleColumnId="notes"
          pinColumnId="owner"
          sortColumnIds={['arr', 'renewalDate']}
        />
      }
      loading={false}
      emptyState={<div>No rows available.</div>}
      footer={\`Page \${controller.pageIndex + 1} of \${controller.pageCount}\`}
    />
  );
}`;function Ct(){return n("div",{className:"space-y-8",children:[n("div",{className:"space-y-4",children:[t("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.design-system"}),n("p",{className:"text-muted-foreground",children:["High-level design system components, patterns, and layouts for LSSM applications. Built on top of ",t("code",{children:"@contractspec/lib.ui-kit"}),"."]})]}),n("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Installation"}),t(wt,{package:"@contractspec/lib.design-system"})]}),n("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"What It Provides"}),n("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[n("li",{children:[t("strong",{children:"Composite Components"}),": Molecules and Organisms that solve common UI problems"]}),n("li",{children:[t("strong",{children:"Layouts"}),": Ready-to-use page structures for dashboards, marketing sites, and lists"]}),n("li",{children:[t("strong",{children:"Data Views"}),": Standardized renderers for lists, tables, and detail views"]}),n("li",{children:[t("strong",{children:"Forms"}),": Zod-integrated form layouts and components"]}),n("li",{children:[t("strong",{children:"Code Display"}),": Syntax-highlighted code blocks with package manager tabs"]}),n("li",{children:[t("strong",{children:"Platform Utilities"}),": Hooks for responsive and adaptive design"]}),n("li",{children:[t("strong",{children:"Legal Templates"}),": Compliant templates for Terms, Privacy, and GDPR"]})]})]}),n("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Data table example"}),n("p",{className:"text-muted-foreground",children:["This is the composed lane from the canonical"," ",t(ce,{href:"/docs/examples/data-grid-showcase",className:"text-[color:var(--rust)] underline underline-offset-4",children:"Data Grid Showcase"}),". The design-system wrapper owns title, description, header actions, and the opinionated card shell on top of the raw web primitive."]}),t(Nt,{language:"tsx",code:St})]}),n("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Key Exports"}),n("div",{className:"grid gap-4 md:grid-cols-2",children:[n("div",{className:"card-subtle p-4",children:[t("h3",{className:"mb-2 font-semibold",children:"Organisms"}),n("ul",{className:"space-y-1 text-muted-foreground text-sm",children:[t("li",{children:"AppLayout, AppHeader, AppSidebar"}),t("li",{children:"MarketingLayout, HeroSection"}),t("li",{children:"ListCardPage, ListTablePage"})]})]}),n("div",{className:"card-subtle p-4",children:[t("h3",{className:"mb-2 font-semibold",children:"Data & Forms"}),n("ul",{className:"space-y-1 text-muted-foreground text-sm",children:[t("li",{children:"DataTable"}),t("li",{children:"DataViewTable"}),t("li",{children:"DataViewRenderer"}),t("li",{children:"ZodForm"}),t("li",{children:"FormLayout, FormDialog"})]})]}),n("div",{className:"card-subtle p-4",children:[t("h3",{className:"mb-2 font-semibold",children:"Code Display"}),n("ul",{className:"space-y-1 text-muted-foreground text-sm",children:[t("li",{children:"CodeBlock (syntax highlighting)"}),t("li",{children:"CommandTabs (package manager tabs)"}),t("li",{children:"InstallCommand (convenience wrapper)"}),t("li",{children:"CopyButton"})]})]}),n("div",{className:"card-subtle p-4",children:[t("h3",{className:"mb-2 font-semibold",children:"Providers"}),t("ul",{className:"space-y-1 text-muted-foreground text-sm",children:t("li",{children:"PackageManagerProvider"})})]})]})]}),n("div",{className:"flex items-center gap-4 pt-4",children:[t(ce,{href:"/docs/libraries/ui-kit-web",className:"btn-ghost",children:"Previous: UI Kit Web"}),n(ce,{href:"/docs/libraries/accessibility",className:"btn-primary",children:["Next: Accessibility ",t(kt,{size:16})]})]})]})}import{CodeBlock as le,InstallCommand as Lt}from"@contractspec/lib.design-system";import Le from"@contractspec/lib.ui-link";import{ChevronRight as Rt}from"lucide-react";import{jsx as w,jsxs as Q}from"react/jsx-runtime";function It(){return Q("div",{className:"space-y-8",children:[Q("div",{className:"space-y-4",children:[w("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.evolution"}),w("p",{className:"text-lg text-muted-foreground",children:"Analyze production telemetry, surface anomalies, and turn them into AI-reviewed spec proposals that can be approved, rolled out, or reverted."})]}),Q("div",{className:"space-y-4",children:[w("h2",{className:"font-bold text-2xl",children:"Installation"}),w(Lt,{package:"@contractspec/lib.evolution"})]}),Q("div",{className:"space-y-3",children:[w("h2",{className:"font-bold text-2xl",children:"From telemetry to intent"}),w(le,{language:"typescript",code:`import { SpecAnalyzer } from '@contractspec/lib.evolution/analyzer';
import { EvolutionPipeline } from '@contractspec/lib.observability';

const analyzer = new SpecAnalyzer();
const pipeline = new EvolutionPipeline({
  onIntent: (intent) => console.log('[intent]', intent),
});

// feed telemetry samples from tracing middleware
pipeline.ingest({
  operation: { name: 'billing.createInvoice', version: 4 },
  durationMs: 612,
  success: false,
  timestamp: new Date(),
  errorCode: 'VALIDATION_FAILED',
});`})]}),Q("div",{className:"space-y-3",children:[w("h2",{className:"font-bold text-2xl",children:"Generate & approve suggestions"}),w(le,{language:"typescript",code:`import {
  SpecGenerator,
  SpecSuggestionOrchestrator,
  InMemorySpecSuggestionRepository,
} from '@contractspec/lib.evolution';

const generator = new SpecGenerator();
const repository = new InMemorySpecSuggestionRepository();
const orchestrator = new SpecSuggestionOrchestrator({ repository });

const suggestion = generator.generateFromIntent(intentPattern, {
  summary: 'Add PO number requirement for acme.corp',
});

await orchestrator.submit(suggestion, sessionState);`})]}),Q("div",{className:"space-y-3",children:[w("h2",{className:"font-bold text-2xl",children:"Write approved specs back to git"}),w(le,{language:"typescript",code:`import { FileSystemSuggestionWriter } from '@contractspec/lib.evolution/approval';

const writer = new FileSystemSuggestionWriter({
  outputDir:
    'packages/libs/contracts-spec/src/generated',
});

await writer.write({
  ...suggestion,
  status: 'approved',
  approvals: { reviewer: 'ops@contractspec', decidedAt: new Date() },
});`})]}),w("div",{className:"grid gap-4 md:grid-cols-2",children:[{title:"Approvals by default",description:"Every suggestion flows through @contractspec/lib.ai-agent's ApprovalWorkflow. Tune auto-approval thresholds per environment."},{title:"Pluggable storage",description:"Use the Prisma repository in production, in-memory for tests, or stream serialized suggestions into your own queue."}].map((E)=>Q("div",{className:"card-subtle space-y-2 p-4",children:[w("h3",{className:"font-semibold text-lg",children:E.title}),w("p",{className:"text-muted-foreground text-sm",children:E.description})]},E.title))}),Q("div",{className:"flex items-center gap-4 pt-4",children:[w(Le,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),Q(Le,{href:"/docs/libraries/observability",className:"btn-primary",children:["Next: Observability ",w(Rt,{size:16})]})]})]})}import{CodeBlock as Tt,InstallCommand as At}from"@contractspec/lib.design-system";import Re from"@contractspec/lib.ui-link";import{ChevronRight as Pt}from"lucide-react";import{jsx as u,jsxs as y}from"react/jsx-runtime";function Bt(){return y("div",{className:"space-y-8",children:[y("div",{className:"space-y-4",children:[u("h1",{className:"font-bold text-4xl",children:"GraphQL Libraries"}),u("p",{className:"text-muted-foreground",children:"This suite of libraries enables seamless GraphQL integration, transforming your ContractSpecs into a type-safe Pothos schema, connecting with Prisma, and enabling Apollo Federation."})]}),y("div",{className:"space-y-4",children:[u("h2",{className:"font-bold text-2xl",children:"Libraries"}),y("div",{className:"grid gap-4 md:grid-cols-1",children:[y("div",{className:"card-subtle p-6",children:[u("h3",{className:"font-bold text-lg",children:"@contractspec/lib.graphql-core"}),u("p",{className:"mt-2 text-muted-foreground text-sm",children:"The foundation. Provides a configured Pothos builder, common scalars (JSON, DateTime), and utilities for mapping ContractSpec I/O to Pothos types."})]}),y("div",{className:"card-subtle p-6",children:[u("h3",{className:"font-bold text-lg",children:"@contractspec/lib.graphql-prisma"}),u("p",{className:"mt-2 text-muted-foreground text-sm",children:"Connects Pothos to Prisma. Automatically generates GraphQL types from your Prisma schema and optimizes queries to prevent N+1 issues."})]}),y("div",{className:"card-subtle p-6",children:[u("h3",{className:"font-bold text-lg",children:"@contractspec/lib.graphql-federation"}),u("p",{className:"mt-2 text-muted-foreground text-sm",children:"Adds Apollo Federation V2 support. Allows your subgraph to define keys and entities, making it ready for a supergraph."})]})]})]}),y("div",{className:"space-y-4",children:[u("h2",{className:"font-bold text-2xl",children:"Installation"}),u(At,{package:["@contractspec/lib.graphql-core","@contractspec/lib.graphql-prisma","@contractspec/lib.graphql-federation"]})]}),y("div",{className:"space-y-4",children:[u("h2",{className:"font-bold text-2xl",children:"Usage: Building a Schema"}),u("p",{className:"text-muted-foreground",children:"Here's how to assemble a federated GraphQL schema from your specs:"}),u(Tt,{language:"typescript",code:`import { builder } from '@contractspec/lib.graphql-core';
import { registerContractsOnBuilder } from '@contractspec/lib.contracts-runtime-server-graphql/graphql-pothos';
import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
import { MySpecs } from './specs';

// 1. Register contracts
const registry = new OperationSpecRegistry();
registry.register(MySpecs);

// 2. Mount specs onto Pothos builder
registerContractsOnBuilder(builder, registry);

// 3. Build and print schema
const schema = builder.toSchema();
console.log(printSchema(schema));`})]}),y("div",{className:"space-y-4",children:[u("h2",{className:"font-bold text-2xl",children:"Features"}),y("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[y("li",{children:[u("strong",{children:"Code-First"}),": Define schema in TypeScript (Pothos), get SDL as artifact."]}),y("li",{children:[u("strong",{children:"Spec Integration"}),": `registerContractsOnBuilder` automatically converts Command/Query specs into Mutations/Queries."]}),y("li",{children:[u("strong",{children:"Federation Ready"}),": Just add `provider: 'federation'` to your config."]})]})]}),y("div",{className:"flex items-center gap-4 pt-4",children:[y(Re,{href:"/docs/libraries/data-backend",className:"btn-primary",children:["Next: Data & Backend ",u(Pt,{size:16})]}),u(Re,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"})]})]})}import{CodeBlock as Ie,InstallCommand as Ot}from"@contractspec/lib.design-system";import Te from"@contractspec/lib.ui-link";import{ChevronRight as Dt}from"lucide-react";import{jsx as U,jsxs as ee}from"react/jsx-runtime";function Et(){return ee("div",{className:"space-y-8",children:[ee("div",{className:"space-y-4",children:[U("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.growth"}),U("p",{className:"text-lg text-muted-foreground",children:"Launch experiments without third-party SDKs. Register variants, assign users deterministically, track exposures, and compute significance."})]}),ee("div",{className:"space-y-4",children:[U("h2",{className:"font-bold text-2xl",children:"Installation"}),U(Ot,{package:"@contractspec/lib.growth"})]}),ee("div",{className:"space-y-3",children:[U("h2",{className:"font-bold text-2xl",children:"Register + assign"}),U(Ie,{language:"typescript",code:`import { ExperimentRegistry, ExperimentRunner } from '@contractspec/lib.growth/experiments';

const registry = new ExperimentRegistry().register({
  key: 'pricing.cta',
  version: '1.0.0',
  goal: 'Increase demo bookings',
  variants: [
    { id: 'A', weight: 1 },
    { id: 'B', weight: 1 },
  ],
  primaryMetric: 'demo_booked',
});

const runner = new ExperimentRunner();
const assignment = runner.assign(registry.get('pricing.cta')!, 'user_123');`})]}),ee("div",{className:"space-y-3",children:[U("h2",{className:"font-bold text-2xl",children:"Track + analyze"}),U(Ie,{language:"typescript",code:`import { ExperimentTracker } from '@contractspec/lib.growth/tracker';
import { StatsEngine } from '@contractspec/lib.growth/stats';

const tracker = new ExperimentTracker(new InMemoryTrackerStore());
await tracker.recordAssignment(assignment);
await tracker.recordSample({
  experimentKey: assignment.experimentKey,
  variantId: assignment.variantId,
  metric: 'demo_booked',
  value: 1,
  timestamp: new Date(),
});

const stats = new StatsEngine().summarize(
  await tracker.getSamples(assignment.experimentKey, 'demo_booked'),
  'demo_booked'
);`})]}),ee("div",{className:"flex items-center gap-4 pt-4",children:[U(Te,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),ee(Te,{href:"/docs/libraries/analytics",className:"btn-primary",children:["Next: Analytics ",U(Dt,{size:16})]})]})]})}import{CodeBlock as Ae,InstallCommand as Mt}from"@contractspec/lib.design-system";import Pe from"@contractspec/lib.ui-link";import{ChevronRight as zt}from"lucide-react";import{jsx as W,jsxs as K}from"react/jsx-runtime";function Wt(){return K("div",{className:"space-y-8",children:[K("div",{className:"space-y-4",children:[W("h1",{className:"font-bold text-4xl",children:"Multi-Tenancy Library"}),K("p",{className:"text-lg text-muted-foreground",children:["The ",W("code",{children:"@contractspec/lib.multi-tenancy"})," library provides the core building blocks for secure SaaS applications."]})]}),K("div",{className:"space-y-4",children:[W("h2",{className:"font-bold text-2xl",children:"Installation"}),W(Mt,{package:"@contractspec/lib.multi-tenancy"})]}),K("div",{className:"space-y-4",children:[W("h2",{className:"font-bold text-2xl",children:"Prisma RLS Middleware"}),K("p",{className:"text-muted-foreground",children:["Automatically injects ",W("code",{children:"tenantId"})," into all queries."]}),W(Ae,{language:"typescript",code:`import { createRlsMiddleware } from '@contractspec/lib.multi-tenancy/rls';
import { prisma } from './db';
import { getTenantId } from './context';

prisma.$use(createRlsMiddleware(() => getTenantId()));`})]}),K("div",{className:"space-y-4",children:[W("h2",{className:"font-bold text-2xl",children:"Provisioning Service"}),W("p",{className:"text-muted-foreground",children:"Automates the creation of new tenants, including database setup and default user creation."}),W(Ae,{language:"typescript",code:`import { TenantProvisioningService } from '@contractspec/lib.multi-tenancy/provisioning';

const service = new TenantProvisioningService({ db: prisma });
await service.provision({
  id: 'acme',
  name: 'Acme Corp',
  slug: 'acme',
  ownerEmail: 'admin@acme.com'
});`})]}),K("div",{className:"flex items-center gap-4 pt-4",children:[W(Pe,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),K(Pe,{href:"/docs/libraries/progressive-delivery",className:"btn-primary",children:["Next: Progressive Delivery ",W(zt,{size:16})]})]})]})}import{CodeBlock as ie,InstallCommand as Gt}from"@contractspec/lib.design-system";import Be from"@contractspec/lib.ui-link";import{ChevronRight as Ft}from"lucide-react";import{jsx as N,jsxs as V}from"react/jsx-runtime";function _t(){return V("div",{className:"space-y-8",children:[V("div",{className:"space-y-4",children:[N("h1",{className:"font-bold text-4xl",children:"Observability Library"}),V("p",{className:"text-lg text-muted-foreground",children:["The ",N("code",{children:"@contractspec/lib.observability"})," library provides a thin wrapper around OpenTelemetry to simplify instrumentation."]})]}),V("div",{className:"space-y-4",children:[N("h2",{className:"font-bold text-2xl",children:"Installation"}),N(Gt,{package:"@contractspec/lib.observability"})]}),V("div",{className:"space-y-4",children:[N("h2",{className:"font-bold text-2xl",children:"Tracing"}),N(ie,{language:"typescript",code:`import { traceAsync, traceSync } from '@contractspec/lib.observability/tracing';

await traceAsync('process_order', async (span) => {
  span.setAttribute('order_id', order.id);
  await db.save(order);
});`})]}),V("div",{className:"space-y-4",children:[N("h2",{className:"font-bold text-2xl",children:"Metrics"}),N(ie,{language:"typescript",code:`import { createCounter, createHistogram } from '@contractspec/lib.observability/metrics';

const ordersCounter = createCounter('orders_total');
const latencyHistogram = createHistogram('request_duration_seconds');

ordersCounter.add(1, { status: 'success' });
latencyHistogram.record(0.123);`})]}),V("div",{className:"space-y-4",children:[N("h2",{className:"font-bold text-2xl",children:"Middleware"}),N("p",{className:"text-muted-foreground",children:"Automatically instrument your HTTP handlers:"}),N(ie,{language:"typescript",code:`import { createTracingMiddleware } from '@contractspec/lib.observability/tracing/middleware';

app.use(createTracingMiddleware());`})]}),V("div",{className:"space-y-4",children:[N("h2",{className:"font-bold text-2xl",children:"Anomaly Detection"}),N("p",{className:"text-muted-foreground text-sm",children:"Includes baseline calculation and anomaly detection helpers for auto-rollback without writing custom math."}),N(ie,{language:"typescript",code:`import { AnomalyDetector, RootCauseAnalyzer, AlertManager } from '@contractspec/lib.observability';

const detector = new AnomalyDetector({ errorRateDelta: 0.4 });
const analyzer = new RootCauseAnalyzer();
const alertManager = new AlertManager({ transport: sendOpsAlert });

const signals = detector.evaluate(point);
signals.forEach((signal) => {
  const analysis = analyzer.analyze(signal, recentDeployments);
  alertManager.notify(signal, analysis);
});`})]}),V("div",{className:"flex items-center gap-4 pt-4",children:[N(Be,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),V(Be,{href:"/docs/libraries/slo",className:"btn-primary",children:["Next: SLO ",N(Ft,{size:16})]})]})]})}import{CodeBlock as se,InstallCommand as Ut}from"@contractspec/lib.design-system";import Oe from"@contractspec/lib.ui-link";import{ChevronRight as Vt}from"lucide-react";import{jsx as I,jsxs as Y}from"react/jsx-runtime";function Ht(){return Y("div",{className:"space-y-8",children:[Y("div",{className:"space-y-4",children:[I("h1",{className:"font-bold text-4xl",children:"Overlay Engine"}),I("p",{className:"text-lg text-muted-foreground",children:"`@contractspec/lib.overlay-engine` keeps OverlaySpecs typed, signed, and auditable across tenants, roles, users, and devices."})]}),Y("div",{className:"space-y-4",children:[I("h2",{className:"font-bold text-2xl",children:"Installation"}),I(Ut,{package:"@contractspec/lib.overlay-engine"})]}),Y("div",{className:"space-y-4",children:[I("h2",{className:"font-bold text-2xl",children:"Define + Sign"}),I(se,{language:"typescript",code:`import { defineOverlay } from '@contractspec/lib.overlay-engine/spec';
import { signOverlay } from '@contractspec/lib.overlay-engine/signer';

const overlay = defineOverlay({
  overlayId: 'acme-order-form',
  version: '1.0.0',
  appliesTo: { capability: 'billing.createOrder', tenantId: 'acme' },
  modifications: [{ type: 'hideField', field: 'internalNotes' }],
});

const signed = await signOverlay(overlay, privateKeyPem);`})]}),Y("div",{className:"space-y-4",children:[I("h2",{className:"font-bold text-2xl",children:"Runtime"}),I("p",{className:"text-muted-foreground",children:"`OverlayRegistry` stores signed overlays with specificity scoring. `OverlayEngine` merges modifications and emits audit events."}),I(se,{language:"typescript",code:`const registry = new OverlayRegistry();
registry.register(signed);

const engine = new OverlayEngine({
  registry,
  audit: (event) => auditLog.write(event),
});

const result = engine.apply({
  target: { fields },
  capability: 'billing.createOrder',
  tenantId: 'acme',
});`})]}),Y("div",{className:"space-y-4",children:[I("h2",{className:"font-bold text-2xl",children:"React Hooks"}),I("p",{className:"text-muted-foreground",children:"Render overlays in React/React Native via `useOverlay`."}),I(se,{language:"typescript",code:`import { useOverlay } from '@contractspec/lib.overlay-engine/react';

const { target } = useOverlay(engine, {
  target: { fields },
  capability: 'billing.createOrder',
  tenantId: 'acme',
});`})]}),Y("div",{className:"flex items-center gap-4 pt-4",children:[I(Oe,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),Y(Oe,{href:"/docs/libraries/workflow-composer",className:"btn-primary",children:["Next: Workflow Composer ",I(Vt,{size:16})]})]})]})}import qt from"@contractspec/lib.ui-link";import{ChevronRight as Qt}from"lucide-react";import{jsx as P,jsxs as x}from"react/jsx-runtime";var Kt=[{title:"Contract and schema foundation",body:"Use these packages to define explicit contracts, schemas, and generated artifacts without inventing a new platform-specific language.",items:[{title:"@contractspec/lib.contracts-spec",description:"Define operations, events, policies, and generated surfaces in TypeScript.",href:"/docs/libraries/contracts"},{title:"@contractspec/lib.schema",description:"Share type-safe schema definitions across validation, clients, and runtime adapters.",href:"/docs/libraries/schema"}]},{title:"Runtime and surface libraries",body:"These packages execute the contract model across UI, data, observability, workflows, and generated runtime behavior.",items:[{title:"@contractspec/lib.runtime",description:"Run typed capability surfaces, execute policies, and connect runtime adapters.",href:"/docs/libraries/runtime"},{title:"@contractspec/lib.ui-kit",description:"Render shared surfaces across web and React Native without forking the contract layer.",href:"/docs/libraries/ui-kit"},{title:"@contractspec/lib.ui-kit-web",description:"Use the raw web primitive layer directly when you want the browser table, accessibility, and interaction model without the design-system shell.",href:"/docs/libraries/ui-kit-web"},{title:"@contractspec/lib.design-system",description:"Build higher-level product surfaces and documented marketing/docs primitives on top of the web and native UI packages.",href:"/docs/libraries/design-system"},{title:"@contractspec/lib.data-views",description:"Generate and render list/detail style surfaces that stay aligned with data contracts.",href:"/docs/libraries/data-views"}]},{title:"Operator and system packages",body:"These packages matter once the system is live and you need governance, resilience, and observability.",items:[{title:"@contractspec/lib.observability",description:"Trace, log, and measure contract execution using the same system boundaries.",href:"/docs/libraries/observability"},{title:"@contractspec/lib.resilience",description:"Add circuit breakers, retries, and failure controls without hiding the integration model.",href:"/docs/libraries/resilience"},{title:"@contractspec/lib.multi-tenancy",description:"Keep tenant-specific config, policy, and surface resolution explicit.",href:"/docs/libraries/multi-tenancy"},{title:"@contractspec/lib.workflow-composer",description:"Compose and extend workflows without smearing orchestration concerns across apps.",href:"/docs/libraries/workflow-composer"}]}];function Jt(){return x("div",{className:"space-y-10",children:[x("div",{className:"space-y-3",children:[P("p",{className:"editorial-kicker",children:"Build"}),P("h1",{className:"font-serif text-4xl tracking-[-0.04em] md:text-5xl",children:"The OSS foundation is a library system, not a closed platform."}),P("p",{className:"max-w-3xl text-lg text-muted-foreground leading-8",children:"ContractSpec is assembled from libraries that remain useful on their own and stronger together. Start with the contract and schema foundation, then add runtime, UI, integration, and operator packages as your system grows."})]}),x("div",{className:"editorial-proof-strip",children:[x("div",{className:"editorial-stat",children:[P("span",{className:"editorial-label",children:"Layering rule"}),P("span",{className:"editorial-stat-value",children:"libs \u2192 bundles \u2192 apps"})]}),P("p",{className:"max-w-2xl text-muted-foreground text-sm leading-7",children:"Keep reusable behavior in libraries, compose it into bundle-level surfaces, and reserve app packages for concrete delivery shells."})]}),P("div",{className:"space-y-6",children:Kt.map((E)=>x("section",{className:"editorial-panel space-y-5",children:[x("div",{className:"space-y-2",children:[P("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:E.title}),P("p",{className:"text-muted-foreground text-sm leading-7",children:E.body})]}),P("div",{className:"grid gap-4 md:grid-cols-2",children:E.items.map((oe)=>x(qt,{href:oe.href,className:"rounded-[24px] border border-border/75 bg-background/70 p-5 transition-colors hover:border-[color:rgb(162_79_42_/_0.45)]",children:[P("h3",{className:"font-semibold text-lg",children:oe.title}),P("p",{className:"mt-2 text-muted-foreground text-sm leading-7",children:oe.description}),x("div",{className:"mt-3 flex items-center gap-2 text-[color:var(--rust)] text-sm",children:["Learn more ",P(Qt,{size:14})]})]},oe.title))})]},E.title))})]})}import{CodeBlock as de,InstallCommand as Zt}from"@contractspec/lib.design-system";import De from"@contractspec/lib.ui-link";import{ChevronRight as Xt}from"lucide-react";import{jsx as k,jsxs as j}from"react/jsx-runtime";function $t(){return j("div",{className:"space-y-8",children:[j("div",{className:"space-y-4",children:[k("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.personalization"}),k("p",{className:"text-lg text-muted-foreground",children:"Track field/feature/workflow usage, analyze drop-offs, and convert insights into OverlaySpecs or workflow tweaks."})]}),j("div",{className:"space-y-4",children:[k("h2",{className:"font-bold text-2xl",children:"Installation"}),k(Zt,{package:"@contractspec/lib.personalization"})]}),j("div",{className:"space-y-4",children:[k("h2",{className:"font-bold text-2xl",children:"Tracker"}),k("p",{className:"text-muted-foreground",children:"Buffer events per tenant/user and emit OpenTelemetry counters automatically."}),k(de,{language:"typescript",code:`import { createBehaviorTracker } from '@contractspec/lib.personalization';

const tracker = createBehaviorTracker({
  store,
  context: { tenantId: ctx.tenant.id, userId: ctx.identity.id },
});

tracker.trackFieldAccess({ operation: 'billing.createOrder', field: 'items' });
tracker.trackWorkflowStep({ workflow: 'invoice', step: 'review', status: 'entered' });`})]}),j("div",{className:"space-y-4",children:[k("h2",{className:"font-bold text-2xl",children:"Analyzer"}),k("p",{className:"text-muted-foreground",children:"Summarize events and highlight unused UI, frequent fields, and workflow bottlenecks."}),k(de,{language:"typescript",code:`import { BehaviorAnalyzer } from '@contractspec/lib.personalization/analyzer';

const analyzer = new BehaviorAnalyzer(store);
const insights = await analyzer.analyze({ tenantId: 'acme', userId: 'ops-42' });
// { unusedFields: ['internalNotes'], workflowBottlenecks: [...] }`})]}),j("div",{className:"space-y-4",children:[k("h2",{className:"font-bold text-2xl",children:"Adapter"}),k("p",{className:"text-muted-foreground",children:"Convert insights into overlays or workflow extension hints."}),k(de,{language:"typescript",code:`import { insightsToOverlaySuggestion } from '@contractspec/lib.personalization/adapter';

const overlay = insightsToOverlaySuggestion(insights, {
  overlayId: 'acme-order-form',
  tenantId: 'acme',
  capability: 'billing.createOrder',
});`})]}),j("div",{className:"flex items-center gap-4 pt-4",children:[k(De,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),j(De,{href:"/docs/libraries/overlay-engine",className:"btn-primary",children:["Next: Overlay Engine ",k(Xt,{size:16})]})]})]})}import{CodeBlock as Ee,InstallCommand as Yt}from"@contractspec/lib.design-system";import Me from"@contractspec/lib.ui-link";import{ChevronRight as xt}from"lucide-react";import{jsx as S,jsxs as G}from"react/jsx-runtime";function jt(){return G("div",{className:"space-y-8",children:[G("div",{className:"space-y-4",children:[S("h1",{className:"font-bold text-4xl",children:"Progressive Delivery Library"}),G("p",{className:"text-lg text-muted-foreground",children:["The ",S("code",{children:"@contractspec/lib.progressive-delivery"})," package helps you ship new specs with confidence: canary + blue-green strategies, metric guardrails, and rollback hooks in one place."]})]}),G("div",{className:"space-y-4",children:[S("h2",{className:"font-bold text-2xl",children:"Installation"}),S(Yt,{package:"@contractspec/lib.progressive-delivery"})]}),G("div",{className:"space-y-4",children:[S("h2",{className:"font-bold text-2xl",children:"Define a Strategy"}),S(Ee,{language:"typescript",code:`import { DeploymentCoordinator, createDefaultCanaryController, TrafficShifter, RollbackManager } from '@contractspec/lib.progressive-delivery';

const strategy = {
  target: { name: 'billing.createInvoice', version: 7 },
  mode: 'canary',
  thresholds: {
    errorRate: 0.01,
    latencyP99: 500,
    latencyP95: 250,
  },
};`})]}),G("div",{className:"space-y-4",children:[S("h2",{className:"font-bold text-2xl",children:"Run the Coordinator"}),S(Ee,{language:"typescript",code:`const eventBus = new DeploymentEventBus();
const controller = createDefaultCanaryController(strategy, fetchMetrics, eventBus);
const coordinator = new DeploymentCoordinator({
  strategy,
  controller,
  trafficShifter: new TrafficShifter(strategy.mode),
  rollbackManager: new RollbackManager({ rollback: revertSpec }),
  applyTrafficSplit: updateFeatureFlag,
  eventBus,
});

const result = await coordinator.run();`}),G("p",{className:"text-muted-foreground text-sm",children:["The coordinator emits ",S("code",{children:"stage_started"}),","," ",S("code",{children:"stage_failed"}),", and ",S("code",{children:"rolled_back"})," events, making it easy to power dashboards or alerting workflows."]})]}),G("div",{className:"space-y-4",children:[S("h2",{className:"font-bold text-2xl",children:"Blue-Green Swap"}),G("p",{className:"text-muted-foreground text-sm",children:["Switch to ",S("code",{children:"mode: 'blue-green'"})," to warm up the new stack in parallel and cut over once smoke tests pass. The same guardrails apply before the final swap."]})]}),G("div",{className:"flex items-center gap-4 pt-4",children:[S(Me,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),G(Me,{href:"/docs/libraries/resilience",className:"btn-primary",children:["Next: Resilience ",S(xt,{size:16})]})]})]})}import{CodeBlock as pe,InstallCommand as ea}from"@contractspec/lib.design-system";import ze from"@contractspec/lib.ui-link";import{ChevronRight as ta}from"lucide-react";import{jsx as C,jsxs as J}from"react/jsx-runtime";function aa(){return J("div",{className:"space-y-8",children:[J("div",{className:"space-y-4",children:[C("h1",{className:"font-bold text-4xl",children:"Resilience Library"}),J("p",{className:"text-lg text-muted-foreground",children:["The ",C("code",{children:"@contractspec/lib.resilience"})," library provides primitives to handle failures gracefully."]})]}),J("div",{className:"space-y-4",children:[C("h2",{className:"font-bold text-2xl",children:"Installation"}),C(ea,{package:"@contractspec/lib.resilience"})]}),J("div",{className:"space-y-4",children:[C("h2",{className:"font-bold text-2xl",children:"Circuit Breaker"}),C("p",{className:"text-muted-foreground",children:"Prevent cascading failures by stopping calls to a failing dependency."}),C(pe,{language:"typescript",code:`import { CircuitBreaker } from '@contractspec/lib.resilience/circuit-breaker';

const breaker = new CircuitBreaker({
  failureThreshold: 5,
  resetTimeoutMs: 30000,
});

const result = await breaker.execute(async () => {
  return await fetch('https://api.stripe.com/v1/charges');
});`})]}),J("div",{className:"space-y-4",children:[C("h2",{className:"font-bold text-2xl",children:"Retry"}),C("p",{className:"text-muted-foreground",children:"Automatically retry transient failures with exponential backoff."}),C(pe,{language:"typescript",code:`import { retry } from '@contractspec/lib.resilience/retry';

const result = await retry(
  async () => fetchUser(id),
  3, // retries
  1000, // initial delay
  true // backoff
);`})]}),J("div",{className:"space-y-4",children:[C("h2",{className:"font-bold text-2xl",children:"Timeout & Fallback"}),C("p",{className:"text-muted-foreground",children:"Set hard limits on execution time and provide default values on failure."}),C(pe,{language:"typescript",code:`import { timeout, fallback } from '@contractspec/lib.resilience';

const result = await fallback(
  () => timeout(slowOperation, 5000),
  defaultValue
);`})]}),J("div",{className:"flex items-center gap-4 pt-4",children:[C(ze,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),J(ze,{href:"/docs/libraries/testing",className:"btn-primary",children:["Next: Testing ",C(ta,{size:16})]})]})]})}import{CodeBlock as oa,InstallCommand as ia}from"@contractspec/lib.design-system";import We from"@contractspec/lib.ui-link";import{ChevronRight as ra}from"lucide-react";import{jsx as d,jsxs as m}from"react/jsx-runtime";function na(){return m("div",{className:"space-y-8",children:[m("div",{className:"space-y-4",children:[d("h1",{className:"font-bold text-4xl",children:"Runtime Libraries"}),d("p",{className:"text-muted-foreground",children:"The presentation runtime libraries provide the engine for rendering ContractSpec-defined UIs. They handle state management, validation, step navigation, and component rendering for Workflows and DataViews."})]}),m("div",{className:"space-y-4",children:[d("h2",{className:"font-bold text-2xl",children:"Installation"}),d(ia,{package:"@contractspec/lib.presentation-runtime-react"})]}),m("div",{className:"space-y-4",children:[d("h2",{className:"font-bold text-2xl",children:"Libraries"}),m("div",{className:"space-y-6",children:[m("div",{className:"card-subtle p-6",children:[d("h3",{className:"font-bold text-lg",children:"@contractspec/lib.presentation-runtime-core"}),m("p",{className:"mt-2 text-muted-foreground text-sm",children:[d("strong",{children:"Framework-Agnostic Core"}),". Contains the state machines, validation logic, and navigation rules for workflows. Can be used to build renderers for any platform (Vue, Svelte, CLI)."]})]}),m("div",{className:"card-subtle p-6",children:[d("h3",{className:"font-bold text-lg",children:"@contractspec/lib.presentation-runtime-react"}),m("p",{className:"mt-2 text-muted-foreground text-sm",children:[d("strong",{children:"React Bindings"}),". Hooks (`useWorkflow`) and components (`WorkflowStepper`, `WorkflowStepRenderer`) for React Web applications. Integrates with `ui-kit-web`."]})]}),m("div",{className:"card-subtle p-6",children:[d("h3",{className:"font-bold text-lg",children:"@contractspec/lib.presentation-runtime-react-native"}),m("p",{className:"mt-2 text-muted-foreground text-sm",children:[d("strong",{children:"React Native Bindings"}),". Optimized for mobile experiences. Handles native navigation integration and uses universal components from `ui-kit`."]})]})]})]}),m("div",{className:"space-y-4",children:[d("h2",{className:"font-bold text-2xl",children:"Example: React Workflow"}),d(oa,{language:"tsx",code:`import { useWorkflow, WorkflowStepRenderer } from '@contractspec/lib.presentation-runtime-react';
import { OnboardingFlow } from './specs/onboarding';

export function OnboardingPage() {
  const workflow = useWorkflow(OnboardingFlow);

  if (workflow.isComplete) {
    return <SuccessScreen data={workflow.result} />;
  }

  return (
    <div className="max-w-md mx-auto py-8">
      <h1 className="text-2xl font-bold mb-4">
        {workflow.currentStep.title}
      </h1>
      
      <WorkflowStepRenderer 
        step={workflow.currentStep}
        onChange={workflow.updateData}
        errors={workflow.errors}
      />
      
      <div className="flex justify-end mt-6 gap-4">
        <button 
          onClick={workflow.prev}
          disabled={!workflow.canGoBack}
          className="btn-ghost"
        >
          Back
        </button>
        <button 
          onClick={workflow.next}
          disabled={!workflow.canProceed}
          className="btn-primary"
        >
          Next
        </button>
      </div>
    </div>
  );
}`})]}),m("div",{className:"space-y-4",children:[d("h2",{className:"font-bold text-2xl",children:"Architecture"}),d("p",{className:"text-muted-foreground",children:'The runtime follows a "render-loop" pattern:'}),m("ol",{className:"list-inside list-decimal space-y-2 text-muted-foreground",children:[m("li",{children:[d("strong",{children:"Spec"}),": Defines the flow, fields, and validation rules."]}),m("li",{children:[d("strong",{children:"Core"}),": Tracks current step, data state, and validation errors."]}),m("li",{children:[d("strong",{children:"Renderer"}),": Maps spec fields to UI components (Input, Select, etc.)."]}),m("li",{children:[d("strong",{children:"User"}),": Interacts with components, updating core state."]}),m("li",{children:[d("strong",{children:"Policy"}),": (Optional) Re-evaluates visibility on every change."]})]})]}),m("div",{className:"flex items-center gap-4 pt-4",children:[d(We,{href:"/docs/libraries/data-backend",className:"btn-ghost",children:"Previous: Data & Backend"}),m(We,{href:"/docs/libraries",className:"btn-primary",children:["Back to Libraries ",d(ra,{size:16})]})]})]})}import{CodeBlock as Ge,InstallCommand as ca}from"@contractspec/lib.design-system";import Fe from"@contractspec/lib.ui-link";import{ChevronRight as la}from"lucide-react";import{jsx as e,jsxs as s}from"react/jsx-runtime";function sa(){return s("div",{className:"space-y-8",children:[s("div",{className:"space-y-4",children:[e("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.schema"}),e("p",{className:"text-muted-foreground",children:"A small schema dictionary to describe operation I/O once and export to Zod (runtime validation), Pothos (GraphQL type refs), and JSON Schema."})]}),s("div",{className:"space-y-4",children:[e("h2",{className:"font-bold text-2xl",children:"Installation"}),e(ca,{package:"@contractspec/lib.schema"})]}),s("div",{className:"space-y-4",children:[e("h2",{className:"font-bold text-2xl",children:"Core Exports"}),s("ul",{className:"space-y-2 text-muted-foreground",children:[s("li",{children:[e("code",{className:"rounded bg-background/50 px-2 py-1",children:"SchemaModel"}),": Compose fields into typed object models"]}),s("li",{children:[e("code",{className:"rounded bg-background/50 px-2 py-1",children:"ScalarTypeEnum"}),": Common scalar types (NonEmptyString, Email, DateTime, etc.)"]}),s("li",{children:[e("code",{className:"rounded bg-background/50 px-2 py-1",children:"defineEnum"}),": Create type-safe enums"]}),s("li",{children:[e("code",{className:"rounded bg-background/50 px-2 py-1",children:"FieldType"}),": Wrap scalars with Zod/GraphQL/JSON Schema"]})]})]}),s("div",{className:"space-y-4",children:[e("h2",{className:"font-bold text-2xl",children:"Example: Basic Schema"}),e(Ge,{language:"typescript",code:`import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';

export const CreateSpotInput = new SchemaModel({
  name: 'CreateSpotInput',
  fields: {
    name: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
    latitude: { type: ScalarTypeEnum.Latitude(), isOptional: false },
    longitude: { type: ScalarTypeEnum.Longitude(), isOptional: false },
  },
});

// Get Zod schema for validation
const zodSchema = CreateSpotInput.getZod();

// Get Pothos input name for GraphQL
const pothosName = CreateSpotInput.getPothosInput();

// Get JSON Schema
const jsonSchema = CreateSpotInput.getJsonSchema();`})]}),s("div",{className:"space-y-4",children:[e("h2",{className:"font-bold text-2xl",children:"Example: Enums"}),e(Ge,{language:"typescript",code:`import { defineEnum, SchemaModel } from '@contractspec/lib.schema';

const Weekday = defineEnum('Weekday', [
  'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU',
] as const);

const RecurrenceRule = new SchemaModel({
  name: 'RecurrenceRule',
  fields: {
    frequency: {
      type: defineEnum('Frequency', ['DAILY', 'WEEKLY', 'MONTHLY'] as const),
      isOptional: false
    },
    byWeekday: { type: Weekday, isOptional: true, isArray: true },
  },
});`})]}),s("div",{className:"space-y-4",children:[e("h2",{className:"font-bold text-2xl",children:"Available Scalars"}),s("div",{className:"grid gap-4 md:grid-cols-2",children:[s("div",{className:"card-subtle p-4",children:[e("h3",{className:"mb-2 font-semibold",children:"Strings"}),s("ul",{className:"space-y-1 text-muted-foreground text-sm",children:[e("li",{children:e("code",{children:"NonEmptyString()"})}),e("li",{children:e("code",{children:"Email()"})}),e("li",{children:e("code",{children:"PhoneNumber()"})}),e("li",{children:e("code",{children:"CountryCode()"})}),e("li",{children:e("code",{children:"Locale()"})}),e("li",{children:e("code",{children:"TimeZone()"})})]})]}),s("div",{className:"card-subtle p-4",children:[e("h3",{className:"mb-2 font-semibold",children:"Numbers"}),s("ul",{className:"space-y-1 text-muted-foreground text-sm",children:[e("li",{children:e("code",{children:"PositiveNumber()"})}),e("li",{children:e("code",{children:"Latitude()"})}),e("li",{children:e("code",{children:"Longitude()"})})]})]}),s("div",{className:"card-subtle p-4",children:[e("h3",{className:"mb-2 font-semibold",children:"Dates & Times"}),s("ul",{className:"space-y-1 text-muted-foreground text-sm",children:[e("li",{children:e("code",{children:"Date()"})}),e("li",{children:e("code",{children:"DateTime()"})})]})]}),s("div",{className:"card-subtle p-4",children:[e("h3",{className:"mb-2 font-semibold",children:"Generic"}),s("ul",{className:"space-y-1 text-muted-foreground text-sm",children:[e("li",{children:e("code",{children:"String()"})}),e("li",{children:e("code",{children:"JSON()"})})]})]})]})]}),s("div",{className:"flex items-center gap-4 pt-4",children:[e(Fe,{href:"/docs/libraries/contracts",className:"btn-ghost",children:"Previous: Contracts"}),s(Fe,{href:"/docs/libraries/ui-kit",className:"btn-primary",children:["Next: UI Kit ",e(la,{size:16})]})]})]})}import{CodeBlock as _e,InstallCommand as da}from"@contractspec/lib.design-system";import Ue from"@contractspec/lib.ui-link";import{ChevronRight as pa}from"lucide-react";import{jsx as B,jsxs as H}from"react/jsx-runtime";function ma(){return H("div",{className:"space-y-8",children:[H("div",{className:"space-y-4",children:[B("h1",{className:"font-bold text-4xl",children:"SLO Library"}),H("p",{className:"text-lg text-muted-foreground",children:[B("code",{children:"@contractspec/lib.slo"})," keeps service level objectives front and center\u2014declarative definitions, rolling snapshots, burn-rate math, and automated incidents."]})]}),H("div",{className:"space-y-4",children:[B("h2",{className:"font-bold text-2xl",children:"Installation"}),B(da,{package:"@contractspec/lib.slo"})]}),H("div",{className:"space-y-4",children:[B("h2",{className:"font-bold text-2xl",children:"Define Targets"}),B(_e,{language:"typescript",code:`const definition: SLODefinition = {
  id: 'billing.createInvoice.availability',
  targetAvailability: 0.999,
  latencyP99TargetMs: 500,
  rollingWindowMs: 7 * 24 * 60 * 60 * 1000,
  alerts: { fastBurnThreshold: 14, slowBurnThreshold: 6 },
};`})]}),H("div",{className:"space-y-4",children:[B("h2",{className:"font-bold text-2xl",children:"Monitor Burn Rate"}),B(_e,{language:"typescript",code:`const monitor = new SLOMonitor({ definition, incidentManager });
const { snapshot, burnRate } = monitor.recordWindow({
  good: 12500,
  bad: 3,
  latencyP99: 420,
  latencyP95: 210,
});`}),H("p",{className:"text-muted-foreground text-sm",children:["When burn rate exceeds the configured thresholds the monitor calls your",B("code",{children:"IncidentManager"}),", providing the snapshot that triggered the alert."]})]}),H("div",{className:"space-y-4",children:[B("h2",{className:"font-bold text-2xl",children:"History & Reporting"}),B("p",{className:"text-muted-foreground text-sm",children:"`SLOTracker.getHistory()` returns the latest snapshots so dashboards can show trends without hitting a warehouse. Prisma models persist everything for long-term audits."})]}),H("div",{className:"flex items-center gap-4 pt-4",children:[B(Ue,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),H(Ue,{href:"/docs/libraries/cost-tracking",className:"btn-primary",children:["Next: Cost Tracking ",B(pa,{size:16})]})]})]})}import{CodeBlock as Ve,InstallCommand as ua}from"@contractspec/lib.design-system";import He from"@contractspec/lib.ui-link";import{ChevronRight as ga}from"lucide-react";import{jsx as L,jsxs as O}from"react/jsx-runtime";function fa(){return O("div",{className:"space-y-8",children:[O("div",{className:"space-y-4",children:[L("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.support-bot"}),L("p",{className:"text-lg text-muted-foreground",children:"Build AI-first support flows using drop-in classifiers, knowledge-grounded resolvers, and tone-aware responders\u2014all wired into the agent runner."})]}),O("div",{className:"space-y-4",children:[L("h2",{className:"font-bold text-2xl",children:"Installation"}),L(ua,{package:"@contractspec/lib.support-bot"})]}),O("div",{className:"space-y-3",children:[L("h2",{className:"font-bold text-2xl",children:"Wire the primitives"}),L(Ve,{language:"typescript",code:`import { TicketClassifier, TicketResolver, AutoResponder } from '@contractspec/lib.support-bot';

const classifier = new TicketClassifier();
const resolver = new TicketResolver({ knowledge });
const responder = new AutoResponder();

const classification = await classifier.classify(ticket);
const resolution = await resolver.resolve(ticket);
const draft = await responder.draft(ticket, resolution, classification);`})]}),O("div",{className:"space-y-3",children:[L("h2",{className:"font-bold text-2xl",children:"Expose as agent tools"}),L(Ve,{language:"typescript",code:`import { createSupportTools } from '@contractspec/lib.support-bot/bot';

const tools = createSupportTools({ resolver, classifier, responder });
// Pass these tools into your host runtime or agent adapter.`})]}),O("div",{className:"space-y-3",children:[L("h2",{className:"font-bold text-2xl",children:"Included modules"}),O("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[O("li",{children:[L("strong",{children:"TicketClassifier"}),": heuristics + optional LLM validation for category/priority."]}),O("li",{children:[L("strong",{children:"TicketResolver"}),": RAG resolver that can plug into any knowledge retriever."]}),O("li",{children:[L("strong",{children:"AutoResponder"}),": generates drafts, citations, and tone-aware copy."]}),O("li",{children:[L("strong",{children:"SupportFeedbackLoop"}),": track auto-resolution rates and sentiment trends."]})]})]}),O("div",{className:"flex items-center gap-4 pt-4",children:[L(He,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),O(He,{href:"/docs/libraries/growth",className:"btn-primary",children:["Next: Growth ",L(ga,{size:16})]})]})]})}import{CodeBlock as me,InstallCommand as ha}from"@contractspec/lib.design-system";import qe from"@contractspec/lib.ui-link";import{ChevronRight as ba}from"lucide-react";import{jsx as R,jsxs as Z}from"react/jsx-runtime";function va(){return Z("div",{className:"space-y-8",children:[Z("div",{className:"space-y-4",children:[R("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.testing"}),R("p",{className:"text-lg text-muted-foreground",children:"Golden tests ensure new rollouts behave exactly like the traffic that inspired them. Record requests in production, replay them locally, and ship with confidence."})]}),Z("div",{className:"space-y-4",children:[R("h2",{className:"font-bold text-2xl",children:"Installation"}),R(ha,{package:"@contractspec/lib.testing"})]}),Z("div",{className:"space-y-3",children:[R("h2",{className:"font-bold text-2xl",children:"Record traffic"}),R(me,{language:"typescript",code:`import {
  TrafficRecorder,
  InMemoryTrafficStore,
} from '@contractspec/lib.testing/recorder';

const recorder = new TrafficRecorder({
  store: new InMemoryTrafficStore(),
  sampleRate: 0.02,
  sanitize: (snapshot) => ({
    ...snapshot,
    input: { ...snapshot.input, secret: undefined },
  }),
});

await recorder.record({
  operation: { name: 'orders.create', version: 6 },
  input: payload,
  output,
  success: true,
  tenantId: ctx.organizationId ?? undefined,
});`})]}),Z("div",{className:"space-y-3",children:[R("h2",{className:"font-bold text-2xl",children:"Generate suites"}),R(me,{language:"typescript",code:`import { GoldenTestGenerator } from '@contractspec/lib.testing';

const generator = new GoldenTestGenerator();
const code = generator.generate(snapshots, {
  suiteName: 'orders.create golden path',
  runnerImport: './tests/run-operation',
  runnerFunction: 'runOrdersCommand',
  framework: 'vitest',
});`})]}),Z("div",{className:"space-y-3",children:[R("h2",{className:"font-bold text-2xl",children:"CLI workflow"}),R(me,{language:"bash",code:"contractspec test generate \\\n  --operation orders.create \\\n  --output tests/orders.create.golden.test.ts \\\n  --runner-import ./tests/run-operation \\\n  --runner-fn runOrdersCommand \\\n  --from-production \\\n  --days 7 \\\n  --sample-rate 0.05"})]}),R("div",{className:"grid gap-4 md:grid-cols-2",children:[{title:"Framework agnostic",description:"Vitest by default, Jest via `generateJestSuite`, or call `runGoldenTests` manually inside CI."},{title:"Sanitize & sample",description:"Scrub payloads before persistence and control sample rates per operation to stay within compliance limits."}].map((E)=>Z("div",{className:"card-subtle space-y-2 p-4",children:[R("h3",{className:"font-semibold text-lg",children:E.title}),R("p",{className:"text-muted-foreground text-sm",children:E.description})]},E.title))}),Z("div",{className:"flex items-center gap-4 pt-4",children:[R(qe,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),Z(qe,{href:"/docs/libraries/resilience",className:"btn-primary",children:["Next: Resilience ",R(ba,{size:16})]})]})]})}import{CodeBlock as ya,InstallCommand as Na}from"@contractspec/lib.design-system";import ue from"@contractspec/lib.ui-link";import{ChevronRight as wa}from"lucide-react";import{jsx as i,jsxs as p}from"react/jsx-runtime";var ka=`import { DataTable } from '@contractspec/lib.ui-kit/ui/data-table';
import { useContractTable } from '@contractspec/lib.presentation-runtime-react';

import { SHOWCASE_ROWS } from '@contractspec/example.data-grid-showcase/ui/data-grid-showcase.data';
import { useShowcaseColumns } from '@contractspec/example.data-grid-showcase/ui/data-grid-showcase.columns';
import {
  ExpandedRowContent,
  ShowcaseToolbar,
} from '@contractspec/example.data-grid-showcase/ui/data-grid-showcase.parts';

export function NativeAccountGrid() {
  const columns = useShowcaseColumns();

  const controller = useContractTable({
    data: SHOWCASE_ROWS,
    columns,
    selectionMode: 'single',
    initialState: {
      sorting: [{ id: 'arr', desc: true }],
      pagination: { pageIndex: 0, pageSize: 4 },
      columnVisibility: { notes: false },
      columnPinning: { left: ['account'], right: [] },
    },
    renderExpandedContent: (row) => <ExpandedRowContent row={row} />,
    getCanExpand: () => true,
  });

  return (
    <DataTable
      controller={controller}
      toolbar={
        <ShowcaseToolbar
          controller={controller}
          label="Native primitive"
          primaryColumnId="account"
          toggleColumnId="notes"
          pinColumnId="owner"
          sortColumnIds={['arr', 'renewalDate']}
        />
      }
      loading={false}
      footer={\`Rows \${controller.rows.length}\`}
    />
  );
}`;function Sa(){return p("div",{className:"space-y-8",children:[p("div",{className:"space-y-4",children:[i("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.ui-kit"}),p("p",{className:"text-muted-foreground",children:["Universal UI components for React Native and Web, built on top of",i("code",{children:"nativewind"})," and ",i("code",{children:"@rn-primitives"}),"."]})]}),p("div",{className:"space-y-4",children:[i("h2",{className:"font-bold text-2xl",children:"Installation"}),i(Na,{package:"@contractspec/lib.ui-kit"})]}),p("div",{className:"space-y-4",children:[i("h2",{className:"font-bold text-2xl",children:"Key Features"}),p("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[p("li",{children:[i("strong",{children:"Universal"}),": Components render natively on iOS/Android and as standard HTML on web"]}),p("li",{children:[i("strong",{children:"Styled with NativeWind"}),": Uses Tailwind CSS classes for styling"]}),p("li",{children:[i("strong",{children:"Accessible"}),": Leverages ",i("code",{children:"@rn-primitives"})," ","(Radix UI for Native)"]}),p("li",{children:[i("strong",{children:"Atomic Design"}),": Exports atoms, molecules, and organisms"]})]})]}),p("div",{className:"space-y-4",children:[i("h2",{className:"font-bold text-2xl",children:"Data table example"}),p("p",{className:"text-muted-foreground",children:["The canonical"," ",i(ue,{href:"/docs/examples/data-grid-showcase",className:"text-[color:var(--rust)] underline underline-offset-4",children:"Data Grid Showcase"})," ","uses ",i("code",{children:"@contractspec/lib.ui-kit/ui/data-table"})," as the native-first primitive lane. It shares the same controller model as the web renderer while keeping the React Native / Expo surface explicit."]}),i(ya,{language:"tsx",code:ka})]}),p("div",{className:"space-y-4",children:[i("h2",{className:"font-bold text-2xl",children:"Core Components"}),p("div",{className:"grid gap-4 md:grid-cols-3",children:[p("div",{className:"card-subtle p-4",children:[i("h3",{className:"mb-2 font-semibold",children:"Form Controls"}),p("ul",{className:"space-y-1 text-muted-foreground text-sm",children:[i("li",{children:"Button"}),i("li",{children:"Input"}),i("li",{children:"Checkbox"}),i("li",{children:"Switch"}),i("li",{children:"Select"})]})]}),p("div",{className:"card-subtle p-4",children:[i("h3",{className:"mb-2 font-semibold",children:"Layout"}),p("ul",{className:"space-y-1 text-muted-foreground text-sm",children:[i("li",{children:"Card"}),i("li",{children:"Stack"}),i("li",{children:"Separator"}),i("li",{children:"Sheet"})]})]}),p("div",{className:"card-subtle p-4",children:[i("h3",{className:"mb-2 font-semibold",children:"Feedback"}),p("ul",{className:"space-y-1 text-muted-foreground text-sm",children:[i("li",{children:"Alert"}),i("li",{children:"Skeleton"}),i("li",{children:"Progress"}),i("li",{children:"Tooltip"})]})]})]})]}),p("div",{className:"flex items-center gap-4 pt-4",children:[i(ue,{href:"/docs/libraries/schema",className:"btn-ghost",children:"Previous: Schema"}),p(ue,{href:"/docs/libraries/ui-kit-web",className:"btn-primary",children:["Next: UI Kit Web ",i(wa,{size:16})]})]})]})}import{CodeBlock as Ca,InstallCommand as La}from"@contractspec/lib.design-system";import ge from"@contractspec/lib.ui-link";import{ChevronRight as Ra}from"lucide-react";import{jsx as D,jsxs as X}from"react/jsx-runtime";var Ia=`import { DataTable } from '@contractspec/lib.ui-kit-web/ui/data-table';
import { useContractTable } from '@contractspec/lib.presentation-runtime-react';

import { SHOWCASE_ROWS } from '@contractspec/example.data-grid-showcase/ui/data-grid-showcase.data';
import { useShowcaseColumns } from '@contractspec/example.data-grid-showcase/ui/data-grid-showcase.columns';
import {
  ExpandedRowContent,
  ShowcaseToolbar,
} from '@contractspec/example.data-grid-showcase/ui/data-grid-showcase.parts';

export function WebAccountGrid() {
  const columns = useShowcaseColumns();

  const controller = useContractTable({
    data: SHOWCASE_ROWS,
    columns,
    selectionMode: 'single',
    initialState: {
      sorting: [{ id: 'lastActivityAt', desc: true }],
      pagination: { pageIndex: 0, pageSize: 4 },
      columnVisibility: { notes: false },
      columnPinning: { left: ['account'], right: [] },
    },
    renderExpandedContent: (row) => <ExpandedRowContent row={row} />,
    getCanExpand: () => true,
  });

  return (
    <DataTable
      controller={controller}
      toolbar={
        <ShowcaseToolbar
          controller={controller}
          label="Web primitive"
          primaryColumnId="account"
          toggleColumnId="notes"
          pinColumnId="owner"
          sortColumnIds={['arr', 'renewalDate']}
        />
      }
      loading={false}
      emptyState={<div>No rows available.</div>}
      footer={\`Rows \${controller.totalItems}\`}
    />
  );
}`;function Ta(){return X("div",{className:"space-y-8",children:[X("div",{className:"space-y-4",children:[D("h1",{className:"font-bold text-4xl",children:"@contractspec/lib.ui-kit-web"}),D("p",{className:"text-muted-foreground",children:"Web-first React and Next primitives for ContractSpec. The canonical data-table example uses this package to render the raw browser table layer directly, without the design-system shell on top."})]}),X("div",{className:"space-y-4",children:[D("h2",{className:"font-bold text-2xl",children:"Installation"}),D(La,{package:"@contractspec/lib.ui-kit-web"})]}),X("div",{className:"space-y-4",children:[D("h2",{className:"font-bold text-2xl",children:"Data table example"}),X("p",{className:"text-muted-foreground",children:["This is the raw browser lane from the canonical"," ",D(ge,{href:"/docs/examples/data-grid-showcase",className:"text-[color:var(--rust)] underline underline-offset-4",children:"Data Grid Showcase"}),". It demonstrates the primitive renderer with sorting, pagination, single selection, column visibility, column resizing, left/right pinning, row expansion, loading, and empty-state slots."]}),D(Ca,{language:"tsx",filename:"web-account-grid.tsx",code:Ia})]}),X("div",{className:"space-y-4",children:[D("h2",{className:"font-bold text-2xl",children:"What this layer owns"}),X("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[D("li",{children:"The raw table renderer and browser interaction model."}),D("li",{children:"Pagination, column visibility menus, pin menus, resize handles, and empty/loading states."}),D("li",{children:"Accessibility helpers and other web-specific primitives that stay outside the native-first package."})]})]}),X("div",{className:"flex items-center gap-4 pt-4",children:[D(ge,{href:"/docs/libraries/ui-kit",className:"btn-ghost",children:"Previous: UI Kit"}),X(ge,{href:"/docs/libraries/design-system",className:"btn-primary",children:["Next: Design System ",D(Ra,{size:16})]})]})]})}import{CodeBlock as Qe,InstallCommand as Aa}from"@contractspec/lib.design-system";import Ke from"@contractspec/lib.ui-link";import{ChevronRight as Pa}from"lucide-react";import{jsx as q,jsxs as te}from"react/jsx-runtime";function Ba(){return te("div",{className:"space-y-8",children:[te("div",{className:"space-y-4",children:[q("h1",{className:"font-bold text-4xl",children:"Workflow Composer"}),q("p",{className:"text-lg text-muted-foreground",children:"`@contractspec/lib.workflow-composer` injects tenant-/role-/device-specific steps into base WorkflowSpecs and keeps transitions valid."})]}),te("div",{className:"space-y-4",children:[q("h2",{className:"font-bold text-2xl",children:"Installation"}),q(Aa,{package:"@contractspec/lib.workflow-composer"})]}),te("div",{className:"space-y-4",children:[q("h2",{className:"font-bold text-2xl",children:"Register extensions"}),q(Qe,{language:"typescript",code:`const composer = new WorkflowComposer();

composer.register({
  workflow: 'billing.invoiceApproval',
  tenantId: 'acme',
  customSteps: [
    {
      after: 'validate-invoice',
      inject: {
        id: 'acme-legal',
        type: 'human',
        label: 'ACME Legal Review',
      },
      transitionTo: 'final-approval',
    },
  ],
  hiddenSteps: ['internal-audit'],
});`})]}),te("div",{className:"space-y-4",children:[q("h2",{className:"font-bold text-2xl",children:"Compose at runtime"}),q(Qe,{language:"typescript",code:`const tenantWorkflow = composer.compose({
  base: BaseInvoiceWorkflow,
  tenantId: 'acme',
});

workflowRunner.execute(tenantWorkflow, ctx);`})]}),te("div",{className:"flex items-center gap-4 pt-4",children:[q(Ke,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),te(Ke,{href:"/docs/libraries/workflows",className:"btn-primary",children:["Next: Workflow Runtime ",q(Pa,{size:16})]})]})]})}import{CodeBlock as Oa,InstallCommand as Da}from"@contractspec/lib.design-system";import Je from"@contractspec/lib.ui-link";import{ChevronRight as Ea}from"lucide-react";import{jsx as r,jsxs as T}from"react/jsx-runtime";function Ma(){return T("div",{className:"space-y-8",children:[T("div",{className:"space-y-4",children:[r("h1",{className:"font-bold text-4xl",children:"Workflow Runtime Library"}),T("p",{className:"text-lg text-muted-foreground",children:["The ",r("code",{children:"@contractspec/lib.contracts-spec/workflow"})," library provides the core ",r("code",{children:"WorkflowRunner"})," for executing stateful, durable workflows."]})]}),T("div",{className:"space-y-4",children:[r("h2",{className:"font-bold text-2xl",children:"Installation"}),r(Da,{package:"@contractspec/lib.contracts-spec"})]}),T("div",{className:"space-y-4",children:[r("h2",{className:"font-bold text-2xl",children:"WorkflowRunner"}),r("p",{className:"text-muted-foreground",children:"The runner manages execution state, step transitions, retries, and compensation."}),r(Oa,{language:"typescript",code:`import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters/memory-store';
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';

const registry = new WorkflowRegistry();
registry.register(MyWorkflow);

const runner = new WorkflowRunner({
  registry,
  stateStore: new InMemoryStateStore(),
  opExecutor: async (op, input, ctx) => {
    // Execute operation using your adapter (REST, GraphQL, etc.)
    return await myAdapter.execute(op, input);
  },
});

// Start a workflow
const workflowId = await runner.start('my.workflow', 1, { userId: '123' });

// Execute next step (usually called by a worker or queue consumer)
await runner.executeStep(workflowId);`})]}),T("div",{className:"space-y-4",children:[r("h2",{className:"font-bold text-2xl",children:"State Persistence"}),T("p",{className:"text-muted-foreground",children:["The runner relies on a ",r("code",{children:"StateStore"})," to persist workflow execution history. ContractSpec ships with:"]}),T("ul",{className:"list-disc space-y-2 pl-6 text-muted-foreground",children:[T("li",{children:[r("code",{children:"InMemoryStateStore"})," - for testing and development."]}),T("li",{children:[r("code",{children:"PrismaStateStore"})," - for production using Prisma ORM."]})]})]}),T("div",{className:"space-y-4",children:[r("h2",{className:"font-bold text-2xl",children:"Events"}),r("p",{className:"text-muted-foreground",children:"The runner emits events that you can subscribe to for monitoring:"}),T("ul",{className:"list-disc space-y-2 pl-6 text-muted-foreground",children:[r("li",{children:r("code",{children:"workflow.started"})}),r("li",{children:r("code",{children:"workflow.step_completed"})}),r("li",{children:r("code",{children:"workflow.step_failed"})}),r("li",{children:r("code",{children:"workflow.step_retrying"})}),r("li",{children:r("code",{children:"workflow.completed"})}),r("li",{children:r("code",{children:"workflow.cancelled"})}),r("li",{children:r("code",{children:"workflow.compensation_step_completed"})})]})]}),T("div",{className:"flex items-center gap-4 pt-4",children:[r(Je,{href:"/docs/libraries",className:"btn-ghost",children:"Back to Libraries"}),T(Je,{href:"/docs/libraries/data-views",className:"btn-primary",children:["Next: Data Views ",r(Ea,{size:16})]})]})]})}export{Ma as LibrariesWorkflowsPage,Ba as LibrariesWorkflowComposerPage,Ta as LibrariesUIKitWebPage,Sa as LibrariesUIKitPage,va as LibrariesTestingPage,fa as LibrariesSupportBotPage,sa as LibrariesSchemaPage,ma as LibrariesSLOPage,na as LibrariesRuntimePage,aa as LibrariesResiliencePage,jt as LibrariesProgressiveDeliveryPage,$t as LibrariesPersonalizationPage,Jt as LibrariesOverviewPage,Ht as LibrariesOverlayEnginePage,_t as LibrariesObservabilityPage,Wt as LibrariesMultiTenancyPage,Et as LibrariesGrowthPage,Bt as LibrariesGraphQLPage,It as LibrariesEvolutionPage,Ct as LibrariesDesignSystemPage,yt as LibrariesDataViewsPage,ht as LibrariesDataBackendPage,ut as LibrariesCostTrackingPage,dt as LibrariesContractsPage,rt as LibrariesContentGenPage,tt as LibrariesAnalyticsPage,je as LibrariesAiAgentPage,$e as LibrariesAccessibilityPage};
