{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "error-report-model",
  "type": "registry:lib",
  "title": "Error report rules",
  "description": "@interlace/ui — the pure rules of error reporting: a typed report, a flood counted not repeated, a redaction hook, restore from untrusted storage, text for a diagnostics screen. No DOM, no network, no storage library.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "feedback",
    "util"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/error-report-core.json",
    "https://ds.interlace.tools/r/error-report-log-model.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/lib/error-report-model.ts",
      "target": "lib/error-report-model.ts",
      "type": "registry:lib",
      "content": "import {\n  DEFAULT_COALESCE_MS,\n  DEFAULT_MAX,\n  DEFAULT_MAX_MESSAGE,\n  DEFAULT_MAX_STACK_LINES,\n  buildReport,\n  createCoreLog,\n  defaultMakeId,\n  trimMessage,\n  trimStack,\n  type ErrorLog,\n  type ErrorLogCore,\n  type ErrorLogOptions,\n  type ErrorReport,\n  type Limits,\n} from '@/lib/error-report-log-model';\n\n// @interlace/error-report-model v1.0.2 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/error-report-model\n// What changed since: https://ds.interlace.tools/c/error-report-model#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui: the rest of the rules of error reporting, as pure functions: the log's\n * listeners, `restore` and `clear` (`extendErrorLog`), rows restored from untrusted storage, the\n * device log (`installErrorLog`), the text of a diagnostics screen (`formatReports`),\n * `wrapNativeHandler` for React Native and the copy of `ErrorFallback`. The small half, which the\n * first page load needs (the report, the log, the browser handlers), is in\n * `error-report-log-model`; this file re-exports it, so every old import still works. A page\n * imports this file only where it listens, restores, formats or shows a fallback, so the first\n * load does not carry any of it. `@interlace/native` imports this file, it does not copy it.\n *\n * See `error-report-log-model` for what a report holds and what it never holds. Nothing here\n * sends anything.\n */\n\nimport { coreErrorLog } from '@/lib/error-report-core';\n\nexport * from '@/lib/error-report-log-model';\n\nexport const REDACTION_FAILED = '[redaction failed]';\n\n/** The app's own `redact` can throw; what it was given is then replaced, never passed on. */\nfunction guardRedact(redact: Limits['redact']): Limits['redact'] {\n  if (!redact) return undefined;\n  return (text) => {\n    try {\n      return String(redact(text));\n    } catch {\n      return REDACTION_FAILED;\n    }\n  };\n}\n\n/** `buildReport`, with the app's `redact` contained: a redactor that throws costs the text, not the report. */\nexport function toReport(\n  error: unknown,\n  where: string,\n  fatal: boolean,\n  meta: { id: string; at: number },\n  limits: Limits,\n): ErrorReport {\n  return buildReport(error, where, fatal, meta, { ...limits, redact: guardRedact(limits.redact) });\n}\n\n/**\n * Rows from storage are untrusted. A row needs a finite numeric `at`, a string `where` and\n * `message`, and a boolean `fatal`; the rest is repaired (`count` 1, a fresh id) or dropped.\n */\nexport function parseReports(\n  rows: unknown,\n  makeId: () => string,\n  limits: Pick<ErrorLogOptions, 'maxMessage' | 'maxStackLines'> = {},\n): ErrorReport[] {\n  if (!Array.isArray(rows)) return [];\n  const maxMessage = limits.maxMessage ?? DEFAULT_MAX_MESSAGE;\n  const maxStackLines = limits.maxStackLines ?? DEFAULT_MAX_STACK_LINES;\n  const kept: ErrorReport[] = [];\n  for (const row of rows as unknown[]) {\n    // A row that is not an object has no `at`, `where` or `message` of its own and is dropped below.\n    const r = (row ?? {}) as Record<string, unknown>;\n    if (!Number.isFinite(r.at)) continue;\n    if (typeof r.where !== 'string' || typeof r.message !== 'string') continue;\n    if (typeof r.fatal !== 'boolean') continue;\n    const report: ErrorReport = {\n      id: typeof r.id === 'string' && r.id !== '' ? r.id : makeId(),\n      at: r.at as number,\n      where: r.where,\n      message: trimMessage(r.message, maxMessage),\n      fatal: r.fatal,\n      count: Number.isInteger(r.count) ? Math.max(1, r.count as number) : 1,\n    };\n    if (typeof r.stack === 'string' && r.stack !== '') {\n      report.stack = trimStack(r.stack, maxStackLines);\n    }\n    kept.push(report);\n  }\n  return kept;\n}\n\n/**\n * The whole log over a small one: adds the listeners (`subscribe`), `restore` and `clear`.\n * Restored rows are untrusted and go through `parseReports`. `core.onChange` is taken, so a core\n * is extended once.\n */\nexport function extendErrorLog(\n  core: ErrorLogCore,\n  limits: Pick<ErrorLogOptions, 'maxMessage' | 'maxStackLines'> = {},\n): ErrorLog {\n  const { max, makeId } = core.settings;\n  const listeners = new Set<() => void>();\n  core.onChange = () => {\n    for (const listener of [...listeners]) {\n      try {\n        listener();\n      } catch {\n        // A listener's bug is not a reason to lose the report that woke it.\n      }\n    }\n  };\n  return {\n    report: core.report,\n    recent: core.recent,\n    setReporter: core.setReporter,\n    restore(earlier) {\n      const known = new Set(core.recent().map((r) => r.id));\n      const fresh = parseReports(earlier, makeId, limits).filter((r) => !known.has(r.id));\n      core.replace([...fresh, ...core.recent()].slice(-max));\n    },\n    subscribe(listener) {\n      listeners.add(listener);\n      return () => {\n        listeners.delete(listener);\n      };\n    },\n    clear() {\n      core.replace([]);\n    },\n  };\n}\n\n/** The log, with its own state. The module-level functions in `error-report.ts` wrap one of these. */\nexport function createErrorLog(options: ErrorLogOptions = {}): ErrorLog {\n  const limits: Limits = {\n    maxMessage: options.maxMessage ?? DEFAULT_MAX_MESSAGE,\n    maxStackLines: options.maxStackLines ?? DEFAULT_MAX_STACK_LINES,\n    redact: options.redact,\n  };\n  return extendErrorLog(\n    createCoreLog({\n      max: options.max ?? DEFAULT_MAX,\n      coalesceMs: options.coalesceMs ?? DEFAULT_COALESCE_MS,\n      now: options.now ?? Date.now,\n      makeId: options.makeId ?? defaultMakeId,\n      build: (error, where, fatal, meta) => toReport(error, where, fatal, meta, limits),\n    }),\n    limits,\n  );\n}\n\n/** The module's own full log: the same reports as `reportError`, with listeners and restore. */\nexport const defaultErrorLog: ErrorLog = /* @__PURE__ */ extendErrorLog(coreErrorLog);\n\nexport const subscribeErrors: ErrorLog['subscribe'] = (listener) =>\n  defaultErrorLog.subscribe(listener);\nexport const restoreRecent: ErrorLog['restore'] = (earlier) => defaultErrorLog.restore(earlier);\n\n/** Reports kept on the device. `load` returns what was saved; anything it returns is untrusted. */\nexport interface ErrorStore {\n  load(): unknown | null | Promise<unknown | null>;\n  save(reports: readonly ErrorReport[]): void | Promise<void>;\n}\n\nconst persistence = new WeakMap<ErrorLog, { off?: () => void }>();\n\n/**\n * Keep the log (the default one unless you pass another) on the device. Loads what an earlier session saved, restores it (so a diagnostics\n * screen reads earlier sessions first), then saves after every change. A `load` or `save` that\n * throws or rejects is swallowed: failing to store an error must not report an error.\n *\n * It listens to the log; it does not take the reporter, so a crash service's `setReporter` and\n * the device log work together. Installing again on the same log replaces the first install.\n */\nexport async function installErrorLog(\n  store: ErrorStore,\n  log: ErrorLog = defaultErrorLog,\n): Promise<void> {\n  persistence.get(log)?.off?.();\n  const entry: { off?: () => void } = {};\n  persistence.set(log, entry);\n  let earlier: unknown = null;\n  try {\n    earlier = await store.load();\n  } catch {\n    // Nothing was kept, or it could not be read: start empty.\n  }\n  if (persistence.get(log) !== entry) return; // a newer install took over while this one waited\n  log.restore(earlier as readonly unknown[]); // untrusted: anything that is not a list restores nothing\n  entry.off = log.subscribe(() => {\n    try {\n      Promise.resolve(store.save(log.recent())).catch(() => undefined);\n    } catch {\n      // Failing to store an error is not an error to report.\n    }\n  });\n}\n\nexport interface ErrorFormatOptions {\n  /** A BCP 47 tag for the time. Defaults to the device's. */\n  locale?: string;\n  /** An IANA zone for the time. Defaults to the device's. */\n  timeZone?: string;\n}\n\n/**\n * Plain text, one line per report, oldest first: `Nov 27, 2026, 10:04 AM  route: /play  Something\n * broke (x3)`. It never includes a stack: a person shares this text.\n */\nexport function formatReports(\n  reports: readonly ErrorReport[],\n  options: ErrorFormatOptions = {},\n): string {\n  const time = new Intl.DateTimeFormat(options.locale, {\n    dateStyle: 'medium',\n    timeStyle: 'short',\n    timeZone: options.timeZone,\n  });\n  return reports\n    .map((r) => {\n      const message = r.message.replace(/\\s+/g, ' ').trim();\n      const count = r.count > 1 ? ` (x${r.count})` : '';\n      return `${time.format(r.at)}  ${r.where}  ${message}${count}`;\n    })\n    .join('\\n');\n}\n\ntype NativeHandler = (error: unknown, isFatal?: boolean) => void;\n\n/** React Native's `ErrorUtils`, as far as this needs it. */\nexport interface ErrorUtilsLike {\n  getGlobalHandler?: () => NativeHandler | undefined;\n  setGlobalHandler: (handler: NativeHandler) => void;\n}\n\nconst wrapped = new WeakSet<object>();\n\n/**\n * Route uncaught JS errors through `log`, then to the platform's own handler with the same\n * arguments, so the red screen in development and the crash in production still happen.\n * Idempotent. Without `utils` it does nothing.\n */\nexport function wrapNativeHandler(utils: ErrorUtilsLike | null | undefined, log: ErrorLog): void {\n  if (!utils || wrapped.has(utils)) return;\n  wrapped.add(utils);\n  const previous = utils.getGlobalHandler?.();\n  utils.setGlobalHandler((error, isFatal) => {\n    log.report(error, 'uncaught', Boolean(isFatal));\n    previous?.(error, isFatal);\n  });\n}\n\n/* ───────────────────────── ErrorFallback copy, shared by web and native ───────────────────── */\n\nexport interface ErrorFallbackLabels {\n  title: string;\n  description: string;\n  retry: string;\n  back: string;\n  /** Receives the four-character reference, not the whole id. */\n  referenceLine: (reference: string) => string;\n}\n\n/** Said when the screen has no way to retry and none to leave: no instruction it cannot honour. */\nconst DESCRIPTIONS = {\n  both: 'Try again, or go back.',\n  retry: 'Try again in a moment.',\n  back: 'Go back and try something else.',\n  neither: 'Please come back in a moment.',\n} as const;\n\nexport const DEFAULT_ERROR_FALLBACK_LABELS: ErrorFallbackLabels = {\n  title: 'Something went wrong here',\n  description: DESCRIPTIONS.both, // `resolveFallbackLabels` picks the one that fits the actions\n  retry: 'Try again',\n  back: 'Go back',\n  referenceLine: (reference) => `Reference: ${reference}`,\n};\n\n/**\n * The words on a fallback. A `description` the app wrote is used as given; otherwise the default\n * names only the actions the screen actually offers.\n */\nexport function resolveFallbackLabels(\n  labels: Partial<ErrorFallbackLabels> | undefined,\n  actions: { canRetry: boolean; canBack: boolean },\n): ErrorFallbackLabels {\n  const key = actions.canRetry\n    ? actions.canBack\n      ? 'both'\n      : 'retry'\n    : actions.canBack\n      ? 'back'\n      : 'neither';\n  const given = Object.fromEntries(\n    Object.entries(labels ?? {}).filter(([, value]) => value !== undefined),\n  );\n  return { ...DEFAULT_ERROR_FALLBACK_LABELS, description: DESCRIPTIONS[key], ...given };\n}\n\n/** The short reference a person can quote: the first four characters of the id. */\nexport function referenceOf(id: string): string {\n  return id.slice(0, 4);\n}\n"
    }
  ],
  "meta": {
    "tier": "util",
    "client": false,
    "minViewport": null,
    "loading": false,
    "version": "1.0.2",
    "since": "2.3.0"
  },
  "docs": "## @interlace/error-report-model\n\nInstalled to `lib/error-report-model.ts`.\n\n```tsx\nimport { /* … */ } from '@/lib/error-report-model';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/error-report-model"
}
