@deepcitation/deepcitation-js 1.1.28 → 1.1.30

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.
@@ -0,0 +1,45 @@
1
+ import { Citation, Verification } from './types/index.js';
2
+
3
+ /**
4
+ * Generates a unique, deterministic key for a citation based on its content.
5
+ * @param citation - The citation to generate a key for
6
+ * @returns A unique, deterministic key for the citation
7
+ */
8
+ declare function generateCitationKey(citation: Citation): string;
9
+ /**
10
+ * Generates a unique, deterministic key for a verification based on its content.
11
+ * @param verification - The verification to generate a key for
12
+ * @returns
13
+ */
14
+ declare function generateVerificationKey(verification: Verification): string;
15
+ /**
16
+ * Generates a unique instance ID for a citation component render.
17
+ * Combines the citation key with a random suffix for uniqueness.
18
+ */
19
+ declare function generateCitationInstanceId(citationKey: string): string;
20
+ /**
21
+ * Gets the display text for a citation (keySpan with fallback to number).
22
+ */
23
+ declare function getCitationDisplayText(citation: Citation, options?: {
24
+ fallbackDisplay?: string | null;
25
+ }): string;
26
+ /**
27
+ * Gets the citation number as a string.
28
+ */
29
+ declare function getCitationNumber(citation: Citation): string;
30
+ /**
31
+ * Gets the keySpan text from a citation.
32
+ */
33
+ declare function getCitationKeySpanText(citation: Citation): string;
34
+ /**
35
+ * Joins class names, filtering out falsy values.
36
+ * This is a minimal implementation for the base component.
37
+ */
38
+ declare function classNames(...classes: (string | undefined | null | false)[]): string;
39
+ /**
40
+ * Default padding values for citation styling.
41
+ */
42
+ declare const CITATION_X_PADDING = 4;
43
+ declare const CITATION_Y_PADDING = 1;
44
+
45
+ export { CITATION_X_PADDING as C, generateVerificationKey as a, generateCitationInstanceId as b, CITATION_Y_PADDING as c, getCitationDisplayText as d, getCitationNumber as e, getCitationKeySpanText as f, generateCitationKey as g, classNames as h };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepcitation/deepcitation-js",
3
- "version": "1.1.28",
3
+ "version": "1.1.30",
4
4
  "description": "DeepCitation JavaScript SDK for deterministic AI citation verification",
5
5
  "type": "module",
6
6
  "private": false,
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-O2XFH626.js';var H=(t,e)=>{let n=/<cite\s+(?:fileId|attachmentId)='(\w{0,25})'\s+start_page[\_a-zA-Z]*='page[\_a-zA-Z]*(\d+)_index_(\d+)'\s+full_phrase='((?:[^'\\]|\\.)*)'\s+key_span='((?:[^'\\]|\\.)*)'\s+line(?:_ids|Ids)='([^']+)'(?:\s+(value|reasoning)='((?:[^'\\]|\\.)*)')?\s*\/>/g;return t.replace(n,(o,r,s,l,i,p,c,a)=>e&&p?.replace(/key_span=['"]|['"]/g,"")||"")},G=t=>t.replace(/<page_number_\d+_index_\d+>/g,"").replace(/<\/page_number_\d+_index_\d+>/g,"").trim(),X=t=>{let e=/<line id="[^"]*">|<\/line>/g;return t.replace(e,"")},U=t=>{if(!t)return null;let e=t.match(/\d+/)?.[0];return e?parseInt(e):null},K=t=>{let e=t?.trim()||"",n=e.split(/(<cite[\s\S]*?(?:\/>|<\/cite>))/gm);return n.length<=1?T(e):(e=n.map(o=>o.startsWith("<cite")?T(o):o).join(""),e)},T=t=>{let e=t;e=e.replace(/><\/cite>/g,"/>");let n=l=>{let i=l.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},o=l=>l.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),r=/(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*\/?>)/gm;e=e.replace(r,(l,i,p,c)=>{let a=c;return a.endsWith(p)&&(a=a.slice(0,-1)),a=a.replace(/(\r?\n)+/g," "),a=o(a),a=a.replace(/(\*|_){2,}/g,""),a=a.replace(/\\\\'/g,"'"),a=a.replace(/\\'/g,"'"),a=a.replace(/'/g,"\\'"),a=a.replace(/\\\\"/g,'"'),a=a.replace(/\\"/g,'"'),a=a.replace(/"/g,'\\"'),a=a.replace(/\*/g,""),`${n(i)}='${a}'`}),e=e.replace(/(line_ids|lineIds|timestamps)=['"]?([\[\]\(\){}A-Za-z0-9_\-, ]+)['"]?(\s*\/?>|\s+)/gm,(l,i,p,c)=>{let a=p.replace(/[A-Za-z\[\]\(\){}]/g,"");return a=a.replace(/(\d+)-(\d+)/g,(_,h,f)=>{let y=parseInt(h,10),I=parseInt(f,10),u=[];if(y<=I)for(let g=y;g<=I;g++)u.push(g);else u.push(y);return u.join(",")}),a=a.replace(/,+/g,",").replace(/^,|,$/g,""),`${n(i)}='${a}'${c}`});let s=l=>{let i=/([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(['"])((?:[^'"\\\n]|\\.)*)(?:\2)/g,p={},c;for(;c=i.exec(l);){let u=c[1],g=c[3],C=n(u);p[C]=g;}let a=Object.keys(p);if(a.length===0)return l;let _=typeof p.timestamps=="string"&&p.timestamps.length>0,h=a.filter(u=>u.startsWith("start_page")),f=[];p.attachment_id&&f.push("attachment_id"),_?(p.full_phrase&&f.push("full_phrase"),f.push("timestamps")):(h.includes("start_page_key")&&f.push("start_page_key"),h.filter(u=>u!=="start_page_key").sort().forEach(u=>f.push(u)),p.full_phrase&&f.push("full_phrase"),p.key_span&&f.push("key_span"),p.line_ids&&f.push("line_ids")),p.reasoning&&f.push("reasoning"),p.value&&f.push("value");let y=new Set(f);return a.filter(u=>!y.has(u)).sort().forEach(u=>f.push(u)),`<cite ${f.map(u=>`${u}='${p[u]}'`).join(" ")} />`};return e=e.replace(/<cite\b[\s\S]*?\/>/gm,l=>s(l)),e};function L(t){return new TextEncoder().encode(t)}function j(t){let e=1732584193,n=4023233417,o=2562383102,r=271733878,s=3285377520,l=t.length,i=l*8,p=l+1+8,c=Math.ceil(p/64)*64,a=new ArrayBuffer(c),_=new Uint8Array(a),h=new DataView(a);_.set(t),_[l]=128,h.setUint32(c-8,Math.floor(i/4294967296),false),h.setUint32(c-4,i>>>0,false);let f=new Uint32Array(80);for(let I=0;I<c;I+=64){for(let d=0;d<16;d++)f[d]=h.getUint32(I+d*4,false);for(let d=16;d<80;d++){let x=f[d-3]^f[d-8]^f[d-14]^f[d-16];f[d]=x<<1|x>>>31;}let u=e,g=n,C=o,b=r,w=s;for(let d=0;d<80;d++){let x,m;d<20?(x=g&C|~g&b,m=1518500249):d<40?(x=g^C^b,m=1859775393):d<60?(x=g&C|g&b|C&b,m=2400959708):(x=g^C^b,m=3395469782);let P=(u<<5|u>>>27)+x+w+m+f[d]>>>0;w=b,b=C,C=(g<<30|g>>>2)>>>0,g=u,u=P;}e=e+u>>>0,n=n+g>>>0,o=o+C>>>0,r=r+b>>>0,s=s+w>>>0;}let y=I=>I.toString(16).padStart(8,"0");return y(e)+y(n)+y(o)+y(r)+y(s)}function v(t){try{if(!t)return "";let e=typeof t=="string"?t:JSON.stringify(t);return j(L(e))}catch(e){console.error("Error in making the hash:",e);}return ""}function k(t){let e=t.pageNumber||U(t.startPageKey),n=[t.attachmentId||"",e?.toString()||"",t.fullPhrase||"",t.keySpan?.toString()||"",t.lineIds?.join(",")||"",t.timestamps?.startTime||"",t.timestamps?.endTime||""];return v(n.join("|")).slice(0,16)}function nt(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 v(e.join("|")).slice(0,16)}function it(t){let e=Math.random().toString(36).slice(2,11);return `${t}-${e}`}var rt=4,st=1;function J(t){if(!t)return;let e=[],n=t.split(",");for(let o of n){let r=o.trim();if(r)if(r.includes("-")){let[s,l]=r.split("-"),i=parseInt(s,10),p=parseInt(l,10);if(!isNaN(i)&&!isNaN(p)&&i<=p)for(let c=i;c<=p;c++)e.push(c);else isNaN(i)||e.push(i);}else {let s=parseInt(r,10);isNaN(s)||e.push(s);}}if(e.length!==0)return [...new Set(e)].sort((o,r)=>o-r)}function ct(t){let e=t?.status,n=e==="not_found",o=e==="found_phrase_missed_value",r=e==="found_key_span_only",s=e==="partial_text_found"||e==="found_on_other_page"||e==="found_on_other_line"||e==="first_word_found";return {isVerified:e==="found"||r||s||o,isMiss:n,isPartialMatch:s,isPending:e==="pending"||e==="loading"||!e}}var Z=(t,e,n,o)=>{let r=m=>m?m.replace(/^['"]|['"]$/g,"").replace(/\\'/g,"'"):void 0,s=n?.current?n.current++:void 0,l=t.substring(0,t.indexOf("<cite")),i=t.includes("/>")?t.slice(t.indexOf("/>")+2):"",p=t.substring(t.indexOf("<cite"),t.indexOf("/>")+2),c=(m,P)=>{for(let M of P){let z=new RegExp(`${M}='((?:[^'\\\\]|\\\\.)*)'`),N=m.match(z);if(N)return N[1]}},a=c(p,["attachment_id","attachmentId","file_id","fileId"]),_=a?.length===20?a:e||a,h=c(p,["start_page_key","startPageKey","start_page"]),f,y;if(h){let m=h.match(/page[\_a-zA-Z]*(\d+)_index_(\d+)/);m&&(f=parseInt(m[1]),y=parseInt(m[2]));}let I=r(c(p,["full_phrase","fullPhrase"])),u=r(c(p,["key_span","keySpan"])),g=r(c(p,["reasoning"])),C=r(c(p,["value"])),b;try{let P=c(p,["line_ids","lineIds"])?.replace(/[A-Za-z_[\](){}:]/g,"");b=P?J(P):void 0;}catch(m){o&&console.error("Error parsing lineIds",m);}let w=c(p,["timestamps"]),d;if(w){let[m,P]=w.split("-")||[];d={startTime:m,endTime:P};}let x={attachmentId:_,pageNumber:f,startPageKey:`page_number_${f||1}_index_${y||0}`,fullPhrase:I,keySpan:u||C,citationNumber:s,lineIds:b,beforeCite:l,timestamps:d,reasoning:g};return {beforeCite:l,afterCite:i,citation:x}},W=(t,e)=>{if(!t)return null;let n=t.fullPhrase??t.full_phrase,o=t.startPageKey??t.start_page_key,r=t.keySpan??t.key_span,s=t.lineIds??t.line_ids,l=t.attachmentId??t.attachment_id??t.fileId??t.file_id,i=t.reasoning,p=t.value;if(!n)return null;let c;if(o){let h=o.match(/page[_a-zA-Z]*(\d+)_index_(\d+)/i);if(h)c=parseInt(h[1],10);else {let f=o.match(/^(\d+)_(\d+)$/);f&&(c=parseInt(f[1],10));}}let a=s?.length?[...s].sort((h,f)=>h-f):void 0;return {attachmentId:l,pageNumber:c,fullPhrase:n,citationNumber:e,lineIds:a,keySpan:r||p,reasoning:i}},$=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),S=t=>Array.isArray(t)?t.length>0&&t.some($):typeof t=="object"&&t!==null?$(t):false,V=t=>{let e={},n=Array.isArray(t)?t:[t],o=1;for(let r of n){let s=W(r,o++);if(s&&s.fullPhrase){let l=k(s);e[l]=s;}}return e},O=(t,e)=>{if(!(!t||typeof t!="object")){if(t.citation&&S(t.citation)){let n=Array.isArray(t.citation)?t.citation:[t.citation];e.push(...n);}if(t.citations&&S(t.citations)){let n=Array.isArray(t.citations)?t.citations:[t.citations];e.push(...n);}if(Array.isArray(t))for(let n of t)O(n,e);else for(let n of Object.keys(t))n!=="citation"&&n!=="citations"&&O(t[n],e);}},B=t=>{let e=K(t),n=/<cite\s+[^>]*\/>/g,o=e.match(n);if(!o||o.length===0)return {};let r={},s={current:1};for(let l of o){let{citation:i}=Z(l,void 0,s);if(i&&i.fullPhrase){let p=k(i);r[p]=i;}}return r},D=t=>{if(!t)return {};let e={};if(typeof t=="object"){if(S(t)){let r=V(t);Object.assign(e,r);}else {let r=[];if(O(t,r),r.length>0){let s=V(r);Object.assign(e,s);}}let n=JSON.stringify(t),o=B(n);Object.assign(e,o);}else if(typeof t=="string"){let n=B(t);Object.assign(e,n);}return e};function pt(t){let e=new Map,n=Array.isArray(t)?t.map((o,r)=>[k(o)||String(r+1),o]):Object.entries(t);for(let[o,r]of n){let s=r.attachmentId||"";e.has(s)||e.set(s,{}),e.get(s)[o]=r;}return e}function ft(t){let e={},n=Array.isArray(t)?t.map((o,r)=>[k(o)||String(r+1),o]):Object.entries(t);for(let[o,r]of n){let s=r.attachmentId||"";e[s]||(e[s]={}),e[s][o]=r;}return e}var q="https://api.deepcitation.com";function E(t,e){if(typeof Buffer<"u"&&Buffer.isBuffer(t)){let n=Uint8Array.from(t);return {blob:new Blob([n]),name:e||"document"}}if(t instanceof Blob)return {blob:t,name:e||(t instanceof File?t.name:"document")};throw new Error("Invalid file type. Expected File, Blob, or Buffer.")}async function F(t,e){return (await t.json().catch(()=>({})))?.error?.message||`${e} failed with status ${t.status}`}var R=class{constructor(e){a(this,"apiKey");a(this,"apiUrl");if(!e.apiKey)throw new Error("DeepCitation API key is required. Get one at https://deepcitation.com/dashboard");this.apiKey=e.apiKey,this.apiUrl=e.apiUrl?.replace(/\/$/,"")||q;}async uploadFile(e,n){let{blob:o,name:r}=E(e,n?.filename),s=new FormData;s.append("file",o,r),n?.attachmentId&&s.append("attachmentId",n.attachmentId),n?.filename&&s.append("filename",n.filename);let l=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s});if(!l.ok)throw new Error(await F(l,"Upload"));return await l.json()}async convertToPdf(e){let n=typeof e=="string"?{url:e}:e,{url:o,file:r,filename:s,attachmentId:l}=n;if(!o&&!r)throw new Error("Either url or file must be provided");let i;if(o)i=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({url:o,filename:s,attachmentId:l})});else {let{blob:p,name:c}=E(r,s),a=new FormData;a.append("file",p,c),l&&a.append("attachmentId",l),s&&a.append("filename",s),i=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:a});}if(!i.ok)throw new Error(await F(i,"Conversion"));return await i.json()}async prepareConvertedFile(e){let n=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({attachmentId:e.attachmentId})});if(!n.ok)throw new Error(await F(n,"Prepare"));return await n.json()}async prepareFiles(e){if(e.length===0)return {fileDataParts:[],deepTextPromptPortion:[]};let n=e.map(({file:l,filename:i,attachmentId:p})=>this.uploadFile(l,{filename:i,attachmentId:p}).then(c=>({result:c,filename:i}))),r=(await Promise.all(n)).map(({result:l,filename:i})=>({attachmentId:l.attachmentId,deepTextPromptPortion:l.deepTextPromptPortion,filename:i||l.metadata?.filename})),s=r.map(l=>l.deepTextPromptPortion);return {fileDataParts:r,deepTextPromptPortion:s}}async verifyCitations(e,n,o){let r={};if(Array.isArray(n))for(let c of n){let a=k(c);r[a]=c;}else if(typeof n=="object"&&n!==null)if("fullPhrase"in n||"value"in n){let c=k(n);r[c]=n;}else Object.assign(r,n);else throw new Error("Invalid citations format");let s=`${this.apiUrl}/verifyCitations`,l={data:{attachmentId:e,citations:r,outputImageFormat:o?.outputImageFormat||"avif"}},i=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok)throw new Error(await F(i,"Verification"));return await i.json()}async verifyCitationsFromLlmOutput(e,n){let{llmOutput:o,outputImageFormat:r="avif"}=e;if(n||(n=D(o)),Object.keys(n).length===0)return {verifications:{}};let s=new Map;for(let[c,a]of Object.entries(n)){let _=a.attachmentId||"";s.has(_)||s.set(_,{}),s.get(_)[c]=a;}let l=[];for(let[c,a]of s)c&&l.push(this.verifyCitations(c,a,{outputImageFormat:r}));let i=await Promise.all(l),p={};for(let c of i)Object.assign(p,c.verifications);return {verifications:p}}};
2
- export{H as a,G as b,X as c,U as d,K as e,v as f,k as g,nt as h,it as i,rt as j,st as k,ct as l,Z as m,D as n,pt as o,ft as p,R as q};
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkF2MMVEVC_cjs=require('./chunk-F2MMVEVC.cjs');var H=(t,e)=>{let n=/<cite\s+(?:fileId|attachmentId)='(\w{0,25})'\s+start_page[\_a-zA-Z]*='page[\_a-zA-Z]*(\d+)_index_(\d+)'\s+full_phrase='((?:[^'\\]|\\.)*)'\s+key_span='((?:[^'\\]|\\.)*)'\s+line(?:_ids|Ids)='([^']+)'(?:\s+(value|reasoning)='((?:[^'\\]|\\.)*)')?\s*\/>/g;return t.replace(n,(o,r,s,l,i,p,c,a)=>e&&p?.replace(/key_span=['"]|['"]/g,"")||"")},G=t=>t.replace(/<page_number_\d+_index_\d+>/g,"").replace(/<\/page_number_\d+_index_\d+>/g,"").trim(),X=t=>{let e=/<line id="[^"]*">|<\/line>/g;return t.replace(e,"")},U=t=>{if(!t)return null;let e=t.match(/\d+/)?.[0];return e?parseInt(e):null},K=t=>{let e=t?.trim()||"",n=e.split(/(<cite[\s\S]*?(?:\/>|<\/cite>))/gm);return n.length<=1?T(e):(e=n.map(o=>o.startsWith("<cite")?T(o):o).join(""),e)},T=t=>{let e=t;e=e.replace(/><\/cite>/g,"/>");let n=l=>{let i=l.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},o=l=>l.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),r=/(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*\/?>)/gm;e=e.replace(r,(l,i,p,c)=>{let a=c;return a.endsWith(p)&&(a=a.slice(0,-1)),a=a.replace(/(\r?\n)+/g," "),a=o(a),a=a.replace(/(\*|_){2,}/g,""),a=a.replace(/\\\\'/g,"'"),a=a.replace(/\\'/g,"'"),a=a.replace(/'/g,"\\'"),a=a.replace(/\\\\"/g,'"'),a=a.replace(/\\"/g,'"'),a=a.replace(/"/g,'\\"'),a=a.replace(/\*/g,""),`${n(i)}='${a}'`}),e=e.replace(/(line_ids|lineIds|timestamps)=['"]?([\[\]\(\){}A-Za-z0-9_\-, ]+)['"]?(\s*\/?>|\s+)/gm,(l,i,p,c)=>{let a=p.replace(/[A-Za-z\[\]\(\){}]/g,"");return a=a.replace(/(\d+)-(\d+)/g,(_,h,f)=>{let y=parseInt(h,10),I=parseInt(f,10),u=[];if(y<=I)for(let g=y;g<=I;g++)u.push(g);else u.push(y);return u.join(",")}),a=a.replace(/,+/g,",").replace(/^,|,$/g,""),`${n(i)}='${a}'${c}`});let s=l=>{let i=/([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(['"])((?:[^'"\\\n]|\\.)*)(?:\2)/g,p={},c;for(;c=i.exec(l);){let u=c[1],g=c[3],C=n(u);p[C]=g;}let a=Object.keys(p);if(a.length===0)return l;let _=typeof p.timestamps=="string"&&p.timestamps.length>0,h=a.filter(u=>u.startsWith("start_page")),f=[];p.attachment_id&&f.push("attachment_id"),_?(p.full_phrase&&f.push("full_phrase"),f.push("timestamps")):(h.includes("start_page_key")&&f.push("start_page_key"),h.filter(u=>u!=="start_page_key").sort().forEach(u=>f.push(u)),p.full_phrase&&f.push("full_phrase"),p.key_span&&f.push("key_span"),p.line_ids&&f.push("line_ids")),p.reasoning&&f.push("reasoning"),p.value&&f.push("value");let y=new Set(f);return a.filter(u=>!y.has(u)).sort().forEach(u=>f.push(u)),`<cite ${f.map(u=>`${u}='${p[u]}'`).join(" ")} />`};return e=e.replace(/<cite\b[\s\S]*?\/>/gm,l=>s(l)),e};function L(t){return new TextEncoder().encode(t)}function j(t){let e=1732584193,n=4023233417,o=2562383102,r=271733878,s=3285377520,l=t.length,i=l*8,p=l+1+8,c=Math.ceil(p/64)*64,a=new ArrayBuffer(c),_=new Uint8Array(a),h=new DataView(a);_.set(t),_[l]=128,h.setUint32(c-8,Math.floor(i/4294967296),false),h.setUint32(c-4,i>>>0,false);let f=new Uint32Array(80);for(let I=0;I<c;I+=64){for(let d=0;d<16;d++)f[d]=h.getUint32(I+d*4,false);for(let d=16;d<80;d++){let x=f[d-3]^f[d-8]^f[d-14]^f[d-16];f[d]=x<<1|x>>>31;}let u=e,g=n,C=o,b=r,w=s;for(let d=0;d<80;d++){let x,m;d<20?(x=g&C|~g&b,m=1518500249):d<40?(x=g^C^b,m=1859775393):d<60?(x=g&C|g&b|C&b,m=2400959708):(x=g^C^b,m=3395469782);let P=(u<<5|u>>>27)+x+w+m+f[d]>>>0;w=b,b=C,C=(g<<30|g>>>2)>>>0,g=u,u=P;}e=e+u>>>0,n=n+g>>>0,o=o+C>>>0,r=r+b>>>0,s=s+w>>>0;}let y=I=>I.toString(16).padStart(8,"0");return y(e)+y(n)+y(o)+y(r)+y(s)}function v(t){try{if(!t)return "";let e=typeof t=="string"?t:JSON.stringify(t);return j(L(e))}catch(e){console.error("Error in making the hash:",e);}return ""}function k(t){let e=t.pageNumber||U(t.startPageKey),n=[t.attachmentId||"",e?.toString()||"",t.fullPhrase||"",t.keySpan?.toString()||"",t.lineIds?.join(",")||"",t.timestamps?.startTime||"",t.timestamps?.endTime||""];return v(n.join("|")).slice(0,16)}function nt(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 v(e.join("|")).slice(0,16)}function it(t){let e=Math.random().toString(36).slice(2,11);return `${t}-${e}`}var rt=4,st=1;function J(t){if(!t)return;let e=[],n=t.split(",");for(let o of n){let r=o.trim();if(r)if(r.includes("-")){let[s,l]=r.split("-"),i=parseInt(s,10),p=parseInt(l,10);if(!isNaN(i)&&!isNaN(p)&&i<=p)for(let c=i;c<=p;c++)e.push(c);else isNaN(i)||e.push(i);}else {let s=parseInt(r,10);isNaN(s)||e.push(s);}}if(e.length!==0)return [...new Set(e)].sort((o,r)=>o-r)}function ct(t){let e=t?.status,n=e==="not_found",o=e==="found_phrase_missed_value",r=e==="found_key_span_only",s=e==="partial_text_found"||e==="found_on_other_page"||e==="found_on_other_line"||e==="first_word_found";return {isVerified:e==="found"||r||s||o,isMiss:n,isPartialMatch:s,isPending:e==="pending"||e==="loading"||!e}}var Z=(t,e,n,o)=>{let r=m=>m?m.replace(/^['"]|['"]$/g,"").replace(/\\'/g,"'"):void 0,s=n?.current?n.current++:void 0,l=t.substring(0,t.indexOf("<cite")),i=t.includes("/>")?t.slice(t.indexOf("/>")+2):"",p=t.substring(t.indexOf("<cite"),t.indexOf("/>")+2),c=(m,P)=>{for(let M of P){let z=new RegExp(`${M}='((?:[^'\\\\]|\\\\.)*)'`),N=m.match(z);if(N)return N[1]}},a=c(p,["attachment_id","attachmentId","file_id","fileId"]),_=a?.length===20?a:e||a,h=c(p,["start_page_key","startPageKey","start_page"]),f,y;if(h){let m=h.match(/page[\_a-zA-Z]*(\d+)_index_(\d+)/);m&&(f=parseInt(m[1]),y=parseInt(m[2]));}let I=r(c(p,["full_phrase","fullPhrase"])),u=r(c(p,["key_span","keySpan"])),g=r(c(p,["reasoning"])),C=r(c(p,["value"])),b;try{let P=c(p,["line_ids","lineIds"])?.replace(/[A-Za-z_[\](){}:]/g,"");b=P?J(P):void 0;}catch(m){o&&console.error("Error parsing lineIds",m);}let w=c(p,["timestamps"]),d;if(w){let[m,P]=w.split("-")||[];d={startTime:m,endTime:P};}let x={attachmentId:_,pageNumber:f,startPageKey:`page_number_${f||1}_index_${y||0}`,fullPhrase:I,keySpan:u||C,citationNumber:s,lineIds:b,beforeCite:l,timestamps:d,reasoning:g};return {beforeCite:l,afterCite:i,citation:x}},W=(t,e)=>{if(!t)return null;let n=t.fullPhrase??t.full_phrase,o=t.startPageKey??t.start_page_key,r=t.keySpan??t.key_span,s=t.lineIds??t.line_ids,l=t.attachmentId??t.attachment_id??t.fileId??t.file_id,i=t.reasoning,p=t.value;if(!n)return null;let c;if(o){let h=o.match(/page[_a-zA-Z]*(\d+)_index_(\d+)/i);if(h)c=parseInt(h[1],10);else {let f=o.match(/^(\d+)_(\d+)$/);f&&(c=parseInt(f[1],10));}}let a=s?.length?[...s].sort((h,f)=>h-f):void 0;return {attachmentId:l,pageNumber:c,fullPhrase:n,citationNumber:e,lineIds:a,keySpan:r||p,reasoning:i}},$=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),S=t=>Array.isArray(t)?t.length>0&&t.some($):typeof t=="object"&&t!==null?$(t):false,V=t=>{let e={},n=Array.isArray(t)?t:[t],o=1;for(let r of n){let s=W(r,o++);if(s&&s.fullPhrase){let l=k(s);e[l]=s;}}return e},O=(t,e)=>{if(!(!t||typeof t!="object")){if(t.citation&&S(t.citation)){let n=Array.isArray(t.citation)?t.citation:[t.citation];e.push(...n);}if(t.citations&&S(t.citations)){let n=Array.isArray(t.citations)?t.citations:[t.citations];e.push(...n);}if(Array.isArray(t))for(let n of t)O(n,e);else for(let n of Object.keys(t))n!=="citation"&&n!=="citations"&&O(t[n],e);}},B=t=>{let e=K(t),n=/<cite\s+[^>]*\/>/g,o=e.match(n);if(!o||o.length===0)return {};let r={},s={current:1};for(let l of o){let{citation:i}=Z(l,void 0,s);if(i&&i.fullPhrase){let p=k(i);r[p]=i;}}return r},D=t=>{if(!t)return {};let e={};if(typeof t=="object"){if(S(t)){let r=V(t);Object.assign(e,r);}else {let r=[];if(O(t,r),r.length>0){let s=V(r);Object.assign(e,s);}}let n=JSON.stringify(t),o=B(n);Object.assign(e,o);}else if(typeof t=="string"){let n=B(t);Object.assign(e,n);}return e};function pt(t){let e=new Map,n=Array.isArray(t)?t.map((o,r)=>[k(o)||String(r+1),o]):Object.entries(t);for(let[o,r]of n){let s=r.attachmentId||"";e.has(s)||e.set(s,{}),e.get(s)[o]=r;}return e}function ft(t){let e={},n=Array.isArray(t)?t.map((o,r)=>[k(o)||String(r+1),o]):Object.entries(t);for(let[o,r]of n){let s=r.attachmentId||"";e[s]||(e[s]={}),e[s][o]=r;}return e}var q="https://api.deepcitation.com";function E(t,e){if(typeof Buffer<"u"&&Buffer.isBuffer(t)){let n=Uint8Array.from(t);return {blob:new Blob([n]),name:e||"document"}}if(t instanceof Blob)return {blob:t,name:e||(t instanceof File?t.name:"document")};throw new Error("Invalid file type. Expected File, Blob, or Buffer.")}async function F(t,e){return (await t.json().catch(()=>({})))?.error?.message||`${e} failed with status ${t.status}`}var R=class{constructor(e){chunkF2MMVEVC_cjs.a(this,"apiKey");chunkF2MMVEVC_cjs.a(this,"apiUrl");if(!e.apiKey)throw new Error("DeepCitation API key is required. Get one at https://deepcitation.com/dashboard");this.apiKey=e.apiKey,this.apiUrl=e.apiUrl?.replace(/\/$/,"")||q;}async uploadFile(e,n){let{blob:o,name:r}=E(e,n?.filename),s=new FormData;s.append("file",o,r),n?.attachmentId&&s.append("attachmentId",n.attachmentId),n?.filename&&s.append("filename",n.filename);let l=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s});if(!l.ok)throw new Error(await F(l,"Upload"));return await l.json()}async convertToPdf(e){let n=typeof e=="string"?{url:e}:e,{url:o,file:r,filename:s,attachmentId:l}=n;if(!o&&!r)throw new Error("Either url or file must be provided");let i;if(o)i=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({url:o,filename:s,attachmentId:l})});else {let{blob:p,name:c}=E(r,s),a=new FormData;a.append("file",p,c),l&&a.append("attachmentId",l),s&&a.append("filename",s),i=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:a});}if(!i.ok)throw new Error(await F(i,"Conversion"));return await i.json()}async prepareConvertedFile(e){let n=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({attachmentId:e.attachmentId})});if(!n.ok)throw new Error(await F(n,"Prepare"));return await n.json()}async prepareFiles(e){if(e.length===0)return {fileDataParts:[],deepTextPromptPortion:[]};let n=e.map(({file:l,filename:i,attachmentId:p})=>this.uploadFile(l,{filename:i,attachmentId:p}).then(c=>({result:c,filename:i}))),r=(await Promise.all(n)).map(({result:l,filename:i})=>({attachmentId:l.attachmentId,deepTextPromptPortion:l.deepTextPromptPortion,filename:i||l.metadata?.filename})),s=r.map(l=>l.deepTextPromptPortion);return {fileDataParts:r,deepTextPromptPortion:s}}async verifyCitations(e,n,o){let r={};if(Array.isArray(n))for(let c of n){let a=k(c);r[a]=c;}else if(typeof n=="object"&&n!==null)if("fullPhrase"in n||"value"in n){let c=k(n);r[c]=n;}else Object.assign(r,n);else throw new Error("Invalid citations format");let s=`${this.apiUrl}/verifyCitations`,l={data:{attachmentId:e,citations:r,outputImageFormat:o?.outputImageFormat||"avif"}},i=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok)throw new Error(await F(i,"Verification"));return await i.json()}async verifyCitationsFromLlmOutput(e,n){let{llmOutput:o,outputImageFormat:r="avif"}=e;if(n||(n=D(o)),Object.keys(n).length===0)return {verifications:{}};let s=new Map;for(let[c,a]of Object.entries(n)){let _=a.attachmentId||"";s.has(_)||s.set(_,{}),s.get(_)[c]=a;}let l=[];for(let[c,a]of s)c&&l.push(this.verifyCitations(c,a,{outputImageFormat:r}));let i=await Promise.all(l),p={};for(let c of i)Object.assign(p,c.verifications);return {verifications:p}}};
2
- exports.a=H;exports.b=G;exports.c=X;exports.d=U;exports.e=K;exports.f=v;exports.g=k;exports.h=nt;exports.i=it;exports.j=rt;exports.k=st;exports.l=ct;exports.m=Z;exports.n=D;exports.o=pt;exports.p=ft;exports.q=R;