{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pii-post-guard",
  "title": "PII Post Guard",
  "description": "Post composer guard that says who will see the post and finds phone numbers, emails, addresses, Aadhaar, PAN, card numbers and OTPs with real checks (Verhoeff, Luhn, PAN holder type, OTP keywords) rather than loose digit runs, masking one or all the way each format expects.",
  "dependencies": [
    "lucide-react"
  ],
  "files": [
    {
      "path": "registry/default/pii-post-guard/pii-post-guard.tsx",
      "content": "\"use client\"\r\n\r\n// Bollard UI — pii-post-guard · MIT licence · https://bollard-ui.vercel.app/components/pii-post-guard\r\n\r\nimport * as React from \"react\"\r\nimport { EyeOff, Globe, Loader2, ShieldAlert } from \"lucide-react\"\r\n\r\nimport { cn } from \"@/lib/utils\"\r\nimport { detectPii, maskMatches, maskPii, PII_KINDS, type PiiKind, type PiiMatch } from \"./pii\"\r\n\r\nexport { detectPii, luhn, maskMatches, maskPii, PII_KINDS, verhoeff, type PiiKind, type PiiMatch } from \"./pii\"\r\n\r\n/** Who will see the post. */\r\nexport interface PostAudience {\r\n  /** Short name shown as the audience, e.g. \"Public\" or \"Followers\". */\r\n  label: string\r\n  /** Who that is, read in a sentence: \"anyone on the internet\", \"your 1,204 followers\". */\r\n  who: string\r\n  /** One extra line of consequence, e.g. about search engines. */\r\n  note?: string\r\n}\r\n\r\n/** Every visible string. `{label}`, `{who}`, `{list}` and `{kind}` are filled in. */\r\nexport const PII_POST_MESSAGES = {\r\n  /** Label used when the `label` prop is not set. */\r\n  label: \"Write a post\",\r\n  audienceLine: \"{label} · visible to {who}\",\r\n  summary: \"Your {list} will be visible to {who}.\",\r\n  kinds: { otp: \"OTP\", card: \"card number\", aadhaar: \"Aadhaar number\", pan: \"PAN\", email: \"email address\", address: \"address\", phone: \"phone number\" } as Record<PiiKind, string>,\r\n  why: {\r\n    otp: \"No genuine company asks for an OTP in a comment. Anyone who reads it can use it.\",\r\n    card: \"A card number is half of what fraud needs. Post the last 4 at most.\",\r\n    aadhaar: \"UIDAI's own rule: show only the last 4 digits.\",\r\n    pan: \"PAN plus a name is enough to attempt loans in your name.\",\r\n    email: \"Public addresses get scraped for spam and phishing.\",\r\n    address: \"Tells strangers where you live or will be.\",\r\n    phone: \"Public numbers get scraped for spam and fake KYC calls.\",\r\n  } as Record<PiiKind, string>,\r\n  addressMask: \"[address removed]\",\r\n  mask: \"Mask\",\r\n  maskAll: \"Mask all\",\r\n  keep: \"Keep\",\r\n  masked: \"Masked {kind}.\",\r\n  maskedAll: \"Masked everything. Check the post still reads right.\",\r\n  post: \"Post\",\r\n  postAnyway: \"Post anyway\",\r\n}\r\n\r\nexport type PiiPostMessages = typeof PII_POST_MESSAGES\r\n\r\nconst fill = (template: string, values: Record<string, string | number>) =>\r\n  template.replace(/\\{(\\w+)\\}/g, (match, key: string) => String(values[key] ?? match))\r\n\r\nconst SEVERE: PiiKind[] = [\"otp\", \"card\", \"aadhaar\"]\r\nconst keyOf = (m: Pick<PiiMatch, \"kind\" | \"value\">) => `${m.kind}:${m.value}`\r\n\r\nexport interface PiiPostGuardProps extends Omit<React.ComponentProps<\"textarea\">, \"value\" | \"defaultValue\" | \"onChange\"> {\r\n  /** Visible label. */\r\n  label?: string\r\n  /** Controlled text. */\r\n  value?: string\r\n  /** Initial text when uncontrolled. */\r\n  defaultValue?: string\r\n  /** Called with the text on every change, including masking. */\r\n  onValueChange?: (text: string) => void\r\n  /** Who will see the post. Defaults to the public internet. */\r\n  audience?: PostAudience\r\n  /** Which details to look for. Defaults to all of them. */\r\n  kinds?: PiiKind[]\r\n  /** Your own masking, e.g. to match a house style. Defaults to `maskPii`. */\r\n  mask?: (match: PiiMatch) => string\r\n  /** Pause in ms before findings refresh while typing, so nothing is announced per keystroke. */\r\n  delay?: number\r\n  /** Locale for joining the list of kinds (\"phone number and PAN\"). */\r\n  locale?: string\r\n  /** Called on Post. With details left, the first click jumps to them and the second posts. May return a Promise. */\r\n  onPost?: (text: string) => void | Promise<void>\r\n  /** Any visible string; `kinds` and `why` may be partial. */\r\n  messages?: Partial<Omit<PiiPostMessages, \"kinds\" | \"why\">> & { kinds?: Partial<PiiPostMessages[\"kinds\"]>; why?: Partial<PiiPostMessages[\"why\"]> }\r\n  /** Class for the outer wrapper. */\r\n  className?: string\r\n}\r\n\r\n/**\r\n * Stops people posting their phone number, email, address, Aadhaar, PAN, card number or an OTP\r\n * to a public feed, comment or review. It says who will see the post, finds each detail with real\r\n * checks (Verhoeff, Luhn, PAN holder type) instead of loose digit runs, and masks one or all of\r\n * them in one tap using each format's own convention.\r\n */\r\nexport function PiiPostGuard({\r\n  label,\r\n  value,\r\n  defaultValue = \"\",\r\n  onValueChange,\r\n  audience,\r\n  kinds = PII_KINDS,\r\n  mask,\r\n  delay = 600,\r\n  locale,\r\n  onPost,\r\n  messages,\r\n  className,\r\n  id,\r\n  rows = 4,\r\n  onBlur,\r\n  onPaste,\r\n  ref,\r\n  \"aria-describedby\": describedBy,\r\n  ...props\r\n}: PiiPostGuardProps) {\r\n  const t = { ...PII_POST_MESSAGES, ...messages, kinds: { ...PII_POST_MESSAGES.kinds, ...messages?.kinds }, why: { ...PII_POST_MESSAGES.why, ...messages?.why } }\r\n  const who: PostAudience = audience ?? { label: \"Public\", who: \"anyone on the internet\", note: \"Search engines can index it, and screenshots outlive a delete.\" }\r\n  const [inner, setInner] = React.useState(defaultValue)\r\n  const text = typeof (value ?? inner) === \"string\" ? (value ?? inner) : \"\"\r\n  const [settled, setSettled] = React.useState(text)\r\n  const [kept, setKept] = React.useState<Set<string>>(() => new Set())\r\n  const [announcement, setAnnouncement] = React.useState(\"\")\r\n  const [asked, setAsked] = React.useState(false)\r\n  const [pending, setPending] = React.useState(false)\r\n  const fieldRef = React.useRef<HTMLTextAreaElement>(null)\r\n  const panelRef = React.useRef<HTMLDivElement>(null)\r\n  const autoId = React.useId()\r\n  const fieldId = id ?? autoId\r\n  const audienceId = `${fieldId}-audience`\r\n  const findingsId = `${fieldId}-findings`\r\n\r\n  React.useImperativeHandle(ref, () => fieldRef.current as HTMLTextAreaElement)\r\n\r\n  React.useEffect(() => {\r\n    const timer = setTimeout(() => setSettled(text), delay)\r\n    return () => clearTimeout(timer)\r\n  }, [text, delay])\r\n\r\n  // Findings come from the settled text, so the panel doesn't flicker mid-word; any the user has\r\n  // since edited away drop out at once.\r\n  const findings = React.useMemo(() => {\r\n    const seen = new Set<string>()\r\n    return detectPii(settled, kinds).filter((m) => {\r\n      const key = keyOf(m)\r\n      if (kept.has(key) || seen.has(key) || !text.includes(m.value)) return false\r\n      seen.add(key)\r\n      return true\r\n    })\r\n  }, [settled, kinds, kept, text])\r\n  const severe = findings.some((m) => SEVERE.includes(m.kind))\r\n  const kindList = [...new Set(findings.map((m) => t.kinds[m.kind]))]\r\n  const list = typeof Intl.ListFormat === \"function\" ? new Intl.ListFormat(locale, { type: \"conjunction\" }).format(kindList) : kindList.join(\", \")\r\n  const summary = findings.length ? fill(t.summary, { list, who: who.who }) : \"\"\r\n\r\n  // A mask announces what it did; the summary it changes is not read over it.\r\n  const actedAt = React.useRef(0)\r\n  React.useEffect(() => {\r\n    if (Date.now() - actedAt.current > 500) setAnnouncement(summary)\r\n  }, [summary])\r\n\r\n  const commit = (next: string) => {\r\n    if (value === undefined) setInner(next)\r\n    setSettled(next)\r\n    onValueChange?.(next)\r\n    setAsked(false)\r\n  }\r\n  const masked = (m: PiiMatch) => (mask ? mask(m) : maskPii(m, t.addressMask))\r\n\r\n  const maskOne = (m: PiiMatch, index: number) => {\r\n    actedAt.current = Date.now()\r\n    // Mask by position in the current text: every copy of this detail, nothing that merely contains its digits.\r\n    commit(maskMatches(text, detectPii(text, kinds).filter((d) => keyOf(d) === keyOf(m)), masked))\r\n    setAnnouncement(fill(t.masked, { kind: t.kinds[m.kind] }))\r\n    requestAnimationFrame(() => {\r\n      const buttons = panelRef.current?.querySelectorAll<HTMLElement>(\"[data-mask]\")\r\n      ;(buttons?.[Math.min(index, buttons.length - 1)] ?? fieldRef.current)?.focus()\r\n    })\r\n  }\r\n\r\n  const maskAll = () => {\r\n    const open = new Set(findings.map(keyOf))\r\n    const next = maskMatches(text, detectPii(text, kinds).filter((d) => open.has(keyOf(d))), masked)\r\n    actedAt.current = Date.now()\r\n    commit(next)\r\n    setAnnouncement(t.maskedAll)\r\n    fieldRef.current?.focus()\r\n  }\r\n\r\n  const post = async () => {\r\n    if (findings.length && !asked) {\r\n      setAsked(true)\r\n      panelRef.current?.querySelector<HTMLElement>(\"[data-mask-all]\")?.focus()\r\n      return\r\n    }\r\n    if (!onPost || pending) return\r\n    setPending(true)\r\n    try {\r\n      await onPost(text)\r\n    } catch {\r\n      // The caller reports posting failures; the button becomes usable again.\r\n    } finally {\r\n      setPending(false)\r\n    }\r\n  }\r\n\r\n  const tone = severe\r\n    ? { box: \"border-red-500/30 bg-red-500/5\", text: \"text-red-800 dark:text-red-300\", solid: \"bg-red-700 text-white hover:bg-red-800 dark:bg-red-400 dark:text-red-950\" }\r\n    : { box: \"border-amber-500/30 bg-amber-500/5\", text: \"text-amber-800 dark:text-amber-300\", solid: \"bg-amber-700 text-white hover:bg-amber-800 dark:bg-amber-400 dark:text-amber-950\" }\r\n  const small = \"inline-flex h-6 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-none transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50\"\r\n\r\n  return (\r\n    <div data-slot=\"pii-post-guard\" data-state={findings.length ? (severe ? \"danger\" : \"warning\") : \"ok\"} className={cn(\"grid w-full max-w-md gap-1.5 text-sm\", className)}>\r\n      <label htmlFor={fieldId} className=\"font-medium\">{label ?? t.label}</label>\r\n      <textarea\r\n        ref={fieldRef}\r\n        id={fieldId}\r\n        rows={rows}\r\n        value={text}\r\n        onChange={(event) => {\r\n          if (value === undefined) setInner(event.target.value)\r\n          onValueChange?.(event.target.value)\r\n          setAsked(false)\r\n        }}\r\n        onPaste={(event) => {\r\n          onPaste?.(event)\r\n          requestAnimationFrame(() => setSettled(fieldRef.current?.value ?? \"\"))\r\n        }}\r\n        onBlur={(event) => {\r\n          onBlur?.(event)\r\n          setSettled(event.target.value)\r\n        }}\r\n        aria-describedby={[describedBy, audienceId, findings.length ? findingsId : \"\"].filter(Boolean).join(\" \")}\r\n        data-warning={findings.length ? \"\" : undefined}\r\n        className=\"min-h-20 w-full min-w-0 resize-y rounded-md border bg-transparent px-3 py-2 text-base shadow-xs outline-none transition-[color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-warning:border-amber-500 md:text-sm dark:bg-input/30 dark:data-warning:border-amber-400\"\r\n        {...props}\r\n      />\r\n      <p id={audienceId} className=\"flex gap-1.5 text-xs text-muted-foreground\">\r\n        <Globe aria-hidden className=\"mt-0.5 size-3.5 shrink-0\" />\r\n        <span className=\"min-w-0\">\r\n          {fill(t.audienceLine, { label: who.label, who: who.who })}\r\n          {who.note && <>. {who.note}</>}\r\n        </span>\r\n      </p>\r\n      <span aria-live=\"polite\" className=\"sr-only\">{announcement}</span>\r\n      {findings.length > 0 && (\r\n        <div ref={panelRef} className={cn(\"mt-1.5 space-y-2 rounded-md border p-3\", tone.box)}>\r\n          <div className={cn(\"flex flex-wrap items-start gap-x-3 gap-y-2\", tone.text)}>\r\n            <p className=\"flex min-w-0 flex-1 basis-48 gap-1.5 font-medium\">\r\n              <ShieldAlert aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\r\n              <span id={findingsId} className=\"min-w-0\">{summary}</span>\r\n            </p>\r\n            <button type=\"button\" data-mask-all onClick={maskAll} aria-describedby={findingsId} className={cn(small, \"h-8 gap-1.5 px-3 text-sm\", tone.solid)}>\r\n              <EyeOff aria-hidden className=\"size-4\" />\r\n              {t.maskAll}\r\n            </button>\r\n          </div>\r\n          <ul className=\"space-y-2\">\r\n            {findings.map((m, index) => (\r\n              <li key={keyOf(m)} className=\"grid gap-1 border-t border-current/10 pt-2 text-xs\">\r\n                <div className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1\">\r\n                  <span className=\"inline-block font-medium first-letter:uppercase\">{t.kinds[m.kind]}</span>\r\n                  <span className=\"flex min-w-0 flex-wrap gap-x-1.5 font-mono\">\r\n                    <span className=\"break-all line-through decoration-current/50 sm:whitespace-nowrap\">{m.value}</span>\r\n                    <span aria-hidden>→</span>\r\n                    <span className=\"sr-only\">, becomes </span>\r\n                    <span className=\"break-all sm:whitespace-nowrap\">{masked(m)}</span>\r\n                  </span>\r\n                  <span className=\"ml-auto flex gap-1\">\r\n                    <button type=\"button\" data-mask onClick={() => maskOne(m, index)} className={cn(small, \"border border-current/25 hover:bg-current/10\")} aria-label={`${t.mask} ${t.kinds[m.kind]}`}>\r\n                      {t.mask}\r\n                    </button>\r\n                    <button\r\n                      type=\"button\"\r\n                      onClick={() => {\r\n                        setKept((k) => new Set(k).add(keyOf(m)))\r\n                        requestAnimationFrame(() => (panelRef.current?.querySelectorAll<HTMLElement>(\"[data-mask]\")[index] ?? fieldRef.current)?.focus())\r\n                      }}\r\n                      className={cn(small, \"text-muted-foreground hover:bg-accent hover:text-foreground\")}\r\n                      aria-label={`${t.keep} ${t.kinds[m.kind]}`}\r\n                    >\r\n                      {t.keep}\r\n                    </button>\r\n                  </span>\r\n                </div>\r\n                <p className=\"text-muted-foreground\">{t.why[m.kind]}</p>\r\n              </li>\r\n            ))}\r\n          </ul>\r\n        </div>\r\n      )}\r\n      {onPost && (\r\n        <div className=\"mt-1.5 flex justify-end\">\r\n          <button\r\n            type=\"button\"\r\n            onClick={post}\r\n            disabled={pending || !text.trim()}\r\n            className={cn(\r\n              \"inline-flex h-9 items-center gap-2 rounded-md px-4 text-sm font-medium outline-none transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-60\",\r\n              asked && findings.length ? tone.solid : \"bg-primary text-primary-foreground hover:bg-primary/90\",\r\n            )}\r\n          >\r\n            {pending && <Loader2 aria-hidden className=\"size-4 animate-spin\" />}\r\n            {asked && findings.length ? t.postAnyway : t.post}\r\n          </button>\r\n        </div>\r\n      )}\r\n    </div>\r\n  )\r\n}\r\n",
      "type": "registry:ui",
      "target": "@ui/pii-post-guard.tsx"
    },
    {
      "path": "registry/default/pii-post-guard/pii.ts",
      "content": "// Bollard UI — pii-post-guard · MIT licence · https://bollard-ui.vercel.app/components/pii-post-guard\r\n\r\n/** The kinds of personal detail the guard looks for. */\r\nexport type PiiKind = \"otp\" | \"card\" | \"aadhaar\" | \"pan\" | \"email\" | \"address\" | \"phone\"\r\n\r\nexport interface PiiMatch {\r\n  kind: PiiKind\r\n  /** The text as written. */\r\n  value: string\r\n  start: number\r\n  end: number\r\n}\r\n\r\n/** Kinds in priority order: when two overlap, the earlier kind wins. */\r\nexport const PII_KINDS: PiiKind[] = [\"otp\", \"card\", \"aadhaar\", \"pan\", \"email\", \"address\", \"phone\"]\r\n\r\nconst D = [\r\n  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],\r\n  [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],\r\n  [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],\r\n]\r\nconst P = [\r\n  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],\r\n  [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],\r\n]\r\n\r\n/** Verhoeff check used by Aadhaar: catches every single wrong digit and every swapped neighbour pair. */\r\nexport function verhoeff(digits: string) {\r\n  let c = 0\r\n  const list = digits.replace(/\\D/g, \"\").split(\"\").reverse()\r\n  list.forEach((d, i) => (c = D[c][P[i % 8][Number(d)]]))\r\n  return list.length > 0 && c === 0\r\n}\r\n\r\n/** Luhn check used by payment cards. */\r\nexport function luhn(digits: string) {\r\n  const list = digits.replace(/\\D/g, \"\")\r\n  let sum = 0\r\n  for (let i = 0; i < list.length; i++) {\r\n    let d = Number(list[list.length - 1 - i])\r\n    if (i % 2) d = d * 2 > 9 ? d * 2 - 9 : d * 2\r\n    sum += d\r\n  }\r\n  return list.length >= 13 && sum % 10 === 0\r\n}\r\n\r\nconst digitCount = (s: string) => s.replace(/\\D/g, \"\").length\r\nconst ADDRESS_WORDS = /\\b(flat|house|h\\.?\\s?no|plot|apt|apartment|floor|wing|tower|block|sector|road|rd|street|lane|marg|nagar|colony|society|chowk|layout|cross|near|opp|opposite|behind|village|taluka|district)\\b/i\r\nconst ADDRESS_START = /\\b(?:flat|house|h\\.?\\s?no|plot|apt|apartment|room|door|shop)\\b|(?:^|[\\s,])[A-Za-z]?[-/]?\\d{1,4}[A-Za-z]?(?:[-/]\\d{1,4}[A-Za-z]?)?\\s*,/i\r\nconst NOT_OTP_CODE = \"(?<!(?:promo|coupon|discount|zip|postal|pin|area|country|referral|source|error|status|dress|qr)[\\\\s-]?)\"\r\n\r\nconst DETECTORS: Record<PiiKind, (text: string) => { start: number; end: number }[]> = {\r\n  otp: (text) => {\r\n    const found: { start: number; end: number }[] = []\r\n    const before = new RegExp(`\\\\b(?:otp|one[- ]time (?:password|code)|verification code|security code|passcode|login code|${NOT_OTP_CODE}code|pin(?![\\\\s-]?code))\\\\b[^\\\\d\\\\n]{0,20}?(\\\\d{4,8})(?!\\\\d)|ओटीपी[^\\\\d\\\\n]{0,20}?(\\\\d{4,8})(?!\\\\d)`, \"gi\")\r\n    for (const m of text.matchAll(before)) {\r\n      const digits = m[1] ?? m[2]\r\n      const start = m.index + m[0].lastIndexOf(digits)\r\n      found.push({ start, end: start + digits.length })\r\n    }\r\n    for (const m of text.matchAll(/(?<![\\d,.])(\\d{4,8})(?!\\d)\\s+(?:is\\s+(?:my|the|your)\\s+)?(?:otp|verification code)\\b/gi))\r\n      found.push({ start: m.index, end: m.index + m[1].length })\r\n    return found\r\n  },\r\n  card: (text) =>\r\n    [...text.matchAll(/(?<![\\d-])\\d(?:[ -]?\\d){12,18}(?![\\d-])/g)]\r\n      // Real card numbers start 2–6 (Visa, Mastercard, Amex, Discover, RuPay 6x) or 8 (RuPay 8x).\r\n      .filter((m) => /^[2-68]/.test(m[0]) && luhn(m[0]) && !/^(\\d)\\1+$/.test(m[0].replace(/\\D/g, \"\")))\r\n      .map((m) => ({ start: m.index, end: m.index + m[0].length })),\r\n  aadhaar: (text) =>\r\n    [...text.matchAll(/(?<![\\d-])[2-9]\\d{3}([ -]?)\\d{4}\\1\\d{4}(?![\\d-])/g)].filter((m) => verhoeff(m[0])).map((m) => ({ start: m.index, end: m.index + m[0].length })),\r\n  pan: (text) => [...text.matchAll(/\\b[A-Z]{3}[ABCFGHJLPT][A-Z]\\d{4}[A-Z]\\b/gi)].map((m) => ({ start: m.index, end: m.index + m[0].length })),\r\n  email: (text) => [...text.matchAll(/[\\p{L}\\p{N}._%+-]+@[\\p{L}\\p{N}-]+(?:\\.[\\p{L}\\p{N}-]+)*\\.\\p{L}{2,}/gu)].map((m) => ({ start: m.index, end: m.index + m[0].length })),\r\n  address: (text) => {\r\n    const found: { start: number; end: number }[] = []\r\n    // Indian addresses: an address word within the same line before a 6-digit PIN code.\r\n    for (const pin of text.matchAll(/(?<![\\d-])[1-9]\\d{2}\\s?\\d{3}(?![\\d-])/g)) {\r\n      const from = Math.max(0, pin.index - 140)\r\n      let window = text.slice(from, pin.index)\r\n      // Start after the last line break, \"!\", \"?\", \"Label:\" or full stop before a capital (\"Thanks. Flat 12…\").\r\n      const breaks = [...window.matchAll(/\\n|[!?]|:\\s|\\.\\s+(?=[A-Z])/g)]\r\n      const cut = breaks.length ? breaks[breaks.length - 1].index + breaks[breaks.length - 1][0].length : 0\r\n      const offset = from + cut\r\n      window = window.slice(cut)\r\n      if (!ADDRESS_WORDS.test(window)) continue\r\n      const startMatch = window.match(ADDRESS_START) ?? window.match(ADDRESS_WORDS)\r\n      const lead = startMatch ? startMatch.index! + (startMatch[0].length - startMatch[0].trimStart().replace(/^,/, \"\").trimStart().length) : 0\r\n      found.push({ start: offset + lead, end: pin.index + pin[0].length })\r\n    }\r\n    // US-style street lines: \"221 Baker Street\", \"1600 Amphitheatre Pkwy, Suite 4\".\r\n    for (const m of text.matchAll(/\\b\\d{1,5}\\s+(?:[A-Z][a-z]+\\s+){1,3}(?:St|Street|Ave|Avenue|Rd|Road|Blvd|Boulevard|Lane|Ln|Dr|Drive|Way|Court|Ct|Pkwy|Parkway)\\b\\.?(?:,?\\s+(?:Apt|Suite|Unit|#)\\s*\\w+)?/g))\r\n      found.push({ start: m.index, end: m.index + m[0].length })\r\n    return found\r\n  },\r\n  phone: (text) =>\r\n    [\r\n      ...text.matchAll(/(?<![\\w+])(?:(?:\\+|00)91[\\s-]?|0)?[6-9]\\d{4}[\\s-]?\\d{5}(?!\\d)/g),\r\n      ...text.matchAll(/(?<![\\w+])\\+\\d{1,3}[\\s.-]?\\(?\\d{1,4}\\)?(?:[\\s.-]?\\d{2,4}){2,4}(?!\\d)/g),\r\n      ...text.matchAll(/(?<![\\d(])\\(?\\b\\d{3}\\)?[\\s.-]\\d{3}[\\s.-]\\d{4}(?!\\d)/g),\r\n    ]\r\n      .filter((m) => digitCount(m[0]) >= 10 && digitCount(m[0]) <= 15)\r\n      .map((m) => ({ start: m.index, end: m.index + m[0].length })),\r\n}\r\n\r\n/**\r\n * Finds personal details in text: OTPs next to words like \"OTP\" or \"code\", Luhn-valid card numbers,\r\n * Verhoeff-valid Aadhaar numbers, PANs with a real holder-type letter, emails, street addresses\r\n * ending in a PIN code, and phone numbers. Overlaps go to the likelier kind. Never throws.\r\n */\r\nexport function detectPii(text: string, kinds: PiiKind[] = PII_KINDS): PiiMatch[] {\r\n  if (typeof text !== \"string\" || !text) return []\r\n  const accepted: PiiMatch[] = []\r\n  for (const kind of PII_KINDS) {\r\n    if (!kinds.includes(kind)) continue\r\n    let spans: { start: number; end: number }[] = []\r\n    try {\r\n      spans = DETECTORS[kind](text)\r\n    } catch {\r\n      continue\r\n    }\r\n    for (const { start, end } of spans) {\r\n      if (end <= start || accepted.some((m) => start < m.end && end > m.start)) continue\r\n      accepted.push({ kind, value: text.slice(start, end), start, end })\r\n    }\r\n  }\r\n  return accepted.sort((a, b) => a.start - b.start)\r\n}\r\n\r\n/** Keeps the last `keep` digits and the layout: \"98765 43210\" → \"XXXXX XXX10\". */\r\nconst maskDigits = (value: string, keep: number) => {\r\n  let left = value.replace(/\\D/g, \"\").length - keep\r\n  return value.replace(/\\d/g, (d) => (left-- > 0 ? \"X\" : d))\r\n}\r\n\r\n/**\r\n * The masked form of a detail, following each format's convention (UIDAI's \"XXXX XXXX 1234\",\r\n * cards' last four). `addressText` replaces an address outright.\r\n */\r\nexport function maskPii(match: Pick<PiiMatch, \"kind\" | \"value\">, addressText = \"[address removed]\"): string {\r\n  const { kind, value } = match\r\n  switch (kind) {\r\n    case \"otp\": return value.replace(/\\d/g, \"X\")\r\n    case \"card\":\r\n    case \"aadhaar\": return maskDigits(value, 4)\r\n    case \"pan\": return \"XXXXXX\" + value.slice(-4)\r\n    case \"email\": {\r\n      const at = value.lastIndexOf(\"@\")\r\n      return `${value[0]}•••${value.slice(at)}`\r\n    }\r\n    case \"address\": return addressText\r\n    case \"phone\": {\r\n      const country = value.match(/^(?:\\+|00)\\d{1,3}[\\s-]?/)?.[0] ?? \"\"\r\n      return country + maskDigits(value.slice(country.length), 2)\r\n    }\r\n  }\r\n}\r\n\r\n/**\r\n * Replaces each match by its position, so masking one detail never touches the same digits\r\n * inside another number (\"OTP 4829\" masked leaves \"order 148290\" alone). Matches must come\r\n * from `detectPii(text)`; any whose text no longer sits at its offset is skipped.\r\n */\r\nexport function maskMatches(text: string, matches: PiiMatch[], replace: (match: PiiMatch) => string = (m) => maskPii(m)): string {\r\n  let out = text\r\n  for (const m of [...matches].sort((a, b) => b.start - a.start)) {\r\n    if (out.slice(m.start, m.end) === m.value) out = out.slice(0, m.start) + replace(m) + out.slice(m.end)\r\n  }\r\n  return out\r\n}\r\n",
      "type": "registry:ui",
      "target": "@components/pii-post-guard/pii.ts"
    }
  ],
  "meta": {
    "stops": "Helps stop an Aadhaar number being posted in public",
    "mistakes": [
      "posted phone number publicly",
      "aadhaar in review",
      "pan card shared in comment",
      "otp posted publicly",
      "email in public post"
    ],
    "aliases": [
      "pii",
      "aadhaar",
      "pan",
      "phone number",
      "comment box",
      "review",
      "mask",
      "luhn",
      "verhoeff"
    ],
    "flows": [
      "messaging",
      "india",
      "forms"
    ],
    "fields": [
      "id-number",
      "phone",
      "email"
    ],
    "summary": "Before a public post goes out, finds phone numbers, emails, Aadhaar, PAN, card numbers or OTPs in it and masks them in one tap.",
    "server": "Scan and redact on the server before publishing, and never log the raw text.",
    "catches": [
      "Aadhaar numbers (Verhoeff check)",
      "Card numbers (Luhn check)",
      "PAN numbers, including holder type",
      "Phone numbers, emails and street addresses",
      "OTPs near words like code or OTP"
    ],
    "limits": [
      "India-focused identifiers; other countries' IDs aren't detected",
      "Addresses are detected heuristically",
      "The post still goes out if the user chooses to; it masks, it doesn't block"
    ],
    "a11y": [
      "Visible label; textarea is described by the audience line and findings",
      "Announcements go to a polite live region",
      "Focus moves to the next mask button, then back to the field"
    ],
    "usage": "import { PII_POST_MESSAGES } from \"@/components/ui/pii-post-guard\"",
    "runtimeDependencies": [
      "lucide-react"
    ],
    "zeroRuntimeDependencies": false
  },
  "docs": "https://bollard-ui.vercel.app/components/pii-post-guard",
  "categories": [
    "Sharing, sending and paying"
  ],
  "type": "registry:ui"
}
