{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "error-report-log-model",
  "type": "registry:lib",
  "title": "Error report log (small)",
  "description": "@interlace/ui — the small half of error reporting: a typed report, a flood counted not repeated, the ring of recent reports and the browser handlers. All a first page load needs; no DOM, no network.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "feedback",
    "util"
  ],
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/interlace-ui/lib/error-report-log-model.ts",
      "target": "lib/error-report-log-model.ts",
      "type": "registry:lib",
      "content": "export interface ErrorReport {\n  /** A stable id for this report, from `makeId`; never derived from the message. */\n  id: string;\n  /** Epoch ms from the injected clock. */\n  at: number;\n  /** What the person was doing, chosen by the caller: 'checkout: save', 'uncaught', 'route: /play'. */\n  where: string;\n  /** Redacted, then trimmed to `maxMessage` characters. */\n  message: string;\n  /** Redacted, then trimmed to `maxStackLines` lines. Absent when the thrown value had no stack. */\n  stack?: string;\n  fatal: boolean;\n  /** 1 for a single report; more when the same `where` and `message` repeated within `coalesceMs`. */\n  count: number;\n}\n\nexport type Reporter = (report: ErrorReport) => void;\n\nexport interface ErrorLogOptions {\n  /** How many reports the log keeps. @default 25 */\n  max?: number;\n  /** Characters kept of a message. @default 300 */\n  maxMessage?: number;\n  /** Lines kept of a stack. @default 12 */\n  maxStackLines?: number;\n  /** Repeats of one `where` and `message` inside this window are one report with a count. @default 1000 */\n  coalesceMs?: number;\n  now?: () => number;\n  makeId?: () => string;\n  /** Applied to message and stack before anything is kept or reported. The app's redaction hook. */\n  redact?: (text: string) => string;\n}\n\n/**\n * The part of a log the first load needs: build a report, keep it, tell the reporter. It also\n * carries what the rest is built from (`extendErrorLog` in `error-report-model` adds `restore`,\n * `subscribe` and `clear`), so those are not in the first load's bytes.\n */\nexport interface ErrorLogCore {\n  /** Builds a report, keeps it, tells the reporter. Never throws. Returns the kept report, or\n   * `undefined` when it was dropped (a reporter that reported from inside itself). */\n  report(error: unknown, where: string, fatal?: boolean): ErrorReport | undefined;\n  /** Oldest first. The same array until something changes, so it can feed `useSyncExternalStore`. */\n  recent(): readonly ErrorReport[];\n  /** `null` restores the development logger. */\n  setReporter(next: Reporter | null): void;\n  /** Swap the kept rows for `next`, then call `onChange`. The one way `restore` and `clear` write. */\n  replace(next: readonly ErrorReport[]): void;\n  /** Called after every report and every `replace`. Set by whatever wants to hear a change. */\n  onChange: (() => void) | undefined;\n  /** What the log was made with, for the features built on it. */\n  readonly settings: CoreSettings;\n}\n\n/** Everything the small log needs, with no defaults of its own: the caller says all of it. */\nexport interface CoreSettings {\n  /** How many reports are kept. */\n  max: number;\n  /** Repeats of one `where` and `message` inside this window are one report with a count. */\n  coalesceMs: number;\n  now: () => number;\n  makeId: () => string;\n  /** Turns what was thrown into a report: `buildReport` with limits, or `toReport` with redaction. */\n  build: (error: unknown, where: string, fatal: boolean, meta: { id: string; at: number }) => ErrorReport;\n}\n\nexport interface ErrorLog {\n  /** Builds a report, keeps it, tells the reporter. Never throws. Returns the kept report, or\n   * `undefined` when it was dropped (a reporter that reported from inside itself). */\n  report(error: unknown, where: string, fatal?: boolean): ErrorReport | undefined;\n  /** Oldest first. The same array until something changes, so it can feed `useSyncExternalStore`. */\n  recent(): readonly ErrorReport[];\n  /** Validated; rows already in the log (by id) are skipped; kept ones go in front. */\n  restore(earlier: readonly unknown[]): void;\n  /** `null` restores the development logger. */\n  setReporter(next: Reporter | null): void;\n  subscribe(listener: () => void): () => void;\n  clear(): void;\n}\n\nexport const DEFAULT_MAX = 25;\nexport const DEFAULT_MAX_MESSAGE = 300;\nexport const DEFAULT_MAX_STACK_LINES = 12;\nexport const DEFAULT_COALESCE_MS = 1000;\nexport const UNPRINTABLE = '[unprintable error]';\nexport const ELLIPSIS = '…';\n\ndeclare const __DEV__: boolean | undefined;\n// Bundlers replace `process.env.NODE_ENV` at build time; this only types it, with no @types/node.\ndeclare const process: { env: { NODE_ENV?: string } } | undefined;\n\n/** React Native sets `__DEV__`; on the web a bundler sets `process.env.NODE_ENV`. */\nexport function isDevelopment(): boolean {\n  if (typeof __DEV__ !== 'undefined') return Boolean(__DEV__);\n  return typeof process !== 'undefined' && process.env.NODE_ENV !== 'production';\n}\n\n/** The only default reporter: one console line in development, nothing in production. */\nexport const developmentReporter: Reporter = (report) => {\n  if (isDevelopment()) console.warn(`[${report.where}] ${report.message}`);\n};\n\nlet idCounter = 0;\n/** A short random id. Never derived from the message. */\nexport function defaultMakeId(): string {\n  idCounter += 1;\n  return Math.floor(Math.random() * 36 ** 6)\n    .toString(36)\n    .padStart(6, '0')\n    .concat(idCounter.toString(36));\n}\n\n/** Keep at most `max` characters, the last one an ellipsis when something was cut. */\nexport function trimMessage(text: string, max: number): string {\n  if (text.length <= max) return text;\n  return text.slice(0, Math.max(0, max - ELLIPSIS.length)) + ELLIPSIS;\n}\n\n/** Keep the first `maxLines` lines. */\nexport function trimStack(text: string, maxLines: number): string {\n  return text.split('\\n').slice(0, maxLines).join('\\n');\n}\n\nfunction printable(value: unknown): string {\n  try {\n    return String(value);\n  } catch {\n    return UNPRINTABLE;\n  }\n}\n\n/** What `buildReport` cuts to, and the one thing it may call first. */\nexport interface Limits {\n  maxMessage: number;\n  maxStackLines: number;\n  /** Must not throw: `toReport` in `error-report-model` is the one that guards the app's own. */\n  redact?: (text: string) => string;\n}\n\n/** What was thrown, as a message and an optional stack. Anything at all can be thrown. */\nexport function buildReport(\n  error: unknown,\n  where: string,\n  fatal: boolean,\n  meta: { id: string; at: number },\n  limits: Limits,\n): ErrorReport {\n  const redact = limits.redact ?? ((text: string) => text);\n  const isError = error instanceof Error;\n  // Redact the whole text first, then cut: a secret split by the cut would escape the pattern.\n  const message = trimMessage(redact(printable(isError ? error.message : error)), limits.maxMessage);\n  const report: ErrorReport = { id: meta.id, at: meta.at, where, message, fatal, count: 1 };\n  if (isError && typeof error.stack === 'string' && error.stack !== '') {\n    report.stack = trimStack(redact(error.stack), limits.maxStackLines);\n  }\n  return report;\n}\n\n/** The limits the module's own log is built with. */\nexport const DEFAULT_LIMITS: Limits = {\n  maxMessage: DEFAULT_MAX_MESSAGE,\n  maxStackLines: DEFAULT_MAX_STACK_LINES,\n};\n\n/** The small log: what the first load needs, and the seams the other features are built on. */\nexport function createCoreLog(settings: CoreSettings): ErrorLogCore {\n  const { max, coalesceMs, now, makeId, build } = settings;\n  let reports: readonly ErrorReport[] = [];\n  let reporter: Reporter = developmentReporter;\n  let reporting = false;\n\n  const core: ErrorLogCore = {\n    onChange: undefined,\n    settings,\n    report(error, where, fatal = false) {\n      // A reporter that reports from inside itself is dropped: a reporter bug cannot loop.\n      if (reporting) return undefined;\n      try {\n        const at = now();\n        const built = build(error, where, fatal, { id: makeId(), at });\n        const newest = reports[reports.length - 1];\n        let kept: ErrorReport;\n        if (\n          newest !== undefined &&\n          newest.where === built.where &&\n          newest.message === built.message &&\n          at - newest.at <= coalesceMs\n        ) {\n          kept = { ...newest, at, count: newest.count + 1, fatal: newest.fatal || built.fatal };\n          reports = [...reports.slice(0, -1), kept];\n        } else {\n          kept = built;\n          reports = [...reports, built].slice(-max);\n        }\n        reporting = true;\n        try {\n          reporter(kept);\n        } catch {\n          // Reporting must never become the next crash.\n        } finally {\n          reporting = false;\n        }\n        core.onChange?.();\n        return kept;\n      } catch {\n        // A clock or an id maker that throws: the report is lost, the app is not.\n      }\n      return undefined;\n    },\n    recent: () => reports,\n    setReporter(next) {\n      reporter = next ?? developmentReporter;\n    },\n    replace(next) {\n      reports = next;\n      core.onChange?.();\n    },\n  };\n  return core;\n}\n\n/** The slice of an event target the browser handlers need (a `Window`, or a test's fake). */\nexport type GlobalEventTarget = Pick<Window, 'addEventListener' | 'removeEventListener'>;\n\ninterface ErrorEventLike {\n  error?: unknown;\n  message?: unknown;\n}\ninterface RejectionEventLike {\n  reason?: unknown;\n}\n\nconst installed = new WeakMap<object, () => void>();\n\n/**\n * Report `error` and `unhandledrejection` on `target`. Idempotent per target; returns the remover.\n * It never calls `preventDefault`, so the browser console still logs.\n */\nexport function attachGlobalHandlers(\n  target: GlobalEventTarget,\n  log: Pick<ErrorLogCore, 'report'>,\n): () => void {\n  const existing = installed.get(target);\n  if (existing) return existing;\n  const onError = (event: ErrorEventLike) => {\n    log.report(event.error ?? event.message, 'uncaught', false);\n  };\n  const onRejection = (event: RejectionEventLike) => {\n    log.report(event.reason, 'unhandled rejection', false);\n  };\n  target.addEventListener('error', onError as EventListener);\n  target.addEventListener('unhandledrejection', onRejection as EventListener);\n  const remove = () => {\n    target.removeEventListener('error', onError as EventListener);\n    target.removeEventListener('unhandledrejection', onRejection as EventListener);\n    installed.delete(target);\n  };\n  installed.set(target, remove);\n  return remove;\n}\n\n/**\n * @interlace/ui: the small half of error reporting, as pure functions: what a report holds, how a\n * flood of the same failure becomes one row with a count, how rows are kept and trimmed, and the\n * browser's two handlers. This is all the first page load needs (`reportError` and\n * `installGlobalHandlers`), so it holds nothing else: no listeners, no restore-from-storage rules,\n * no text formatting, no fallback copy. Those live in `error-report-model`, which a page imports\n * only where it uses them. No DOM, no React, no storage library, no network: the clock, the id maker\n * and the event target are all passed in.\n *\n * ## What a report holds, and what it never holds\n *\n * | Holds                                                      | Never holds                        |\n * | ---------------------------------------------------------- | ---------------------------------- |\n * | `where`: a place the developer named ('checkout: save')   | props, state, storage contents     |\n * | `message` and `stack`, redacted, then trimmed to a limit   | the URL's query string or hash     |\n * | a time, a count, a random id, whether it was fatal         | a name, an email, a device id      |\n *\n * Nothing here sends anything. The default reporter writes one development line to the console\n * and does nothing in production; a crash service is one `setReporter` call.\n */\n\n/** One caught failure, as the log keeps it and a reporter receives it. */\n\n// @interlace/error-report-log-model v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/error-report-log-model\n// What changed since: https://ds.interlace.tools/c/error-report-log-model#history\n// Generated banner — keep it, the upgrade diff reads this version.\n"
    }
  ],
  "meta": {
    "tier": "util",
    "client": false,
    "minViewport": null,
    "loading": false,
    "version": "1.0.0",
    "since": "2.4.0"
  },
  "docs": "## @interlace/error-report-log-model\n\nInstalled to `lib/error-report-log-model.ts`.\n\n```tsx\nimport { /* … */ } from '@/lib/error-report-log-model';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/error-report-log-model"
}
