{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "duel",
  "type": "registry:ui",
  "title": "Duel",
  "description": "Two players, one game, by link. The first player finishes and sends a challenge (`DuelInvite`); the second opens it and sees who they are up against (`DuelCard`); after playing the same game, both see the rounds side by side (`DuelCompare`). The challenge…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/celebrate.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/motion-token.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/duel.tsx",
      "target": "components/ui/games/duel.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/duel v1.0.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/duel\n// What changed since: https://ds.interlace.tools/c/duel#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Duel: DuelInvite, DuelCard, DuelCompare\n *\n * Two players, one game, by link. The first player finishes and sends a\n * challenge (`DuelInvite`); the second opens it and sees who they are up\n * against (`DuelCard`); after playing the same game, both see the rounds\n * side by side (`DuelCompare`). The challenge lives in the link\n * (`games/duel-model`: `encodeDuel`, `decodeDuel`, `duelHref`), and the\n * comparison is pure (`compareDuel`), so a server shows the same result.\n *\n * ## Anatomy\n *\n *   DuelInvite                     (div — data-slot=\"duel-invite\")\n *     ├─ p                         (data-slot=\"duel-invite-title\")\n *     ├─ div                       (data-slot=\"duel-invite-actions\": Send (Web Share) and Copy link)\n *     └─ span aria-live            (data-slot=\"duel-invite-status\")\n *\n *   DuelCard                       (section — data-slot=\"duel-card\")\n *     ├─ h2                        (data-slot=\"duel-card-title\": \"Avery challenged you\")\n *     ├─ p                         (data-slot=\"duel-card-score\": \"4,200 points to beat.\")\n *     └─ Button                    (data-slot=\"duel-card-accept\")\n *\n *   DuelCompare                    (section — data-slot=\"duel-compare\", data-winner=a|b|tie)\n *     ├─ p                         (data-slot=\"duel-compare-verdict\": \"You won by 120 points.\")\n *     ├─ div                       (data-slot=\"duel-compare-players\": a | vs | b, totals, rounds won)\n *     └─ table                     (data-slot=\"duel-compare-rounds\": a row per round,\n *                                   each side's points and a bar growing out from the middle)\n *\n * ## Words first\n *\n * Who won, by how much, and who took each round are words: the verdict, a\n * \"Won\" tag on the winner, and the winner's cell in each row says so for a\n * screen reader. Bars and weight repeat it for the eye.\n *\n * ## Motion\n *\n * The bars grow out from the middle, 40ms apart (transform only), and a\n * Celebrate burst marks the viewer's win. Under reduced motion they are\n * simply there.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                    |\n * | ---- | ------------------------- | ----------------------------------------------------- |\n * | R4   | Extends native el         | `div` / `section` props                               |\n * | R6   | data-slot per part        | duel-invite-*, duel-card-*, duel-compare-*            |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                     |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                  |\n * | R19  | Tokens only               | primary, muted, border                                |\n * | R26  | A11y                      | verdict in words; captioned table with row headers    |\n */\n\nimport { Copy, Share2, Swords } from 'lucide-react';\n\nimport { Celebrate } from '@/components/ui/effects/celebrate';\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { motionDuration, motionEase } from '@/lib/motion-token';\nimport { Button } from '@/components/ui/button';\nimport { compareDuel, type DuelPlayer, type DuelSide } from '@/components/ui/games/duel-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\n\n// --- DuelInvite -------------------------------------------------------------------\n\ninterface DuelInviteLabels {\n  /** @default 'Challenge a friend to the same game' */\n  title?: string;\n  /** @default 'Send a challenge' */\n  share?: string;\n  /** @default 'Copy link' */\n  copy?: string;\n  /** Name of the link field shown when copying fails. @default 'Challenge link' */\n  field?: string;\n  /** @default 'Link copied.' */\n  copied?: string;\n  /** @default 'Copy failed. Select the link and copy it.' */\n  copyFailed?: string;\n}\n\ntype DuelInviteProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  /** The challenge link, e.g. `duelHref(location.href, encodeDuel(challenge))`. */\n  href: string;\n  /** The message that travels with the link. */\n  message?: string;\n  /** How it went out. */\n  onShare?: (method: 'share' | 'copy') => void;\n  labels?: DuelInviteLabels;\n};\n\nfunction DuelInvite({ href, message, onShare, labels, className, ...props }: DuelInviteProps) {\n  const [canShare, setCanShare] = React.useState(false);\n  const [status, setStatus] = React.useState('');\n  const [failed, setFailed] = React.useState(false);\n  const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined);\n  React.useEffect(() => {\n    setCanShare(typeof navigator !== 'undefined' && typeof navigator.share === 'function');\n    return () => clearTimeout(timer.current);\n  }, []);\n\n  // Clear, then set a moment later, so a second copy is announced again.\n  const announce = (text: string) => {\n    setStatus('');\n    clearTimeout(timer.current);\n    timer.current = setTimeout(() => setStatus(text), 50);\n  };\n\n  const copy = async () => {\n    try {\n      await navigator.clipboard.writeText(message ? `${message} ${href}` : href);\n      setFailed(false);\n      announce(labels?.copied ?? 'Link copied.');\n      onShare?.('copy');\n    } catch {\n      setFailed(true);\n      announce(labels?.copyFailed ?? 'Copy failed. Select the link and copy it.');\n    }\n  };\n\n  const share = async () => {\n    try {\n      await navigator.share(message ? { text: message, url: href } : { url: href });\n      onShare?.('share');\n    } catch (error) {\n      // Closed the sheet: nothing to say. Anything else: copy instead.\n      if ((error as Error)?.name !== 'AbortError') await copy();\n    }\n  };\n\n  return (\n    <div\n      data-slot=\"duel-invite\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('border-border bg-card text-card-foreground grid gap-3 rounded-xl border p-5', className)}\n      {...props}\n    >\n      <p data-slot=\"duel-invite-title\" className=\"font-heading flex items-center gap-2 font-semibold\">\n        <Swords aria-hidden className=\"text-primary size-5 shrink-0\" />\n        {labels?.title ?? 'Challenge a friend to the same game'}\n      </p>\n      <div data-slot=\"duel-invite-actions\" className=\"flex flex-wrap gap-2\">\n        {canShare ? (\n          <Button type=\"button\" onClick={share}>\n            <Share2 aria-hidden />\n            {labels?.share ?? 'Send a challenge'}\n          </Button>\n        ) : null}\n        <Button type=\"button\" variant={canShare ? 'outline' : 'default'} onClick={copy}>\n          <Copy aria-hidden />\n          {labels?.copy ?? 'Copy link'}\n        </Button>\n      </div>\n      {failed ? (\n        <input\n          readOnly\n          value={href}\n          aria-label={labels?.field ?? 'Challenge link'}\n          onFocus={(e) => e.currentTarget.select()}\n          className=\"border-input bg-background w-full rounded-lg border px-3 py-2 text-sm\"\n        />\n      ) : null}\n      <span data-slot=\"duel-invite-status\" aria-live=\"polite\" className=\"sr-only\">\n        {status}\n      </span>\n    </div>\n  );\n}\nDuelInvite.displayName = 'DuelInvite';\n\n// --- DuelCard -------------------------------------------------------------------\n\ninterface DuelCardLabels {\n  /** @default (name) => `${name} challenged you` */\n  title?: (name: string) => string;\n  /** @default (score) => `${score} points to beat.` */\n  score?: (score: string) => string;\n  /** @default 'Play the same game' */\n  accept?: string;\n}\n\ntype DuelCardProps = Omit<React.ComponentProps<'section'>, 'children'> & {\n  /** Who sent it. */\n  name: string;\n  /** Their score. */\n  score: number;\n  /** Starts the game. Leave out to show no button. */\n  onAccept?: () => void;\n  /** Under the score: what the game is, how long it takes. */\n  description?: React.ReactNode;\n  format?: Intl.NumberFormatOptions;\n  locale?: string;\n  labels?: DuelCardLabels;\n};\n\nfunction DuelCard({ name, score, onAccept, description, format, locale, labels, className, ...props }: DuelCardProps) {\n  const headingId = React.useId();\n  const nf = new Intl.NumberFormat(locale, format);\n  return (\n    <section\n      data-slot=\"duel-card\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      aria-labelledby={headingId}\n      className={cn(\n        'border-border bg-card text-card-foreground grid justify-items-start gap-3 rounded-xl border p-5',\n        className,\n      )}\n      {...props}\n    >\n      <Swords aria-hidden className=\"text-primary size-6\" />\n      <h2 id={headingId} data-slot=\"duel-card-title\" className=\"font-heading text-xl font-semibold\">\n        {(labels?.title ?? ((n: string) => `${n} challenged you`))(name)}\n      </h2>\n      <p data-slot=\"duel-card-score\" className=\"text-lg tabular-nums\">\n        {(labels?.score ?? ((s: string) => `${s} points to beat.`))(nf.format(score))}\n      </p>\n      {description ? <div className=\"text-muted-foreground text-sm\">{description}</div> : null}\n      {onAccept ? (\n        <Button data-slot=\"duel-card-accept\" type=\"button\" size=\"lg\" className=\"mt-1\" onClick={onAccept}>\n          {labels?.accept ?? 'Play the same game'}\n        </Button>\n      ) : null}\n    </section>\n  );\n}\nDuelCard.displayName = 'DuelCard';\n\n// --- DuelCompare ----------------------------------------------------------------\n\ninterface DuelCompareLabels {\n  /** The verdict. Gets the winner's name (or null on a tie), the margin and the totals, formatted. */\n  verdict?: (r: { winner: string | null; you: boolean; margin: string; total: string }) => string;\n  /** @default 'vs' */\n  versus?: string;\n  /** On the winner. @default 'Won' */\n  won?: string;\n  /** @default (n) => n === 1 ? '1 round won' : `${n} rounds won` */\n  roundsWon?: (n: number) => string;\n  /** @default (n) => `Round ${n}` */\n  round?: (n: number) => string;\n  /** The rounds column, for assistive tech. @default 'Round' */\n  roundColumn?: string;\n  /** Spoken in the winner's cell. @default 'won the round' */\n  roundWinner?: string;\n  /** For a round a player did not play. @default 'not played' */\n  missing?: string;\n  /** Names the table. @default 'Round by round' */\n  caption?: string;\n}\n\nconst VERDICT: NonNullable<DuelCompareLabels['verdict']> = ({ winner, you, margin, total }) =>\n  winner === null\n    ? `A tie, at ${total} points each.`\n    : you\n      ? `You won by ${margin} points.`\n      : `${winner} won by ${margin} points.`;\n\ntype DuelCompareProps = Omit<React.ComponentProps<'section'>, 'children'> & {\n  /** Usually the challenger. */\n  a: DuelPlayer;\n  /** Usually the viewer. */\n  b: DuelPlayer;\n  /** Which side is the viewer, so the verdict says \"You\". */\n  you?: 'a' | 'b';\n  /** 'asc' when fewer points is better (time, guesses). @default 'desc' */\n  order?: 'desc' | 'asc';\n  /** Grow the bars on mount. @default true */\n  animate?: boolean;\n  format?: Intl.NumberFormatOptions;\n  locale?: string;\n  labels?: DuelCompareLabels;\n};\n\nfunction Bar({ value, max, side, win }: { value: number | null; max: number; side: 'a' | 'b'; win: boolean }) {\n  const pct = value === null || max <= 0 ? 0 : Math.max(0, Math.min(100, (value / max) * 100));\n  return (\n    <span\n      aria-hidden\n      className={cn('flex h-2 w-full @sm:w-auto @sm:flex-1', side === 'a' ? 'justify-end' : 'justify-start')}\n    >\n      <span\n        data-slot=\"duel-compare-bar\"\n        className={cn(\n          'block h-full rounded-full',\n          side === 'a' ? 'origin-right rtl:origin-left' : 'origin-left rtl:origin-right',\n          win ? 'bg-primary' : 'bg-muted-foreground/40',\n        )}\n        style={{ width: `${pct}%` }}\n      />\n    </span>\n  );\n}\n\nfunction DuelCompare({\n  a,\n  b,\n  you,\n  order = 'desc',\n  animate = true,\n  format,\n  locale,\n  labels,\n  className,\n  ...props\n}: DuelCompareProps) {\n  const reduced = useReducedMotion();\n  const ref = React.useRef<HTMLElement>(null);\n  const [cheer, setCheer] = React.useState(0);\n  const result = compareDuel(a, b, { order });\n  const nf = new Intl.NumberFormat(locale, format);\n  const L = labels ?? {};\n  const players = { a, b };\n  const max = Math.max(0, ...result.rounds.flatMap((r) => [r.a ?? 0, r.b ?? 0]));\n  const youWon = you !== undefined && result.winner === you;\n  const fmt = (v: number | null) => (v === null ? (L.missing ?? 'not played') : nf.format(v));\n\n  React.useEffect(() => {\n    if (!animate || reduced) return;\n    const bars = ref.current?.querySelectorAll<HTMLElement>('[data-slot=\"duel-compare-bar\"]') ?? [];\n    const running: Animation[] = [];\n    bars.forEach((bar, i) => {\n      if (typeof bar.animate !== 'function') return;\n      running.push(\n        bar.animate([{ transform: 'scaleX(0)' }, { transform: 'scaleX(1)' }], {\n          duration: motionDuration(bar, 'slow'),\n          delay: Math.floor(i / 2) * 40,\n          easing: motionEase(bar, 'enter'),\n          fill: 'backwards',\n        }),\n      );\n    });\n    // Cheer only when someone celebrates: a late state update with nothing to\n    // show re-renders the result for no reason, mid-way through an a11y scan.\n    const t = youWon\n      ? setTimeout(() => setCheer((c) => c + 1), Math.floor(bars.length / 2) * 40 + 400)\n      : undefined;\n    return () => {\n      clearTimeout(t);\n      running.forEach((r) => r.cancel());\n    };\n    // Once on mount: new a/b values update the bars in place and don't re-animate.\n    // eslint-disable-next-line react-features/hooks-exhaustive-deps -- youWon is read once, like a/b.\n  }, [animate, reduced]);\n\n  const verdict = (L.verdict ?? VERDICT)({\n    winner: result.winner === 'tie' ? null : players[result.winner].name,\n    you: youWon,\n    margin: nf.format(result.margin),\n    total: nf.format(result.totals.a),\n  });\n\n  const head = (side: 'a' | 'b') => {\n    const p = players[side];\n    const won = result.winner === side;\n    const total = <span className=\"text-3xl font-semibold tabular-nums\">{nf.format(result.totals[side])}</span>;\n    return (\n      <div\n        data-slot=\"duel-compare-player\"\n        data-side={side}\n        data-won={won ? '' : undefined}\n        className={cn(\n          'flex min-w-0 flex-col gap-1 rounded-xl border p-3',\n          side === 'a' ? 'items-end text-end' : 'items-start text-start',\n          won ? 'border-primary' : 'border-border',\n        )}\n      >\n        <span\n          className={cn(\n            'flex max-w-full min-w-0 flex-wrap items-center gap-x-2 gap-y-1',\n            side === 'a' ? 'justify-end' : 'justify-start',\n          )}\n        >\n          <span className=\"min-w-0 font-semibold break-words\">{p.name}</span>\n          {won ? (\n            <span className=\"bg-primary text-primary-foreground shrink-0 rounded-full px-2 text-xs leading-5 font-semibold\">\n              {L.won ?? 'Won'}\n            </span>\n          ) : null}\n        </span>\n        {won && youWon ? (\n          <Celebrate play={cheer || null} tone=\"highlight\">\n            {total}\n          </Celebrate>\n        ) : (\n          total\n        )}\n        <span className=\"text-muted-foreground text-xs tabular-nums\">\n          {(L.roundsWon ?? ((n: number) => (n === 1 ? '1 round won' : `${n} rounds won`)))(result.won[side])}\n        </span>\n      </div>\n    );\n  };\n\n  const cell = (side: 'a' | 'b', r: (typeof result.rounds)[number]) => {\n    const value = r[side];\n    const win = r.winner === side;\n    return (\n      <td className={cn('py-2 tabular-nums', side === 'a' ? 'pe-2 text-end' : 'ps-2 text-start')}>\n        <span\n          className={cn(\n            'flex flex-col gap-1 @sm:items-center @sm:gap-2',\n            side === 'a' ? 'items-end @sm:flex-row-reverse' : 'items-start @sm:flex-row',\n            win ? 'font-semibold' : 'text-muted-foreground',\n          )}\n        >\n          <span className=\"shrink-0 @sm:w-14\">{fmt(value)}</span>\n          <Bar value={value} max={max} side={side} win={win} />\n          {win ? <span className=\"sr-only\">{L.roundWinner ?? 'won the round'}</span> : null}\n        </span>\n      </td>\n    );\n  };\n\n  return (\n    <section\n      ref={ref}\n      data-slot=\"duel-compare\"\n      data-winner={result.winner}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('@container grid gap-4', className)}\n      {...props}\n    >\n      <p data-slot=\"duel-compare-verdict\" className=\"font-heading text-center text-xl font-semibold\">\n        {verdict}\n      </p>\n      <div data-slot=\"duel-compare-players\" className=\"grid grid-cols-[1fr_auto_1fr] items-stretch gap-2\">\n        {head('a')}\n        <span className=\"text-muted-foreground self-center text-sm\">{L.versus ?? 'vs'}</span>\n        {head('b')}\n      </div>\n      {result.rounds.length ? (\n        <table data-slot=\"duel-compare-rounds\" className=\"w-full table-fixed border-collapse text-sm\">\n          <caption className=\"sr-only\">{L.caption ?? 'Round by round'}</caption>\n          <colgroup>\n            <col />\n            <col className=\"w-20\" />\n            <col />\n          </colgroup>\n          <thead className=\"sr-only\">\n            <tr>\n              <th scope=\"col\">{a.name}</th>\n              <th scope=\"col\">{L.roundColumn ?? 'Round'}</th>\n              <th scope=\"col\">{b.name}</th>\n            </tr>\n          </thead>\n          <tbody>\n            {result.rounds.map((r) => (\n              <tr key={r.round} data-winner={r.winner} className=\"border-border border-t first:border-t-0\">\n                {cell('a', r)}\n                <th scope=\"row\" className=\"text-muted-foreground py-2 text-center text-xs font-normal\">\n                  {(L.round ?? ((n: number) => `Round ${n}`))(r.round)}\n                </th>\n                {cell('b', r)}\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      ) : null}\n    </section>\n  );\n}\nDuelCompare.displayName = 'DuelCompare';\n\nexport { DuelInvite, DuelCard, DuelCompare };\nexport type { DuelInviteProps, DuelInviteLabels, DuelCardProps, DuelCardLabels, DuelCompareProps, DuelCompareLabels };\nexport type { DuelSide };\n"
    },
    {
      "path": "registry/interlace-ui/games/duel-model.ts",
      "target": "components/ui/games/duel-model.ts",
      "type": "registry:ui",
      "content": "export interface DuelPlayer {\n  /** Display name, as the player typed it. */\n  name: string;\n  /** Points per round, in order. */\n  rounds: number[];\n}\n\nexport interface DuelChallenge {\n  /** Format version. */\n  v: 1;\n  /** Which game, e.g. \"closer\". */\n  game: string;\n  /** What makes the second game the same as the first: a seed, a day key, a puzzle id. */\n  seed: string;\n  /** The player who sends the challenge. */\n  from: DuelPlayer;\n  /** When it was played, in ms. */\n  at?: number;\n  /** An optional server signature, carried and never checked here. */\n  sig?: string;\n}\n\nexport const DUEL_LIMITS = {\n  game: 40,\n  seed: 80,\n  name: 24,\n  rounds: 50,\n  /** The most points (either sign) one round may carry: 50 of them still sum to a finite total. */\n  points: 1e9,\n  sig: 200,\n  token: 4096,\n} as const;\n\n// --- base64url over UTF-8, without Buffer, so it runs in any runtime ---------------\n\nconst B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\n\nfunction toBase64Url(bytes: Uint8Array): string {\n  let out = '';\n  for (let i = 0; i < bytes.length; i += 3) {\n    const n = (bytes[i]! << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);\n    const chars = [B64[(n >>> 18) & 63], B64[(n >>> 12) & 63], B64[(n >>> 6) & 63], B64[n & 63]];\n    out += chars.slice(0, Math.min(4, bytes.length - i + 1)).join('');\n  }\n  return out;\n}\n\nfunction fromBase64Url(text: string): Uint8Array | null {\n  if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return null;\n  const bytes: number[] = [];\n  for (let i = 0; i < text.length; i += 4) {\n    const chunk = text.slice(i, i + 4);\n    let n = 0;\n    for (let j = 0; j < 4; j++) n = (n << 6) | (j < chunk.length ? B64.indexOf(chunk[j]!) : 0);\n    bytes.push((n >>> 16) & 255);\n    if (chunk.length > 2) bytes.push((n >>> 8) & 255);\n    if (chunk.length > 3) bytes.push(n & 255);\n  }\n  return new Uint8Array(bytes);\n}\n\n// --- Encode / decode ------------------------------------------------------------\n\nconst clip = (s: string, max: number) => Array.from(s.trim()).slice(0, max).join('');\n\n/** A challenge, cleaned to the limits: what `encodeDuel` writes and `decodeDuel` returns. */\nfunction clean(input: unknown): DuelChallenge | null {\n  if (!input || typeof input !== 'object') return null;\n  const o = input as Record<string, unknown>;\n  const from = o.from as Record<string, unknown> | undefined;\n  if (o.v !== 1 || typeof o.game !== 'string' || typeof o.seed !== 'string') return null;\n  if (!from || typeof from !== 'object' || typeof from.name !== 'string' || !Array.isArray(from.rounds)) return null;\n  if (from.rounds.length > DUEL_LIMITS.rounds) return null;\n  if (!from.rounds.every((r) => typeof r === 'number' && Math.abs(r) <= DUEL_LIMITS.points)) return null;\n  const game = clip(o.game, DUEL_LIMITS.game);\n  const name = clip(from.name, DUEL_LIMITS.name);\n  if (!game || !name) return null;\n  const out: DuelChallenge = {\n    v: 1,\n    game,\n    seed: clip(o.seed, DUEL_LIMITS.seed),\n    from: { name, rounds: (from.rounds as number[]).slice() },\n  };\n  if (typeof o.at === 'number' && Number.isFinite(o.at)) out.at = o.at;\n  if (typeof o.sig === 'string' && o.sig) out.sig = clip(o.sig, DUEL_LIMITS.sig);\n  return out;\n}\n\n/** The challenge as a URL-safe token. Throws a TypeError for an invalid challenge. */\nexport function encodeDuel(challenge: DuelChallenge): string {\n  const c = clean(challenge);\n  if (!c) throw new TypeError('Not a valid duel challenge.');\n  return toBase64Url(new TextEncoder().encode(JSON.stringify(c)));\n}\n\n/** The challenge in a token, or null when the token is missing, too long or malformed. */\nexport function decodeDuel(token: string | null | undefined): DuelChallenge | null {\n  if (!token || token.length > DUEL_LIMITS.token) return null;\n  const bytes = fromBase64Url(token);\n  if (!bytes) return null;\n  try {\n    return clean(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));\n  } catch {\n    return null;\n  }\n}\n\n/** `base` with the token in its query (`?duel=…` by default), keeping what is there. */\nexport function duelHref(base: string, token: string, param = 'duel'): string {\n  const [path, hash = ''] = base.split('#');\n  const sep = path!.includes('?') ? '&' : '?';\n  return `${path}${sep}${encodeURIComponent(param)}=${encodeURIComponent(token)}${hash ? `#${hash}` : ''}`;\n}\n\n// --- Compare ----------------------------------------------------------------------\n\nexport type DuelSide = 'a' | 'b' | 'tie';\n\nexport interface DuelRoundResult {\n  /** 1-based. */\n  round: number;\n  /** Points, or null when that player has no such round. */\n  a: number | null;\n  b: number | null;\n  winner: DuelSide;\n}\n\nexport interface DuelResult {\n  rounds: DuelRoundResult[];\n  totals: { a: number; b: number };\n  /** Rounds each side won. */\n  won: { a: number; b: number };\n  winner: DuelSide;\n  /** How far ahead the winner is; 0 on a tie. */\n  margin: number;\n}\n\nconst sum = (xs: readonly number[]) => xs.reduce((t, x) => t + x, 0);\n\n/**\n * Both players' rounds side by side. The winner is the higher total\n * (`order: 'asc'` for games where less is better, like time); a round with\n * a missing side goes to the side that played it.\n */\nexport function compareDuel(\n  a: Pick<DuelPlayer, 'rounds'>,\n  b: Pick<DuelPlayer, 'rounds'>,\n  options: { order?: 'desc' | 'asc' } = {},\n): DuelResult {\n  const better = options.order === 'asc' ? -1 : 1;\n  const pick = (x: number, y: number): DuelSide => (x === y ? 'tie' : (x - y) * better > 0 ? 'a' : 'b');\n  const n = Math.max(a.rounds.length, b.rounds.length);\n  const rounds: DuelRoundResult[] = [];\n  const won = { a: 0, b: 0 };\n  for (let i = 0; i < n; i++) {\n    const ra = i < a.rounds.length ? a.rounds[i]! : null;\n    const rb = i < b.rounds.length ? b.rounds[i]! : null;\n    const winner: DuelSide = ra === null ? 'b' : rb === null ? 'a' : pick(ra, rb);\n    if (winner !== 'tie') won[winner]++;\n    rounds.push({ round: i + 1, a: ra, b: rb, winner });\n  }\n  const totals = { a: sum(a.rounds), b: sum(b.rounds) };\n  const winner = pick(totals.a, totals.b);\n  return { rounds, totals, won, winner, margin: Math.abs(totals.a - totals.b) };\n}\n\n/**\n * @interlace/ui — games/duel-model\n *\n * Two players, one game, no accounts and no server round: the first player\n * plays, sends a link, and the second plays the same game (same seed, same\n * questions) and sees both results side by side. The challenge travels in\n * the link itself as a short base64url token.\n *\n *   encodeDuel(challenge) → \"eyJ2IjoxLC…\"   (put it in ?duel=…)\n *   decodeDuel(token)     → the challenge, or null for anything malformed\n *   compareDuel(a, b)     → per-round winners, totals, the winner and margin\n *\n * ## Trust\n *\n * A link is a friendly claim, not a proof: anyone can edit the score in it.\n * That is fine between friends. Where it matters (a prize, a public board),\n * store the challenge on a server and put its id in the link, or pass a\n * server signature in `sig`; this model carries it and never checks it.\n *\n * `decodeDuel` treats the token as untrusted input: it caps every length,\n * drops what it does not know, and returns null rather than throwing.\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.1",
    "since": "2.0.0"
  },
  "docs": "## @interlace/duel\n\nInstalled to `components/ui/games/duel.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/duel';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/duel\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
