@deepcitation/deepcitation-js 1.1.49 → 1.1.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +156 -157
- package/lib/{chunk-D2TKEF6D.cjs → chunk-4ILSZKAP.cjs} +3 -2
- package/lib/chunk-4ILSZKAP.cjs.map +1 -0
- package/lib/chunk-5XGN7UAV.js +2 -0
- package/lib/chunk-5XGN7UAV.js.map +1 -0
- package/lib/{chunk-2PRW5PVT.cjs → chunk-ALJ2ZQ2S.cjs} +2 -1
- package/lib/chunk-ALJ2ZQ2S.cjs.map +1 -0
- package/lib/{chunk-F2MMVEVC.cjs → chunk-BYLIBOAU.cjs} +2 -1
- package/lib/chunk-BYLIBOAU.cjs.map +1 -0
- package/lib/{chunk-ND6LFDGK.js → chunk-KBDVUQEE.js} +2 -1
- package/lib/chunk-KBDVUQEE.js.map +1 -0
- package/lib/{chunk-PKXMJNRX.js → chunk-LLLVZOXB.js} +2 -1
- package/lib/chunk-LLLVZOXB.js.map +1 -0
- package/lib/{chunk-DHVODVIA.cjs → chunk-PJWAX2VG.cjs} +2 -1
- package/lib/chunk-PJWAX2VG.cjs.map +1 -0
- package/lib/{chunk-UUR2SQKU.cjs → chunk-QUW3L3UU.cjs} +2 -1
- package/lib/chunk-QUW3L3UU.cjs.map +1 -0
- package/lib/chunk-R57DQBOT.js +2 -0
- package/lib/chunk-R57DQBOT.js.map +1 -0
- package/lib/{chunk-3XSZLKJW.js → chunk-TDGYSF3B.js} +3 -2
- package/lib/chunk-TDGYSF3B.js.map +1 -0
- package/lib/client/index.cjs +2 -1
- package/lib/client/index.cjs.map +1 -0
- package/lib/client/index.js +2 -1
- package/lib/client/index.js.map +1 -0
- package/lib/index.cjs +2 -1
- package/lib/index.cjs.map +1 -0
- package/lib/index.js +2 -1
- package/lib/index.js.map +1 -0
- package/lib/prompts/index.cjs +2 -1
- package/lib/prompts/index.cjs.map +1 -0
- package/lib/prompts/index.js +2 -1
- package/lib/prompts/index.js.map +1 -0
- package/lib/react/index.cjs +4 -3
- package/lib/react/index.cjs.map +1 -0
- package/lib/react/index.js +3 -2
- package/lib/react/index.js.map +1 -0
- package/lib/types/index.cjs +2 -1
- package/lib/types/index.cjs.map +1 -0
- package/lib/types/index.js +2 -1
- package/lib/types/index.js.map +1 -0
- package/package.json +161 -152
- package/src/tailwind.css +5 -5
- package/lib/chunk-HRCAI3NV.js +0 -1
- package/lib/chunk-O2XFH626.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/sha.ts","../src/parsing/parseCitation.ts","../src/parsing/normalizeCitation.ts","../src/react/utils.ts"],"names":["utf8Encode","str","sha1","message","h0","h1","h2","h3","h4","msgLen","bitLen","totalLen","paddedLen","padded","paddedView","dataView","w","offset","i","val","a","b","c","d","e","f","k","temp","hex","n","sha1Hash","data","error","attributeRegexCache","getAttributeRegex","name","regex","parseLineIds","lineIdsString","lineIds","parts","part","trimmed","startStr","endStr","start","end","num","getCitationStatus","verification","status","isMiss","isVerified","isPartialMatch","isPending","parseCitation","fragment","mdAttachmentId","citationCounterRef","isVerbose","cleanAndUnescape","result","citationNumber","beforeCite","afterCite","middleCite","extractAttribute","tag","attrNames","match","rawAttachmentId","attachmentId","startPageKeyRaw","pageNumber","pageIndex","pageMatch","fullPhrase","keySpan","reasoning","value","timestampsRaw","timestamps","startTime","endTime","citation","parseJsonCitation","jsonCitation","startPageKey","rawLineIds","simpleMatch","hasCitationProperties","item","isJsonCitationFormat","extractJsonCitations","citations","items","citationKey","generateCitationKey","findJsonCitationsInObject","obj","found","key","extractXmlCitations","text","normalizedText","normalizeCitations","citeRegex","matches","getAllCitationsFromLlmOutput","llmOutput","jsonCitations","foundJsonCitations","xmlCitations","groupCitationsByAttachmentId","grouped","entries","idx","groupCitationsByAttachmentIdObject","parseCiteAttributes","citeTag","attrs","attrRegex","normalizedKey","getVerificationTextIndicator","replaceCitations","markdownWithCitations","options","leaveKeySpanBehind","verifications","showVerificationStatus","citationIndex","citationRegex","output","parsePageNumber","lineIdsStr","nums","_match","startNum","endNum","range","s","unescapeQuotes","numericKey","indicator","removeCitations","removePageNumberMetadata","pageText","removeLineIdMetadata","lineIdRegex","getCitationPageNumber","extractAndRelocateCitationContent","citePart","nonSelfClosingMatch","unclosedMatch","selfClosingTag","normalizeCitationContent","openingTag","innerContent","relocatedContent","normalizedCitation","response","trimmedResponse","citationParts","input","normalized","canonicalizeCiteAttributeKey","lowerKey","htmlEntityMap","htmlEntityRegex","decodeHtmlEntities","textAttributeRegex","openQuote","rawContent","content","rawValue","trailingChars","cleanedValue","_rangeMatch","reorderCiteTagAttributes","rawKey","keys","hasTimestamps","startPageKeys","ordered","used","cn","classes","isUrlCitation","keyParts","generateVerificationKey","generateCitationInstanceId","randomSuffix","getCitationDisplayText","fallbackDisplay","getCitationNumber","getCitationKeySpanText","classNames","CITATION_X_PADDING","CITATION_Y_PADDING"],"mappings":"aAMA,SAASA,CAAAA,CAAWC,CAAAA,CAAyB,CAE3C,OADgB,IAAI,WAAA,EAAY,CACjB,MAAA,CAAOA,CAAG,CAC3B,CAEA,SAASC,CAAAA,CAAKC,CAAAA,CAA6B,CAEzC,IAAIC,CAAAA,CAAK,UAAA,CACLC,CAAAA,CAAK,UAAA,CACLC,CAAAA,CAAK,UAAA,CACLC,CAAAA,CAAK,SAAA,CACLC,CAAAA,CAAK,UAAA,CAGHC,CAAAA,CAASN,CAAAA,CAAQ,OACjBO,CAAAA,CAASD,CAAAA,CAAS,CAAA,CAIlBE,CAAAA,CAAWF,CAAAA,CAAS,CAAA,CAAI,CAAA,CACxBG,CAAAA,CAAY,IAAA,CAAK,IAAA,CAAKD,CAAAA,CAAW,EAAE,CAAA,CAAI,EAAA,CAGvCE,CAAAA,CAAS,IAAI,YAAYD,CAAS,CAAA,CAClCE,CAAAA,CAAa,IAAI,UAAA,CAAWD,CAAM,CAAA,CAClCE,CAAAA,CAAW,IAAI,QAAA,CAASF,CAAM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Based on the FIPS 180-4 specification.\n * No external dependencies.\n */\n\nfunction utf8Encode(str: string): Uint8Array {\n const encoder = new TextEncoder();\n return encoder.encode(str);\n}\n\nfunction sha1(message: Uint8Array): string {\n // Initial hash values\n let h0 = 0x67452301;\n let h1 = 0xefcdab89;\n let h2 = 0x98badcfe;\n let h3 = 0x10325476;\n let h4 = 0xc3d2e1f0;\n\n // Pre-processing: adding padding bits\n const msgLen = message.length;\n const bitLen = msgLen * 8;\n\n // Calculate padded length: message + 1 (0x80) + padding + 8 (length)\n // Total must be multiple of 64 bytes (512 bits)\n const totalLen = msgLen + 1 + 8; // minimum: msg + 0x80 + 64-bit length\n const paddedLen = Math.ceil(totalLen / 64) * 64;\n\n // Create padded buffer\n const padded = new ArrayBuffer(paddedLen);\n const paddedView = new Uint8Array(padded);\n const dataView = new DataView(padded);\n\n // Copy message\n paddedView.set(message);\n\n // Append bit '1' (0x80)\n paddedView[msgLen] = 0x80;\n\n // Append length as 64-bit big-endian (in bits)\n // High 32 bits (for messages > 512MB, which we don't support)\n dataView.setUint32(paddedLen - 8, Math.floor(bitLen / 0x100000000), false);\n // Low 32 bits\n dataView.setUint32(paddedLen - 4, bitLen >>> 0, false);\n\n // Process each 512-bit (64-byte) chunk\n const w = new Uint32Array(80);\n\n for (let offset = 0; offset < paddedLen; offset += 64) {\n // Break chunk into sixteen 32-bit big-endian words\n for (let i = 0; i < 16; i++) {\n w[i] = dataView.getUint32(offset + i * 4, false);\n }\n\n // Extend the sixteen 32-bit words into eighty 32-bit words\n for (let i = 16; i < 80; i++) {\n const val = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16];\n w[i] = (val << 1) | (val >>> 31);\n }\n\n // Initialize working variables\n let a = h0;\n let b = h1;\n let c = h2;\n let d = h3;\n let e = h4;\n\n // Main loop\n for (let i = 0; i < 80; i++) {\n let f: number;\n let k: number;\n\n if (i < 20) {\n f = (b & c) | (~b & d);\n k = 0x5a827999;\n } else if (i < 40) {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n } else if (i < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n\n const temp = (((a << 5) | (a >>> 27)) + f + e + k + w[i]) >>> 0;\n e = d;\n d = c;\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = temp;\n }\n\n // Add this chunk's hash to result\n h0 = (h0 + a) >>> 0;\n h1 = (h1 + b) >>> 0;\n h2 = (h2 + c) >>> 0;\n h3 = (h3 + d) >>> 0;\n h4 = (h4 + e) >>> 0;\n }\n\n // Produce the final hash value (160-bit) as hex string\n const hex = (n: number) => n.toString(16).padStart(8, \"0\");\n return hex(h0) + hex(h1) + hex(h2) + hex(h3) + hex(h4);\n}\n\n/**\n * Computes a SHA-1 hash of the provided data.\n * Used internally by generateCitationKey in react/utils.ts\n */\nexport function sha1Hash(data: string | any): string {\n try {\n if (!data) return \"\";\n const str = typeof data === \"string\" ? data : JSON.stringify(data);\n return sha1(utf8Encode(str));\n } catch (error) {\n console.error(\"Error in making the hash:\", error);\n }\n return \"\";\n}\n","import { type Verification } from \"../types/verification.js\";\nimport { type Citation, type CitationStatus } from \"../types/citation.js\";\nimport { normalizeCitations } from \"./normalizeCitation.js\";\nimport { generateCitationKey } from \"../react/utils.js\";\n\nconst attributeRegexCache = new Map<string, RegExp>();\n\nfunction getAttributeRegex(name: string): RegExp {\n let regex = attributeRegexCache.get(name);\n if (!regex) {\n regex = new RegExp(`${name}='((?:[^'\\\\\\\\]|\\\\\\\\.)*)'`);\n attributeRegexCache.set(name, regex);\n }\n return regex;\n}\n\n/**\n * Parses a line_ids string that may contain individual numbers, ranges, or both.\n * Examples: \"1,2,3\", \"5-10\", \"1,5-7,10\", \"20-20\"\n *\n * @param lineIdsString - The raw line_ids string (e.g., \"1,5-7,10\")\n * @returns Sorted array of unique line IDs, or undefined if empty/invalid\n */\nfunction parseLineIds(lineIdsString: string): number[] | undefined {\n if (!lineIdsString) return undefined;\n\n const lineIds: number[] = [];\n const parts = lineIdsString.split(\",\");\n\n for (const part of parts) {\n const trimmed = part.trim();\n if (!trimmed) continue;\n\n // Check if this part is a range (e.g., \"5-10\")\n if (trimmed.includes(\"-\")) {\n const [startStr, endStr] = trimmed.split(\"-\");\n const start = parseInt(startStr, 10);\n const end = parseInt(endStr, 10);\n\n if (!isNaN(start) && !isNaN(end) && start <= end) {\n // Expand the range\n for (let i = start; i <= end; i++) {\n lineIds.push(i);\n }\n } else if (!isNaN(start)) {\n // If only start is valid, just use it\n lineIds.push(start);\n }\n } else {\n // Single number\n const num = parseInt(trimmed, 10);\n if (!isNaN(num)) {\n lineIds.push(num);\n }\n }\n }\n\n if (lineIds.length === 0) return undefined;\n\n // Sort and deduplicate\n return [...new Set(lineIds)].sort((a, b) => a - b);\n}\n\n/**\n * Calculates the verification status of a citation based on the found highlight and search state.\n *\n * @param verification - The found highlight location, or null/undefined if not found\n * @returns An object containing boolean flags for verification status\n */\nexport function getCitationStatus(\n verification: Verification | null | undefined\n): CitationStatus {\n const status = verification?.status;\n\n const isMiss = [\"not_found\"].includes(status || \"\");\n \n const isVerified = [\"found\", \"found_key_span_only\", \"found_phrase_missed_value\"].includes(status || \"\");\n const isPartialMatch = [\"partial_text_found\", \"found_on_other_page\", \"found_on_other_line\", \"first_word_found\"].includes(status || \"\");\n\n const isPending = [\"pending\", \"loading\", null, undefined].includes(status);\n\n return { isVerified, isMiss, isPartialMatch, isPending };\n}\n\nexport const parseCitation = (\n fragment: string,\n mdAttachmentId?: string | null,\n citationCounterRef?: any | null,\n isVerbose?: boolean\n) => {\n // Helper: Remove wrapper quotes and fully unescape content\n // Handles: \\' -> ', \\\" -> \", \\n -> space, \\\\ -> \\\n const cleanAndUnescape = (str?: string) => {\n if (!str) return undefined;\n let result = str;\n // Remove surrounding quotes if present, but only if not escaped\n // Check start: remove leading quote only if it exists\n if (result.startsWith(\"'\") || result.startsWith('\"')) {\n result = result.slice(1);\n }\n // Check end: remove trailing quote only if it's not escaped (not preceded by \\)\n if ((result.endsWith(\"'\") || result.endsWith('\"')) && !result.endsWith(\"\\\\'\") && !result.endsWith('\\\\\"')) {\n result = result.slice(0, -1);\n }\n // Replace escaped double quotes with actual double quotes\n result = result.replace(/\\\\\"/g, '\"');\n // Replace escaped single quotes with actual single quotes\n result = result.replace(/\\\\'/g, \"'\");\n // Replace literal \\n sequences with spaces (newlines in attribute values)\n result = result.replace(/\\\\n/g, \" \");\n // Replace double backslashes with single backslash\n result = result.replace(/\\\\\\\\/g, \"\\\\\");\n return result;\n };\n\n const citationNumber = citationCounterRef?.current\n ? citationCounterRef.current++\n : undefined;\n\n const beforeCite = fragment.substring(0, fragment.indexOf(\"<cite\"));\n const afterCite = fragment.includes(\"/>\")\n ? fragment.slice(fragment.indexOf(\"/>\") + 2)\n : \"\";\n const middleCite = fragment.substring(\n fragment.indexOf(\"<cite\"),\n fragment.indexOf(\"/>\") + 2\n );\n\n const extractAttribute = (tag: string, attrNames: string[]): string | undefined => {\n for (const name of attrNames) {\n const regex = getAttributeRegex(name);\n const match = tag.match(regex);\n if (match) {\n return match[1];\n }\n }\n return undefined;\n };\n\n // Extract all attributes by name (order-independent)\n let rawAttachmentId = extractAttribute(middleCite, ['attachment_id', 'attachmentId', 'file_id', 'fileId']);\n let attachmentId = rawAttachmentId?.length === 20 ? rawAttachmentId : mdAttachmentId || rawAttachmentId;\n\n const startPageKeyRaw = extractAttribute(middleCite, ['start_page_key', 'startPageKey', 'start_page']);\n let pageNumber: number | undefined;\n let pageIndex: number | undefined;\n if (startPageKeyRaw) {\n const pageMatch = startPageKeyRaw.match(/page[\\_a-zA-Z]*(\\d+)_index_(\\d+)/);\n if (pageMatch) {\n pageNumber = parseInt(pageMatch[1]);\n pageIndex = parseInt(pageMatch[2]);\n }\n }\n\n // Use helper to handle escaped quotes inside the phrase\n let fullPhrase = cleanAndUnescape(extractAttribute(middleCite, ['full_phrase', 'fullPhrase']));\n let keySpan = cleanAndUnescape(extractAttribute(middleCite, ['key_span', 'keySpan']));\n let reasoning = cleanAndUnescape(extractAttribute(middleCite, ['reasoning']));\n let value = cleanAndUnescape(extractAttribute(middleCite, ['value']));\n\n let lineIds: number[] | undefined;\n try {\n const lineIdsRaw = extractAttribute(middleCite, ['line_ids', 'lineIds']);\n const lineIdsString = lineIdsRaw?.replace(/[A-Za-z_[\\](){}:]/g, \"\");\n lineIds = lineIdsString ? parseLineIds(lineIdsString) : undefined;\n } catch (e) {\n if (isVerbose) console.error(\"Error parsing lineIds\", e);\n }\n\n // Check for AV citation (has timestamps instead of line_ids)\n const timestampsRaw = extractAttribute(middleCite, ['timestamps']);\n let timestamps: { startTime?: string; endTime?: string } | undefined;\n\n if (timestampsRaw) {\n const [startTime, endTime] = timestampsRaw.split(\"-\") || [];\n timestamps = { startTime, endTime };\n }\n\n const citation: Citation = {\n attachmentId: attachmentId,\n pageNumber,\n startPageKey: `page_number_${pageNumber || 1}_index_${pageIndex || 0}`,\n fullPhrase,\n keySpan: keySpan || value,\n citationNumber,\n lineIds,\n beforeCite,\n timestamps,\n reasoning,\n };\n\n return {\n beforeCite,\n afterCite,\n citation,\n };\n};\n\n/**\n * Parses a JSON-based citation object into a Citation.\n * Supports both camelCase and snake_case property names.\n *\n * @param jsonCitation - The JSON citation object (can have camelCase or snake_case properties)\n * @param citationNumber - Optional citation number for ordering\n * @returns Parsed Citation object\n */\nconst parseJsonCitation = (\n jsonCitation: any,\n citationNumber?: number\n): Citation | null => {\n if (!jsonCitation) {\n return null;\n }\n\n // Support both camelCase and snake_case property names\n const fullPhrase = jsonCitation.fullPhrase ?? jsonCitation.full_phrase;\n const startPageKey = jsonCitation.startPageKey ?? jsonCitation.start_page_key;\n const keySpan = jsonCitation.keySpan ?? jsonCitation.key_span;\n const rawLineIds = jsonCitation.lineIds ?? jsonCitation.line_ids;\n const attachmentId = jsonCitation.attachmentId ?? jsonCitation.attachment_id ?? jsonCitation.fileId ?? jsonCitation.file_id;\n const reasoning = jsonCitation.reasoning;\n const value = jsonCitation.value;\n\n if (!fullPhrase) {\n return null;\n }\n\n // Parse startPageKey format: \"page_number_PAGE_index_INDEX\" or simple \"PAGE_INDEX\"\n let pageNumber: number | undefined;\n if (startPageKey) {\n // Try full format first: page_number_5_index_2 or pageKey_5_index_2\n const pageMatch = startPageKey.match(/page[_a-zA-Z]*(\\d+)_index_(\\d+)/i);\n if (pageMatch) {\n pageNumber = parseInt(pageMatch[1], 10);\n } else {\n // Try simple n_m format: 5_4 (page 5, index 4)\n const simpleMatch = startPageKey.match(/^(\\d+)_(\\d+)$/);\n if (simpleMatch) {\n pageNumber = parseInt(simpleMatch[1], 10);\n }\n }\n }\n\n // Sort lineIds if present\n const lineIds = rawLineIds?.length\n ? [...rawLineIds].sort((a: number, b: number) => a - b)\n : undefined;\n\n const citation: Citation = {\n attachmentId,\n pageNumber,\n fullPhrase,\n citationNumber,\n lineIds,\n keySpan: keySpan || value,\n reasoning,\n };\n\n return citation;\n};\n\n/**\n * Checks if an object has citation-like properties (camelCase or snake_case).\n */\nconst hasCitationProperties = (item: any): boolean =>\n typeof item === \"object\" &&\n item !== null &&\n (\"fullPhrase\" in item ||\n \"full_phrase\" in item ||\n \"startPageKey\" in item ||\n \"start_page_key\" in item ||\n \"keySpan\" in item ||\n \"key_span\" in item ||\n \"lineIds\" in item ||\n \"line_ids\" in item);\n\n/**\n * Checks if the input appears to be JSON-based citations.\n * Looks for array of objects with citation-like properties (supports both camelCase and snake_case).\n */\nconst isJsonCitationFormat = (data: any): data is Citation[] | Citation => {\n if (Array.isArray(data)) {\n return data.length > 0 && data.some(hasCitationProperties);\n }\n if (typeof data === \"object\" && data !== null) {\n return hasCitationProperties(data);\n }\n return false;\n};\n\n/**\n * Extracts citations from JSON format (array or single object).\n */\nconst extractJsonCitations = (\n data: Citation[] | Citation\n): { [key: string]: Citation } => {\n const citations: { [key: string]: Citation } = {};\n const items = Array.isArray(data) ? data : [data];\n\n let citationNumber = 1;\n for (const item of items) {\n const citation = parseJsonCitation(item, citationNumber++);\n if (citation && citation.fullPhrase) {\n const citationKey = generateCitationKey(citation);\n citations[citationKey] = citation;\n }\n }\n\n return citations;\n};\n\n/**\n * Recursively traverses an object looking for `citation` or `citations` properties\n * that match our JSON citation format.\n */\nconst findJsonCitationsInObject = (obj: any, found: Citation[]): void => {\n if (!obj || typeof obj !== \"object\") return;\n\n // Check for citation/citations properties\n if (obj.citation && isJsonCitationFormat(obj.citation)) {\n const items = Array.isArray(obj.citation) ? obj.citation : [obj.citation];\n found.push(...items);\n }\n if (obj.citations && isJsonCitationFormat(obj.citations)) {\n const items = Array.isArray(obj.citations)\n ? obj.citations\n : [obj.citations];\n found.push(...items);\n }\n\n // Recurse into object properties\n if (Array.isArray(obj)) {\n for (const item of obj) {\n findJsonCitationsInObject(item, found);\n }\n } else {\n for (const key of Object.keys(obj)) {\n if (key !== \"citation\" && key !== \"citations\") {\n findJsonCitationsInObject(obj[key], found);\n }\n }\n }\n};\n\n/**\n * Extracts XML citations from text using <cite ... /> tags.\n */\nconst extractXmlCitations = (text: string): { [key: string]: Citation } => {\n const normalizedText = normalizeCitations(text);\n\n // Find all <cite ... /> tags\n // This regex handles > characters inside quoted attribute values and escaped quotes:\n // - '(?:[^'\\\\]|\\\\.)*' matches single-quoted strings with escaped chars\n // - \"(?:[^\"\\\\]|\\\\.)*\" matches double-quoted strings with escaped chars\n // - [^'\">/] matches any char that's not a quote, >, or /\n // - The whole pattern repeats until we hit />\n const citeRegex = /<cite\\s+(?:'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|[^'\">/])*\\/>/g;\n const matches = normalizedText.match(citeRegex);\n\n if (!matches || matches.length === 0) return {};\n\n const citations: { [key: string]: Citation } = {};\n const citationCounterRef = { current: 1 };\n\n for (const match of matches) {\n const { citation } = parseCitation(match, undefined, citationCounterRef);\n if (citation && citation.fullPhrase) {\n const citationKey = generateCitationKey(citation);\n citations[citationKey] = citation;\n }\n }\n\n return citations;\n};\n\n/**\n * Extracts all citations from LLM output.\n * Supports both XML <cite ... /> tags (embedded in strings/markdown) and JSON-based citation formats.\n *\n * For object input:\n * - Traverses the object looking for `citation` or `citations` properties matching JSON format\n * - Also stringifies the object to find embedded XML citations in markdown content\n *\n * @param llmOutput - The LLM output (string or object)\n * @returns Dictionary of parsed Citation objects keyed by citation key\n */\nexport const getAllCitationsFromLlmOutput = (\n llmOutput: any\n): { [key: string]: Citation } => {\n if (!llmOutput) return {};\n\n const citations: { [key: string]: Citation } = {};\n\n if (typeof llmOutput === \"object\") {\n // Check if the root object itself is JSON citation format\n if (isJsonCitationFormat(llmOutput)) {\n const jsonCitations = extractJsonCitations(llmOutput);\n Object.assign(citations, jsonCitations);\n } else {\n // Traverse object for nested citation/citations properties\n const foundJsonCitations: Citation[] = [];\n findJsonCitationsInObject(llmOutput, foundJsonCitations);\n\n if (foundJsonCitations.length > 0) {\n const jsonCitations = extractJsonCitations(foundJsonCitations);\n Object.assign(citations, jsonCitations);\n }\n }\n\n // Also stringify and parse for embedded XML citations in markdown\n const text = JSON.stringify(llmOutput);\n const xmlCitations = extractXmlCitations(text);\n Object.assign(citations, xmlCitations);\n } else if (typeof llmOutput === \"string\") {\n // String input - parse for XML citations\n const xmlCitations = extractXmlCitations(llmOutput);\n Object.assign(citations, xmlCitations);\n }\n\n return citations;\n};\n\n/**\n * Groups citations by their attachmentId for multi-file verification scenarios.\n * This is useful when you have citations from multiple files and need to\n * verify them against their respective attachments.\n *\n * @param citations - Array of Citation objects or a dictionary of citations\n * @returns Map of attachmentId to dictionary of citations from that file\n *\n * @example\n * ```typescript\n * const citations = getAllCitationsFromLlmOutput(response.content);\n * const citationsByAttachment = groupCitationsByAttachmentId(citations);\n *\n * // Verify citations for each file\n * for (const [attachmentId, fileCitations] of citationsByAttachment) {\n * const verified = await deepcitation.verifyCitations(attachmentId, fileCitations);\n * // Process verification results...\n * }\n * ```\n */\nexport function groupCitationsByAttachmentId(\n citations: Citation[] | { [key: string]: Citation }\n): Map<string, { [key: string]: Citation }> {\n const grouped = new Map<string, { [key: string]: Citation }>();\n\n // Normalize input to entries\n const entries: [string, Citation][] = Array.isArray(citations)\n ? citations.map((c, idx) => [generateCitationKey(c) || String(idx + 1), c])\n : Object.entries(citations);\n\n for (const [key, citation] of entries) {\n const attachmentId = citation.attachmentId || \"\";\n\n if (!grouped.has(attachmentId)) {\n grouped.set(attachmentId, {});\n }\n\n grouped.get(attachmentId)![key] = citation;\n }\n\n return grouped;\n}\n\n/**\n * Groups citations by their attachmentId and returns as a plain object.\n * Alternative to groupCitationsByAttachmentId that returns a plain object instead of a Map.\n *\n * @param citations - Array of Citation objects or a dictionary of citations\n * @returns Object with attachmentId keys mapping to citation dictionaries\n *\n * @example\n * ```typescript\n * const citations = getAllCitationsFromLlmOutput(response.content);\n * const citationsByAttachment = groupCitationsByAttachmentIdObject(citations);\n *\n * // Verify citations for each file using Promise.all\n * const verificationPromises = Object.entries(citationsByAttachment).map(\n * ([attachmentId, fileCitations]) => deepcitation.verifyCitations(attachmentId, fileCitations)\n * );\n * const results = await Promise.all(verificationPromises);\n * ```\n */\nexport function groupCitationsByAttachmentIdObject(\n citations: Citation[] | { [key: string]: Citation }\n): { [attachmentId: string]: { [key: string]: Citation } } {\n const grouped: { [attachmentId: string]: { [key: string]: Citation } } = {};\n\n // Normalize input to entries\n const entries: [string, Citation][] = Array.isArray(citations)\n ? citations.map((c, idx) => [generateCitationKey(c) || String(idx + 1), c])\n : Object.entries(citations);\n\n for (const [key, citation] of entries) {\n const attachmentId = citation.attachmentId || \"\";\n\n if (!grouped[attachmentId]) {\n grouped[attachmentId] = {};\n }\n\n grouped[attachmentId][key] = citation;\n }\n\n return grouped;\n}\n","import type { Verification } from \"../types/verification.js\";\nimport type { Citation } from \"../types/citation.js\";\nimport { getCitationStatus } from \"./parseCitation.js\";\nimport { generateCitationKey } from \"../react/utils.js\";\n\nexport interface ReplaceCitationsOptions {\n /**\n * If true, leaves the key_span text behind when removing citations.\n * @default false\n */\n leaveKeySpanBehind?: boolean;\n\n /**\n * Map of citation keys to verification results.\n * Used to determine verification status for each citation.\n */\n verifications?: Record<string, Verification>;\n\n /**\n * If true and verifications are provided, appends a verification status indicator.\n * Uses: ✓ (verified), ⚠ (partial), ✗ (not found), ◌ (pending)\n * @default false\n */\n showVerificationStatus?: boolean;\n}\n\n/**\n * Parse attributes from a cite tag in any order.\n * Returns an object with all found attributes.\n */\nconst parseCiteAttributes = (\n citeTag: string\n): Record<string, string | undefined> => {\n const attrs: Record<string, string | undefined> = {};\n\n // Match attribute patterns: key='value' or key=\"value\"\n const attrRegex =\n /([a-zA-Z_][a-zA-Z0-9_]*)\\s*=\\s*(['\"])((?:[^'\"\\\\]|\\\\.)*)\\2/g;\n let match;\n\n while ((match = attrRegex.exec(citeTag)) !== null) {\n const key = match[1]\n .toLowerCase()\n .replace(/([a-z])([A-Z])/g, \"$1_$2\")\n .toLowerCase();\n const value = match[3];\n\n // Normalize key names\n const normalizedKey =\n key === \"fileid\" || key === \"file_id\" || key === \"attachmentid\"\n ? \"attachment_id\"\n : key === \"keyspan\"\n ? \"key_span\"\n : key === \"fullphrase\"\n ? \"full_phrase\"\n : key === \"lineids\"\n ? \"line_ids\"\n : key === \"startpagekey\" || key === \"start_pagekey\"\n ? \"start_page_key\"\n : key;\n\n attrs[normalizedKey] = value;\n }\n\n return attrs;\n};\n\n/**\n * Get verification status indicator character for plain text/terminal output.\n * Returns: ☑️ (fully verified), ✅ (partial match), ❌ (not found), ⌛ (pending/null), ◌ (unknown)\n *\n * For web UI, use the React CitationComponent instead which provides\n * proper styled indicators with colors and accessibility.\n */\nexport const getVerificationTextIndicator = (\n verification: Verification | null | undefined\n): string => {\n const status = getCitationStatus(verification);\n\n if (status.isMiss) return \"❌\";\n // Check for fully verified (not partial) first\n if (status.isVerified && !status.isPartialMatch) return \"☑️\";\n // Then check for partial match\n if (status.isPartialMatch) return \"✅\";\n\n if (status.isPending) return \"⌛\";\n\n return \"◌\";\n};\n\n/**\n * Replaces citation tags in markdown text with optional replacement content.\n *\n * @param markdownWithCitations - The text containing <cite /> tags\n * @param options - Configuration options\n * @returns The text with citations replaced\n *\n * @example\n * ```typescript\n * // Remove all citations\n * const clean = replaceCitations(llmOutput);\n *\n * // Leave key_span text behind\n * const withKeySpans = replaceCitations(llmOutput, { leaveKeySpanBehind: true });\n *\n * // Show verification status indicators\n * const withStatus = replaceCitations(llmOutput, {\n * leaveKeySpanBehind: true,\n * verifications: verificationMap,\n * showVerificationStatus: true,\n * });\n * // Output: \"Revenue grew 45% year-over-year Revenue Growth✓\"\n * ```\n */\nexport const replaceCitations = (\n markdownWithCitations: string,\n options: ReplaceCitationsOptions = {}\n): string => {\n const {\n leaveKeySpanBehind = false,\n verifications,\n showVerificationStatus = false,\n } = options;\n\n // Track citation index for matching with numbered verification keys\n let citationIndex = 0;\n\n // Flexible regex that matches any <cite ... /> tag\n const citationRegex = /<cite\\s+[^>]*?\\/>/g;\n\n return markdownWithCitations.replace(citationRegex, (match) => {\n citationIndex++;\n const attrs = parseCiteAttributes(match);\n\n // Determine what to output\n let output = \"\";\n\n if (leaveKeySpanBehind && attrs.key_span) {\n // Unescape the key_span value\n output = attrs.key_span.replace(/\\\\'/g, \"'\").replace(/\\\\\"/g, '\"');\n }\n\n // Add verification status if requested\n if (showVerificationStatus && verifications) {\n // Try to find verification by various key strategies\n let verification: Verification | undefined;\n\n // Build a Citation object from parsed attributes to generate the key\n const parsePageNumber = (startPageKey?: string): number | undefined => {\n if (!startPageKey) return undefined;\n const match = startPageKey.match(/page[_a-zA-Z]*(\\d+)/);\n return match ? parseInt(match[1], 10) : undefined;\n };\n\n const parseLineIds = (lineIdsStr?: string): number[] | undefined => {\n if (!lineIdsStr) return undefined;\n\n // First expand ranges (e.g., \"62-63\" -> \"62,63\")\n let expanded = lineIdsStr.replace(\n /(\\d+)-(\\d+)/g,\n (_match, start, end) => {\n const startNum = parseInt(start, 10);\n const endNum = parseInt(end, 10);\n if (startNum <= endNum) {\n const range = [];\n for (let i = startNum; i <= endNum; i++) {\n range.push(i);\n }\n return range.join(\",\");\n }\n return start;\n }\n );\n\n const nums = expanded.split(\",\").map((s) => parseInt(s.trim(), 10)).filter((n) => !isNaN(n));\n return nums.length > 0 ? nums : undefined;\n };\n\n // Unescape quotes in fullPhrase and keySpan to match how citations are parsed\n // by getAllCitationsFromLlmOutput (which returns unescaped values)\n const unescapeQuotes = (str: string | undefined): string | undefined =>\n str?.replace(/\\\\'/g, \"'\").replace(/\\\\\"/g, '\"');\n\n const citation: Citation = {\n attachmentId: attrs.attachment_id,\n pageNumber: parsePageNumber(attrs.start_page_key),\n fullPhrase: unescapeQuotes(attrs.full_phrase),\n keySpan: unescapeQuotes(attrs.key_span),\n lineIds: parseLineIds(attrs.line_ids),\n };\n\n // Strategy 1: Match by citationKey (hash) - most reliable\n const citationKey = generateCitationKey(citation);\n verification = verifications[citationKey];\n\n // Strategy 2: Fall back to numbered keys (1, 2, 3, etc.)\n if (!verification) {\n const numericKey = String(citationIndex);\n verification = verifications[numericKey];\n }\n\n const indicator = getVerificationTextIndicator(verification);\n output = output ? `${output}${indicator}` : indicator;\n }\n\n return output;\n });\n};\n\n/**\n * @deprecated Use `replaceCitations` instead. This function is kept for backward compatibility.\n */\nexport const removeCitations = (\n markdownWithCitations: string,\n leaveKeySpanBehind?: boolean\n): string => {\n return replaceCitations(markdownWithCitations, { leaveKeySpanBehind });\n};\n\nexport const removePageNumberMetadata = (pageText: string): string => {\n return pageText\n .replace(/<page_number_\\d+_index_\\d+>/g, \"\")\n .replace(/<\\/page_number_\\d+_index_\\d+>/g, \"\")\n .trim();\n};\n\nexport const removeLineIdMetadata = (pageText: string): string => {\n const lineIdRegex = /<line id=\"[^\"]*\">|<\\/line>/g;\n return pageText.replace(lineIdRegex, \"\");\n};\n\nexport const getCitationPageNumber = (\n startPageKey?: string | null\n): number | null => {\n //page_number_{page_number}_index_{page_index} or page_number_{page_number} or page_key_{page_number}_index_{page_index}\n if (!startPageKey) return null;\n\n //regex first \\d+ is the page number\n const pageNumber = startPageKey.match(/\\d+/)?.[0];\n return pageNumber ? parseInt(pageNumber) : null;\n};\n\n/**\n * Extracts content from a non-self-closing citation tag and moves it before the citation.\n * Converts <cite ...>content</cite> to: content<cite ... />\n *\n * @param citePart - The citation part that may contain inner content\n * @returns The normalized citation with content moved before it\n */\nconst extractAndRelocateCitationContent = (citePart: string): string => {\n // Check if this is a non-self-closing citation: <cite ...>content</cite>\n // Match: <cite with attributes> then content then </cite>\n // The attribute regex handles escaped quotes: (?:[^'\\\\]|\\\\.)* matches non-quote/non-backslash OR backslash+any\n const nonSelfClosingMatch = citePart.match(\n /^(<cite\\s+(?:'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|[^'\">/])*>)([\\s\\S]*?)<\\/cite>$/\n );\n\n if (!nonSelfClosingMatch) {\n // Check if this is an unclosed citation ending with just >\n // Pattern: <cite attributes> (no closing tag)\n const unclosedMatch = citePart.match(\n /^(<cite\\s+(?:'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|[^'\">/])*>)$/\n );\n if (unclosedMatch) {\n // Convert <cite ... > to self-closing <cite ... />\n const selfClosingTag = unclosedMatch[1].replace(/>$/, \" />\");\n return normalizeCitationContent(selfClosingTag);\n }\n // Already self-closing or doesn't match pattern, normalize as-is\n return normalizeCitationContent(citePart);\n }\n\n const [, openingTag, innerContent] = nonSelfClosingMatch;\n\n // If there's no inner content, just normalize the citation\n if (!innerContent || !innerContent.trim()) {\n return normalizeCitationContent(citePart);\n }\n\n // Extract the attributes from the opening tag\n // Convert <cite attributes> to <cite attributes />\n const selfClosingTag = openingTag.replace(/>$/, \" />\");\n\n // Move inner content before the citation and normalize\n // The inner content is trimmed to avoid extra whitespace issues\n const relocatedContent = innerContent.trim();\n\n // Normalize the self-closing citation tag\n const normalizedCitation = normalizeCitationContent(selfClosingTag);\n\n // Return content followed by the citation\n return relocatedContent + normalizedCitation;\n};\n\nexport const normalizeCitations = (response: string): string => {\n let trimmedResponse = response?.trim() || \"\";\n\n // Fix missing < before cite tags\n // LLMs sometimes output 'cite' without the leading '<'\n // Match 'cite' followed by a space and attribute pattern, but NOT preceded by '<' or a letter\n // This avoids matching words like \"excite\" or \"recite\"\n trimmedResponse = trimmedResponse.replace(\n /(?<![<a-zA-Z])cite\\s+(attachment_id|file_id|fileId|attachmentId)\\s*=/gi,\n \"<cite $1=\"\n );\n\n // Split on citation tags - captures three patterns:\n // 1. Self-closing: <cite ... />\n // 2. With closing tag: <cite ...>content</cite>\n // 3. Unclosed (ends with >): <cite ...> (no closing tag, no </cite> anywhere after)\n // Pattern 3 uses negative lookahead to avoid matching when </cite> follows\n const citationParts = trimmedResponse.split(\n /(<cite[\\s\\S]*?(?:\\/>|<\\/cite>|>(?=\\s*$|[\\r\\n])(?![\\s\\S]*<\\/cite>)))/gm\n );\n if (citationParts.length <= 1) {\n // Handle unclosed citations by converting to self-closing\n const unclosedMatch = trimmedResponse.match(/<cite\\s+(?:'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|[^'\">/])*>/g);\n if (unclosedMatch && unclosedMatch.length > 0) {\n const result = trimmedResponse.replace(\n /<cite\\s+(?:'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|[^'\">/])*>/g,\n (match) => match.replace(/>$/, ' />')\n );\n return normalizeCitationContent(result);\n }\n return normalizeCitationContent(trimmedResponse);\n }\n\n trimmedResponse = citationParts\n .map((part) =>\n part.startsWith(\"<cite\")\n ? extractAndRelocateCitationContent(part)\n : part\n )\n .join(\"\");\n\n return trimmedResponse;\n};\n\nconst normalizeCitationContent = (input: string): string => {\n let normalized = input;\n\n // 0. Unescape all backslash-escaped underscores\n // This handles Markdown-processed output where underscores get escaped (e.g., attachment\\_id -> attachment_id, page\\_number\\_1 -> page_number_1)\n normalized = normalized.replace(/\\\\_/g, \"_\");\n\n // 1. Standardize self-closing tags\n // Replace ></cite> with /> for consistency\n normalized = normalized.replace(/><\\/cite>/g, \"/>\");\n\n const canonicalizeCiteAttributeKey = (key: string): string => {\n const lowerKey = key.toLowerCase();\n if (lowerKey === \"fullphrase\" || lowerKey === \"full_phrase\")\n return \"full_phrase\";\n if (lowerKey === \"lineids\" || lowerKey === \"line_ids\") return \"line_ids\";\n if (\n lowerKey === \"startpagekey\" ||\n lowerKey === \"start_pagekey\" ||\n lowerKey === \"start_page_key\"\n )\n return \"start_page_key\";\n if (\n lowerKey === \"fileid\" ||\n lowerKey === \"file_id\" ||\n lowerKey === \"attachmentid\" ||\n lowerKey === \"attachment_id\"\n )\n return \"attachment_id\";\n if (lowerKey === \"keyspan\" || lowerKey === \"key_span\") return \"key_span\";\n if (lowerKey === \"reasoning\" || lowerKey === \"value\") return lowerKey;\n if (\n lowerKey === \"timestamps\" ||\n lowerKey === \"timestamp\" ||\n lowerKey === \"timestamps\"\n )\n return \"timestamps\";\n\n return lowerKey;\n };\n\n const htmlEntityMap: Record<string, string> = {\n '"': '\"',\n ''': \"'\",\n '<': '<',\n '>': '>',\n '&': '&',\n };\n const htmlEntityRegex = /&(?:quot|apos|lt|gt|amp);/g;\n const decodeHtmlEntities = (str: string) => {\n return str.replace(htmlEntityRegex, (match) => htmlEntityMap[match] || match);\n };\n\n const textAttributeRegex =\n /(fullPhrase|full_phrase|keySpan|key_span|reasoning|value)\\s*=\\s*(['\"])([\\s\\S]*?)(?=\\s+(?:line_ids|lineIds|timestamps|fileId|file_id|attachmentId|attachment_id|start_page_key|start_pageKey|startPageKey|keySpan|key_span|reasoning|value|full_phrase)\\s*=|\\s*\\/>|['\"]>)/gm;\n\n normalized = normalized.replace(\n textAttributeRegex,\n (_match, key, openQuote, rawContent) => {\n let content = rawContent;\n\n if (content.endsWith(openQuote)) {\n content = content.slice(0, -1);\n }\n\n // Flatten newlines and remove markdown markers\n content = content.replace(/(\\r?\\n)+|(\\*|_){2,}|\\*/g, (match: string) => {\n if (match.includes('\\n') || match.includes('\\r')) return ' ';\n return '';\n });\n\n content = decodeHtmlEntities(content);\n\n // Normalize quotes\n content = content.replace(/\\\\\\\\'/g, \"'\").replace(/\\\\'/g, \"'\").replace(/'/g, \"\\\\'\");\n content = content.replace(/\\\\\\\\\"/g, '\"').replace(/\\\\\"/g, '\"').replace(/\"/g, '\\\\\"');\n\n return `${canonicalizeCiteAttributeKey(key)}='${content}'`;\n }\n );\n normalized = normalized.replace(\n /(line_ids|lineIds|timestamps)=['\"]?([\\[\\]\\(\\){}A-Za-z0-9_\\-, ]+)['\"]?(\\s*\\/?>|\\s+)/gm,\n (_match, key, rawValue, trailingChars) => {\n // Clean up the value (remove generic text, keep numbers/separators)\n let cleanedValue = rawValue.replace(/[A-Za-z\\[\\]\\(\\){}]/g, \"\");\n\n // Expand ranges (e.g., \"1-3\" -> \"1,2,3\")\n cleanedValue = cleanedValue.replace(\n /(\\d+)-(\\d+)/g,\n (_rangeMatch: string, start: string, end: string) => {\n const startNum = parseInt(start, 10);\n const endNum = parseInt(end, 10);\n const range = [];\n\n // Handle ascending range\n if (startNum <= endNum) {\n for (let i = startNum; i <= endNum; i++) {\n range.push(i);\n }\n } else {\n // Fallback for weird descending ranges or just return start\n range.push(startNum);\n }\n return range.join(\",\");\n }\n );\n\n // Normalize commas\n cleanedValue = cleanedValue.replace(/,+/g, \",\").replace(/^,|,$/g, \"\");\n\n // Return standardized format: key='value' + preserved trailing characters (space or />)\n return `${canonicalizeCiteAttributeKey(\n key\n )}='${cleanedValue}'${trailingChars}`;\n }\n );\n\n // 4. Re-order <cite ... /> attributes to match the strict parsing expectations in `citationParser.ts`\n // (the parser uses regexes that assume a canonical attribute order).\n const reorderCiteTagAttributes = (tag: string): string => {\n // Match both single-quoted and double-quoted attributes\n const attrRegex =\n /([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(['\"])((?:[^'\"\\\\\\n]|\\\\.)*)(?:\\2)/g;\n const attrs: Record<string, string> = {};\n let match: RegExpExecArray | null;\n\n while ((match = attrRegex.exec(tag))) {\n const rawKey = match[1];\n const value = match[3]; // match[2] is the quote character\n const key = canonicalizeCiteAttributeKey(rawKey);\n attrs[key] = value;\n }\n\n // If we didn't find any parsable attrs, don't touch the tag.\n const keys = Object.keys(attrs);\n if (keys.length === 0) return tag;\n\n const hasTimestamps =\n typeof attrs.timestamps === \"string\" && attrs.timestamps.length > 0;\n const startPageKeys = keys.filter((k) => k.startsWith(\"start_page\"));\n\n const ordered: string[] = [];\n\n // Shared first\n if (attrs.attachment_id) ordered.push(\"attachment_id\");\n\n if (hasTimestamps) {\n // AV citations: attachment_id, full_phrase, key_span, timestamps, (optional reasoning/value), then any extras\n if (attrs.full_phrase) ordered.push(\"full_phrase\");\n if (attrs.key_span) ordered.push(\"key_span\");\n ordered.push(\"timestamps\");\n } else {\n // Document citations: attachment_id, start_page*, full_phrase, key_span, line_ids, (optional reasoning/value), then any extras\n if (startPageKeys.includes(\"start_page_key\"))\n ordered.push(\"start_page_key\");\n startPageKeys\n .filter((k) => k !== \"start_page_key\")\n .sort()\n .forEach((k) => ordered.push(k));\n\n if (attrs.full_phrase) ordered.push(\"full_phrase\");\n if (attrs.key_span) ordered.push(\"key_span\");\n if (attrs.line_ids) ordered.push(\"line_ids\");\n }\n\n // Optional attrs supported by the parser (but not required)\n if (attrs.reasoning) ordered.push(\"reasoning\");\n if (attrs.value) ordered.push(\"value\");\n\n // Any remaining attributes, stable + deterministic (alpha)\n const used = new Set(ordered);\n keys\n .filter((k) => !used.has(k))\n .sort()\n .forEach((k) => ordered.push(k));\n\n const rebuiltAttrs = ordered.map((k) => `${k}='${attrs[k]}'`).join(\" \");\n return `<cite ${rebuiltAttrs} />`;\n };\n\n normalized = normalized.replace(/<cite\\b[\\s\\S]*?\\/>/gm, (tag) =>\n reorderCiteTagAttributes(tag)\n );\n\n return normalized;\n};\n","import type { Citation } from \"../types/citation.js\";\nimport type { Verification } from \"../types/verification.js\";\nimport { sha1Hash } from \"../utils/sha.js\";\nimport { getCitationPageNumber } from \"../parsing/normalizeCitation.js\";\n\n// =============================================================================\n// UTILITY FUNCTIONS\n// =============================================================================\n\nexport function cn(...classes: (string | undefined | null | false)[]): string {\n return classes.filter(Boolean).join(\" \");\n}\n\n/**\n * Type guard to check if a citation is a URL citation (type: \"url\" or has url field).\n */\nexport function isUrlCitation(citation: Citation): boolean {\n return citation.type === \"url\" || (typeof citation.url === \"string\" && citation.url.length > 0);\n}\n\n/**\n * Generates a unique, deterministic key for a citation based on its content.\n * Works with both document and URL citation types.\n *\n * For URL citations, the URL is included in the key generation for uniqueness.\n *\n * @param citation - The citation to generate a key for\n * @returns A unique, deterministic key for the citation\n */\nexport function generateCitationKey(citation: Citation): string {\n const pageNumber =\n citation.pageNumber || getCitationPageNumber(citation.startPageKey);\n\n // Base key parts for all citations\n const keyParts = [\n citation.attachmentId || \"\",\n pageNumber?.toString() || \"\",\n citation.fullPhrase || \"\",\n citation.keySpan?.toString() || \"\",\n citation.lineIds?.join(\",\") || \"\",\n citation.timestamps?.startTime || \"\",\n citation.timestamps?.endTime || \"\",\n ];\n\n // Add URL-specific fields if present\n if (isUrlCitation(citation)) {\n keyParts.push(\n citation.url || \"\",\n citation.title || \"\",\n citation.domain || \"\",\n );\n }\n\n return sha1Hash(keyParts.join(\"|\")).slice(0, 16);\n}\n\n/**\n * Generates a unique, deterministic key for a verification based on its content.\n * @param verification - The verification to generate a key for\n * @returns\n */\nexport function generateVerificationKey(verification: Verification): string {\n const keyParts = [\n verification.attachmentId || \"\",\n verification.label || \"\",\n verification.verifiedFullPhrase || \"\",\n verification.verifiedKeySpan || \"\",\n verification.verifiedLineIds?.join(\",\") || \"\",\n verification.verifiedPageNumber?.toString() || \"\",\n\n verification.verifiedTimestamps?.startTime || \"\",\n verification.verifiedTimestamps?.endTime || \"\",\n\n verification.verifiedMatchSnippet || \"\",\n verification.hitIndexWithinPage?.toString() || \"\",\n ];\n\n return sha1Hash(keyParts.join(\"|\")).slice(0, 16);\n}\n\n/**\n * Generates a unique instance ID for a citation component render.\n * Combines the citation key with a random suffix for uniqueness.\n */\nexport function generateCitationInstanceId(citationKey: string): string {\n const randomSuffix = Math.random().toString(36).slice(2, 11);\n return `${citationKey}-${randomSuffix}`;\n}\n\n/**\n * Gets the display text for a citation (keySpan with fallback to number).\n */\nexport function getCitationDisplayText(\n citation: Citation,\n options: {\n fallbackDisplay?: string | null;\n } = {}\n): string {\n const { fallbackDisplay } = options;\n return (\n citation.keySpan?.toString() ||\n citation.citationNumber?.toString() ||\n fallbackDisplay ||\n \"1\"\n );\n}\n\n/**\n * Gets the citation number as a string.\n */\nexport function getCitationNumber(citation: Citation): string {\n return citation.citationNumber?.toString() || \"1\";\n}\n\n/**\n * Gets the keySpan text from a citation.\n */\nexport function getCitationKeySpanText(citation: Citation): string {\n return citation.keySpan?.toString() || \"\";\n}\n\n/**\n * Joins class names, filtering out falsy values.\n * This is a minimal implementation for the base component.\n */\nexport function classNames(\n ...classes: (string | undefined | null | false)[]\n): string {\n return classes.filter(Boolean).join(\" \");\n}\n\n/**\n * Default padding values for citation styling.\n */\nexport const CITATION_X_PADDING = 4;\nexport const CITATION_Y_PADDING = 1;\n"]}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
'use strict';var d=Object.defineProperty;var e=(b,a,c)=>a in b?d(b,a,{enumerable:true,configurable:true,writable:true,value:c}):b[a]=c;var f=(b,a,c)=>e(b,typeof a!="symbol"?a+"":a,c);exports.a=f
|
|
1
|
+
'use strict';var d=Object.defineProperty;var e=(b,a,c)=>a in b?d(b,a,{enumerable:true,configurable:true,writable:true,value:c}):b[a]=c;var f=(b,a,c)=>e(b,typeof a!="symbol"?a+"":a,c);exports.a=f;//# sourceMappingURL=chunk-BYLIBOAU.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-BYLIBOAU.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-BYLIBOAU.cjs"}
|
|
@@ -68,4 +68,5 @@ ${a}`).join(`
|
|
|
68
68
|
|
|
69
69
|
${d}
|
|
70
70
|
|
|
71
|
-
${i}`;}return {enhancedSystemPrompt:s,enhancedUserPrompt:c}}var O={type:"object",properties:{attachmentId:{type:"string"},reasoning:{type:"string",description:"The logic connecting the form section requirements to the supporting source citation (think first!)"},fullPhrase:{type:"string",description:"The verbatim text of the terse phrase inside <attachment_text /> to support the citation (if there is a detected OCR correction, use the corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},lineIds:{type:"array",items:{type:"number"},description:"Infer lineIds, as we only provide the first, last, and every 5th line. Provide inclusive lineIds for the fullPhrase."}},required:["attachmentId","reasoning","fullPhrase","keySpan","startPageKey","lineIds"]},v={type:"object",properties:{attachmentId:{type:"string"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},fullPhrase:{type:"string",description:"The exact verbatim text of the phrase or paragraph from the source document to support the citation (if there is a detected OCR correction, use the verbatim corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},timestamps:{type:"object",properties:{startTime:{type:"string"},endTime:{type:"string"}},required:["startTime","endTime"],description:"The timestamp of the audio or video frame including milliseconds formatted as: HH:MM:SS.SSS"}},required:["attachmentId","startPageKey","fullPhrase","keySpan","timestamps"]};var u=4,P=3,I=5;function S(t,n){let i={};for(let e of t){for(let r=u;r<=e.length;r++){let s=e.slice(0,r),c=(s.match(/\d/g)||[]).length,o=(s.match(/[a-zA-Z]/g)||[]).length;if(s.length<u||c>0&&o<P||c===0&&o<I||t.some(m=>m!==e&&m.startsWith(s)))continue;let p=m=>m.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),a=(n.match(new RegExp(p(s),"g"))||[]).length,l=(n.match(new RegExp(p(e),"g"))||[]).length;if(a===l){i[s]=e;break}}if(!Object.values(i).includes(e))throw new Error(`Cannot find a safe unique prefix for ID "${e}" that meets the minimum requirements (length: ${u})`)}return i}function w(t,n){if(!n||n.length===0)return {compressed:t,prefixMap:{}};let i=Array.from(new Set(n)),e=JSON.stringify(t),r=S(i,e),s=Object.keys(r).sort((o,p)=>p.length-o.length),c=e;for(let o of s){let a=r[o].replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");c=c.replace(new RegExp(a,"g"),o);}return {compressed:JSON.parse(c),prefixMap:r}}function C(t,n){if(!n||Object.keys(n).length===0)return t;let i=Object.entries(n).sort((a,l)=>l[0].length-a[0].length),e,r=false;typeof t=="string"?e=t:(e=JSON.stringify(t),r=true);let s=e?.length;for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");e=e.replace(new RegExp(m,"g"),l);}let c=["attachmentId","attachment_id","attachment_ID","attachmentID","fileId","file_id","file_ID","fileID","fileid"];for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),h=c.join("|"),f="([\"'`])",g=new RegExp(`(${h})(\\s*=\\s*)${f}${m}\\3`,"g");e=e.replace(g,`$1$2$3${l}$3`);}let o=e?.length,p=s-o;if(p>0)throw new Error(`[decompressedPromptIds] diff ${p} originalLength ${s} newLength ${o}`);return r?JSON.parse(e):e}export{_ as a,y as b,d as c,T as d,x as e,R as f,O as g,v as h,w as i,C as j}
|
|
71
|
+
${i}`;}return {enhancedSystemPrompt:s,enhancedUserPrompt:c}}var O={type:"object",properties:{attachmentId:{type:"string"},reasoning:{type:"string",description:"The logic connecting the form section requirements to the supporting source citation (think first!)"},fullPhrase:{type:"string",description:"The verbatim text of the terse phrase inside <attachment_text /> to support the citation (if there is a detected OCR correction, use the corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},lineIds:{type:"array",items:{type:"number"},description:"Infer lineIds, as we only provide the first, last, and every 5th line. Provide inclusive lineIds for the fullPhrase."}},required:["attachmentId","reasoning","fullPhrase","keySpan","startPageKey","lineIds"]},v={type:"object",properties:{attachmentId:{type:"string"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},fullPhrase:{type:"string",description:"The exact verbatim text of the phrase or paragraph from the source document to support the citation (if there is a detected OCR correction, use the verbatim corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},timestamps:{type:"object",properties:{startTime:{type:"string"},endTime:{type:"string"}},required:["startTime","endTime"],description:"The timestamp of the audio or video frame including milliseconds formatted as: HH:MM:SS.SSS"}},required:["attachmentId","startPageKey","fullPhrase","keySpan","timestamps"]};var u=4,P=3,I=5;function S(t,n){let i={};for(let e of t){for(let r=u;r<=e.length;r++){let s=e.slice(0,r),c=(s.match(/\d/g)||[]).length,o=(s.match(/[a-zA-Z]/g)||[]).length;if(s.length<u||c>0&&o<P||c===0&&o<I||t.some(m=>m!==e&&m.startsWith(s)))continue;let p=m=>m.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),a=(n.match(new RegExp(p(s),"g"))||[]).length,l=(n.match(new RegExp(p(e),"g"))||[]).length;if(a===l){i[s]=e;break}}if(!Object.values(i).includes(e))throw new Error(`Cannot find a safe unique prefix for ID "${e}" that meets the minimum requirements (length: ${u})`)}return i}function w(t,n){if(!n||n.length===0)return {compressed:t,prefixMap:{}};let i=Array.from(new Set(n)),e=JSON.stringify(t),r=S(i,e),s=Object.keys(r).sort((o,p)=>p.length-o.length),c=e;for(let o of s){let a=r[o].replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");c=c.replace(new RegExp(a,"g"),o);}return {compressed:JSON.parse(c),prefixMap:r}}function C(t,n){if(!n||Object.keys(n).length===0)return t;let i=Object.entries(n).sort((a,l)=>l[0].length-a[0].length),e,r=false;typeof t=="string"?e=t:(e=JSON.stringify(t),r=true);let s=e?.length;for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");e=e.replace(new RegExp(m,"g"),l);}let c=["attachmentId","attachment_id","attachment_ID","attachmentID","fileId","file_id","file_ID","fileID","fileid"];for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),h=c.join("|"),f="([\"'`])",g=new RegExp(`(${h})(\\s*=\\s*)${f}${m}\\3`,"g");e=e.replace(g,`$1$2$3${l}$3`);}let o=e?.length,p=s-o;if(p>0)throw new Error(`[decompressedPromptIds] diff ${p} originalLength ${s} newLength ${o}`);return r?JSON.parse(e):e}export{_ as a,y as b,d as c,T as d,x as e,R as f,O as g,v as h,w as i,C as j};//# sourceMappingURL=chunk-KBDVUQEE.js.map
|
|
72
|
+
//# sourceMappingURL=chunk-KBDVUQEE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/prompts/citationPrompts.ts","../src/prompts/promptCompression.ts"],"names":["CITATION_MARKDOWN_SYNTAX_PROMPT","AV_CITATION_MARKDOWN_SYNTAX_PROMPT","CITATION_REMINDER","CITATION_AV_REMINDER","wrapSystemCitationPrompt","options","systemPrompt","isAudioVideo","citationPrompt","reminder","wrapCitationPrompt","userPrompt","deepTextPromptPortion","enhancedSystemPrompt","enhancedUserPrompt","fileTexts","text","index","CITATION_JSON_OUTPUT_FORMAT","CITATION_AV_BASED_JSON_OUTPUT_FORMAT","MIN_PREFIX_LENGTH","MIN_CHARACTERS_PER_PREFIX_WITH_AT_LEAST_ONE_DIGIT","MIN_CHARACTERS_PER_PREFIX_WITH_NO_DIGITS","buildSafePrefixMap","ids","prompt","map","id","len","prefix","digitCount","letterCount","other","esc","s","prefixCount","fullCount","compressPromptIds","obj","uniqueIds","prefixMap","prefixes","a","b","compressedText","escFull","decompressPromptIds","compressed","entries","shouldParseBack","originalLength","full","escPrefix","idAttributeKeys","keyPattern","quotePattern","re","newLength","diff"],"mappings":"AAAO,IAAMA,CAAAA,CAAkC;AAAA;AAAA;;AAAA;AAAA;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;AAAA;;AAAA,CAAA,CAoClCC,CAAAA,CAAqC;AAAA;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA,CAAA,CA8BrCC,CAAAA,CAAoB,iKAAA,CAKpBC,CAAAA,CAAuB,sJAsE7B,SAASC,CAAAA,CACdC,CAAAA,CACQ,CACR,GAAM,CAAE,YAAA,CAAAC,CAAAA,CAAc,YAAA,CAAAC,CAAAA,CAAe,KAAM,CAAA,CAAIF,CAAAA,CAEzCG,CAAAA,CAAiBD,CAAAA,CACnBN,CAAAA,CACAD,CAAAA,CAEES,CAAAA,CAAWF,CAAAA,CAAeJ,CAAAA,CAAuBD,CAAAA,CAGvD,OAAO,CAAA,EAAGM,CAAAA,CAAe,MAAM;;AAAA,EAAOF,CAAAA,CAAa,MAAM;;AAAA,EAAOG,CAAQ,CAAA,CAC1E,CAiCO,SAASC,CAAAA,CACdL,EAC0B,CAC1B,GAAM,CACJ,YAAA,CAAAC,CAAAA,CACA,UAAA,CAAAK,EACA,qBAAA,CAAAC,CAAAA,CACA,YAAA,CAAAL,CAAAA,CAAe,KACjB,CAAA,CAAIF,EAEEQ,CAAAA,CAAuBT,CAAAA,CAAyB,CACpD,YAAA,CAAAE,CAAAA,CACA,YAAA,CAAAC,CACF,CAAC,CAAA,CAGGO,CAAAA,CAAqBH,CAAAA,CAEzB,GAAIC,CAAAA,CAAuB,CACzB,IAAMG,CAAAA,CAAY,KAAA,CAAM,OAAA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OA,CAAAA,CAAK,OAAA,CAAQ,IAAI,MAAA,CAAOoC,CAAAA,CAAW,GAAG,EAAGD,CAAI,EACtD,CAKA,IAAME,CAAAA,CAAkB,CACtB,cAAA,CACA,eAAA,CACA,eAAA,CACA,cAAA,CACA,QAAA,CACA,SAAA,CACA,SAAA,CACA,QAAA,CACA,QACF,CAAA,CAGA,OAAW,CAACxB,CAAAA,CAAQsB,CAAI,CAAA,GAAKH,CAAAA,CAAS,CACpC,IAAMI,CAAAA,CAAYvB,CAAAA,CAAO,OAAA,CAAQ,wBAAA,CAA0B,MAAM,CAAA,CAC3DyB,CAAAA,CAAaD,CAAAA,CAAgB,IAAA,CAAK,GAAG,CAAA,CACrCE,CAAAA,CAAe,UAAA,CAIfC,CAAAA,CAAK,IAAI,MAAA,CACb,CAAA,CAAA,EAAIF,CAAU,CAAA,YAAA,EAAeC,CAAY,CAAA,EAAGH,CAAS,CAAA,GAAA,CAAA,CACrD,GACF,CAAA,CACApC,CAAAA,CAAOA,EAAK,OAAA,CAAQwC,CAAAA,CAAI,CAAA,MAAA,EAASL,CAAI,CAAA,EAAA,CAAI,EAC3C,CACA,IAAMM,CAAAA,CAAYzC,CAAAA,EAAM,MAAA,CAElB0C,CAAAA,CAAOR,CAAAA,CAAiBO,CAAAA,CAC9B,GAAIC,CAAAA,CAAO,EACT,MAAM,IAAI,KAAA,CACR,CAAA,6BAAA,EAAgCA,CAAI,CAAA,gBAAA,EAAmBR,CAAc,CAAA,WAAA,EAAcO,CAAS,CAAA,CAC9F,CAAA,CAGF,OAAOR,CAAAA,CAAmB,IAAA,CAAK,KAAA,CAAMjC,CAAI,EAAUA,CACrD","file":"chunk-KBDVUQEE.js","sourcesContent":["export const CITATION_MARKDOWN_SYNTAX_PROMPT = `\n<citation-instructions priority=\"critical\">\n## REQUIRED: Citation Format\n\n### Scope (Where to use)\nFor every claim, value, or fact in your chat response; you MUST cite the attachment using this exact syntax:\n\n<cite attachment_id='ID' reasoning='why this supports the claim' full_phrase='verbatim quote' key_span='1-3 key words' start_page_key='page_number_N_index_I' line_ids='X-Y' />\n\n### Syntax Rules (MUST follow)\n\n1. **attachment_id**: Use the exact ID from the source document\n2. **reasoning**: Brief explanation of why this citation supports your claim (think first!)\n3. **full_phrase**: Copy text VERBATIM from source. Escape quotes (\\\\') and newlines (\\\\n).\n4. **key_span**: The 1-3 most important words or value from full_phrase\n5. **start_page_key**: ONLY use format \\`page_number_N_index_I\\` from page tags (e.g., \\`<page_number_1_index_0>\\`). Never extract page numbers from document content.\n6. **line_ids**: Inclusive range (e.g., '2-6' or '4'). Infer intermediate lines since only every 5th line is shown.\n\n### Placement Rules\n\n- Place <cite /> inline, typically at the end of a claim\n- One citation per distinct idea, concept, or value (a sentence citing 3 different values needs 3 citations)\n- Do NOT group citations at the end of the document\n- The <cite /> tag is self-closing - never use <cite>...</cite>\n\n### Example Citation 1\n\nThe company reported strong growth<cite attachment_id='abc123' reasoning='directly states revenue growth percentage' full_phrase='Revenue increased 45% year-over-year to $2.3 billion' key_span='increased 45%' start_page_key='page_number_2_index_1' line_ids='12-14' />\n\n### Example Citation 2\n\nThe total amount is $500 USD <cite attachment_id='abc123' reasoning='directly states the total amount' full_phrase='The total amount is $500 USD' key_span='$500 USD' start_page_key='page_number_2_index_1' line_ids='12-14' />\n</citation-instructions>\n\n`;\n\nexport const AV_CITATION_MARKDOWN_SYNTAX_PROMPT = `\n<citation-instructions priority=\"critical\">\n## REQUIRED: Audio/Video Citation Format\n\nFor every claim, value, or fact; you MUST cite the attachment using this exact syntax:\n\n<cite attachment_id='ID' reasoning='why this supports the claim' full_phrase='verbatim transcript quote' key_span='1-3 key words' timestamps='HH:MM:SS.SSS-HH:MM:SS.SSS' />\n\n### Syntax Rules (MUST follow)\n\n1. **attachment_id**: Use the exact ID from the source\n2. **reasoning**: Brief explanation of why this citation supports your claim (think first!)\n3. **full_phrase**: Copy transcript text VERBATIM. Escape quotes (\\\\') and newlines (\\\\n).\n4. **key_span**: The 1-3 most important words or value from full_phrase\n5. **timestamps**: Start and end time with milliseconds (e.g., '00:01:23.456-00:01:45.789')\n\n### Placement Rules\n\n- Place <cite /> inline, typically at the end of a claim\n- One citation per distinct idea, concept, or value (a sentence citing 3 different values needs 3 citations)\n- Do NOT group citations at the end of the document\n- The <cite /> tag is self-closing - never use <cite>...</cite>\n\n</citation-instructions>\n`;\n\n/**\n * A brief reminder to reinforce citation requirements in user messages.\n * Use this when you want to add emphasis without repeating full instructions.\n */\nexport const CITATION_REMINDER = `<citation-reminder>STOP and CHECK: Did you use <cite /> tags with all required attributes for every claim, value, or fact from attachments?</citation-reminder>`;\n\n/**\n * Audio/video version of the citation reminder.\n */\nexport const CITATION_AV_REMINDER = `<citation-reminder>STOP and CHECK: Did you use <cite /> tags with timestamps for every claim, value, or fact from source media?</citation-reminder>`;\n\nexport interface WrapSystemPromptOptions {\n /** The original system prompt to wrap with citation instructions */\n systemPrompt: string;\n /** Whether to use audio/video citation format (with timestamps) instead of text-based (with line IDs) */\n isAudioVideo?: boolean;\n}\n\nexport interface WrapCitationPromptOptions {\n /** The original system prompt to wrap with citation instructions */\n systemPrompt: string;\n /** The original user prompt */\n userPrompt: string;\n /** The extracted file text with metadata (from uploadFile response). Can be a single string or array for multiple files. */\n deepTextPromptPortion?: string | string[];\n /** Whether to use audio/video citation format (with timestamps) instead of text-based (with line IDs) */\n isAudioVideo?: boolean;\n}\n\nexport interface WrapCitationPromptResult {\n /** Enhanced system prompt with citation instructions */\n enhancedSystemPrompt: string;\n /** Enhanced user prompt (currently passed through unchanged) */\n enhancedUserPrompt: string;\n}\n\n/**\n * Wraps your existing system prompt with DeepCitation's citation syntax instructions.\n * This enables LLMs to output verifiable citations that can be checked against attachments.\n *\n * ## Why We Wrap (Instructions at Start + Reminder at End)\n *\n * This function places full citation instructions at the **start** of your system prompt\n * and a brief reminder at the **end**. This \"wrap\" strategy is intentional and based on\n * two key principles:\n *\n * ### 1. Recency Effect (RE2)\n * LLMs exhibit a \"recency bias\" where instructions closer to the end of the context\n * window have stronger influence on output. The reminder at the end reinforces citation\n * requirements right before generation begins.\n *\n * ### 2. Chain-of-Thought (CoT) Attribute Ordering\n * The citation attributes are ordered to encourage the model to \"think first\":\n * `attachment_id` → `reasoning` → `full_phrase` → `key_span` → `start_page_key` → `line_ids`\n *\n * By placing `reasoning` early, the model must articulate WHY it's citing before\n * specifying WHAT it's citing. Then `full_phrase` comes before `key_span` so the model\n * first produces the complete verbatim quote, then extracts the key span from it,\n * ensuring `key_span` is always a valid substring of `full_phrase`.\n *\n * ### Why Not Just Append?\n * In large system prompts, appended instructions can get \"lost\" in the middle of the\n * effective context. Prepending ensures citation instructions have high priority,\n * while the reminder leverages recency for reinforcement.\n *\n * @example\n * ```typescript\n * import { wrapSystemCitationPrompt } from '@deepcitation/deepcitation-js';\n *\n * const systemPrompt = \"You are a helpful assistant that analyzes documents.\";\n * const enhanced = wrapSystemCitationPrompt({ systemPrompt });\n *\n * // Use enhanced prompt with your LLM\n * const response = await openai.chat.completions.create({\n * messages: [{ role: \"system\", content: enhanced }],\n * // ...\n * });\n * ```\n */\nexport function wrapSystemCitationPrompt(\n options: WrapSystemPromptOptions\n): string {\n const { systemPrompt, isAudioVideo = false } = options;\n\n const citationPrompt = isAudioVideo\n ? AV_CITATION_MARKDOWN_SYNTAX_PROMPT\n : CITATION_MARKDOWN_SYNTAX_PROMPT;\n\n const reminder = isAudioVideo ? CITATION_AV_REMINDER : CITATION_REMINDER;\n\n // Full instructions at start (high priority), brief reminder at end (recency effect)\n return `${citationPrompt.trim()}\\n\\n${systemPrompt.trim()}\\n\\n${reminder}`;\n}\n\n/**\n * Wraps both system and user prompts with DeepCitation's citation syntax instructions.\n * This is the recommended way to prepare prompts for citation verification.\n *\n * @example\n * ```typescript\n * import { wrapCitationPrompt } from '@deepcitation/deepcitation-js';\n *\n * // Single file\n * const { enhancedSystemPrompt, enhancedUserPrompt } = wrapCitationPrompt({\n * systemPrompt: \"You are a helpful assistant.\",\n * userPrompt: \"Analyze this document and summarize it.\",\n * deepTextPromptPortion, // from uploadFile response\n * });\n *\n * // Multiple files\n * const { enhancedSystemPrompt, enhancedUserPrompt } = wrapCitationPrompt({\n * systemPrompt: \"You are a helpful assistant.\",\n * userPrompt: \"Compare these documents.\",\n * deepTextPromptPortion: [deepTextPromptPortion1, deepTextPromptPortion2], // array of file texts\n * });\n *\n * // Use enhanced prompts with your LLM\n * const response = await llm.chat({\n * messages: [\n * { role: \"system\", content: enhancedSystemPrompt },\n * { role: \"user\", content: enhancedUserPrompt },\n * ],\n * });\n * ```\n */\nexport function wrapCitationPrompt(\n options: WrapCitationPromptOptions\n): WrapCitationPromptResult {\n const {\n systemPrompt,\n userPrompt,\n deepTextPromptPortion,\n isAudioVideo = false,\n } = options;\n\n const enhancedSystemPrompt = wrapSystemCitationPrompt({\n systemPrompt,\n isAudioVideo,\n });\n\n // Build enhanced user prompt with file content if provided\n let enhancedUserPrompt = userPrompt;\n\n if (deepTextPromptPortion) {\n const fileTexts = Array.isArray(deepTextPromptPortion)\n ? deepTextPromptPortion\n : [deepTextPromptPortion];\n const fileContent = fileTexts\n .map((text, index) => {\n if (fileTexts.length === 1) {\n return `\\n${text}`;\n }\n return `\\n${text}`;\n })\n .join(\"\\n\\n\");\n\n enhancedUserPrompt = `${fileContent}\\n\\n${CITATION_REMINDER}\\n\\n${userPrompt}`;\n }\n\n\n\n return {\n enhancedSystemPrompt,\n enhancedUserPrompt,\n };\n}\n\nexport const CITATION_JSON_OUTPUT_FORMAT = {\n type: \"object\",\n properties: {\n attachmentId: { type: \"string\" },\n reasoning: {\n type: \"string\",\n description:\n \"The logic connecting the form section requirements to the supporting source citation (think first!)\",\n },\n fullPhrase: {\n type: \"string\",\n description:\n \"The verbatim text of the terse phrase inside <attachment_text /> to support the citation (if there is a detected OCR correction, use the corrected text)\",\n },\n keySpan: {\n type: \"string\",\n description:\n \"The verbatim 1-3 words within fullPhrase that best support the citation\",\n },\n startPageKey: {\n type: \"string\",\n description:\n 'Only return a result like \"page_number_PAGE_index_INDEX\" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.',\n },\n lineIds: {\n type: \"array\",\n items: { type: \"number\" },\n description:\n \"Infer lineIds, as we only provide the first, last, and every 5th line. Provide inclusive lineIds for the fullPhrase.\",\n },\n },\n required: [\n \"attachmentId\",\n \"reasoning\",\n \"fullPhrase\",\n \"keySpan\",\n \"startPageKey\",\n \"lineIds\",\n ],\n};\n\nexport const CITATION_AV_BASED_JSON_OUTPUT_FORMAT = {\n type: \"object\",\n properties: {\n attachmentId: { type: \"string\" },\n startPageKey: {\n type: \"string\",\n description:\n 'Only return a result like \"page_number_PAGE_index_INDEX\" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.',\n },\n fullPhrase: {\n type: \"string\",\n description:\n \"The exact verbatim text of the phrase or paragraph from the source document to support the citation (if there is a detected OCR correction, use the verbatim corrected text)\",\n },\n keySpan: {\n type: \"string\",\n description:\n \"The verbatim 1-3 words within fullPhrase that best support the citation\",\n },\n timestamps: {\n type: \"object\",\n properties: {\n startTime: { type: \"string\" },\n endTime: { type: \"string\" },\n },\n required: [\"startTime\", \"endTime\"],\n description:\n \"The timestamp of the audio or video frame including milliseconds formatted as: HH:MM:SS.SSS\",\n },\n },\n required: [\"attachmentId\", \"startPageKey\", \"fullPhrase\", \"keySpan\", \"timestamps\"],\n};\n","import { CompressedResult } from \"./types.js\";\n\nconst MIN_PREFIX_LENGTH = 4;\nconst MIN_CHARACTERS_PER_PREFIX_WITH_AT_LEAST_ONE_DIGIT = 3;\nconst MIN_CHARACTERS_PER_PREFIX_WITH_NO_DIGITS = 5;\n\n/**\n * Build a map from each ID's minimal unique prefix to the full ID,\n * such that the prefix only ever appears in the prompt where the full ID appears.\n */\nfunction buildSafePrefixMap(\n ids: string[],\n prompt: string\n): Record<string, string> {\n const map: Record<string, string> = {};\n\n for (const id of ids) {\n for (let len = MIN_PREFIX_LENGTH; len <= id.length; len++) {\n const prefix = id.slice(0, len);\n\n // Check minimum requirements\n const digitCount = (prefix.match(/\\d/g) || []).length;\n const letterCount = (prefix.match(/[a-zA-Z]/g) || []).length;\n\n if (\n prefix.length < MIN_PREFIX_LENGTH ||\n (digitCount > 0 &&\n letterCount < MIN_CHARACTERS_PER_PREFIX_WITH_AT_LEAST_ONE_DIGIT) ||\n (digitCount === 0 &&\n letterCount < MIN_CHARACTERS_PER_PREFIX_WITH_NO_DIGITS)\n ) {\n continue;\n }\n\n // 1) Unique among IDs\n if (ids.some((other) => other !== id && other.startsWith(prefix))) {\n continue;\n }\n\n // 2) Only appears in prompt as part of the full ID\n const esc = (s: string) => s.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n const prefixCount = (prompt.match(new RegExp(esc(prefix), \"g\")) || [])\n .length;\n const fullCount = (prompt.match(new RegExp(esc(id), \"g\")) || []).length;\n if (prefixCount !== fullCount) {\n continue;\n }\n\n map[prefix] = id;\n break;\n }\n\n if (!Object.values(map).includes(id)) {\n throw new Error(\n `Cannot find a safe unique prefix for ID \"${id}\" that meets the minimum requirements (length: ${MIN_PREFIX_LENGTH})`\n );\n }\n }\n\n return map;\n}\n\n/**\n * Compress all occurrences of `ids` inside `obj`, returning a new object\n * plus the `prefixMap` needed to decompress.\n */\nexport function compressPromptIds<T>(\n obj: T,\n ids: string[] | undefined\n): CompressedResult<T> {\n if (!ids || ids.length === 0) {\n return { compressed: obj, prefixMap: {} };\n }\n\n const uniqueIds = Array.from(new Set(ids));\n const text = JSON.stringify(obj);\n const prefixMap = buildSafePrefixMap(uniqueIds, text);\n\n // Sort prefixes by descending length to avoid partial matches\n const prefixes = Object.keys(prefixMap).sort((a, b) => b.length - a.length);\n\n let compressedText = text;\n for (const prefix of prefixes) {\n const full = prefixMap[prefix];\n const escFull = full.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n compressedText = compressedText.replace(new RegExp(escFull, \"g\"), prefix);\n }\n\n return {\n compressed: JSON.parse(compressedText) as T,\n prefixMap,\n };\n}\n\n/**\n * Decompress all minimal prefixes back into their full IDs,\n * using the `prefixMap` returned from `compressPromptIds`.\n *\n * If you pass in a string, it will return a string.\n * If you pass in an object, it will JSON‑serialize and parse it back.\n */\nexport function decompressPromptIds<T>(\n compressed: T | string,\n prefixMap: Record<string, string>\n): T | string {\n if (!prefixMap || Object.keys(prefixMap).length === 0) {\n return compressed;\n }\n\n // Prepare sorted [prefix, full] entries (longest prefix first)\n const entries = Object.entries(prefixMap).sort(\n (a, b) => b[0].length - a[0].length\n );\n\n // Decide whether we're working on a string or an object\n let text: string;\n let shouldParseBack = false;\n\n if (typeof compressed === \"string\") {\n text = compressed;\n } else {\n text = JSON.stringify(compressed);\n shouldParseBack = true;\n }\n\n const originalLength = text?.length;\n\n // Perform all prefix → full-ID replacements\n for (const [prefix, full] of entries) {\n const escPrefix = prefix.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n text = text.replace(new RegExp(escPrefix, \"g\"), full);\n }\n\n // Handle cases where the LLM may output ID in a different attribute format\n // We look for common ID attribute patterns and replace compressed prefixes within them\n // Note: fileId variants are supported for backwards compatibility with legacy citations\n const idAttributeKeys = [\n \"attachmentId\",\n \"attachment_id\",\n \"attachment_ID\",\n \"attachmentID\",\n \"fileId\",\n \"file_id\",\n \"file_ID\",\n \"fileID\",\n \"fileid\",\n ];\n\n // For each prefix, look for it within ID attribute values and replace with full ID\n for (const [prefix, full] of entries) {\n const escPrefix = prefix.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n const keyPattern = idAttributeKeys.join(\"|\");\n const quotePattern = \"([\\\"'`])\";\n\n // Match: attributeName = 'prefix' or attributeName=\"prefix\" etc.\n // Only replace the prefix part, preserving the attribute name and quotes\n const re = new RegExp(\n `(${keyPattern})(\\\\s*=\\\\s*)${quotePattern}${escPrefix}\\\\3`,\n \"g\"\n );\n text = text.replace(re, `$1$2$3${full}$3`);\n }\n const newLength = text?.length;\n\n const diff = originalLength - newLength;\n if (diff > 0) {\n throw new Error(\n `[decompressedPromptIds] diff ${diff} originalLength ${originalLength} newLength ${newLength}`\n );\n }\n\n return shouldParseBack ? (JSON.parse(text) as T) : text;\n}\n"]}
|
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
function Z(t){return new TextEncoder().encode(t)}function W(t){let e=1732584193,s=4023233417,r=2562383102,n=271733878,a=3285377520,y=t.length,h=y*8,o=y+1+8,i=Math.ceil(o/64)*64,u=new ArrayBuffer(i),k=new Uint8Array(u),c=new DataView(u);k.set(t),k[y]=128,c.setUint32(i-8,Math.floor(h/4294967296),false),c.setUint32(i-4,h>>>0,false);let d=new Uint32Array(80);for(let f=0;f<i;f+=64){for(let m=0;m<16;m++)d[m]=c.getUint32(f+m*4,false);for(let m=16;m<80;m++){let A=d[m-3]^d[m-8]^d[m-14]^d[m-16];d[m]=A<<1|A>>>31;}let C=e,g=s,l=r,x=n,b=a;for(let m=0;m<80;m++){let A,_;m<20?(A=g&l|~g&x,_=1518500249):m<40?(A=g^l^x,_=1859775393):m<60?(A=g&l|g&x|l&x,_=2400959708):(A=g^l^x,_=3395469782);let p=(C<<5|C>>>27)+A+b+_+d[m]>>>0;b=x,x=l,l=(g<<30|g>>>2)>>>0,g=C,C=p;}e=e+C>>>0,s=s+g>>>0,r=r+l>>>0,n=n+x>>>0,a=a+b>>>0;}let I=f=>f.toString(16).padStart(8,"0");return I(e)+I(s)+I(r)+I(n)+I(a)}function R(t){try{if(!t)return "";let e=typeof t=="string"?t:JSON.stringify(t);return W(Z(e))}catch(e){console.error("Error in making the hash:",e);}return ""}var v=new Map;function U(t){let e=v.get(t);return e||(e=new RegExp(`${t}='((?:[^'\\\\]|\\\\.)*)'`),v.set(t,e)),e}function D(t){if(!t)return;let e=[],s=t.split(",");for(let r of s){let n=r.trim();if(n)if(n.includes("-")){let[a,y]=n.split("-"),h=parseInt(a,10),o=parseInt(y,10);if(!isNaN(h)&&!isNaN(o)&&h<=o)for(let i=h;i<=o;i++)e.push(i);else isNaN(h)||e.push(h);}else {let a=parseInt(n,10);isNaN(a)||e.push(a);}}if(e.length!==0)return [...new Set(e)].sort((r,n)=>r-n)}function O(t){let e=t?.status,s=["not_found"].includes(e||""),r=["found","found_key_span_only","found_phrase_missed_value"].includes(e||""),n=["partial_text_found","found_on_other_page","found_on_other_line","first_word_found"].includes(e||""),a=["pending","loading",null,void 0].includes(e);return {isVerified:r,isMiss:s,isPartialMatch:n,isPending:a}}var B=(t,e,s,r)=>{let n=_=>{if(!_)return;let p=_;return (p.startsWith("'")||p.startsWith('"'))&&(p=p.slice(1)),(p.endsWith("'")||p.endsWith('"'))&&!p.endsWith("\\'")&&!p.endsWith('\\"')&&(p=p.slice(0,-1)),p=p.replace(/\\"/g,'"'),p=p.replace(/\\'/g,"'"),p=p.replace(/\\n/g," "),p=p.replace(/\\\\/g,"\\"),p},a=s?.current?s.current++:void 0,y=t.substring(0,t.indexOf("<cite")),h=t.includes("/>")?t.slice(t.indexOf("/>")+2):"",o=t.substring(t.indexOf("<cite"),t.indexOf("/>")+2),i=(_,p)=>{for(let w of p){let P=U(w),T=_.match(P);if(T)return T[1]}},u=i(o,["attachment_id","attachmentId","file_id","fileId"]),k=u?.length===20?u:e||u,c=i(o,["start_page_key","startPageKey","start_page"]),d,I;if(c){let _=c.match(/page[\_a-zA-Z]*(\d+)_index_(\d+)/);_&&(d=parseInt(_[1]),I=parseInt(_[2]));}let f=n(i(o,["full_phrase","fullPhrase"])),C=n(i(o,["key_span","keySpan"])),g=n(i(o,["reasoning"])),l=n(i(o,["value"])),x;try{let p=i(o,["line_ids","lineIds"])?.replace(/[A-Za-z_[\](){}:]/g,"");x=p?D(p):void 0;}catch(_){r&&console.error("Error parsing lineIds",_);}let b=i(o,["timestamps"]),m;if(b){let[_,p]=b.split("-")||[];m={startTime:_,endTime:p};}let A={attachmentId:k,pageNumber:d,startPageKey:`page_number_${d||1}_index_${I||0}`,fullPhrase:f,keySpan:C||l,citationNumber:a,lineIds:x,beforeCite:y,timestamps:m,reasoning:g};return {beforeCite:y,afterCite:h,citation:A}},J=(t,e)=>{if(!t)return null;let s=t.fullPhrase??t.full_phrase,r=t.startPageKey??t.start_page_key,n=t.keySpan??t.key_span,a=t.lineIds??t.line_ids,y=t.attachmentId??t.attachment_id??t.fileId??t.file_id,h=t.reasoning,o=t.value;if(!s)return null;let i;if(r){let c=r.match(/page[_a-zA-Z]*(\d+)_index_(\d+)/i);if(c)i=parseInt(c[1],10);else {let d=r.match(/^(\d+)_(\d+)$/);d&&(i=parseInt(d[1],10));}}let u=a?.length?[...a].sort((c,d)=>c-d):void 0;return {attachmentId:y,pageNumber:i,fullPhrase:s,citationNumber:e,lineIds:u,keySpan:n||o,reasoning:h}},M=t=>typeof t=="object"&&t!==null&&("fullPhrase"in t||"full_phrase"in t||"startPageKey"in t||"start_page_key"in t||"keySpan"in t||"key_span"in t||"lineIds"in t||"line_ids"in t),$=t=>Array.isArray(t)?t.length>0&&t.some(M):typeof t=="object"&&t!==null?M(t):false,z=t=>{let e={},s=Array.isArray(t)?t:[t],r=1;for(let n of s){let a=J(n,r++);if(a&&a.fullPhrase){let y=S(a);e[y]=a;}}return e},K=(t,e)=>{if(!(!t||typeof t!="object")){if(t.citation&&$(t.citation)){let s=Array.isArray(t.citation)?t.citation:[t.citation];e.push(...s);}if(t.citations&&$(t.citations)){let s=Array.isArray(t.citations)?t.citations:[t.citations];e.push(...s);}if(Array.isArray(t))for(let s of t)K(s,e);else for(let s of Object.keys(t))s!=="citation"&&s!=="citations"&&K(t[s],e);}},V=t=>{let e=E(t),s=/<cite\s+(?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|[^'">/])*\/>/g,r=e.match(s);if(!r||r.length===0)return {};let n={},a={current:1};for(let y of r){let{citation:h}=B(y,void 0,a);if(h&&h.fullPhrase){let o=S(h);n[o]=h;}}return n},tt=t=>{if(!t)return {};let e={};if(typeof t=="object"){if($(t)){let n=z(t);Object.assign(e,n);}else {let n=[];if(K(t,n),n.length>0){let a=z(n);Object.assign(e,a);}}let s=JSON.stringify(t),r=V(s);Object.assign(e,r);}else if(typeof t=="string"){let s=V(t);Object.assign(e,s);}return e};function et(t){let e=new Map,s=Array.isArray(t)?t.map((r,n)=>[S(r)||String(n+1),r]):Object.entries(t);for(let[r,n]of s){let a=n.attachmentId||"";e.has(a)||e.set(a,{}),e.get(a)[r]=n;}return e}function nt(t){let e={},s=Array.isArray(t)?t.map((r,n)=>[S(r)||String(n+1),r]):Object.entries(t);for(let[r,n]of s){let a=n.attachmentId||"";e[a]||(e[a]={}),e[a][r]=n;}return e}var F=t=>{let e={},s=/([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(['"])((?:[^'"\\]|\\.)*)\2/g,r;for(;(r=s.exec(t))!==null;){let n=r[1].toLowerCase().replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase(),a=r[3],y=n==="fileid"||n==="file_id"||n==="attachmentid"?"attachment_id":n==="keyspan"?"key_span":n==="fullphrase"?"full_phrase":n==="lineids"?"line_ids":n==="startpagekey"||n==="start_pagekey"?"start_page_key":n;e[y]=a;}return e},H=t=>{let e=O(t);return e.isMiss?"\u274C":e.isVerified&&!e.isPartialMatch?"\u2611\uFE0F":e.isPartialMatch?"\u2705":e.isPending?"\u231B":"\u25CC"},q=(t,e={})=>{let{leaveKeySpanBehind:s=false,verifications:r,showVerificationStatus:n=false}=e,a=0,y=/<cite\s+[^>]*?\/>/g;return t.replace(y,h=>{a++;let o=F(h),i="";if(s&&o.key_span&&(i=o.key_span.replace(/\\'/g,"'").replace(/\\"/g,'"')),n&&r){let u,k=g=>{if(!g)return;let l=g.match(/page[_a-zA-Z]*(\d+)/);return l?parseInt(l[1],10):void 0},c=g=>{if(!g)return;let x=g.replace(/(\d+)-(\d+)/g,(b,m,A)=>{let _=parseInt(m,10),p=parseInt(A,10);if(_<=p){let w=[];for(let P=_;P<=p;P++)w.push(P);return w.join(",")}return m}).split(",").map(b=>parseInt(b.trim(),10)).filter(b=>!isNaN(b));return x.length>0?x:void 0},d=g=>g?.replace(/\\'/g,"'").replace(/\\"/g,'"'),I={attachmentId:o.attachment_id,pageNumber:k(o.start_page_key),fullPhrase:d(o.full_phrase),keySpan:d(o.key_span),lineIds:c(o.line_ids)},f=S(I);if(u=r[f],!u){let g=String(a);u=r[g];}let C=H(u);i=i?`${i}${C}`:C;}return i})},at=(t,e)=>q(t,{leaveKeySpanBehind:e}),ot=t=>t.replace(/<page_number_\d+_index_\d+>/g,"").replace(/<\/page_number_\d+_index_\d+>/g,"").trim(),ct=t=>{let e=/<line id="[^"]*">|<\/line>/g;return t.replace(e,"")},L=t=>{if(!t)return null;let e=t.match(/\d+/)?.[0];return e?parseInt(e):null},G=t=>{let e=t.match(/^(<cite\s+(?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|[^'">/])*>)([\s\S]*?)<\/cite>$/);if(!e){let h=t.match(/^(<cite\s+(?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|[^'">/])*>)$/);if(h){let o=h[1].replace(/>$/," />");return N(o)}return N(t)}let[,s,r]=e;if(!r||!r.trim())return N(t);let n=s.replace(/>$/," />"),a=r.trim(),y=N(n);return a+y},E=t=>{let e=t?.trim()||"";e=e.replace(/(?<![<a-zA-Z])cite\s+(attachment_id|file_id|fileId|attachmentId)\s*=/gi,"<cite $1=");let s=e.split(/(<cite[\s\S]*?(?:\/>|<\/cite>|>(?=\s*$|[\r\n])(?![\s\S]*<\/cite>)))/gm);if(s.length<=1){let r=e.match(/<cite\s+(?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|[^'">/])*>/g);if(r&&r.length>0){let n=e.replace(/<cite\s+(?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|[^'">/])*>/g,a=>a.replace(/>$/," />"));return N(n)}return N(e)}return e=s.map(r=>r.startsWith("<cite")?G(r):r).join(""),e},N=t=>{let e=t;e=e.replace(/\\_/g,"_"),e=e.replace(/><\/cite>/g,"/>");let s=o=>{let i=o.toLowerCase();return i==="fullphrase"||i==="full_phrase"?"full_phrase":i==="lineids"||i==="line_ids"?"line_ids":i==="startpagekey"||i==="start_pagekey"||i==="start_page_key"?"start_page_key":i==="fileid"||i==="file_id"||i==="attachmentid"||i==="attachment_id"?"attachment_id":i==="keyspan"||i==="key_span"?"key_span":i==="reasoning"||i==="value"?i:i==="timestamps"||i==="timestamp"||i==="timestamps"?"timestamps":i},r={""":'"',"'":"'","<":"<",">":">","&":"&"},n=/&(?:quot|apos|lt|gt|amp);/g,a=o=>o.replace(n,i=>r[i]||i),y=/(fullPhrase|full_phrase|keySpan|key_span|reasoning|value)\s*=\s*(['"])([\s\S]*?)(?=\s+(?:line_ids|lineIds|timestamps|fileId|file_id|attachmentId|attachment_id|start_page_key|start_pageKey|startPageKey|keySpan|key_span|reasoning|value|full_phrase)\s*=|\s*\/>|['"]>)/gm;e=e.replace(y,(o,i,u,k)=>{let c=k;return c.endsWith(u)&&(c=c.slice(0,-1)),c=c.replace(/(\r?\n)+|(\*|_){2,}|\*/g,d=>d.includes(`
|
|
2
|
-
`)||d.includes("\r")?" ":""),c=a(c),c=c.replace(/\\\\'/g,"'").replace(/\\'/g,"'").replace(/'/g,"\\'"),c=c.replace(/\\\\"/g,'"').replace(/\\"/g,'"').replace(/"/g,'\\"'),`${s(i)}='${c}'`}),e=e.replace(/(line_ids|lineIds|timestamps)=['"]?([\[\]\(\){}A-Za-z0-9_\-, ]+)['"]?(\s*\/?>|\s+)/gm,(o,i,u,k)=>{let c=u.replace(/[A-Za-z\[\]\(\){}]/g,"");return c=c.replace(/(\d+)-(\d+)/g,(d,I,f)=>{let C=parseInt(I,10),g=parseInt(f,10),l=[];if(C<=g)for(let x=C;x<=g;x++)l.push(x);else l.push(C);return l.join(",")}),c=c.replace(/,+/g,",").replace(/^,|,$/g,""),`${s(i)}='${c}'${k}`});let h=o=>{let i=/([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(['"])((?:[^'"\\\n]|\\.)*)(?:\2)/g,u={},k;for(;k=i.exec(o);){let l=k[1],x=k[3],b=s(l);u[b]=x;}let c=Object.keys(u);if(c.length===0)return o;let d=typeof u.timestamps=="string"&&u.timestamps.length>0,I=c.filter(l=>l.startsWith("start_page")),f=[];u.attachment_id&&f.push("attachment_id"),d?(u.full_phrase&&f.push("full_phrase"),u.key_span&&f.push("key_span"),f.push("timestamps")):(I.includes("start_page_key")&&f.push("start_page_key"),I.filter(l=>l!=="start_page_key").sort().forEach(l=>f.push(l)),u.full_phrase&&f.push("full_phrase"),u.key_span&&f.push("key_span"),u.line_ids&&f.push("line_ids")),u.reasoning&&f.push("reasoning"),u.value&&f.push("value");let C=new Set(f);return c.filter(l=>!C.has(l)).sort().forEach(l=>f.push(l)),`<cite ${f.map(l=>`${l}='${u[l]}'`).join(" ")} />`};return e=e.replace(/<cite\b[\s\S]*?\/>/gm,o=>h(o)),e};function ft(...t){return t.filter(Boolean).join(" ")}function X(t){return t.type==="url"||typeof t.url=="string"&&t.url.length>0}function S(t){let e=t.pageNumber||L(t.startPageKey),s=[t.attachmentId||"",e?.toString()||"",t.fullPhrase||"",t.keySpan?.toString()||"",t.lineIds?.join(",")||"",t.timestamps?.startTime||"",t.timestamps?.endTime||""];return X(t)&&s.push(t.url||"",t.title||"",t.domain||""),R(s.join("|")).slice(0,16)}function gt(t){let e=[t.attachmentId||"",t.label||"",t.verifiedFullPhrase||"",t.verifiedKeySpan||"",t.verifiedLineIds?.join(",")||"",t.verifiedPageNumber?.toString()||"",t.verifiedTimestamps?.startTime||"",t.verifiedTimestamps?.endTime||"",t.verifiedMatchSnippet||"",t.hitIndexWithinPage?.toString()||""];return R(e.join("|")).slice(0,16)}function dt(t){let e=Math.random().toString(36).slice(2,11);return `${t}-${e}`}function mt(t,e={}){let{fallbackDisplay:s}=e;return t.keySpan?.toString()||t.citationNumber?.toString()||s||"1"}function ht(t){return t.citationNumber?.toString()||"1"}function yt(t){return t.keySpan?.toString()||""}function _t(...t){return t.filter(Boolean).join(" ")}var xt=4,Ct=1;export{R as a,ft as b,X as c,S as d,gt as e,dt as f,mt as g,ht as h,yt as i,_t as j,xt as k,Ct as l,H as m,q as n,at as o,ot as p,ct as q,L as r,E as s,O as t,B as u,tt as v,et as w,nt as x}
|
|
2
|
+
`)||d.includes("\r")?" ":""),c=a(c),c=c.replace(/\\\\'/g,"'").replace(/\\'/g,"'").replace(/'/g,"\\'"),c=c.replace(/\\\\"/g,'"').replace(/\\"/g,'"').replace(/"/g,'\\"'),`${s(i)}='${c}'`}),e=e.replace(/(line_ids|lineIds|timestamps)=['"]?([\[\]\(\){}A-Za-z0-9_\-, ]+)['"]?(\s*\/?>|\s+)/gm,(o,i,u,k)=>{let c=u.replace(/[A-Za-z\[\]\(\){}]/g,"");return c=c.replace(/(\d+)-(\d+)/g,(d,I,f)=>{let C=parseInt(I,10),g=parseInt(f,10),l=[];if(C<=g)for(let x=C;x<=g;x++)l.push(x);else l.push(C);return l.join(",")}),c=c.replace(/,+/g,",").replace(/^,|,$/g,""),`${s(i)}='${c}'${k}`});let h=o=>{let i=/([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(['"])((?:[^'"\\\n]|\\.)*)(?:\2)/g,u={},k;for(;k=i.exec(o);){let l=k[1],x=k[3],b=s(l);u[b]=x;}let c=Object.keys(u);if(c.length===0)return o;let d=typeof u.timestamps=="string"&&u.timestamps.length>0,I=c.filter(l=>l.startsWith("start_page")),f=[];u.attachment_id&&f.push("attachment_id"),d?(u.full_phrase&&f.push("full_phrase"),u.key_span&&f.push("key_span"),f.push("timestamps")):(I.includes("start_page_key")&&f.push("start_page_key"),I.filter(l=>l!=="start_page_key").sort().forEach(l=>f.push(l)),u.full_phrase&&f.push("full_phrase"),u.key_span&&f.push("key_span"),u.line_ids&&f.push("line_ids")),u.reasoning&&f.push("reasoning"),u.value&&f.push("value");let C=new Set(f);return c.filter(l=>!C.has(l)).sort().forEach(l=>f.push(l)),`<cite ${f.map(l=>`${l}='${u[l]}'`).join(" ")} />`};return e=e.replace(/<cite\b[\s\S]*?\/>/gm,o=>h(o)),e};function ft(...t){return t.filter(Boolean).join(" ")}function X(t){return t.type==="url"||typeof t.url=="string"&&t.url.length>0}function S(t){let e=t.pageNumber||L(t.startPageKey),s=[t.attachmentId||"",e?.toString()||"",t.fullPhrase||"",t.keySpan?.toString()||"",t.lineIds?.join(",")||"",t.timestamps?.startTime||"",t.timestamps?.endTime||""];return X(t)&&s.push(t.url||"",t.title||"",t.domain||""),R(s.join("|")).slice(0,16)}function gt(t){let e=[t.attachmentId||"",t.label||"",t.verifiedFullPhrase||"",t.verifiedKeySpan||"",t.verifiedLineIds?.join(",")||"",t.verifiedPageNumber?.toString()||"",t.verifiedTimestamps?.startTime||"",t.verifiedTimestamps?.endTime||"",t.verifiedMatchSnippet||"",t.hitIndexWithinPage?.toString()||""];return R(e.join("|")).slice(0,16)}function dt(t){let e=Math.random().toString(36).slice(2,11);return `${t}-${e}`}function mt(t,e={}){let{fallbackDisplay:s}=e;return t.keySpan?.toString()||t.citationNumber?.toString()||s||"1"}function ht(t){return t.citationNumber?.toString()||"1"}function yt(t){return t.keySpan?.toString()||""}function _t(...t){return t.filter(Boolean).join(" ")}var xt=4,Ct=1;export{R as a,ft as b,X as c,S as d,gt as e,dt as f,mt as g,ht as h,yt as i,_t as j,xt as k,Ct as l,H as m,q as n,at as o,ot as p,ct as q,L as r,E as s,O as t,B as u,tt as v,et as w,nt as x};//# sourceMappingURL=chunk-LLLVZOXB.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-LLLVZOXB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/sha.ts","../src/parsing/parseCitation.ts","../src/parsing/normalizeCitation.ts","../src/react/utils.ts"],"names":["utf8Encode","str","sha1","message","h0","h1","h2","h3","h4","msgLen","bitLen","totalLen","paddedLen","padded","paddedView","dataView","w","offset","i","val","a","b","c","d","e","f","k","temp","hex","n","sha1Hash","data","error","attributeRegexCache","getAttributeRegex","name","regex","parseLineIds","lineIdsString","lineIds","parts","part","trimmed","startStr","endStr","start","end","num","getCitationStatus","verification","status","isMiss","isVerified","isPartialMatch","isPending","parseCitation","fragment","mdAttachmentId","citationCounterRef","isVerbose","cleanAndUnescape","result","citationNumber","beforeCite","afterCite","middleCite","extractAttribute","tag","attrNames","match","rawAttachmentId","attachmentId","startPageKeyRaw","pageNumber","pageIndex","pageMatch","fullPhrase","keySpan","reasoning","value","timestampsRaw","timestamps","startTime","endTime","citation","parseJsonCitation","jsonCitation","startPageKey","rawLineIds","simpleMatch","hasCitationProperties","item","isJsonCitationFormat","extractJsonCitations","citations","items","citationKey","generateCitationKey","findJsonCitationsInObject","obj","found","key","extractXmlCitations","text","normalizedText","normalizeCitations","citeRegex","matches","getAllCitationsFromLlmOutput","llmOutput","jsonCitations","foundJsonCitations","xmlCitations","groupCitationsByAttachmentId","grouped","entries","idx","groupCitationsByAttachmentIdObject","parseCiteAttributes","citeTag","attrs","attrRegex","normalizedKey","getVerificationTextIndicator","replaceCitations","markdownWithCitations","options","leaveKeySpanBehind","verifications","showVerificationStatus","citationIndex","citationRegex","output","parsePageNumber","lineIdsStr","nums","_match","startNum","endNum","range","s","unescapeQuotes","numericKey","indicator","removeCitations","removePageNumberMetadata","pageText","removeLineIdMetadata","lineIdRegex","getCitationPageNumber","extractAndRelocateCitationContent","citePart","nonSelfClosingMatch","unclosedMatch","selfClosingTag","normalizeCitationContent","openingTag","innerContent","relocatedContent","normalizedCitation","response","trimmedResponse","citationParts","input","normalized","canonicalizeCiteAttributeKey","lowerKey","htmlEntityMap","htmlEntityRegex","decodeHtmlEntities","textAttributeRegex","openQuote","rawContent","content","rawValue","trailingChars","cleanedValue","_rangeMatch","reorderCiteTagAttributes","rawKey","keys","hasTimestamps","startPageKeys","ordered","used","cn","classes","isUrlCitation","keyParts","generateVerificationKey","generateCitationInstanceId","randomSuffix","getCitationDisplayText","fallbackDisplay","getCitationN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A,CACvC,CAKO,SAASC,EAAAA,CACd5G,CAAAA,CACA0C,CAAAA,CAEI,EAAC,CACG,CACR,GAAM,CAAE,eAAA,CAAAmE,CAAgB,CAAA,CAAInE,CAAAA,CAC5B,OACE1C,CAAAA,CAAS,SAAS,QAAA,EAAS,EAC3BA,CAAAA,CAAS,cAAA,EAAgB,UAAS,EAClC6G,CAAAA,EACA,GAEJ,CAKO,SAASC,EAAAA,CAAkB9G,CAAAA,CAA4B,CAC5D,OAAOA,CAAAA,CAAS,cAAA,EAAgB,QAAA,EAAS,EAAK,GAChD,CAKO,SAAS+G,EAAAA,CAAuB/G,CAAAA,CAA4B,CACjE,OAAOA,CAAAA,CAAS,OAAA,EAAS,UAAS,EAAK,EACzC,CAMO,SAASgH,EAAAA,CAAAA,GACXV,CAAAA,CACK,CACR,OAAOA,EAAQ,MAAA,CAAO,OAAO,CAAA,CAAE,IAAA,CAAK,GAAG,CACzC,CAKO,IAAMW,EAAAA,CAAqB,EACrBC,EAAAA,CAAqB","file":"chunk-LLLVZOXB.js","sourcesContent":["/**\n * Pure JavaScript SHA-1 implementation.\n * Based on the FIPS 180-4 specification.\n * No external dependencies.\n */\n\nfunction utf8Encode(str: string): Uint8Array {\n const encoder = new TextEncoder();\n return encoder.encode(str);\n}\n\nfunction sha1(message: Uint8Array): string {\n // Initial hash values\n let h0 = 0x67452301;\n let h1 = 0xefcdab89;\n let h2 = 0x98badcfe;\n let h3 = 0x10325476;\n let h4 = 0xc3d2e1f0;\n\n // Pre-processing: adding padding bits\n const msgLen = message.length;\n const bitLen = msgLen * 8;\n\n // Calculate padded length: message + 1 (0x80) + padding + 8 (length)\n // Total must be multiple of 64 bytes (512 bits)\n const totalLen = msgLen + 1 + 8; // minimum: msg + 0x80 + 64-bit length\n const paddedLen = Math.ceil(totalLen / 64) * 64;\n\n // Create padded buffer\n const padded = new ArrayBuffer(paddedLen);\n const paddedView = new Uint8Array(padded);\n const dataView = new DataView(padded);\n\n // Copy message\n paddedView.set(message);\n\n // Append bit '1' (0x80)\n paddedView[msgLen] = 0x80;\n\n // Append length as 64-bit big-endian (in bits)\n // High 32 bits (for messages > 512MB, which we don't support)\n dataView.setUint32(paddedLen - 8, Math.floor(bitLen / 0x100000000), false);\n // Low 32 bits\n dataView.setUint32(paddedLen - 4, bitLen >>> 0, false);\n\n // Process each 512-bit (64-byte) chunk\n const w = new Uint32Array(80);\n\n for (let offset = 0; offset < paddedLen; offset += 64) {\n // Break chunk into sixteen 32-bit big-endian words\n for (let i = 0; i < 16; i++) {\n w[i] = dataView.getUint32(offset + i * 4, false);\n }\n\n // Extend the sixteen 32-bit words into eighty 32-bit words\n for (let i = 16; i < 80; i++) {\n const val = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16];\n w[i] = (val << 1) | (val >>> 31);\n }\n\n // Initialize working variables\n let a = h0;\n let b = h1;\n let c = h2;\n let d = h3;\n let e = h4;\n\n // Main loop\n for (let i = 0; i < 80; i++) {\n let f: number;\n let k: number;\n\n if (i < 20) {\n f = (b & c) | (~b & d);\n k = 0x5a827999;\n } else if (i < 40) {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n } else if (i < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n\n const temp = (((a << 5) | (a >>> 27)) + f + e + k + w[i]) >>> 0;\n e = d;\n d = c;\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = temp;\n }\n\n // Add this chunk's hash to result\n h0 = (h0 + a) >>> 0;\n h1 = (h1 + b) >>> 0;\n h2 = (h2 + c) >>> 0;\n h3 = (h3 + d) >>> 0;\n h4 = (h4 + e) >>> 0;\n }\n\n // Produce the final hash value (160-bit) as hex string\n const hex = (n: number) => n.toString(16).padStart(8, \"0\");\n return hex(h0) + hex(h1) + hex(h2) + hex(h3) + hex(h4);\n}\n\n/**\n * Computes a SHA-1 hash of the provided data.\n * Used internally by generateCitationKey in react/utils.ts\n */\nexport function sha1Hash(data: string | any): string {\n try {\n if (!data) return \"\";\n const str = typeof data === \"string\" ? data : JSON.stringify(data);\n return sha1(utf8Encode(str));\n } catch (error) {\n console.error(\"Error in making the hash:\", error);\n }\n return \"\";\n}\n","import { type Verification } from \"../types/verification.js\";\nimport { type Citation, type CitationStatus } from \"../types/citation.js\";\nimport { normalizeCitations } from \"./normalizeCitation.js\";\nimport { generateCitationKey } from \"../react/utils.js\";\n\nconst attributeRegexCache = new Map<string, RegExp>();\n\nfunction getAttributeRegex(name: string): RegExp {\n let regex = attributeRegexCache.get(name);\n if (!regex) {\n regex = new RegExp(`${name}='((?:[^'\\\\\\\\]|\\\\\\\\.)*)'`);\n attributeRegexCache.set(name, regex);\n }\n return regex;\n}\n\n/**\n * Parses a line_ids string that may contain individual numbers, ranges, or both.\n * Examples: \"1,2,3\", \"5-10\", \"1,5-7,10\", \"20-20\"\n *\n * @param lineIdsString - The raw line_ids string (e.g., \"1,5-7,10\")\n * @returns Sorted array of unique line IDs, or undefined if empty/invalid\n */\nfunction parseLineIds(lineIdsString: string): number[] | undefined {\n if (!lineIdsString) return undefined;\n\n const lineIds: number[] = [];\n const parts = lineIdsString.split(\",\");\n\n for (const part of parts) {\n const trimmed = part.trim();\n if (!trimmed) continue;\n\n // Check if this part is a range (e.g., \"5-10\")\n if (trimmed.includes(\"-\")) {\n const [startStr, endStr] = trimmed.split(\"-\");\n const start = parseInt(startStr, 10);\n const end = parseInt(endStr, 10);\n\n if (!isNaN(start) && !isNaN(end) && start <= end) {\n // Expand the range\n for (let i = start; i <= end; i++) {\n lineIds.push(i);\n }\n } else if (!isNaN(start)) {\n // If only start is valid, just use it\n lineIds.push(start);\n }\n } else {\n // Single number\n const num = parseInt(trimmed, 10);\n if (!isNaN(num)) {\n lineIds.push(num);\n }\n }\n }\n\n if (lineIds.length === 0) return undefined;\n\n // Sort and deduplicate\n return [...new Set(lineIds)].sort((a, b) => a - b);\n}\n\n/**\n * Calculates the verification status of a citation based on the found highlight and search state.\n *\n * @param verification - The found highlight location, or null/undefined if not found\n * @returns An object containing boolean flags for verification status\n */\nexport function getCitationStatus(\n verification: Verification | null | undefined\n): CitationStatus {\n const status = verification?.status;\n\n const isMiss = [\"not_found\"].includes(status || \"\");\n \n const isVerified = [\"found\", \"found_key_span_only\", \"found_phrase_missed_value\"].includes(status || \"\");\n const isPartialMatch = [\"partial_text_found\", \"found_on_other_page\", \"found_on_other_line\", \"first_word_found\"].includes(status || \"\");\n\n const isPending = [\"pending\", \"loading\", null, undefined].includes(status);\n\n return { isVerified, isMiss, isPartialMatch, isPending };\n}\n\nexport const parseCitation = (\n fragment: string,\n mdAttachmentId?: string | null,\n citationCounterRef?: any | null,\n isVerbose?: boolean\n) => {\n // Helper: Remove wrapper quotes and fully unescape content\n // Handles: \\' -> ', \\\" -> \", \\n -> space, \\\\ -> \\\n const cleanAndUnescape = (str?: string) => {\n if (!str) return undefined;\n let result = str;\n // Remove surrounding quotes if present, but only if not escaped\n // Check start: remove leading quote only if it exists\n if (result.startsWith(\"'\") || result.startsWith('\"')) {\n result = result.slice(1);\n }\n // Check end: remove trailing quote only if it's not escaped (not preceded by \\)\n if ((result.endsWith(\"'\") || result.endsWith('\"')) && !result.endsWith(\"\\\\'\") && !result.endsWith('\\\\\"')) {\n result = result.slice(0, -1);\n }\n // Replace escaped double quotes with actual double quotes\n result = result.replace(/\\\\\"/g, '\"');\n // Replace escaped single quotes with actual single quotes\n result = result.replace(/\\\\'/g, \"'\");\n // Replace literal \\n sequences with spaces (newlines in attribute values)\n result = result.replace(/\\\\n/g, \" \");\n // Replace double backslashes with single backslash\n result = result.replace(/\\\\\\\\/g, \"\\\\\");\n return result;\n };\n\n const citationNumber = citationCounterRef?.current\n ? citationCounterRef.current++\n : undefined;\n\n const beforeCite = fragment.substring(0, fragment.indexOf(\"<cite\"));\n const afterCite = fragment.includes(\"/>\")\n ? fragment.slice(fragment.indexOf(\"/>\") + 2)\n : \"\";\n const middleCite = fragment.substring(\n fragment.indexOf(\"<cite\"),\n fragment.indexOf(\"/>\") + 2\n );\n\n const extractAttribute = (tag: string, attrNames: string[]): string | undefined => {\n for (const name of attrNames) {\n const regex = getAttributeRegex(name);\n const match = tag.match(regex);\n if (match) {\n return match[1];\n }\n }\n return undefined;\n };\n\n // Extract all attributes by name (order-independent)\n let rawAttachmentId = extractAttribute(middleCite, ['attachment_id', 'attachmentId', 'file_id', 'fileId']);\n let attachmentId = rawAttachmentId?.length === 20 ? rawAttachmentId : mdAttachmentId || rawAttachmentId;\n\n const startPageKeyRaw = extractAttribute(middleCite, ['start_page_key', 'startPageKey', 'start_page']);\n let pageNumber: number | undefined;\n let pageIndex: number | undefined;\n if (startPageKeyRaw) {\n const pageMatch = startPageKeyRaw.match(/page[\\_a-zA-Z]*(\\d+)_index_(\\d+)/);\n if (pageMatch) {\n pageNumber = parseInt(pageMatch[1]);\n pageIndex = parseInt(pageMatch[2]);\n }\n }\n\n // Use helper to handle escaped quotes inside the phrase\n let fullPhrase = cleanAndUnescape(extractAttribute(middleCite, ['full_phrase', 'fullPhrase']));\n let keySpan = cleanAndUnescape(extractAttribute(middleCite, ['key_span', 'keySpan']));\n let reasoning = cleanAndUnescape(extractAttribute(middleCite, ['reasoning']));\n let value = cleanAndUnescape(extractAttribute(middleCite, ['value']));\n\n let lineIds: number[] | undefined;\n try {\n const lineIdsRaw = extractAttribute(middleCite, ['line_ids', 'lineIds']);\n const lineIdsString = lineIdsRaw?.replace(/[A-Za-z_[\\](){}:]/g, \"\");\n lineIds = lineIdsString ? parseLineIds(lineIdsString) : undefined;\n } catch (e) {\n if (isVerbose) console.error(\"Error parsing lineIds\", e);\n }\n\n // Check for AV citation (has timestamps instead of line_ids)\n const timestampsRaw = extractAttribute(middleCite, ['timestamps']);\n let timestamps: { startTime?: string; endTime?: string } | undefined;\n\n if (timestampsRaw) {\n const [startTime, endTime] = timestampsRaw.split(\"-\") || [];\n timestamps = { startTime, endTime };\n }\n\n const citation: Citation = {\n attachmentId: attachmentId,\n pageNumber,\n startPageKey: `page_number_${pageNumber || 1}_index_${pageIndex || 0}`,\n fullPhrase,\n keySpan: keySpan || value,\n citationNumber,\n lineIds,\n beforeCite,\n timestamps,\n reasoning,\n };\n\n return {\n beforeCite,\n afterCite,\n citation,\n };\n};\n\n/**\n * Parses a JSON-based citation object into a Citation.\n * Supports both camelCase and snake_case property names.\n *\n * @param jsonCitation - The JSON citation object (can have camelCase or snake_case properties)\n * @param citationNumber - Optional citation number for ordering\n * @returns Parsed Citation object\n */\nconst parseJsonCitation = (\n jsonCitation: any,\n citationNumber?: number\n): Citation | null => {\n if (!jsonCitation) {\n return null;\n }\n\n // Support both camelCase and snake_case property names\n const fullPhrase = jsonCitation.fullPhrase ?? jsonCitation.full_phrase;\n const startPageKey = jsonCitation.startPageKey ?? jsonCitation.start_page_key;\n const keySpan = jsonCitation.keySpan ?? jsonCitation.key_span;\n const rawLineIds = jsonCitation.lineIds ?? jsonCitation.line_ids;\n const attachmentId = jsonCitation.attachmentId ?? jsonCitation.attachment_id ?? jsonCitation.fileId ?? jsonCitation.file_id;\n const reasoning = jsonCitation.reasoning;\n const value = jsonCitation.value;\n\n if (!fullPhrase) {\n return null;\n }\n\n // Parse startPageKey format: \"page_number_PAGE_index_INDEX\" or simple \"PAGE_INDEX\"\n let pageNumber: number | undefined;\n if (startPageKey) {\n // Try full format first: page_number_5_index_2 or pageKey_5_index_2\n const pageMatch = startPageKey.match(/page[_a-zA-Z]*(\\d+)_index_(\\d+)/i);\n if (pageMatch) {\n pageNumber = parseInt(pageMatch[1], 10);\n } else {\n // Try simple n_m format: 5_4 (page 5, index 4)\n const simpleMatch = startPageKey.match(/^(\\d+)_(\\d+)$/);\n if (simpleMatch) {\n pageNumber = parseInt(simpleMatch[1], 10);\n }\n }\n }\n\n // Sort lineIds if present\n const lineIds = rawLineIds?.length\n ? [...rawLineIds].sort((a: number, b: number) => a - b)\n : undefined;\n\n const citation: Citation = {\n attachmentId,\n pageNumber,\n fullPhrase,\n citationNumber,\n lineIds,\n keySpan: keySpan || value,\n reasoning,\n };\n\n return citation;\n};\n\n/**\n * Checks if an object has citation-like properties (camelCase or snake_case).\n */\nconst hasCitationProperties = (item: any): boolean =>\n typeof item === \"object\" &&\n item !== null &&\n (\"fullPhrase\" in item ||\n \"full_phrase\" in item ||\n \"startPageKey\" in item ||\n \"start_page_key\" in item ||\n \"keySpan\" in item ||\n \"key_span\" in item ||\n \"lineIds\" in item ||\n \"line_ids\" in item);\n\n/**\n * Checks if the input appears to be JSON-based citations.\n * Looks for array of objects with citation-like properties (supports both camelCase and snake_case).\n */\nconst isJsonCitationFormat = (data: any): data is Citation[] | Citation => {\n if (Array.isArray(data)) {\n return data.length > 0 && data.some(hasCitationProperties);\n }\n if (typeof data === \"object\" && data !== null) {\n return hasCitationProperties(data);\n }\n return false;\n};\n\n/**\n * Extracts citations from JSON format (array or single object).\n */\nconst extractJsonCitations = (\n data: Citation[] | Citation\n): { [key: string]: Citation } => {\n const citations: { [key: string]: Citation } = {};\n const items = Array.isArray(data) ? data : [data];\n\n let citationNumber = 1;\n for (const item of items) {\n const citation = parseJsonCitation(item, citationNumber++);\n if (citation && citation.fullPhrase) {\n const citationKey = generateCitationKey(citation);\n citations[citationKey] = citation;\n }\n }\n\n return citations;\n};\n\n/**\n * Recursively traverses an object looking for `citation` or `citations` properties\n * that match our JSON citation format.\n */\nconst findJsonCitationsInObject = (obj: any, found: Citation[]): void => {\n if (!obj || typeof obj !== \"object\") return;\n\n // Check for citation/citations properties\n if (obj.citation && isJsonCitationFormat(obj.citation)) {\n const items = Array.isArray(obj.citation) ? obj.citation : [obj.citation];\n found.push(...items);\n }\n if (obj.citations && isJsonCitationFormat(obj.citations)) {\n const items = Array.isArray(obj.citations)\n ? obj.citations\n : [obj.citations];\n found.push(...items);\n }\n\n // Recurse into object properties\n if (Array.isArray(obj)) {\n for (const item of obj) {\n findJsonCitationsInObject(item, found);\n }\n } else {\n for (const key of Object.keys(obj)) {\n if (key !== \"citation\" && key !== \"citations\") {\n findJsonCitationsInObject(obj[key], found);\n }\n }\n }\n};\n\n/**\n * Extracts XML citations from text using <cite ... /> tags.\n */\nconst extractXmlCitations = (text: string): { [key: string]: Citation } => {\n const normalizedText = normalizeCitations(text);\n\n // Find all <cite ... /> tags\n // This regex handles > characters inside quoted attribute values and escaped quotes:\n // - '(?:[^'\\\\]|\\\\.)*' matches single-quoted strings with escaped chars\n // - \"(?:[^\"\\\\]|\\\\.)*\" matches double-quoted strings with escaped chars\n // - [^'\">/] matches any char that's not a quote, >, or /\n // - The whole pattern repeats until we hit />\n const citeRegex = /<cite\\s+(?:'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|[^'\">/])*\\/>/g;\n const matches = normalizedText.match(citeRegex);\n\n if (!matches || matches.length === 0) return {};\n\n const citations: { [key: string]: Citation } = {};\n const citationCounterRef = { current: 1 };\n\n for (const match of matches) {\n const { citation } = parseCitation(match, undefined, citationCounterRef);\n if (citation && citation.fullPhrase) {\n const citationKey = generateCitationKey(citation);\n citations[citationKey] = citation;\n }\n }\n\n return citations;\n};\n\n/**\n * Extracts all citations from LLM output.\n * Supports both XML <cite ... /> tags (embedded in strings/markdown) and JSON-based citation formats.\n *\n * For object input:\n * - Traverses the object looking for `citation` or `citations` properties matching JSON format\n * - Also stringifies the object to find embedded XML citations in markdown content\n *\n * @param llmOutput - The LLM output (string or object)\n * @returns Dictionary of parsed Citation objects keyed by citation key\n */\nexport const getAllCitationsFromLlmOutput = (\n llmOutput: any\n): { [key: string]: Citation } => {\n if (!llmOutput) return {};\n\n const citations: { [key: string]: Citation } = {};\n\n if (typeof llmOutput === \"object\") {\n // Check if the root object itself is JSON citation format\n if (isJsonCitationFormat(llmOutput)) {\n const jsonCitations = extractJsonCitations(llmOutput);\n Object.assign(citations, jsonCitations);\n } else {\n // Traverse object for nested citation/citations properties\n const foundJsonCitations: Citation[] = [];\n findJsonCitationsInObject(llmOutput, foundJsonCitations);\n\n if (foundJsonCitations.length > 0) {\n const jsonCitations = extractJsonCitations(foundJsonCitations);\n Object.assign(citations, jsonCitations);\n }\n }\n\n // Also stringify and parse for embedded XML citations in markdown\n const text = JSON.stringify(llmOutput);\n const xmlCitations = extractXmlCitations(text);\n Object.assign(citations, xmlCitations);\n } else if (typeof llmOutput === \"string\") {\n // String input - parse for XML citations\n const xmlCitations = extractXmlCitations(llmOutput);\n Object.assign(citations, xmlCitations);\n }\n\n return citations;\n};\n\n/**\n * Groups citations by their attachmentId for multi-file verification scenarios.\n * This is useful when you have citations from multiple files and need to\n * verify them against their respective attachments.\n *\n * @param citations - Array of Citation objects or a dictionary of citations\n * @returns Map of attachmentId to dictionary of citations from that file\n *\n * @example\n * ```typescript\n * const citations = getAllCitationsFromLlmOutput(response.content);\n * const citationsByAttachment = groupCitationsByAttachmentId(citations);\n *\n * // Verify citations for each file\n * for (const [attachmentId, fileCitations] of citationsByAttachment) {\n * const verified = await deepcitation.verifyCitations(attachmentId, fileCitations);\n * // Process verification results...\n * }\n * ```\n */\nexport function groupCitationsByAttachmentId(\n citations: Citation[] | { [key: string]: Citation }\n): Map<string, { [key: string]: Citation }> {\n const grouped = new Map<string, { [key: string]: Citation }>();\n\n // Normalize input to entries\n const entries: [string, Citation][] = Array.isArray(citations)\n ? citations.map((c, idx) => [generateCitationKey(c) || String(idx + 1), c])\n : Object.entries(citations);\n\n for (const [key, citation] of entries) {\n const attachmentId = citation.attachmentId || \"\";\n\n if (!grouped.has(attachmentId)) {\n grouped.set(attachmentId, {});\n }\n\n grouped.get(attachmentId)![key] = citation;\n }\n\n return grouped;\n}\n\n/**\n * Groups citations by their attachmentId and returns as a plain object.\n * Alternative to groupCitationsByAttachmentId that returns a plain object instead of a Map.\n *\n * @param citations - Array of Citation objects or a dictionary of citations\n * @returns Object with attachmentId keys mapping to citation dictionaries\n *\n * @example\n * ```typescript\n * const citations = getAllCitationsFromLlmOutput(response.content);\n * const citationsByAttachment = groupCitationsByAttachmentIdObject(citations);\n *\n * // Verify citations for each file using Promise.all\n * const verificationPromises = Object.entries(citationsByAttachment).map(\n * ([attachmentId, fileCitations]) => deepcitation.verifyCitations(attachmentId, fileCitations)\n * );\n * const results = await Promise.all(verificationPromises);\n * ```\n */\nexport function groupCitationsByAttachmentIdObject(\n citations: Citation[] | { [key: string]: Citation }\n): { [attachmentId: string]: { [key: string]: Citation } } {\n const grouped: { [attachmentId: string]: { [key: string]: Citation } } = {};\n\n // Normalize input to entries\n const entries: [string, Citation][] = Array.isArray(citations)\n ? citations.map((c, idx) => [generateCitationKey(c) || String(idx + 1), c])\n : Object.entries(citations);\n\n for (const [key, citation] of entries) {\n const attachmentId = citation.attachmentId || \"\";\n\n if (!grouped[attachmentId]) {\n grouped[attachmentId] = {};\n }\n\n grouped[attachmentId][key] = citation;\n }\n\n return grouped;\n}\n","import type { Verification } from \"../types/verification.js\";\nimport type { Citation } from \"../types/citation.js\";\nimport { getCitationStatus } from \"./parseCitation.js\";\nimport { generateCitationKey } from \"../react/utils.js\";\n\nexport interface ReplaceCitationsOptions {\n /**\n * If true, leaves the key_span text behind when removing citations.\n * @default false\n */\n leaveKeySpanBehind?: boolean;\n\n /**\n * Map of citation keys to verification results.\n * Used to determine verification status for each citation.\n */\n verifications?: Record<string, Verification>;\n\n /**\n * If true and verifications are provided, appends a verification status indicator.\n * Uses: ✓ (verified), ⚠ (partial), ✗ (not found), ◌ (pending)\n * @default false\n */\n showVerificationStatus?: boolean;\n}\n\n/**\n * Parse attributes from a cite tag in any order.\n * Returns an object with all found attributes.\n */\nconst parseCiteAttributes = (\n citeTag: string\n): Record<string, string | undefined> => {\n const attrs: Record<string, string | undefined> = {};\n\n // Match attribute patterns: key='value' or key=\"value\"\n const attrRegex =\n /([a-zA-Z_][a-zA-Z0-9_]*)\\s*=\\s*(['\"])((?:[^'\"\\\\]|\\\\.)*)\\2/g;\n let match;\n\n while ((match = attrRegex.exec(citeTag)) !== null) {\n const key = match[1]\n .toLowerCase()\n .replace(/([a-z])([A-Z])/g, \"$1_$2\")\n .toLowerCase();\n const value = match[3];\n\n // Normalize key names\n const normalizedKey =\n key === \"fileid\" || key === \"file_id\" || key === \"attachmentid\"\n ? \"attachment_id\"\n : key === \"keyspan\"\n ? \"key_span\"\n : key === \"fullphrase\"\n ? \"full_phrase\"\n : key === \"lineids\"\n ? \"line_ids\"\n : key === \"startpagekey\" || key === \"start_pagekey\"\n ? \"start_page_key\"\n : key;\n\n attrs[normalizedKey] = value;\n }\n\n return attrs;\n};\n\n/**\n * Get verification status indicator character for plain text/terminal output.\n * Returns: ☑️ (fully verified), ✅ (partial match), ❌ (not found), ⌛ (pending/null), ◌ (unknown)\n *\n * For web UI, use the React CitationComponent instead which provides\n * proper styled indicators with colors and accessibility.\n */\nexport const getVerificationTextIndicator = (\n verification: Verification | null | undefined\n): string => {\n const status = getCitationStatus(verification);\n\n if (status.isMiss) return \"❌\";\n // Check for fully verified (not partial) first\n if (status.isVerified && !status.isPartialMatch) return \"☑️\";\n // Then check for partial match\n if (status.isPartialMatch) return \"✅\";\n\n if (status.isPending) return \"⌛\";\n\n return \"◌\";\n};\n\n/**\n * Replaces citation tags in markdown text with optional replacement content.\n *\n * @param markdownWithCitations - The text containing <cite /> tags\n * @param options - Configuration options\n * @returns The text with citations replaced\n *\n * @example\n * ```typescript\n * // Remove all citations\n * const clean = replaceCitations(llmOutput);\n *\n * // Leave key_span text behind\n * const withKeySpans = replaceCitations(llmOutput, { leaveKeySpanBehind: true });\n *\n * // Show verification status indicators\n * const withStatus = replaceCitations(llmOutput, {\n * leaveKeySpanBehind: true,\n * verifications: verificationMap,\n * showVerificationStatus: true,\n * });\n * // Output: \"Revenue grew 45% year-over-year Revenue Growth✓\"\n * ```\n */\nexport const replaceCitations = (\n markdownWithCitations: string,\n options: ReplaceCitationsOptions = {}\n): string => {\n const {\n leaveKeySpanBehind = false,\n verifications,\n showVerificationStatus = false,\n } = options;\n\n // Track citation index for matching with numbered verification keys\n let citationIndex = 0;\n\n // Flexible regex that matches any <cite ... /> tag\n const citationRegex = /<cite\\s+[^>]*?\\/>/g;\n\n return markdownWithCitations.replace(citationRegex, (match) => {\n citationIndex++;\n const attrs = parseCiteAttributes(match);\n\n // Determine what to output\n let output = \"\";\n\n if (leaveKeySpanBehind && attrs.key_span) {\n // Unescape the key_span value\n output = attrs.key_span.replace(/\\\\'/g, \"'\").replace(/\\\\\"/g, '\"');\n }\n\n // Add verification status if requested\n if (showVerificationStatus && verifications) {\n // Try to find verification by various key strategies\n let verification: Verification | undefined;\n\n // Build a Citation object from parsed attributes to generate the key\n const parsePageNumber = (startPageKey?: string): number | undefined => {\n if (!startPageKey) return undefined;\n const match = startPageKey.match(/page[_a-zA-Z]*(\\d+)/);\n return match ? parseInt(match[1], 10) : undefined;\n };\n\n const parseLineIds = (lineIdsStr?: string): number[] | undefined => {\n if (!lineIdsStr) return undefined;\n\n // First expand ranges (e.g., \"62-63\" -> \"62,63\")\n let expanded = lineIdsStr.replace(\n /(\\d+)-(\\d+)/g,\n (_match, start, end) => {\n const startNum = parseInt(start, 10);\n const endNum = parseInt(end, 10);\n if (startNum <= endNum) {\n const range = [];\n for (let i = startNum; i <= endNum; i++) {\n range.push(i);\n }\n return range.join(\",\");\n }\n return start;\n }\n );\n\n const nums = expanded.split(\",\").map((s) => parseInt(s.trim(), 10)).filter((n) => !isNaN(n));\n return nums.length > 0 ? nums : undefined;\n };\n\n // Unescape quotes in fullPhrase and keySpan to match how citations are parsed\n // by getAllCitationsFromLlmOutput (which returns unescaped values)\n const unescapeQuotes = (str: string | undefined): string | undefined =>\n str?.replace(/\\\\'/g, \"'\").replace(/\\\\\"/g, '\"');\n\n const citation: Citation = {\n attachmentId: attrs.attachment_id,\n pageNumber: parsePageNumber(attrs.start_page_key),\n fullPhrase: unescapeQuotes(attrs.full_phrase),\n keySpan: unescapeQuotes(attrs.key_span),\n lineIds: parseLineIds(attrs.line_ids),\n };\n\n // Strategy 1: Match by citationKey (hash) - most reliable\n const citationKey = generateCitationKey(citation);\n verification = verifications[citationKey];\n\n // Strategy 2: Fall back to numbered keys (1, 2, 3, etc.)\n if (!verification) {\n const numericKey = String(citationIndex);\n verification = verifications[numericKey];\n }\n\n const indicator = getVerificationTextIndicator(verification);\n output = output ? `${output}${indicator}` : indicator;\n }\n\n return output;\n });\n};\n\n/**\n * @deprecated Use `replaceCitations` instead. This function is kept for backward compatibility.\n */\nexport const removeCitations = (\n markdownWithCitations: string,\n leaveKeySpanBehind?: boolean\n): string => {\n return replaceCitations(markdownWithCitations, { leaveKeySpanBehind });\n};\n\nexport const removePageNumberMetadata = (pageText: string): string => {\n return pageText\n .replace(/<page_number_\\d+_index_\\d+>/g, \"\")\n .replace(/<\\/page_number_\\d+_index_\\d+>/g, \"\")\n .trim();\n};\n\nexport const removeLineIdMetadata = (pageText: string): string => {\n const lineIdRegex = /<line id=\"[^\"]*\">|<\\/line>/g;\n return pageText.replace(lineIdRegex, \"\");\n};\n\nexport const getCitationPageNumber = (\n startPageKey?: string | null\n): number | null => {\n //page_number_{page_number}_index_{page_index} or page_number_{page_number} or page_key_{page_number}_index_{page_index}\n if (!startPageKey) return null;\n\n //regex first \\d+ is the page number\n const pageNumber = startPageKey.match(/\\d+/)?.[0];\n return pageNumber ? parseInt(pageNumber) : null;\n};\n\n/**\n * Extracts content from a non-self-closing citation tag and moves it before the citation.\n * Converts <cite ...>content</cite> to: content<cite ... />\n *\n * @param citePart - The citation part that may contain inner content\n * @returns The normalized citation with content moved before it\n */\nconst extractAndRelocateCitationContent = (citePart: string): string => {\n // Check if this is a non-self-closing citation: <cite ...>content</cite>\n // Match: <cite with attributes> then content then </cite>\n // The attribute regex handles escaped quotes: (?:[^'\\\\]|\\\\.)* matches non-quote/non-backslash OR backslash+any\n const nonSelfClosingMatch = citePart.match(\n /^(<cite\\s+(?:'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|[^'\">/])*>)([\\s\\S]*?)<\\/cite>$/\n );\n\n if (!nonSelfClosingMatch) {\n // Check if this is an unclosed citation ending with just >\n // Pattern: <cite attributes> (no closing tag)\n const unclosedMatch = citePart.match(\n /^(<cite\\s+(?:'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|[^'\">/])*>)$/\n );\n if (unclosedMatch) {\n // Convert <cite ... > to self-closing <cite ... />\n const selfClosingTag = unclosedMatch[1].replace(/>$/, \" />\");\n return normalizeCitationContent(selfClosingTag);\n }\n // Already self-closing or doesn't match pattern, normalize as-is\n return normalizeCitationContent(citePart);\n }\n\n const [, openingTag, innerContent] = nonSelfClosingMatch;\n\n // If there's no inner content, just normalize the citation\n if (!innerContent || !innerContent.trim()) {\n return normalizeCitationContent(citePart);\n }\n\n // Extract the attributes from the opening tag\n // Convert <cite attributes> to <cite attributes />\n const selfClosingTag = openingTag.replace(/>$/, \" />\");\n\n // Move inner content before the citation and normalize\n // The inner content is trimmed to avoid extra whitespace issues\n const relocatedContent = innerContent.trim();\n\n // Normalize the self-closing citation tag\n const normalizedCitation = normalizeCitationContent(selfClosingTag);\n\n // Return content followed by the citation\n return relocatedContent + normalizedCitation;\n};\n\nexport const normalizeCitations = (response: string): string => {\n let trimmedResponse = response?.trim() || \"\";\n\n // Fix missing < before cite tags\n // LLMs sometimes output 'cite' without the leading '<'\n // Match 'cite' followed by a space and attribute pattern, but NOT preceded by '<' or a letter\n // This avoids matching words like \"excite\" or \"recite\"\n trimmedResponse = trimmedResponse.replace(\n /(?<![<a-zA-Z])cite\\s+(attachment_id|file_id|fileId|attachmentId)\\s*=/gi,\n \"<cite $1=\"\n );\n\n // Split on citation tags - captures three patterns:\n // 1. Self-closing: <cite ... />\n // 2. With closing tag: <cite ...>content</cite>\n // 3. Unclosed (ends with >): <cite ...> (no closing tag, no </cite> anywhere after)\n // Pattern 3 uses negative lookahead to avoid matching when </cite> follows\n const citationParts = trimmedResponse.split(\n /(<cite[\\s\\S]*?(?:\\/>|<\\/cite>|>(?=\\s*$|[\\r\\n])(?![\\s\\S]*<\\/cite>)))/gm\n );\n if (citationParts.length <= 1) {\n // Handle unclosed citations by converting to self-closing\n const unclosedMatch = trimmedResponse.match(/<cite\\s+(?:'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|[^'\">/])*>/g);\n if (unclosedMatch && unclosedMatch.length > 0) {\n const result = trimmedResponse.replace(\n /<cite\\s+(?:'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|[^'\">/])*>/g,\n (match) => match.replace(/>$/, ' />')\n );\n return normalizeCitationContent(result);\n }\n return normalizeCitationContent(trimmedResponse);\n }\n\n trimmedResponse = citationParts\n .map((part) =>\n part.startsWith(\"<cite\")\n ? extractAndRelocateCitationContent(part)\n : part\n )\n .join(\"\");\n\n return trimmedResponse;\n};\n\nconst normalizeCitationContent = (input: string): string => {\n let normalized = input;\n\n // 0. Unescape all backslash-escaped underscores\n // This handles Markdown-processed output where underscores get escaped (e.g., attachment\\_id -> attachment_id, page\\_number\\_1 -> page_number_1)\n normalized = normalized.replace(/\\\\_/g, \"_\");\n\n // 1. Standardize self-closing tags\n // Replace ></cite> with /> for consistency\n normalized = normalized.replace(/><\\/cite>/g, \"/>\");\n\n const canonicalizeCiteAttributeKey = (key: string): string => {\n const lowerKey = key.toLowerCase();\n if (lowerKey === \"fullphrase\" || lowerKey === \"full_phrase\")\n return \"full_phrase\";\n if (lowerKey === \"lineids\" || lowerKey === \"line_ids\") return \"line_ids\";\n if (\n lowerKey === \"startpagekey\" ||\n lowerKey === \"start_pagekey\" ||\n lowerKey === \"start_page_key\"\n )\n return \"start_page_key\";\n if (\n lowerKey === \"fileid\" ||\n lowerKey === \"file_id\" ||\n lowerKey === \"attachmentid\" ||\n lowerKey === \"attachment_id\"\n )\n return \"attachment_id\";\n if (lowerKey === \"keyspan\" || lowerKey === \"key_span\") return \"key_span\";\n if (lowerKey === \"reasoning\" || lowerKey === \"value\") return lowerKey;\n if (\n lowerKey === \"timestamps\" ||\n lowerKey === \"timestamp\" ||\n lowerKey === \"timestamps\"\n )\n return \"timestamps\";\n\n return lowerKey;\n };\n\n const htmlEntityMap: Record<string, string> = {\n '"': '\"',\n ''': \"'\",\n '<': '<',\n '>': '>',\n '&': '&',\n };\n const htmlEntityRegex = /&(?:quot|apos|lt|gt|amp);/g;\n const decodeHtmlEntities = (str: string) => {\n return str.replace(htmlEntityRegex, (match) => htmlEntityMap[match] || match);\n };\n\n const textAttributeRegex =\n /(fullPhrase|full_phrase|keySpan|key_span|reasoning|value)\\s*=\\s*(['\"])([\\s\\S]*?)(?=\\s+(?:line_ids|lineIds|timestamps|fileId|file_id|attachmentId|attachment_id|start_page_key|start_pageKey|startPageKey|keySpan|key_span|reasoning|value|full_phrase)\\s*=|\\s*\\/>|['\"]>)/gm;\n\n normalized = normalized.replace(\n textAttributeRegex,\n (_match, key, openQuote, rawContent) => {\n let content = rawContent;\n\n if (content.endsWith(openQuote)) {\n content = content.slice(0, -1);\n }\n\n // Flatten newlines and remove markdown markers\n content = content.replace(/(\\r?\\n)+|(\\*|_){2,}|\\*/g, (match: string) => {\n if (match.includes('\\n') || match.includes('\\r')) return ' ';\n return '';\n });\n\n content = decodeHtmlEntities(content);\n\n // Normalize quotes\n content = content.replace(/\\\\\\\\'/g, \"'\").replace(/\\\\'/g, \"'\").replace(/'/g, \"\\\\'\");\n content = content.replace(/\\\\\\\\\"/g, '\"').replace(/\\\\\"/g, '\"').replace(/\"/g, '\\\\\"');\n\n return `${canonicalizeCiteAttributeKey(key)}='${content}'`;\n }\n );\n normalized = normalized.replace(\n /(line_ids|lineIds|timestamps)=['\"]?([\\[\\]\\(\\){}A-Za-z0-9_\\-, ]+)['\"]?(\\s*\\/?>|\\s+)/gm,\n (_match, key, rawValue, trailingChars) => {\n // Clean up the value (remove generic text, keep numbers/separators)\n let cleanedValue = rawValue.replace(/[A-Za-z\\[\\]\\(\\){}]/g, \"\");\n\n // Expand ranges (e.g., \"1-3\" -> \"1,2,3\")\n cleanedValue = cleanedValue.replace(\n /(\\d+)-(\\d+)/g,\n (_rangeMatch: string, start: string, end: string) => {\n const startNum = parseInt(start, 10);\n const endNum = parseInt(end, 10);\n const range = [];\n\n // Handle ascending range\n if (startNum <= endNum) {\n for (let i = startNum; i <= endNum; i++) {\n range.push(i);\n }\n } else {\n // Fallback for weird descending ranges or just return start\n range.push(startNum);\n }\n return range.join(\",\");\n }\n );\n\n // Normalize commas\n cleanedValue = cleanedValue.replace(/,+/g, \",\").replace(/^,|,$/g, \"\");\n\n // Return standardized format: key='value' + preserved trailing characters (space or />)\n return `${canonicalizeCiteAttributeKey(\n key\n )}='${cleanedValue}'${trailingChars}`;\n }\n );\n\n // 4. Re-order <cite ... /> attributes to match the strict parsing expectations in `citationParser.ts`\n // (the parser uses regexes that assume a canonical attribute order).\n const reorderCiteTagAttributes = (tag: string): string => {\n // Match both single-quoted and double-quoted attributes\n const attrRegex =\n /([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(['\"])((?:[^'\"\\\\\\n]|\\\\.)*)(?:\\2)/g;\n const attrs: Record<string, string> = {};\n let match: RegExpExecArray | null;\n\n while ((match = attrRegex.exec(tag))) {\n const rawKey = match[1];\n const value = match[3]; // match[2] is the quote character\n const key = canonicalizeCiteAttributeKey(rawKey);\n attrs[key] = value;\n }\n\n // If we didn't find any parsable attrs, don't touch the tag.\n const keys = Object.keys(attrs);\n if (keys.length === 0) return tag;\n\n const hasTimestamps =\n typeof attrs.timestamps === \"string\" && attrs.timestamps.length > 0;\n const startPageKeys = keys.filter((k) => k.startsWith(\"start_page\"));\n\n const ordered: string[] = [];\n\n // Shared first\n if (attrs.attachment_id) ordered.push(\"attachment_id\");\n\n if (hasTimestamps) {\n // AV citations: attachment_id, full_phrase, key_span, timestamps, (optional reasoning/value), then any extras\n if (attrs.full_phrase) ordered.push(\"full_phrase\");\n if (attrs.key_span) ordered.push(\"key_span\");\n ordered.push(\"timestamps\");\n } else {\n // Document citations: attachment_id, start_page*, full_phrase, key_span, line_ids, (optional reasoning/value), then any extras\n if (startPageKeys.includes(\"start_page_key\"))\n ordered.push(\"start_page_key\");\n startPageKeys\n .filter((k) => k !== \"start_page_key\")\n .sort()\n .forEach((k) => ordered.push(k));\n\n if (attrs.full_phrase) ordered.push(\"full_phrase\");\n if (attrs.key_span) ordered.push(\"key_span\");\n if (attrs.line_ids) ordered.push(\"line_ids\");\n }\n\n // Optional attrs supported by the parser (but not required)\n if (attrs.reasoning) ordered.push(\"reasoning\");\n if (attrs.value) ordered.push(\"value\");\n\n // Any remaining attributes, stable + deterministic (alpha)\n const used = new Set(ordered);\n keys\n .filter((k) => !used.has(k))\n .sort()\n .forEach((k) => ordered.push(k));\n\n const rebuiltAttrs = ordered.map((k) => `${k}='${attrs[k]}'`).join(\" \");\n return `<cite ${rebuiltAttrs} />`;\n };\n\n normalized = normalized.replace(/<cite\\b[\\s\\S]*?\\/>/gm, (tag) =>\n reorderCiteTagAttributes(tag)\n );\n\n return normalized;\n};\n","import type { Citation } from \"../types/citation.js\";\nimport type { Verification } from \"../types/verification.js\";\nimport { sha1Hash } from \"../utils/sha.js\";\nimport { getCitationPageNumber } from \"../parsing/normalizeCitation.js\";\n\n// =============================================================================\n// UTILITY FUNCTIONS\n// =============================================================================\n\nexport function cn(...classes: (string | undefined | null | false)[]): string {\n return classes.filter(Boolean).join(\" \");\n}\n\n/**\n * Type guard to check if a citation is a URL citation (type: \"url\" or has url field).\n */\nexport function isUrlCitation(citation: Citation): boolean {\n return citation.type === \"url\" || (typeof citation.url === \"string\" && citation.url.length > 0);\n}\n\n/**\n * Generates a unique, deterministic key for a citation based on its content.\n * Works with both document and URL citation types.\n *\n * For URL citations, the URL is included in the key generation for uniqueness.\n *\n * @param citation - The citation to generate a key for\n * @returns A unique, deterministic key for the citation\n */\nexport function generateCitationKey(citation: Citation): string {\n const pageNumber =\n citation.pageNumber || getCitationPageNumber(citation.startPageKey);\n\n // Base key parts for all citations\n const keyParts = [\n citation.attachmentId || \"\",\n pageNumber?.toString() || \"\",\n citation.fullPhrase || \"\",\n citation.keySpan?.toString() || \"\",\n citation.lineIds?.join(\",\") || \"\",\n citation.timestamps?.startTime || \"\",\n citation.timestamps?.endTime || \"\",\n ];\n\n // Add URL-specific fields if present\n if (isUrlCitation(citation)) {\n keyParts.push(\n citation.url || \"\",\n citation.title || \"\",\n citation.domain || \"\",\n );\n }\n\n return sha1Hash(keyParts.join(\"|\")).slice(0, 16);\n}\n\n/**\n * Generates a unique, deterministic key for a verification based on its content.\n * @param verification - The verification to generate a key for\n * @returns\n */\nexport function generateVerificationKey(verification: Verification): string {\n const keyParts = [\n verification.attachmentId || \"\",\n verification.label || \"\",\n verification.verifiedFullPhrase || \"\",\n verification.verifiedKeySpan || \"\",\n verification.verifiedLineIds?.join(\",\") || \"\",\n verification.verifiedPageNumber?.toString() || \"\",\n\n verification.verifiedTimestamps?.startTime || \"\",\n verification.verifiedTimestamps?.endTime || \"\",\n\n verification.verifiedMatchSnippet || \"\",\n verification.hitIndexWithinPage?.toString() || \"\",\n ];\n\n return sha1Hash(keyParts.join(\"|\")).slice(0, 16);\n}\n\n/**\n * Generates a unique instance ID for a citation component render.\n * Combines the citation key with a random suffix for uniqueness.\n */\nexport function generateCitationInstanceId(citationKey: string): string {\n const randomSuffix = Math.random().toString(36).slice(2, 11);\n return `${citationKey}-${randomSuffix}`;\n}\n\n/**\n * Gets the display text for a citation (keySpan with fallback to number).\n */\nexport function getCitationDisplayText(\n citation: Citation,\n options: {\n fallbackDisplay?: string | null;\n } = {}\n): string {\n const { fallbackDisplay } = options;\n return (\n citation.keySpan?.toString() ||\n citation.citationNumber?.toString() ||\n fallbackDisplay ||\n \"1\"\n );\n}\n\n/**\n * Gets the citation number as a string.\n */\nexport function getCitationNumber(citation: Citation): string {\n return citation.citationNumber?.toString() || \"1\";\n}\n\n/**\n * Gets the keySpan text from a citation.\n */\nexport function getCitationKeySpanText(citation: Citation): string {\n return citation.keySpan?.toString() || \"\";\n}\n\n/**\n * Joins class names, filtering out falsy values.\n * This is a minimal implementation for the base component.\n */\nexport function classNames(\n ...classes: (string | undefined | null | false)[]\n): string {\n return classes.filter(Boolean).join(\" \");\n}\n\n/**\n * Default padding values for citation styling.\n */\nexport const CITATION_X_PADDING = 4;\nexport const CITATION_Y_PADDING = 1;\n"]}
|
|
@@ -68,4 +68,5 @@ ${a}`).join(`
|
|
|
68
68
|
|
|
69
69
|
${d}
|
|
70
70
|
|
|
71
|
-
${i}`;}return {enhancedSystemPrompt:s,enhancedUserPrompt:c}}var O={type:"object",properties:{attachmentId:{type:"string"},reasoning:{type:"string",description:"The logic connecting the form section requirements to the supporting source citation (think first!)"},fullPhrase:{type:"string",description:"The verbatim text of the terse phrase inside <attachment_text /> to support the citation (if there is a detected OCR correction, use the corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},lineIds:{type:"array",items:{type:"number"},description:"Infer lineIds, as we only provide the first, last, and every 5th line. Provide inclusive lineIds for the fullPhrase."}},required:["attachmentId","reasoning","fullPhrase","keySpan","startPageKey","lineIds"]},v={type:"object",properties:{attachmentId:{type:"string"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},fullPhrase:{type:"string",description:"The exact verbatim text of the phrase or paragraph from the source document to support the citation (if there is a detected OCR correction, use the verbatim corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},timestamps:{type:"object",properties:{startTime:{type:"string"},endTime:{type:"string"}},required:["startTime","endTime"],description:"The timestamp of the audio or video frame including milliseconds formatted as: HH:MM:SS.SSS"}},required:["attachmentId","startPageKey","fullPhrase","keySpan","timestamps"]};var u=4,P=3,I=5;function S(t,n){let i={};for(let e of t){for(let r=u;r<=e.length;r++){let s=e.slice(0,r),c=(s.match(/\d/g)||[]).length,o=(s.match(/[a-zA-Z]/g)||[]).length;if(s.length<u||c>0&&o<P||c===0&&o<I||t.some(m=>m!==e&&m.startsWith(s)))continue;let p=m=>m.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),a=(n.match(new RegExp(p(s),"g"))||[]).length,l=(n.match(new RegExp(p(e),"g"))||[]).length;if(a===l){i[s]=e;break}}if(!Object.values(i).includes(e))throw new Error(`Cannot find a safe unique prefix for ID "${e}" that meets the minimum requirements (length: ${u})`)}return i}function w(t,n){if(!n||n.length===0)return {compressed:t,prefixMap:{}};let i=Array.from(new Set(n)),e=JSON.stringify(t),r=S(i,e),s=Object.keys(r).sort((o,p)=>p.length-o.length),c=e;for(let o of s){let a=r[o].replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");c=c.replace(new RegExp(a,"g"),o);}return {compressed:JSON.parse(c),prefixMap:r}}function C(t,n){if(!n||Object.keys(n).length===0)return t;let i=Object.entries(n).sort((a,l)=>l[0].length-a[0].length),e,r=false;typeof t=="string"?e=t:(e=JSON.stringify(t),r=true);let s=e?.length;for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");e=e.replace(new RegExp(m,"g"),l);}let c=["attachmentId","attachment_id","attachment_ID","attachmentID","fileId","file_id","file_ID","fileID","fileid"];for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),h=c.join("|"),f="([\"'`])",g=new RegExp(`(${h})(\\s*=\\s*)${f}${m}\\3`,"g");e=e.replace(g,`$1$2$3${l}$3`);}let o=e?.length,p=s-o;if(p>0)throw new Error(`[decompressedPromptIds] diff ${p} originalLength ${s} newLength ${o}`);return r?JSON.parse(e):e}exports.a=_;exports.b=y;exports.c=d;exports.d=T;exports.e=x;exports.f=R;exports.g=O;exports.h=v;exports.i=w;exports.j=C
|
|
71
|
+
${i}`;}return {enhancedSystemPrompt:s,enhancedUserPrompt:c}}var O={type:"object",properties:{attachmentId:{type:"string"},reasoning:{type:"string",description:"The logic connecting the form section requirements to the supporting source citation (think first!)"},fullPhrase:{type:"string",description:"The verbatim text of the terse phrase inside <attachment_text /> to support the citation (if there is a detected OCR correction, use the corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},lineIds:{type:"array",items:{type:"number"},description:"Infer lineIds, as we only provide the first, last, and every 5th line. Provide inclusive lineIds for the fullPhrase."}},required:["attachmentId","reasoning","fullPhrase","keySpan","startPageKey","lineIds"]},v={type:"object",properties:{attachmentId:{type:"string"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},fullPhrase:{type:"string",description:"The exact verbatim text of the phrase or paragraph from the source document to support the citation (if there is a detected OCR correction, use the verbatim corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},timestamps:{type:"object",properties:{startTime:{type:"string"},endTime:{type:"string"}},required:["startTime","endTime"],description:"The timestamp of the audio or video frame including milliseconds formatted as: HH:MM:SS.SSS"}},required:["attachmentId","startPageKey","fullPhrase","keySpan","timestamps"]};var u=4,P=3,I=5;function S(t,n){let i={};for(let e of t){for(let r=u;r<=e.length;r++){let s=e.slice(0,r),c=(s.match(/\d/g)||[]).length,o=(s.match(/[a-zA-Z]/g)||[]).length;if(s.length<u||c>0&&o<P||c===0&&o<I||t.some(m=>m!==e&&m.startsWith(s)))continue;let p=m=>m.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),a=(n.match(new RegExp(p(s),"g"))||[]).length,l=(n.match(new RegExp(p(e),"g"))||[]).length;if(a===l){i[s]=e;break}}if(!Object.values(i).includes(e))throw new Error(`Cannot find a safe unique prefix for ID "${e}" that meets the minimum requirements (length: ${u})`)}return i}function w(t,n){if(!n||n.length===0)return {compressed:t,prefixMap:{}};let i=Array.from(new Set(n)),e=JSON.stringify(t),r=S(i,e),s=Object.keys(r).sort((o,p)=>p.length-o.length),c=e;for(let o of s){let a=r[o].replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");c=c.replace(new RegExp(a,"g"),o);}return {compressed:JSON.parse(c),prefixMap:r}}function C(t,n){if(!n||Object.keys(n).length===0)return t;let i=Object.entries(n).sort((a,l)=>l[0].length-a[0].length),e,r=false;typeof t=="string"?e=t:(e=JSON.stringify(t),r=true);let s=e?.length;for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");e=e.replace(new RegExp(m,"g"),l);}let c=["attachmentId","attachment_id","attachment_ID","attachmentID","fileId","file_id","file_ID","fileID","fileid"];for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),h=c.join("|"),f="([\"'`])",g=new RegExp(`(${h})(\\s*=\\s*)${f}${m}\\3`,"g");e=e.replace(g,`$1$2$3${l}$3`);}let o=e?.length,p=s-o;if(p>0)throw new Error(`[decompressedPromptIds] diff ${p} originalLength ${s} newLength ${o}`);return r?JSON.parse(e):e}exports.a=_;exports.b=y;exports.c=d;exports.d=T;exports.e=x;exports.f=R;exports.g=O;exports.h=v;exports.i=w;exports.j=C;//# sourceMappingURL=chunk-PJWAX2VG.cjs.map
|
|
72
|
+
//# sourceMappingURL=chunk-PJWAX2VG.cjs.map
|