revise 2.0.1 → 2.2.0
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/CHANGELOG.md +195 -0
- package/README.md +4 -1
- package/assets/historyMaterializeWorker-B51R08XN.js +612 -0
- package/backend.d.ts +8 -2
- package/backend.js +3 -1
- package/chunks/AgentPageRenderer-CH8kSTJn.js +1 -0
- package/chunks/AgentPageRenderer-P23XVguo.js +1 -0
- package/chunks/AttachmentDocumentImporter-B1WOaa7d.js +1 -0
- package/chunks/AttachmentDocumentImporter-CT_PJp_e.js +1 -0
- package/chunks/BidiText-Swm5fl9J.js +160 -0
- package/chunks/ColorParserFull-BKH72fK8.js +446 -1
- package/chunks/DocumentMutator-btiDK57e.js +31 -0
- package/chunks/DocumentScrubber-CMPfm_HF.js +18 -0
- package/chunks/{DocumentScrubber-DrgzBlx4.js → DocumentScrubber-Cm2kH8op.js} +1 -1
- package/chunks/{DocumentScrubber-W0EfGmL-.js → DocumentScrubber-bJoKijol.js} +1 -1
- package/chunks/DocumentStylesheet-DreoD7sD.js +7 -0
- package/chunks/DocxConverter-BcVG-p5K.js +13 -0
- package/chunks/DocxConverter-D2bO5RE-.js +1125 -0
- package/chunks/DocxConverter-haCfRuWb.js +13 -0
- package/chunks/{DocxGraft-B6W7fbh4.js → DocxGraft-BRKh4mHQ.js} +1 -1
- package/chunks/DocxGraft-BxSQtl12.js +7 -0
- package/chunks/{DocxGraft-Cj7v78BO.js → DocxGraft-C9MBQCnf.js} +1 -1
- package/chunks/FileImporter-CszqRfVU.js +1 -0
- package/chunks/FileImporter-DObFoCCn.js +1 -0
- package/chunks/HorizontalRuleOrnaments-gmUZ3R7Q.js +3 -1
- package/chunks/HtmlConverter-DwXB4IDh.js +267 -0
- package/chunks/ListNumbering-Qlu6AuRZ.js +23 -1
- package/chunks/MarkdownConverter-CUC8GgsS.js +57 -0
- package/chunks/MathRenderer-DT6GyJXb.js +68 -0
- package/chunks/OdtConverter-7h9HHMpL.js +125 -0
- package/chunks/OdtConverter-Ct4qypJk.js +6 -0
- package/chunks/OdtConverter-DFl__sJc.js +6 -0
- package/chunks/OfficeImportShared-BY6FdZ8d.js +1 -0
- package/chunks/OfficeImportShared-BrZoDM0j.js +30 -0
- package/chunks/OfficeImportShared-Bvm-mOyj.js +1 -0
- package/chunks/ParagraphDiffAnalysis-DrmStvmz.js +36 -0
- package/chunks/PdfConverter-1wyvoT7X.js +21 -0
- package/chunks/PdfConverter-BAoEHILo.js +21 -0
- package/chunks/PdfConverter-CKEvFj11.js +448 -0
- package/chunks/{PdfImportService-Dj1-3L2B.js → PdfImportService-BhLPp5uG.js} +2 -2
- package/chunks/{PdfImportService-OE9G383I.js → PdfImportService-xbzrN__L.js} +2 -2
- package/chunks/RtfConverter-Bxn-enp8.js +15 -0
- package/chunks/RtfConverter-LZPzBDSr.js +15 -0
- package/chunks/RtfConverter-_bacXqr1.js +186 -0
- package/chunks/TableBorders-CwnF3jvH.js +30 -0
- package/chunks/TableGrid-DbroRucl.js +12 -0
- package/chunks/TextFileDecoder--rsVs3NR.js +9 -2
- package/chunks/{TxtConverter-BYazsp6P.js → TxtConverter-C7FOwHpH.js} +5 -2
- package/chunks/UnicodeUtils-CXtusU4g.js +10 -0
- package/chunks/XmlConverter-7oo8oeQB.js +2 -0
- package/chunks/XmlConverter-DGORHJcZ.js +96 -0
- package/chunks/XmlConverter-DeLHReK_.js +2 -0
- package/chunks/_commonjsHelpers-DaMA6jEr.js +2 -1
- package/chunks/_revise-sdk-lazy-harfbuzz-CDWdjF9f.js +1 -1
- package/chunks/_revise-sdk-lazy-harfbuzz-X8gnYTZL.js +1 -1
- package/chunks/ar-ComXvtmh.js +13 -0
- package/chunks/backend-DecaBz-I.js +490 -0
- package/chunks/base64-sSPOzq-u.js +198 -0
- package/chunks/browser-module-CFmqfGkE.js +1791 -3
- package/chunks/{browser-module-BbaxnHNK.js → browser-module-Dj5o3kuL.js} +1 -1
- package/chunks/{browser-module-D2ixluMg.js → browser-module-UuM_O36W.js} +1 -1
- package/chunks/bundle.min-DRpfgV69.js +779 -5
- package/chunks/capture-1btcWcPF.js +9 -0
- package/chunks/carrier-DQeng6yq.js +6 -0
- package/chunks/de-BkbpIKxx.js +13 -0
- package/chunks/es-CKkXujOF.js +13 -0
- package/chunks/fil-piIHMc8F.js +13 -0
- package/chunks/footnoteFlatten-DUQticYy.js +6 -0
- package/chunks/fr-DuA8qLje.js +13 -0
- package/chunks/graftExport-CYnStOdU.js +82 -0
- package/chunks/html2canvas.esm-CntiHiYW.js +994 -2
- package/chunks/index-2TBhRkX7.js +387 -0
- package/chunks/index-BWdRWxoH.js +1796 -13
- package/chunks/index-Bf14eTEW.js +1096 -0
- package/chunks/index-BwcX_r62.js +387 -0
- package/chunks/index.es-CI0QPo8w.js +780 -5
- package/chunks/{index.es-B97tjxvW.js → index.es-CI7cDExj.js} +1 -1
- package/chunks/{index.es-mTU7Sl3w.js → index.es-DHpGt6Y5.js} +1 -1
- package/chunks/ja-DgrSs555.js +13 -0
- package/chunks/{jspdf.es.min-Mykp4BZO.js → jspdf.es.min--GshOuIm.js} +1 -1
- package/chunks/jspdf.es.min-DU74zN8b.js +1747 -32
- package/chunks/{jspdf.es.min-DGiD4mlU.js → jspdf.es.min-DurJZ1zW.js} +1 -1
- package/chunks/jszip.min-CPW0h1Kx.js +476 -2
- package/chunks/katex-DWj8TvwO.js +1209 -8
- package/chunks/pdf-BLWDCiFF.js +1826 -10
- package/chunks/pseudoLocale-BoYTjmiK.js +1 -0
- package/chunks/pseudoLocale-DG2NnZmz.js +1 -0
- package/chunks/purify.es-BwLardii.js +107 -2
- package/chunks/serverDocumentSession-CJ1EH3Tp.js +15 -0
- package/chunks/signatures-Bwt_OGik.js +17 -0
- package/chunks/suggestionAuthorship-B-IuLQlE.js +1 -0
- package/chunks/tree-sitter-D6zWWUMP.js +1 -1
- package/chunks/web-tree-sitter-BXGZGnNj.js +2 -1
- package/chunks/zh-9OF3SWWO.js +13 -0
- package/full.js +1 -1
- package/index.d.ts +42 -15
- package/index.js +1 -1
- package/package.json +1 -1
- package/root.js +2 -2
- package/serverToolContract.d.ts +21 -3
- package/serverToolInputs.generated.d.ts +23 -2
- package/style.css +1 -1
- package/assets/historyMaterializeWorker-C4uxcZEh.js +0 -3
- package/chunks/AgentPageRenderer-BIf_Fza8.js +0 -1
- package/chunks/AgentPageRenderer-DT9sNxEn.js +0 -1
- package/chunks/AttachmentDocumentImporter-BUavYRxO.js +0 -1
- package/chunks/AttachmentDocumentImporter-DGwfDJSH.js +0 -1
- package/chunks/BidiText-D7LYTAUL.js +0 -1
- package/chunks/DocumentMutator-CjN7Kk-X.js +0 -31
- package/chunks/DocumentScrubber-C9ZZEcYW.js +0 -1
- package/chunks/DocumentStylesheet-byN5dtC6.js +0 -1
- package/chunks/DocxConverter-Be3uPNcD.js +0 -11
- package/chunks/DocxConverter-CGYMfz-j.js +0 -11
- package/chunks/DocxConverter-DabDLfsu.js +0 -11
- package/chunks/DocxGraft-Duvo2cpy.js +0 -1
- package/chunks/FileImporter-CjUX2S4s.js +0 -1
- package/chunks/FileImporter-DtkbI6rF.js +0 -1
- package/chunks/HtmlConverter-ikXImzTY.js +0 -61
- package/chunks/MarkdownConverter-CFrcLyO_.js +0 -17
- package/chunks/MathRenderer-B0Y1h1JU.js +0 -33
- package/chunks/OdtConverter-BFT_P8SI.js +0 -1
- package/chunks/OdtConverter-Cnda9T0q.js +0 -1
- package/chunks/OdtConverter-WdwwXKVM.js +0 -1
- package/chunks/PdfConverter-D7UM58vc.js +0 -21
- package/chunks/PdfConverter-TB-QPw29.js +0 -21
- package/chunks/PdfConverter-wVP63986.js +0 -21
- package/chunks/RtfConverter-D-oqPWNl.js +0 -14
- package/chunks/RtfConverter-D9zhE07-.js +0 -14
- package/chunks/RtfConverter-DZgwU-_R.js +0 -14
- package/chunks/TableBorders-BorZS8aZ.js +0 -1
- package/chunks/TableGrid-DVWaRZv0.js +0 -1
- package/chunks/ar-C8zx2RwP.js +0 -8
- package/chunks/backend-MFpDFVrD.js +0 -1
- package/chunks/base64-BNMNG-lN.js +0 -1
- package/chunks/capture-qC26xmfy.js +0 -1
- package/chunks/carrier-BWONvrA7.js +0 -1
- package/chunks/de-ByQFqecF.js +0 -8
- package/chunks/es-PHpJXv5S.js +0 -8
- package/chunks/footnoteFlatten-Bdnn_bz1.js +0 -1
- package/chunks/graftExport-CP3h2T88.js +0 -2
- package/chunks/index-CjeGoI2g.js +0 -351
- package/chunks/index-D7V8zn4w.js +0 -36
- package/chunks/index-DyOcu9mD.js +0 -351
- package/chunks/pseudoLocale-C90lXrPg.js +0 -1
- package/chunks/pseudoLocale-UA_TkGrH.js +0 -1
- package/chunks/serverDocumentSession-CRZSb5SO.js +0 -11
- package/chunks/signatures-CsL_TjvW.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a1 as re,T as ne,c1 as x,c2 as ae,c3 as se,aX as C,c4 as M,c5 as ie}from"./index-DyOcu9mD.js";import*as v from"yjs";const E=e=>new Promise(e);Promise.all.bind(Promise);const ce=e=>new Error(e),T=e=>E((t,o)=>{e.onerror=r=>o(new Error(r.target.error)),e.onsuccess=r=>t(r.target.result)}),de=(e,t)=>E((o,r)=>{const n=indexedDB.open(e);n.onupgradeneeded=a=>t(a.target.result),n.onerror=a=>r(ce(a.target.error)),n.onsuccess=a=>{const s=a.target.result;s.onversionchange=()=>{s.close()},o(s)}}),le=e=>T(indexedDB.deleteDatabase(e)),me=(e,t)=>t.forEach(o=>e.createObjectStore.apply(e,o)),_=(e,t,o="readwrite")=>{const r=e.transaction(t,o);return t.map(n=>Pe(r,n))},U=(e,t)=>T(e.count(t)),ue=(e,t)=>T(e.get(t)),j=(e,t)=>T(e.delete(t)),he=(e,t,o)=>T(e.put(t,o)),F=(e,t)=>T(e.add(t)),pe=(e,t,o)=>T(e.getAll(t,o)),fe=(e,t,o)=>{let r=null;return ye(e,t,n=>(r=n,!1),o).then(()=>r)},ge=(e,t=null)=>fe(e,t,"prev"),we=(e,t)=>E((o,r)=>{e.onerror=r,e.onsuccess=async n=>{const a=n.target.result;if(a===null||await t(a)===!1)return o();a.continue()}}),ye=(e,t,o,r="next")=>we(e.openKeyCursor(t,r),n=>o(n.key)),Pe=(e,t)=>e.objectStore(t),Ie=(e,t)=>IDBKeyRange.upperBound(e,t),be=(e,t)=>IDBKeyRange.lowerBound(e,t),L=()=>new Map,Te=(e,t,o)=>{let r=e.get(t);return r===void 0&&e.set(t,r=o()),r},ve=()=>new Set,_e=Array.from;class Ee{constructor(){this._observers=L()}on(t,o){Te(this._observers,t,ve).add(o)}once(t,o){const r=(...n)=>{this.off(t,r),o(...n)};this.on(t,r)}off(t,o){const r=this._observers.get(t);r!==void 0&&(r.delete(o),r.size===0&&this._observers.delete(t))}emit(t,o){return _e((this._observers.get(t)||L()).values()).forEach(r=>r(...o))}destroy(){this._observers=L()}}const $="custom",O="updates",R=500,z=(e,t=()=>{},o=()=>{})=>{const[r]=_(e.db,[O]);return pe(r,be(e._dbref,!1)).then(n=>{e._destroyed||(t(r),v.transact(e.doc,()=>{n.forEach(a=>v.applyUpdate(e.doc,a))},e,!1),o(r))}).then(()=>ge(r).then(n=>{e._dbref=n+1})).then(()=>U(r).then(n=>{e._dbsize=n})).then(()=>r)},De=(e,t=!0)=>z(e).then(o=>{(t||e._dbsize>=R)&&F(o,v.encodeStateAsUpdate(e.doc)).then(()=>j(o,Ie(e._dbref,!0))).then(()=>U(o).then(r=>{e._dbsize=r}))});class ke extends Ee{constructor(t,o){super(),this.doc=o,this.name=t,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=de(t,r=>me(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=E(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,z(this,n=>F(n,v.encodeStateAsUpdate(o)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,n)=>{if(this.db&&n!==this){const[a]=_(this.db,[O]);F(a,r),++this._dbsize>=R&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{De(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},o.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),o.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(t=>{t.close()})}clearData(){return this.destroy().then(()=>{le(this.name)})}get(t){return this._db.then(o=>{const[r]=_(o,[$],"readonly");return ue(r,t)})}set(t,o){return this._db.then(r=>{const[n]=_(r,[$]);return he(n,o,t)})}del(t){return this._db.then(o=>{const[r]=_(o,[$]);return j(r,t)})}}const Se="revise-anonymous-identity",xe=1,D="identities",N="pdf-browser-id",Fe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Le(){return new Promise((e,t)=>{const o=indexedDB.open(Se,xe);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(D)||o.result.createObjectStore(D)},o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)})}async function A(){if(typeof window>"u"||typeof indexedDB>"u"||typeof crypto>"u"||typeof crypto.randomUUID!="function")return null;let e=null;try{return e=await Le(),await new Promise((t,o)=>{const r=e.transaction(D,"readwrite"),n=r.objectStore(D),a=n.get(N);let s="";a.onsuccess=()=>{const c=typeof a.result=="string"?a.result.trim().toLowerCase():"";s=Fe.test(c)?c:crypto.randomUUID(),s!==c&&n.put(s,N)},a.onerror=()=>o(a.error),r.oncomplete=()=>t(s),r.onerror=()=>o(r.error),r.onabort=()=>o(r.error)})}catch(t){return console.warn("Unable to load anonymous PDF browser identity:",t),null}finally{e?.close()}}const J="https://sync.revise-sdk.invalid";function K(){return J}function $e(){return J.replace(/^https/,"wss")}const B="yjs_document_index",Y="anon_session_id",G="yjs_document_deleted_",Ae="local-document-deleted";function W(e){return typeof window<"u"&&localStorage.getItem(G+e)==="1"}function X(){if(typeof window>"u")return[];try{const e=localStorage.getItem(B);return e?JSON.parse(e).filter(t=>!W(t)):[]}catch(e){return console.warn("Failed to read document index:",e),[]}}function Be(e){if(!(typeof window>"u"))try{if(W(e))return;const t=X();t.includes(e)||(t.push(e),localStorage.setItem(B,JSON.stringify(t)))}catch(t){console.warn("Failed to update document index:",t)}}function Ce(e){if(!(typeof window>"u"))try{localStorage.setItem(G+e,"1"),window.dispatchEvent(new CustomEvent(Ae,{detail:{documentId:e}}));const t=X().filter(o=>o!==e);localStorage.setItem(B,JSON.stringify(t))}catch(t){console.warn("Failed to remove from document index:",t)}}function Me(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let o=0;o<8;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function q(){if(typeof window>"u")return"server";let e=localStorage.getItem(Y);return e||(e=crypto.randomUUID().replace(/-/g,"").slice(0,12),localStorage.setItem(Y,e)),e}const Ue=30*60*1e3,je=3e3,Oe=15e3,k=new Map;async function Re(e){const t=Me(),o=q(),r=`anon:${o}:${t}`,n=new v.Doc,a={children:[{type:"paragraph",id:re(),children:[{type:"text",text:"",marks:{}}]}]};ne(n,a),n.transact(()=>{const l=n.getMap("metadata");l.set("id",t),l.set("documentId",t),l.set("title",x(e)),l.set("createdAt",Date.now()),l.set("updatedAt",Date.now()),l.set("lastAccessedAt",Date.now()),l.set("storageType","local")});const s=new ke(t,n);await s.whenSynced;const c=await A(),i=$e(),u=c?`${i}${i.includes("?")?"&":"?"}anonymousBrowserId=${encodeURIComponent(c)}`:i;let p=null;const d=new Promise(l=>{p=l}),f=new ae({url:se(u),name:r,document:n,token:()=>"",onSynced:()=>{p?.()}});return ze(t,n,s,f),Be(t),await Promise.race([d,new Promise(l=>setTimeout(l,Oe))]),{docId:t,anonSessionId:o,anonymousBrowserId:c}}function ze(e,t,o,r){let n=null;const a=new Promise(d=>{n=d});let s=!1;const c=()=>{if(s)return;s=!0;const d=k.get(e);d&&(clearTimeout(d.maxLifetimeTimer),k.delete(e));try{r.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying provider for ${e}:`,f)}try{o.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying persistence for ${e}:`,f)}try{t.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying ydoc for ${e}:`,f)}n?.()},i=t.getMap("import-progress"),u=()=>{const d=i.get("stage");(d==="complete"||d==="error")&&(i.unobserve(u),setTimeout(c,je))};i.observe(u);const p=setTimeout(()=>{console.warn(`[PdfImportKeeper] Import ${e} exceeded max lifetime; releasing`),c()},Ue);k.set(e,{docId:e,ydoc:t,persistence:o,provider:r,done:a,finish:c,maxLifetimeTimer:p})}async function Ne(e){const t=k.get(e);if(t){Ce(e);try{await t.persistence.clearData()}catch(o){console.warn(`[PdfImportKeeper] Error clearing data for ${e}:`,o)}t.finish()}}const Je=10;async function Ke(e){const t=e.batchSize??Je;for(let o=1;o<=e.totalPages;o+=t){const r=Math.min(e.totalPages,o+t-1),n=[];for(let a=o;a<=r;a+=1)n.push(await e.preparePage(a));await e.sendBatch(n,r===e.totalPages)}}const V="https://app-api.revise-sdk.invalid",Ye="https://agent.revise.io",Ge=150;class S extends Error{constructor(t){super(t.message),this.name="PdfLimitError",this.data=t}static ocrLimitExceeded(t,o,r,n,a="month",s=!1,c,i){const u=a==="day"?`You have ${t} free PDF pages left today. Create a free account for more.`:s?`You have ${t} free PDF pages left this month. Create an account for more.`:`You have ${t} PDF pages left this month. Upgrade for more.`;return new S({type:"OCR_LIMIT_EXCEEDED",remaining:t,requested:o,monthlyLimit:r,limitPeriod:a,anonymous:s,freeAccountLimit:c,maxPlanLimit:i,message:u,thumbnails:n})}}function We(){try{return typeof window<"u"?localStorage.getItem("auth_token"):null}catch{return null}}async function Xe(e){try{const t=e?await fetch(`${V}/subscription/pdf-limits`,{method:"GET",headers:{Authorization:`Bearer ${e}`}}):await A().then(r=>fetch(`${Ye}/api/v1/pdf/page-limit`,{method:"GET",headers:r?{"X-Anonymous-Browser-Id":r}:void 0}));if(!t.ok)return console.warn("Failed to fetch OCR limit, using fallback"),H(e);const o=await t.json();return{ocrMonthlyLimit:o.ocrMonthlyLimit||3e3,ocrPagesRemaining:o.ocrPagesRemaining??3e3,limitPeriod:o.limitPeriod==="daily"?"day":"month",anonymous:!e,freeAccountLimit:o.freeAccountLimit,maxPlanLimit:o.maxPlanLimit}}catch(t){return console.warn("Error fetching OCR limit:",t),H(e)}}function H(e){return e?{ocrMonthlyLimit:3e3,ocrPagesRemaining:3e3,limitPeriod:"month",anonymous:!1,freeAccountLimit:100,maxPlanLimit:3e3}:{ocrMonthlyLimit:10,ocrPagesRemaining:10,limitPeriod:"month",anonymous:!0,freeAccountLimit:100,maxPlanLimit:3e3}}async function qe(e,t,o){const r=await fetch(`${V}/uploads/images/presign`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({fileName:`page-${t}.png`,contentType:"image/png",fileSize:e.size,prefix:"pdf-temp"})});if(!r.ok){const c=await r.text();throw new Error(c||`Failed to get upload URL for page ${t}`)}const n=await r.json(),a=new Headers,s={...n.headers||{},"Content-Type":n.contentType||"image/png"};for(const[c,i]of Object.entries(s))i&&a.set(c,i);if(!(await fetch(n.uploadUrl,{method:n.method||"PUT",body:e,headers:a})).ok)throw new Error(`Failed to upload page ${t}`);return n.fileUrl}async function Ve(e){const{totalPages:t,title:o,token:r,timeoutMessage:n,targetDocumentId:a,afterBlockId:s}=e,c=x(o),i=!r&&!a?await Re(c):null,u=!r&&a?{docId:a,anonSessionId:q(),anonymousBrowserId:await A()}:null,p=i??u;try{const d=new AbortController,f=setTimeout(()=>d.abort(),10*60*1e3);let l;try{l=await fetch(`${K()}/api/pdf/import-streaming`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{},Accept:"text/event-stream"},body:JSON.stringify({totalPages:t,title:c,provider:ie,...r&&a?{targetDocumentId:a}:{},...a&&s?{afterBlockId:s}:{},...p?{anonSessionId:p.anonSessionId,anonDocId:p.docId,anonymousBrowserId:p.anonymousBrowserId||void 0}:{}}),signal:d.signal})}catch(P){throw P?.name==="AbortError"?new Error(n):new Error("Failed to start import. Please check your connection and try again.")}finally{clearTimeout(f)}if(!l.ok){const P=await l.text().catch(()=>"");let g={};try{g=JSON.parse(P)}catch{}throw new Error(g.error||P||`Import failed: ${l.status}`)}const h=await He(l);if(!h.importId||!h.uploadToken)throw new Error("Server did not create a page upload session.");return{documentId:h.documentId,title:h.title||c,importId:h.importId,uploadToken:h.uploadToken}}catch(d){throw i&&Ne(i.docId),d}}async function He(e){const t=e.body?.getReader();if(!t)throw new Error("Failed to read server response");const o=new TextDecoder;let r="",n="";for(;;){const{done:a,value:s}=await t.read();if(a)break;r+=o.decode(s,{stream:!0});const c=r.split(`
|
|
2
|
-
`);r=c.pop()||"";for(const i of c)if(i.startsWith("event: "))n=i.slice(7).trim();else if(i.startsWith("data: ")){let u=null;try{u=JSON.parse(i.slice(6))}catch{}if(u){if(n==="document_created")return t.releaseLock(),u;if(n==="error")throw t.releaseLock(),new Error(u.error||"Import failed")}n=""}}throw new Error("Server did not create document. Please try again.")}async function Q(e){const t=await fetch(`${K()}/api/pdf/import-streaming/${encodeURIComponent(e.importId)}/batches`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({uploadToken:e.uploadToken,pages:e.pages,final:e.final,error:e.error})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||"Failed to upload PDF page batch")}}async function Z(e,t){let o;try{o=await e.getPage(t)}catch{throw new Error(`Failed to read page ${t}. The PDF may be damaged.`)}let r=Ge/72,n=o.getViewport({scale:r});r*=1568/Math.max(n.width,n.height),n=o.getViewport({scale:r});const a=document.createElement("canvas"),s=a.getContext("2d");if(!s)throw new Error("Failed to create canvas. Your browser may not support this feature.");a.width=n.width,a.height=n.height,s.fillStyle="white",s.fillRect(0,0,a.width,a.height);try{await o.render({canvasContext:s,viewport:n}).promise}catch{throw new Error(`Failed to render page ${t}. The page may contain unsupported content.`)}const c=40,i=4;let u=!1;for(let m=0;m<c&&!u;m++){const w=Math.floor(a.width*m/c),b=Math.min(i,a.width-w);if(b<=0)continue;const y=s.getImageData(w,0,b,a.height).data;for(let I=0;I<y.length&&!u;I+=4)(y[I]<250||y[I+1]<250||y[I+2]<250)&&(u=!0)}if(!u)throw new Error(`Page ${t} appears blank. The PDF may use an unsupported image format.`);const p=await new Promise((m,w)=>{a.toBlob(b=>{b?m(b):w(new Error(`Failed to process page ${t}. The page may be too complex or large.`))},"image/png")}),d=120,f=d/a.height,l=Math.round(a.width*f),h=document.createElement("canvas");h.width=l,h.height=d;const P=h.getContext("2d");P&&P.drawImage(a,0,0,l,d);const g=h.toDataURL("image/jpeg",.7);return{blob:p,width:n.width,height:n.height,thumbnail:g}}const Qe=5;async function ee(e,t,o){const r=y=>{o&&o(y)},n=We(),{ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p}=await
|
|
1
|
+
import{B as re,a4 as ne,cc as x,cd as ae,ce as se,b1 as C,cf as M,cg as ie}from"./index-2TBhRkX7.js";import*as v from"yjs";const E=e=>new Promise(e);Promise.all.bind(Promise);const ce=e=>new Error(e),T=e=>E((t,o)=>{e.onerror=r=>o(new Error(r.target.error)),e.onsuccess=r=>t(r.target.result)}),de=(e,t)=>E((o,r)=>{const n=indexedDB.open(e);n.onupgradeneeded=a=>t(a.target.result),n.onerror=a=>r(ce(a.target.error)),n.onsuccess=a=>{const s=a.target.result;s.onversionchange=()=>{s.close()},o(s)}}),le=e=>T(indexedDB.deleteDatabase(e)),me=(e,t)=>t.forEach(o=>e.createObjectStore.apply(e,o)),_=(e,t,o="readwrite")=>{const r=e.transaction(t,o);return t.map(n=>Pe(r,n))},U=(e,t)=>T(e.count(t)),ue=(e,t)=>T(e.get(t)),j=(e,t)=>T(e.delete(t)),he=(e,t,o)=>T(e.put(t,o)),F=(e,t)=>T(e.add(t)),pe=(e,t,o)=>T(e.getAll(t,o)),fe=(e,t,o)=>{let r=null;return ye(e,t,n=>(r=n,!1),o).then(()=>r)},ge=(e,t=null)=>fe(e,t,"prev"),we=(e,t)=>E((o,r)=>{e.onerror=r,e.onsuccess=async n=>{const a=n.target.result;if(a===null||await t(a)===!1)return o();a.continue()}}),ye=(e,t,o,r="next")=>we(e.openKeyCursor(t,r),n=>o(n.key)),Pe=(e,t)=>e.objectStore(t),Ie=(e,t)=>IDBKeyRange.upperBound(e,t),be=(e,t)=>IDBKeyRange.lowerBound(e,t),L=()=>new Map,Te=(e,t,o)=>{let r=e.get(t);return r===void 0&&e.set(t,r=o()),r},ve=()=>new Set,_e=Array.from;class Ee{constructor(){this._observers=L()}on(t,o){Te(this._observers,t,ve).add(o)}once(t,o){const r=(...n)=>{this.off(t,r),o(...n)};this.on(t,r)}off(t,o){const r=this._observers.get(t);r!==void 0&&(r.delete(o),r.size===0&&this._observers.delete(t))}emit(t,o){return _e((this._observers.get(t)||L()).values()).forEach(r=>r(...o))}destroy(){this._observers=L()}}const $="custom",O="updates",R=500,z=(e,t=()=>{},o=()=>{})=>{const[r]=_(e.db,[O]);return pe(r,be(e._dbref,!1)).then(n=>{e._destroyed||(t(r),v.transact(e.doc,()=>{n.forEach(a=>v.applyUpdate(e.doc,a))},e,!1),o(r))}).then(()=>ge(r).then(n=>{e._dbref=n+1})).then(()=>U(r).then(n=>{e._dbsize=n})).then(()=>r)},De=(e,t=!0)=>z(e).then(o=>{(t||e._dbsize>=R)&&F(o,v.encodeStateAsUpdate(e.doc)).then(()=>j(o,Ie(e._dbref,!0))).then(()=>U(o).then(r=>{e._dbsize=r}))});class ke extends Ee{constructor(t,o){super(),this.doc=o,this.name=t,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=de(t,r=>me(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=E(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,z(this,n=>F(n,v.encodeStateAsUpdate(o)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,n)=>{if(this.db&&n!==this){const[a]=_(this.db,[O]);F(a,r),++this._dbsize>=R&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{De(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},o.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),o.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(t=>{t.close()})}clearData(){return this.destroy().then(()=>{le(this.name)})}get(t){return this._db.then(o=>{const[r]=_(o,[$],"readonly");return ue(r,t)})}set(t,o){return this._db.then(r=>{const[n]=_(r,[$]);return he(n,o,t)})}del(t){return this._db.then(o=>{const[r]=_(o,[$]);return j(r,t)})}}const Se="revise-anonymous-identity",xe=1,D="identities",N="pdf-browser-id",Fe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Le(){return new Promise((e,t)=>{const o=indexedDB.open(Se,xe);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(D)||o.result.createObjectStore(D)},o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)})}async function A(){if(typeof window>"u"||typeof indexedDB>"u"||typeof crypto>"u"||typeof crypto.randomUUID!="function")return null;let e=null;try{return e=await Le(),await new Promise((t,o)=>{const r=e.transaction(D,"readwrite"),n=r.objectStore(D),a=n.get(N);let s="";a.onsuccess=()=>{const c=typeof a.result=="string"?a.result.trim().toLowerCase():"";s=Fe.test(c)?c:crypto.randomUUID(),s!==c&&n.put(s,N)},a.onerror=()=>o(a.error),r.oncomplete=()=>t(s),r.onerror=()=>o(r.error),r.onabort=()=>o(r.error)})}catch(t){return console.warn("Unable to load anonymous PDF browser identity:",t),null}finally{e?.close()}}const J="https://sync.revise-sdk.invalid";function K(){return J}function $e(){return J.replace(/^https/,"wss")}const B="yjs_document_index",Y="anon_session_id",G="yjs_document_deleted_",Ae="local-document-deleted";function W(e){return typeof window<"u"&&localStorage.getItem(G+e)==="1"}function q(){if(typeof window>"u")return[];try{const e=localStorage.getItem(B);return e?JSON.parse(e).filter(t=>!W(t)):[]}catch(e){return console.warn("Failed to read document index:",e),[]}}function Be(e){if(!(typeof window>"u"))try{if(W(e))return;const t=q();t.includes(e)||(t.push(e),localStorage.setItem(B,JSON.stringify(t)))}catch(t){console.warn("Failed to update document index:",t)}}function Ce(e){if(!(typeof window>"u"))try{localStorage.setItem(G+e,"1"),window.dispatchEvent(new CustomEvent(Ae,{detail:{documentId:e}}));const t=q().filter(o=>o!==e);localStorage.setItem(B,JSON.stringify(t))}catch(t){console.warn("Failed to remove from document index:",t)}}function Me(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let o=0;o<8;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function V(){if(typeof window>"u")return"server";let e=localStorage.getItem(Y);return e||(e=crypto.randomUUID().replace(/-/g,"").slice(0,12),localStorage.setItem(Y,e)),e}const Ue=30*60*1e3,je=3e3,Oe=15e3,k=new Map;async function Re(e){const t=Me(),o=V(),r=`anon:${o}:${t}`,n=new v.Doc,a={children:[{type:"paragraph",id:re(),children:[{type:"text",text:"",marks:{}}]}]};ne(n,a),n.transact(()=>{const l=n.getMap("metadata");l.set("id",t),l.set("documentId",t),l.set("title",x(e)),l.set("createdAt",Date.now()),l.set("updatedAt",Date.now()),l.set("lastAccessedAt",Date.now()),l.set("storageType","local")});const s=new ke(t,n);await s.whenSynced;const c=await A(),i=$e(),u=c?`${i}${i.includes("?")?"&":"?"}anonymousBrowserId=${encodeURIComponent(c)}`:i;let p=null;const d=new Promise(l=>{p=l}),f=new ae({url:se(u),name:r,document:n,token:()=>"",onSynced:()=>{p?.()}});return ze(t,n,s,f),Be(t),await Promise.race([d,new Promise(l=>setTimeout(l,Oe))]),{docId:t,anonSessionId:o,anonymousBrowserId:c}}function ze(e,t,o,r){let n=null;const a=new Promise(d=>{n=d});let s=!1;const c=()=>{if(s)return;s=!0;const d=k.get(e);d&&(clearTimeout(d.maxLifetimeTimer),k.delete(e));try{r.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying provider for ${e}:`,f)}try{o.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying persistence for ${e}:`,f)}try{t.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying ydoc for ${e}:`,f)}n?.()},i=t.getMap("import-progress"),u=()=>{const d=i.get("stage");(d==="complete"||d==="error")&&(i.unobserve(u),setTimeout(c,je))};i.observe(u);const p=setTimeout(()=>{console.warn(`[PdfImportKeeper] Import ${e} exceeded max lifetime; releasing`),c()},Ue);k.set(e,{docId:e,ydoc:t,persistence:o,provider:r,done:a,finish:c,maxLifetimeTimer:p})}async function Ne(e){const t=k.get(e);if(t){Ce(e);try{await t.persistence.clearData()}catch(o){console.warn(`[PdfImportKeeper] Error clearing data for ${e}:`,o)}t.finish()}}const Je=10;async function Ke(e){const t=e.batchSize??Je;for(let o=1;o<=e.totalPages;o+=t){const r=Math.min(e.totalPages,o+t-1),n=[];for(let a=o;a<=r;a+=1)n.push(await e.preparePage(a));await e.sendBatch(n,r===e.totalPages)}}const X="https://app-api.revise-sdk.invalid",Ye="https://agent.revise.io",Ge=150;class S extends Error{constructor(t){super(t.message),this.name="PdfLimitError",this.data=t}static ocrLimitExceeded(t,o,r,n,a="month",s=!1,c,i){const u=a==="day"?`You have ${t} free PDF pages left today. Create a free account for more.`:s?`You have ${t} free PDF pages left this month. Create an account for more.`:`You have ${t} PDF pages left this month. Upgrade for more.`;return new S({type:"OCR_LIMIT_EXCEEDED",remaining:t,requested:o,monthlyLimit:r,limitPeriod:a,anonymous:s,freeAccountLimit:c,maxPlanLimit:i,message:u,thumbnails:n})}}function We(){try{return typeof window<"u"?localStorage.getItem("auth_token"):null}catch{return null}}async function qe(e){try{const t=e?await fetch(`${X}/subscription/pdf-limits`,{method:"GET",headers:{Authorization:`Bearer ${e}`}}):await A().then(r=>fetch(`${Ye}/api/v1/pdf/page-limit`,{method:"GET",headers:r?{"X-Anonymous-Browser-Id":r}:void 0}));if(!t.ok)return console.warn("Failed to fetch OCR limit, using fallback"),H(e);const o=await t.json();return{ocrMonthlyLimit:o.ocrMonthlyLimit||3e3,ocrPagesRemaining:o.ocrPagesRemaining??3e3,limitPeriod:o.limitPeriod==="daily"?"day":"month",anonymous:!e,freeAccountLimit:o.freeAccountLimit,maxPlanLimit:o.maxPlanLimit}}catch(t){return console.warn("Error fetching OCR limit:",t),H(e)}}function H(e){return e?{ocrMonthlyLimit:3e3,ocrPagesRemaining:3e3,limitPeriod:"month",anonymous:!1,freeAccountLimit:100,maxPlanLimit:3e3}:{ocrMonthlyLimit:10,ocrPagesRemaining:10,limitPeriod:"month",anonymous:!0,freeAccountLimit:100,maxPlanLimit:3e3}}async function Ve(e,t,o){const r=await fetch(`${X}/uploads/images/presign`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({fileName:`page-${t}.png`,contentType:"image/png",fileSize:e.size,prefix:"pdf-temp"})});if(!r.ok){const c=await r.text();throw new Error(c||`Failed to get upload URL for page ${t}`)}const n=await r.json(),a=new Headers,s={...n.headers||{},"Content-Type":n.contentType||"image/png"};for(const[c,i]of Object.entries(s))i&&a.set(c,i);if(!(await fetch(n.uploadUrl,{method:n.method||"PUT",body:e,headers:a})).ok)throw new Error(`Failed to upload page ${t}`);return n.fileUrl}async function Xe(e){const{totalPages:t,title:o,token:r,timeoutMessage:n,targetDocumentId:a,afterBlockId:s}=e,c=x(o),i=!r&&!a?await Re(c):null,u=!r&&a?{docId:a,anonSessionId:V(),anonymousBrowserId:await A()}:null,p=i??u;try{const d=new AbortController,f=setTimeout(()=>d.abort(),10*60*1e3);let l;try{l=await fetch(`${K()}/api/pdf/import-streaming`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{},Accept:"text/event-stream"},body:JSON.stringify({totalPages:t,title:c,provider:ie,...r&&a?{targetDocumentId:a}:{},...a&&s?{afterBlockId:s}:{},...p?{anonSessionId:p.anonSessionId,anonDocId:p.docId,anonymousBrowserId:p.anonymousBrowserId||void 0}:{}}),signal:d.signal})}catch(P){throw P?.name==="AbortError"?new Error(n):new Error("Failed to start import. Please check your connection and try again.")}finally{clearTimeout(f)}if(!l.ok){const P=await l.text().catch(()=>"");let g={};try{g=JSON.parse(P)}catch{}throw new Error(g.error||P||`Import failed: ${l.status}`)}const h=await He(l);if(!h.importId||!h.uploadToken)throw new Error("Server did not create a page upload session.");return{documentId:h.documentId,title:h.title||c,importId:h.importId,uploadToken:h.uploadToken}}catch(d){throw i&&Ne(i.docId),d}}async function He(e){const t=e.body?.getReader();if(!t)throw new Error("Failed to read server response");const o=new TextDecoder;let r="",n="";for(;;){const{done:a,value:s}=await t.read();if(a)break;r+=o.decode(s,{stream:!0});const c=r.split(`
|
|
2
|
+
`);r=c.pop()||"";for(const i of c)if(i.startsWith("event: "))n=i.slice(7).trim();else if(i.startsWith("data: ")){let u=null;try{u=JSON.parse(i.slice(6))}catch{}if(u){if(n==="document_created")return t.releaseLock(),u;if(n==="error")throw t.releaseLock(),new Error(u.error||"Import failed")}n=""}}throw new Error("Server did not create document. Please try again.")}async function Q(e){const t=await fetch(`${K()}/api/pdf/import-streaming/${encodeURIComponent(e.importId)}/batches`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({uploadToken:e.uploadToken,pages:e.pages,final:e.final,error:e.error})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||"Failed to upload PDF page batch")}}async function Z(e,t){let o;try{o=await e.getPage(t)}catch{throw new Error(`Failed to read page ${t}. The PDF may be damaged.`)}let r=Ge/72,n=o.getViewport({scale:r});r*=1568/Math.max(n.width,n.height),n=o.getViewport({scale:r});const a=document.createElement("canvas"),s=a.getContext("2d");if(!s)throw new Error("Failed to create canvas. Your browser may not support this feature.");a.width=n.width,a.height=n.height,s.fillStyle="white",s.fillRect(0,0,a.width,a.height);try{await o.render({canvasContext:s,viewport:n}).promise}catch{throw new Error(`Failed to render page ${t}. The page may contain unsupported content.`)}const c=40,i=4;let u=!1;for(let m=0;m<c&&!u;m++){const w=Math.floor(a.width*m/c),b=Math.min(i,a.width-w);if(b<=0)continue;const y=s.getImageData(w,0,b,a.height).data;for(let I=0;I<y.length&&!u;I+=4)(y[I]<250||y[I+1]<250||y[I+2]<250)&&(u=!0)}if(!u)throw new Error(`Page ${t} appears blank. The PDF may use an unsupported image format.`);const p=await new Promise((m,w)=>{a.toBlob(b=>{b?m(b):w(new Error(`Failed to process page ${t}. The page may be too complex or large.`))},"image/png")}),d=120,f=d/a.height,l=Math.round(a.width*f),h=document.createElement("canvas");h.width=l,h.height=d;const P=h.getContext("2d");P&&P.drawImage(a,0,0,l,d);const g=h.toDataURL("image/jpeg",.7);return{blob:p,width:n.width,height:n.height,thumbnail:g}}const Qe=5;async function ee(e,t,o){const r=y=>{o&&o(y)},n=We(),{ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p}=await qe(n);r({stage:"loading",message:"Loading PDF..."});const d=await import("./pdf-BLWDCiFF.js");d.GlobalWorkerOptions.workerSrc=C("pdfjs/worker.js");const f=await e.arrayBuffer(),l=d.getDocument({data:f,wasmUrl:C("pdfjs/")});let h;try{h=await l.promise}catch(y){const I=y?.message?.toLowerCase()||"";throw I.includes("password")||I.includes("encrypted")?new Error("This PDF is password-protected. Please remove the password and try again."):I.includes("invalid")||I.includes("corrupt")?new Error("This PDF appears to be corrupted or invalid. Please try a different file."):new Error("Failed to read PDF file. Please try a different file.")}if(!h.numPages||h.numPages===0)throw new Error("This PDF has no pages.");const P=h.numPages,g=P>s,m=g?Math.min(Qe,P):0,w=[];for(let y=1;y<=m;y++){const{thumbnail:I}=await Z(h,y);w.push(I),r({stage:"rasterizing",currentPage:y,totalPages:m,message:`Preparing preview ${y} of ${m}...`,thumbnail:I})}const b=x(e.name?.replace(/\.pdf$/i,"")||"Imported PDF");return{thumbnails:w,totalPages:P,ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p,exceedsLimit:g,title:b,_pdf:h,_token:n,_file:e}}async function te(e,t,o,r){const n=m=>{t&&t(m)},{_pdf:a,_token:s,_file:c,totalPages:i,title:u,ocrMonthlyLimit:p,ocrPagesRemaining:d,limitPeriod:f,anonymous:l,freeAccountLimit:h,maxPlanLimit:P}=e;if(i>d)throw S.ocrLimitExceeded(d,i,p,e.thumbnails,f,l,h,P);n({stage:"converting",totalPages:i,message:"Creating document..."}),M.track("PDF Import Started",{"Total Pages":i,"File Name":c.name,Anonymous:!s});const g=await Xe({totalPages:i,title:u,token:s,timeoutMessage:"Import timed out after 10 minutes. Please try with a shorter PDF.",targetDocumentId:o,afterBlockId:r});return Ke({totalPages:i,preparePage:async m=>{const{blob:w,thumbnail:b}=await Z(a,m);return n({stage:"rasterizing",currentPage:m,totalPages:i,message:`Processing page ${m} of ${i}`,thumbnail:b}),{url:await Ve(w,m,s),mediaType:"image/png",pageNumber:m}},sendBatch:(m,w)=>Q({importId:g.importId,uploadToken:g.uploadToken,pages:m,final:w})}).catch(async m=>{const w=m instanceof Error?m.message:"Failed to prepare PDF pages";console.error("[PDF Import] Background page upload failed:",m),n({stage:"error",totalPages:i,message:w});try{await Q({importId:g.importId,uploadToken:g.uploadToken,error:w})}catch(b){console.error("[PDF Import] Failed to report page upload error:",b)}}),n({stage:"complete",totalPages:i,message:"Document created! Content is streaming..."}),M.track("PDF Import Completed",{"Document ID":g.documentId,"Total Pages":i,Anonymous:!s}),{documentId:g.documentId,title:g.title,pagesProcessed:i,inputTokens:0,outputTokens:0,streaming:!0}}function oe(e){const t=e.getMap("import-progress");let o=()=>{};const r=new Promise((n,a)=>{const s=()=>{const i=t.get("stage");i!=="complete"&&i!=="error"||(o(),i==="complete"?n():a(new Error(String(t.get("error")||"PDF import failed."))))},c=setTimeout(()=>{o(),a(new Error("PDF import timed out before content was ready."))},9e5);o=()=>{clearTimeout(c),t.unobserve(s)},t.observe(s)});return r.catch(()=>{}),{done:r,cancel:()=>o()}}async function Ze(e,t,o,r,n){const a=await ee(e,void 0,r),s=oe(o);try{const c=await te(a,r,t,n);return await s.done,c}catch(c){throw s.cancel(),c}}export{S as PdfLimitError,te as confirmPdfImport,Ze as importPdfIntoExistingDocument,ee as previewPdfForImport,oe as watchImportCompletion};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a1 as re,T as ne,c1 as x,c2 as ae,c3 as se,aX as C,c4 as M,c5 as ie}from"./index-CjeGoI2g.js";import*as v from"yjs";const E=e=>new Promise(e);Promise.all.bind(Promise);const ce=e=>new Error(e),T=e=>E((t,o)=>{e.onerror=r=>o(new Error(r.target.error)),e.onsuccess=r=>t(r.target.result)}),de=(e,t)=>E((o,r)=>{const n=indexedDB.open(e);n.onupgradeneeded=a=>t(a.target.result),n.onerror=a=>r(ce(a.target.error)),n.onsuccess=a=>{const s=a.target.result;s.onversionchange=()=>{s.close()},o(s)}}),le=e=>T(indexedDB.deleteDatabase(e)),me=(e,t)=>t.forEach(o=>e.createObjectStore.apply(e,o)),_=(e,t,o="readwrite")=>{const r=e.transaction(t,o);return t.map(n=>Pe(r,n))},U=(e,t)=>T(e.count(t)),ue=(e,t)=>T(e.get(t)),j=(e,t)=>T(e.delete(t)),he=(e,t,o)=>T(e.put(t,o)),F=(e,t)=>T(e.add(t)),pe=(e,t,o)=>T(e.getAll(t,o)),fe=(e,t,o)=>{let r=null;return ye(e,t,n=>(r=n,!1),o).then(()=>r)},ge=(e,t=null)=>fe(e,t,"prev"),we=(e,t)=>E((o,r)=>{e.onerror=r,e.onsuccess=async n=>{const a=n.target.result;if(a===null||await t(a)===!1)return o();a.continue()}}),ye=(e,t,o,r="next")=>we(e.openKeyCursor(t,r),n=>o(n.key)),Pe=(e,t)=>e.objectStore(t),Ie=(e,t)=>IDBKeyRange.upperBound(e,t),be=(e,t)=>IDBKeyRange.lowerBound(e,t),L=()=>new Map,Te=(e,t,o)=>{let r=e.get(t);return r===void 0&&e.set(t,r=o()),r},ve=()=>new Set,_e=Array.from;class Ee{constructor(){this._observers=L()}on(t,o){Te(this._observers,t,ve).add(o)}once(t,o){const r=(...n)=>{this.off(t,r),o(...n)};this.on(t,r)}off(t,o){const r=this._observers.get(t);r!==void 0&&(r.delete(o),r.size===0&&this._observers.delete(t))}emit(t,o){return _e((this._observers.get(t)||L()).values()).forEach(r=>r(...o))}destroy(){this._observers=L()}}const $="custom",O="updates",R=500,z=(e,t=()=>{},o=()=>{})=>{const[r]=_(e.db,[O]);return pe(r,be(e._dbref,!1)).then(n=>{e._destroyed||(t(r),v.transact(e.doc,()=>{n.forEach(a=>v.applyUpdate(e.doc,a))},e,!1),o(r))}).then(()=>ge(r).then(n=>{e._dbref=n+1})).then(()=>U(r).then(n=>{e._dbsize=n})).then(()=>r)},De=(e,t=!0)=>z(e).then(o=>{(t||e._dbsize>=R)&&F(o,v.encodeStateAsUpdate(e.doc)).then(()=>j(o,Ie(e._dbref,!0))).then(()=>U(o).then(r=>{e._dbsize=r}))});class ke extends Ee{constructor(t,o){super(),this.doc=o,this.name=t,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=de(t,r=>me(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=E(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,z(this,n=>F(n,v.encodeStateAsUpdate(o)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,n)=>{if(this.db&&n!==this){const[a]=_(this.db,[O]);F(a,r),++this._dbsize>=R&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{De(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},o.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),o.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(t=>{t.close()})}clearData(){return this.destroy().then(()=>{le(this.name)})}get(t){return this._db.then(o=>{const[r]=_(o,[$],"readonly");return ue(r,t)})}set(t,o){return this._db.then(r=>{const[n]=_(r,[$]);return he(n,o,t)})}del(t){return this._db.then(o=>{const[r]=_(o,[$]);return j(r,t)})}}const Se="revise-anonymous-identity",xe=1,D="identities",N="pdf-browser-id",Fe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Le(){return new Promise((e,t)=>{const o=indexedDB.open(Se,xe);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(D)||o.result.createObjectStore(D)},o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)})}async function A(){if(typeof window>"u"||typeof indexedDB>"u"||typeof crypto>"u"||typeof crypto.randomUUID!="function")return null;let e=null;try{return e=await Le(),await new Promise((t,o)=>{const r=e.transaction(D,"readwrite"),n=r.objectStore(D),a=n.get(N);let s="";a.onsuccess=()=>{const c=typeof a.result=="string"?a.result.trim().toLowerCase():"";s=Fe.test(c)?c:crypto.randomUUID(),s!==c&&n.put(s,N)},a.onerror=()=>o(a.error),r.oncomplete=()=>t(s),r.onerror=()=>o(r.error),r.onabort=()=>o(r.error)})}catch(t){return console.warn("Unable to load anonymous PDF browser identity:",t),null}finally{e?.close()}}const J="https://sync.revise-sdk.invalid";function K(){return J}function $e(){return J.replace(/^https/,"wss")}const B="yjs_document_index",Y="anon_session_id",G="yjs_document_deleted_",Ae="local-document-deleted";function W(e){return typeof window<"u"&&localStorage.getItem(G+e)==="1"}function X(){if(typeof window>"u")return[];try{const e=localStorage.getItem(B);return e?JSON.parse(e).filter(t=>!W(t)):[]}catch(e){return console.warn("Failed to read document index:",e),[]}}function Be(e){if(!(typeof window>"u"))try{if(W(e))return;const t=X();t.includes(e)||(t.push(e),localStorage.setItem(B,JSON.stringify(t)))}catch(t){console.warn("Failed to update document index:",t)}}function Ce(e){if(!(typeof window>"u"))try{localStorage.setItem(G+e,"1"),window.dispatchEvent(new CustomEvent(Ae,{detail:{documentId:e}}));const t=X().filter(o=>o!==e);localStorage.setItem(B,JSON.stringify(t))}catch(t){console.warn("Failed to remove from document index:",t)}}function Me(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let o=0;o<8;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function q(){if(typeof window>"u")return"server";let e=localStorage.getItem(Y);return e||(e=crypto.randomUUID().replace(/-/g,"").slice(0,12),localStorage.setItem(Y,e)),e}const Ue=30*60*1e3,je=3e3,Oe=15e3,k=new Map;async function Re(e){const t=Me(),o=q(),r=`anon:${o}:${t}`,n=new v.Doc,a={children:[{type:"paragraph",id:re(),children:[{type:"text",text:"",marks:{}}]}]};ne(n,a),n.transact(()=>{const l=n.getMap("metadata");l.set("id",t),l.set("documentId",t),l.set("title",x(e)),l.set("createdAt",Date.now()),l.set("updatedAt",Date.now()),l.set("lastAccessedAt",Date.now()),l.set("storageType","local")});const s=new ke(t,n);await s.whenSynced;const c=await A(),i=$e(),u=c?`${i}${i.includes("?")?"&":"?"}anonymousBrowserId=${encodeURIComponent(c)}`:i;let p=null;const d=new Promise(l=>{p=l}),f=new ae({url:se(u),name:r,document:n,token:()=>"",onSynced:()=>{p?.()}});return ze(t,n,s,f),Be(t),await Promise.race([d,new Promise(l=>setTimeout(l,Oe))]),{docId:t,anonSessionId:o,anonymousBrowserId:c}}function ze(e,t,o,r){let n=null;const a=new Promise(d=>{n=d});let s=!1;const c=()=>{if(s)return;s=!0;const d=k.get(e);d&&(clearTimeout(d.maxLifetimeTimer),k.delete(e));try{r.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying provider for ${e}:`,f)}try{o.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying persistence for ${e}:`,f)}try{t.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying ydoc for ${e}:`,f)}n?.()},i=t.getMap("import-progress"),u=()=>{const d=i.get("stage");(d==="complete"||d==="error")&&(i.unobserve(u),setTimeout(c,je))};i.observe(u);const p=setTimeout(()=>{console.warn(`[PdfImportKeeper] Import ${e} exceeded max lifetime; releasing`),c()},Ue);k.set(e,{docId:e,ydoc:t,persistence:o,provider:r,done:a,finish:c,maxLifetimeTimer:p})}async function Ne(e){const t=k.get(e);if(t){Ce(e);try{await t.persistence.clearData()}catch(o){console.warn(`[PdfImportKeeper] Error clearing data for ${e}:`,o)}t.finish()}}const Je=10;async function Ke(e){const t=e.batchSize??Je;for(let o=1;o<=e.totalPages;o+=t){const r=Math.min(e.totalPages,o+t-1),n=[];for(let a=o;a<=r;a+=1)n.push(await e.preparePage(a));await e.sendBatch(n,r===e.totalPages)}}const V="https://app-api.revise-sdk.invalid",Ye="https://agent.revise.io",Ge=150;class S extends Error{constructor(t){super(t.message),this.name="PdfLimitError",this.data=t}static ocrLimitExceeded(t,o,r,n,a="month",s=!1,c,i){const u=a==="day"?`You have ${t} free PDF pages left today. Create a free account for more.`:s?`You have ${t} free PDF pages left this month. Create an account for more.`:`You have ${t} PDF pages left this month. Upgrade for more.`;return new S({type:"OCR_LIMIT_EXCEEDED",remaining:t,requested:o,monthlyLimit:r,limitPeriod:a,anonymous:s,freeAccountLimit:c,maxPlanLimit:i,message:u,thumbnails:n})}}function We(){try{return typeof window<"u"?localStorage.getItem("auth_token"):null}catch{return null}}async function Xe(e){try{const t=e?await fetch(`${V}/subscription/pdf-limits`,{method:"GET",headers:{Authorization:`Bearer ${e}`}}):await A().then(r=>fetch(`${Ye}/api/v1/pdf/page-limit`,{method:"GET",headers:r?{"X-Anonymous-Browser-Id":r}:void 0}));if(!t.ok)return console.warn("Failed to fetch OCR limit, using fallback"),H(e);const o=await t.json();return{ocrMonthlyLimit:o.ocrMonthlyLimit||3e3,ocrPagesRemaining:o.ocrPagesRemaining??3e3,limitPeriod:o.limitPeriod==="daily"?"day":"month",anonymous:!e,freeAccountLimit:o.freeAccountLimit,maxPlanLimit:o.maxPlanLimit}}catch(t){return console.warn("Error fetching OCR limit:",t),H(e)}}function H(e){return e?{ocrMonthlyLimit:3e3,ocrPagesRemaining:3e3,limitPeriod:"month",anonymous:!1,freeAccountLimit:100,maxPlanLimit:3e3}:{ocrMonthlyLimit:10,ocrPagesRemaining:10,limitPeriod:"month",anonymous:!0,freeAccountLimit:100,maxPlanLimit:3e3}}async function qe(e,t,o){const r=await fetch(`${V}/uploads/images/presign`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({fileName:`page-${t}.png`,contentType:"image/png",fileSize:e.size,prefix:"pdf-temp"})});if(!r.ok){const c=await r.text();throw new Error(c||`Failed to get upload URL for page ${t}`)}const n=await r.json(),a=new Headers,s={...n.headers||{},"Content-Type":n.contentType||"image/png"};for(const[c,i]of Object.entries(s))i&&a.set(c,i);if(!(await fetch(n.uploadUrl,{method:n.method||"PUT",body:e,headers:a})).ok)throw new Error(`Failed to upload page ${t}`);return n.fileUrl}async function Ve(e){const{totalPages:t,title:o,token:r,timeoutMessage:n,targetDocumentId:a,afterBlockId:s}=e,c=x(o),i=!r&&!a?await Re(c):null,u=!r&&a?{docId:a,anonSessionId:q(),anonymousBrowserId:await A()}:null,p=i??u;try{const d=new AbortController,f=setTimeout(()=>d.abort(),10*60*1e3);let l;try{l=await fetch(`${K()}/api/pdf/import-streaming`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{},Accept:"text/event-stream"},body:JSON.stringify({totalPages:t,title:c,provider:ie,...r&&a?{targetDocumentId:a}:{},...a&&s?{afterBlockId:s}:{},...p?{anonSessionId:p.anonSessionId,anonDocId:p.docId,anonymousBrowserId:p.anonymousBrowserId||void 0}:{}}),signal:d.signal})}catch(P){throw P?.name==="AbortError"?new Error(n):new Error("Failed to start import. Please check your connection and try again.")}finally{clearTimeout(f)}if(!l.ok){const P=await l.text().catch(()=>"");let g={};try{g=JSON.parse(P)}catch{}throw new Error(g.error||P||`Import failed: ${l.status}`)}const h=await He(l);if(!h.importId||!h.uploadToken)throw new Error("Server did not create a page upload session.");return{documentId:h.documentId,title:h.title||c,importId:h.importId,uploadToken:h.uploadToken}}catch(d){throw i&&Ne(i.docId),d}}async function He(e){const t=e.body?.getReader();if(!t)throw new Error("Failed to read server response");const o=new TextDecoder;let r="",n="";for(;;){const{done:a,value:s}=await t.read();if(a)break;r+=o.decode(s,{stream:!0});const c=r.split(`
|
|
2
|
-
`);r=c.pop()||"";for(const i of c)if(i.startsWith("event: "))n=i.slice(7).trim();else if(i.startsWith("data: ")){let u=null;try{u=JSON.parse(i.slice(6))}catch{}if(u){if(n==="document_created")return t.releaseLock(),u;if(n==="error")throw t.releaseLock(),new Error(u.error||"Import failed")}n=""}}throw new Error("Server did not create document. Please try again.")}async function Q(e){const t=await fetch(`${K()}/api/pdf/import-streaming/${encodeURIComponent(e.importId)}/batches`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({uploadToken:e.uploadToken,pages:e.pages,final:e.final,error:e.error})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||"Failed to upload PDF page batch")}}async function Z(e,t){let o;try{o=await e.getPage(t)}catch{throw new Error(`Failed to read page ${t}. The PDF may be damaged.`)}let r=Ge/72,n=o.getViewport({scale:r});r*=1568/Math.max(n.width,n.height),n=o.getViewport({scale:r});const a=document.createElement("canvas"),s=a.getContext("2d");if(!s)throw new Error("Failed to create canvas. Your browser may not support this feature.");a.width=n.width,a.height=n.height,s.fillStyle="white",s.fillRect(0,0,a.width,a.height);try{await o.render({canvasContext:s,viewport:n}).promise}catch{throw new Error(`Failed to render page ${t}. The page may contain unsupported content.`)}const c=40,i=4;let u=!1;for(let m=0;m<c&&!u;m++){const w=Math.floor(a.width*m/c),b=Math.min(i,a.width-w);if(b<=0)continue;const y=s.getImageData(w,0,b,a.height).data;for(let I=0;I<y.length&&!u;I+=4)(y[I]<250||y[I+1]<250||y[I+2]<250)&&(u=!0)}if(!u)throw new Error(`Page ${t} appears blank. The PDF may use an unsupported image format.`);const p=await new Promise((m,w)=>{a.toBlob(b=>{b?m(b):w(new Error(`Failed to process page ${t}. The page may be too complex or large.`))},"image/png")}),d=120,f=d/a.height,l=Math.round(a.width*f),h=document.createElement("canvas");h.width=l,h.height=d;const P=h.getContext("2d");P&&P.drawImage(a,0,0,l,d);const g=h.toDataURL("image/jpeg",.7);return{blob:p,width:n.width,height:n.height,thumbnail:g}}const Qe=5;async function ee(e,t,o){const r=y=>{o&&o(y)},n=We(),{ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p}=await
|
|
1
|
+
import{B as re,a4 as ne,cc as x,cd as ae,ce as se,b1 as C,cf as M,cg as ie}from"./index-BwcX_r62.js";import*as v from"yjs";const E=e=>new Promise(e);Promise.all.bind(Promise);const ce=e=>new Error(e),T=e=>E((t,o)=>{e.onerror=r=>o(new Error(r.target.error)),e.onsuccess=r=>t(r.target.result)}),de=(e,t)=>E((o,r)=>{const n=indexedDB.open(e);n.onupgradeneeded=a=>t(a.target.result),n.onerror=a=>r(ce(a.target.error)),n.onsuccess=a=>{const s=a.target.result;s.onversionchange=()=>{s.close()},o(s)}}),le=e=>T(indexedDB.deleteDatabase(e)),me=(e,t)=>t.forEach(o=>e.createObjectStore.apply(e,o)),_=(e,t,o="readwrite")=>{const r=e.transaction(t,o);return t.map(n=>Pe(r,n))},U=(e,t)=>T(e.count(t)),ue=(e,t)=>T(e.get(t)),j=(e,t)=>T(e.delete(t)),he=(e,t,o)=>T(e.put(t,o)),F=(e,t)=>T(e.add(t)),pe=(e,t,o)=>T(e.getAll(t,o)),fe=(e,t,o)=>{let r=null;return ye(e,t,n=>(r=n,!1),o).then(()=>r)},ge=(e,t=null)=>fe(e,t,"prev"),we=(e,t)=>E((o,r)=>{e.onerror=r,e.onsuccess=async n=>{const a=n.target.result;if(a===null||await t(a)===!1)return o();a.continue()}}),ye=(e,t,o,r="next")=>we(e.openKeyCursor(t,r),n=>o(n.key)),Pe=(e,t)=>e.objectStore(t),Ie=(e,t)=>IDBKeyRange.upperBound(e,t),be=(e,t)=>IDBKeyRange.lowerBound(e,t),L=()=>new Map,Te=(e,t,o)=>{let r=e.get(t);return r===void 0&&e.set(t,r=o()),r},ve=()=>new Set,_e=Array.from;class Ee{constructor(){this._observers=L()}on(t,o){Te(this._observers,t,ve).add(o)}once(t,o){const r=(...n)=>{this.off(t,r),o(...n)};this.on(t,r)}off(t,o){const r=this._observers.get(t);r!==void 0&&(r.delete(o),r.size===0&&this._observers.delete(t))}emit(t,o){return _e((this._observers.get(t)||L()).values()).forEach(r=>r(...o))}destroy(){this._observers=L()}}const $="custom",O="updates",R=500,z=(e,t=()=>{},o=()=>{})=>{const[r]=_(e.db,[O]);return pe(r,be(e._dbref,!1)).then(n=>{e._destroyed||(t(r),v.transact(e.doc,()=>{n.forEach(a=>v.applyUpdate(e.doc,a))},e,!1),o(r))}).then(()=>ge(r).then(n=>{e._dbref=n+1})).then(()=>U(r).then(n=>{e._dbsize=n})).then(()=>r)},De=(e,t=!0)=>z(e).then(o=>{(t||e._dbsize>=R)&&F(o,v.encodeStateAsUpdate(e.doc)).then(()=>j(o,Ie(e._dbref,!0))).then(()=>U(o).then(r=>{e._dbsize=r}))});class ke extends Ee{constructor(t,o){super(),this.doc=o,this.name=t,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=de(t,r=>me(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=E(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,z(this,n=>F(n,v.encodeStateAsUpdate(o)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,n)=>{if(this.db&&n!==this){const[a]=_(this.db,[O]);F(a,r),++this._dbsize>=R&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{De(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},o.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),o.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(t=>{t.close()})}clearData(){return this.destroy().then(()=>{le(this.name)})}get(t){return this._db.then(o=>{const[r]=_(o,[$],"readonly");return ue(r,t)})}set(t,o){return this._db.then(r=>{const[n]=_(r,[$]);return he(n,o,t)})}del(t){return this._db.then(o=>{const[r]=_(o,[$]);return j(r,t)})}}const Se="revise-anonymous-identity",xe=1,D="identities",N="pdf-browser-id",Fe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Le(){return new Promise((e,t)=>{const o=indexedDB.open(Se,xe);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(D)||o.result.createObjectStore(D)},o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)})}async function A(){if(typeof window>"u"||typeof indexedDB>"u"||typeof crypto>"u"||typeof crypto.randomUUID!="function")return null;let e=null;try{return e=await Le(),await new Promise((t,o)=>{const r=e.transaction(D,"readwrite"),n=r.objectStore(D),a=n.get(N);let s="";a.onsuccess=()=>{const c=typeof a.result=="string"?a.result.trim().toLowerCase():"";s=Fe.test(c)?c:crypto.randomUUID(),s!==c&&n.put(s,N)},a.onerror=()=>o(a.error),r.oncomplete=()=>t(s),r.onerror=()=>o(r.error),r.onabort=()=>o(r.error)})}catch(t){return console.warn("Unable to load anonymous PDF browser identity:",t),null}finally{e?.close()}}const J="https://sync.revise-sdk.invalid";function K(){return J}function $e(){return J.replace(/^https/,"wss")}const B="yjs_document_index",Y="anon_session_id",G="yjs_document_deleted_",Ae="local-document-deleted";function W(e){return typeof window<"u"&&localStorage.getItem(G+e)==="1"}function q(){if(typeof window>"u")return[];try{const e=localStorage.getItem(B);return e?JSON.parse(e).filter(t=>!W(t)):[]}catch(e){return console.warn("Failed to read document index:",e),[]}}function Be(e){if(!(typeof window>"u"))try{if(W(e))return;const t=q();t.includes(e)||(t.push(e),localStorage.setItem(B,JSON.stringify(t)))}catch(t){console.warn("Failed to update document index:",t)}}function Ce(e){if(!(typeof window>"u"))try{localStorage.setItem(G+e,"1"),window.dispatchEvent(new CustomEvent(Ae,{detail:{documentId:e}}));const t=q().filter(o=>o!==e);localStorage.setItem(B,JSON.stringify(t))}catch(t){console.warn("Failed to remove from document index:",t)}}function Me(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let o=0;o<8;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function V(){if(typeof window>"u")return"server";let e=localStorage.getItem(Y);return e||(e=crypto.randomUUID().replace(/-/g,"").slice(0,12),localStorage.setItem(Y,e)),e}const Ue=30*60*1e3,je=3e3,Oe=15e3,k=new Map;async function Re(e){const t=Me(),o=V(),r=`anon:${o}:${t}`,n=new v.Doc,a={children:[{type:"paragraph",id:re(),children:[{type:"text",text:"",marks:{}}]}]};ne(n,a),n.transact(()=>{const l=n.getMap("metadata");l.set("id",t),l.set("documentId",t),l.set("title",x(e)),l.set("createdAt",Date.now()),l.set("updatedAt",Date.now()),l.set("lastAccessedAt",Date.now()),l.set("storageType","local")});const s=new ke(t,n);await s.whenSynced;const c=await A(),i=$e(),u=c?`${i}${i.includes("?")?"&":"?"}anonymousBrowserId=${encodeURIComponent(c)}`:i;let p=null;const d=new Promise(l=>{p=l}),f=new ae({url:se(u),name:r,document:n,token:()=>"",onSynced:()=>{p?.()}});return ze(t,n,s,f),Be(t),await Promise.race([d,new Promise(l=>setTimeout(l,Oe))]),{docId:t,anonSessionId:o,anonymousBrowserId:c}}function ze(e,t,o,r){let n=null;const a=new Promise(d=>{n=d});let s=!1;const c=()=>{if(s)return;s=!0;const d=k.get(e);d&&(clearTimeout(d.maxLifetimeTimer),k.delete(e));try{r.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying provider for ${e}:`,f)}try{o.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying persistence for ${e}:`,f)}try{t.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying ydoc for ${e}:`,f)}n?.()},i=t.getMap("import-progress"),u=()=>{const d=i.get("stage");(d==="complete"||d==="error")&&(i.unobserve(u),setTimeout(c,je))};i.observe(u);const p=setTimeout(()=>{console.warn(`[PdfImportKeeper] Import ${e} exceeded max lifetime; releasing`),c()},Ue);k.set(e,{docId:e,ydoc:t,persistence:o,provider:r,done:a,finish:c,maxLifetimeTimer:p})}async function Ne(e){const t=k.get(e);if(t){Ce(e);try{await t.persistence.clearData()}catch(o){console.warn(`[PdfImportKeeper] Error clearing data for ${e}:`,o)}t.finish()}}const Je=10;async function Ke(e){const t=e.batchSize??Je;for(let o=1;o<=e.totalPages;o+=t){const r=Math.min(e.totalPages,o+t-1),n=[];for(let a=o;a<=r;a+=1)n.push(await e.preparePage(a));await e.sendBatch(n,r===e.totalPages)}}const X="https://app-api.revise-sdk.invalid",Ye="https://agent.revise.io",Ge=150;class S extends Error{constructor(t){super(t.message),this.name="PdfLimitError",this.data=t}static ocrLimitExceeded(t,o,r,n,a="month",s=!1,c,i){const u=a==="day"?`You have ${t} free PDF pages left today. Create a free account for more.`:s?`You have ${t} free PDF pages left this month. Create an account for more.`:`You have ${t} PDF pages left this month. Upgrade for more.`;return new S({type:"OCR_LIMIT_EXCEEDED",remaining:t,requested:o,monthlyLimit:r,limitPeriod:a,anonymous:s,freeAccountLimit:c,maxPlanLimit:i,message:u,thumbnails:n})}}function We(){try{return typeof window<"u"?localStorage.getItem("auth_token"):null}catch{return null}}async function qe(e){try{const t=e?await fetch(`${X}/subscription/pdf-limits`,{method:"GET",headers:{Authorization:`Bearer ${e}`}}):await A().then(r=>fetch(`${Ye}/api/v1/pdf/page-limit`,{method:"GET",headers:r?{"X-Anonymous-Browser-Id":r}:void 0}));if(!t.ok)return console.warn("Failed to fetch OCR limit, using fallback"),H(e);const o=await t.json();return{ocrMonthlyLimit:o.ocrMonthlyLimit||3e3,ocrPagesRemaining:o.ocrPagesRemaining??3e3,limitPeriod:o.limitPeriod==="daily"?"day":"month",anonymous:!e,freeAccountLimit:o.freeAccountLimit,maxPlanLimit:o.maxPlanLimit}}catch(t){return console.warn("Error fetching OCR limit:",t),H(e)}}function H(e){return e?{ocrMonthlyLimit:3e3,ocrPagesRemaining:3e3,limitPeriod:"month",anonymous:!1,freeAccountLimit:100,maxPlanLimit:3e3}:{ocrMonthlyLimit:10,ocrPagesRemaining:10,limitPeriod:"month",anonymous:!0,freeAccountLimit:100,maxPlanLimit:3e3}}async function Ve(e,t,o){const r=await fetch(`${X}/uploads/images/presign`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({fileName:`page-${t}.png`,contentType:"image/png",fileSize:e.size,prefix:"pdf-temp"})});if(!r.ok){const c=await r.text();throw new Error(c||`Failed to get upload URL for page ${t}`)}const n=await r.json(),a=new Headers,s={...n.headers||{},"Content-Type":n.contentType||"image/png"};for(const[c,i]of Object.entries(s))i&&a.set(c,i);if(!(await fetch(n.uploadUrl,{method:n.method||"PUT",body:e,headers:a})).ok)throw new Error(`Failed to upload page ${t}`);return n.fileUrl}async function Xe(e){const{totalPages:t,title:o,token:r,timeoutMessage:n,targetDocumentId:a,afterBlockId:s}=e,c=x(o),i=!r&&!a?await Re(c):null,u=!r&&a?{docId:a,anonSessionId:V(),anonymousBrowserId:await A()}:null,p=i??u;try{const d=new AbortController,f=setTimeout(()=>d.abort(),10*60*1e3);let l;try{l=await fetch(`${K()}/api/pdf/import-streaming`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{},Accept:"text/event-stream"},body:JSON.stringify({totalPages:t,title:c,provider:ie,...r&&a?{targetDocumentId:a}:{},...a&&s?{afterBlockId:s}:{},...p?{anonSessionId:p.anonSessionId,anonDocId:p.docId,anonymousBrowserId:p.anonymousBrowserId||void 0}:{}}),signal:d.signal})}catch(P){throw P?.name==="AbortError"?new Error(n):new Error("Failed to start import. Please check your connection and try again.")}finally{clearTimeout(f)}if(!l.ok){const P=await l.text().catch(()=>"");let g={};try{g=JSON.parse(P)}catch{}throw new Error(g.error||P||`Import failed: ${l.status}`)}const h=await He(l);if(!h.importId||!h.uploadToken)throw new Error("Server did not create a page upload session.");return{documentId:h.documentId,title:h.title||c,importId:h.importId,uploadToken:h.uploadToken}}catch(d){throw i&&Ne(i.docId),d}}async function He(e){const t=e.body?.getReader();if(!t)throw new Error("Failed to read server response");const o=new TextDecoder;let r="",n="";for(;;){const{done:a,value:s}=await t.read();if(a)break;r+=o.decode(s,{stream:!0});const c=r.split(`
|
|
2
|
+
`);r=c.pop()||"";for(const i of c)if(i.startsWith("event: "))n=i.slice(7).trim();else if(i.startsWith("data: ")){let u=null;try{u=JSON.parse(i.slice(6))}catch{}if(u){if(n==="document_created")return t.releaseLock(),u;if(n==="error")throw t.releaseLock(),new Error(u.error||"Import failed")}n=""}}throw new Error("Server did not create document. Please try again.")}async function Q(e){const t=await fetch(`${K()}/api/pdf/import-streaming/${encodeURIComponent(e.importId)}/batches`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({uploadToken:e.uploadToken,pages:e.pages,final:e.final,error:e.error})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||"Failed to upload PDF page batch")}}async function Z(e,t){let o;try{o=await e.getPage(t)}catch{throw new Error(`Failed to read page ${t}. The PDF may be damaged.`)}let r=Ge/72,n=o.getViewport({scale:r});r*=1568/Math.max(n.width,n.height),n=o.getViewport({scale:r});const a=document.createElement("canvas"),s=a.getContext("2d");if(!s)throw new Error("Failed to create canvas. Your browser may not support this feature.");a.width=n.width,a.height=n.height,s.fillStyle="white",s.fillRect(0,0,a.width,a.height);try{await o.render({canvasContext:s,viewport:n}).promise}catch{throw new Error(`Failed to render page ${t}. The page may contain unsupported content.`)}const c=40,i=4;let u=!1;for(let m=0;m<c&&!u;m++){const w=Math.floor(a.width*m/c),b=Math.min(i,a.width-w);if(b<=0)continue;const y=s.getImageData(w,0,b,a.height).data;for(let I=0;I<y.length&&!u;I+=4)(y[I]<250||y[I+1]<250||y[I+2]<250)&&(u=!0)}if(!u)throw new Error(`Page ${t} appears blank. The PDF may use an unsupported image format.`);const p=await new Promise((m,w)=>{a.toBlob(b=>{b?m(b):w(new Error(`Failed to process page ${t}. The page may be too complex or large.`))},"image/png")}),d=120,f=d/a.height,l=Math.round(a.width*f),h=document.createElement("canvas");h.width=l,h.height=d;const P=h.getContext("2d");P&&P.drawImage(a,0,0,l,d);const g=h.toDataURL("image/jpeg",.7);return{blob:p,width:n.width,height:n.height,thumbnail:g}}const Qe=5;async function ee(e,t,o){const r=y=>{o&&o(y)},n=We(),{ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p}=await qe(n);r({stage:"loading",message:"Loading PDF..."});const d=await import("./pdf-BLWDCiFF.js");d.GlobalWorkerOptions.workerSrc=C("pdfjs/worker.js");const f=await e.arrayBuffer(),l=d.getDocument({data:f,wasmUrl:C("pdfjs/")});let h;try{h=await l.promise}catch(y){const I=y?.message?.toLowerCase()||"";throw I.includes("password")||I.includes("encrypted")?new Error("This PDF is password-protected. Please remove the password and try again."):I.includes("invalid")||I.includes("corrupt")?new Error("This PDF appears to be corrupted or invalid. Please try a different file."):new Error("Failed to read PDF file. Please try a different file.")}if(!h.numPages||h.numPages===0)throw new Error("This PDF has no pages.");const P=h.numPages,g=P>s,m=g?Math.min(Qe,P):0,w=[];for(let y=1;y<=m;y++){const{thumbnail:I}=await Z(h,y);w.push(I),r({stage:"rasterizing",currentPage:y,totalPages:m,message:`Preparing preview ${y} of ${m}...`,thumbnail:I})}const b=x(e.name?.replace(/\.pdf$/i,"")||"Imported PDF");return{thumbnails:w,totalPages:P,ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p,exceedsLimit:g,title:b,_pdf:h,_token:n,_file:e}}async function te(e,t,o,r){const n=m=>{t&&t(m)},{_pdf:a,_token:s,_file:c,totalPages:i,title:u,ocrMonthlyLimit:p,ocrPagesRemaining:d,limitPeriod:f,anonymous:l,freeAccountLimit:h,maxPlanLimit:P}=e;if(i>d)throw S.ocrLimitExceeded(d,i,p,e.thumbnails,f,l,h,P);n({stage:"converting",totalPages:i,message:"Creating document..."}),M.track("PDF Import Started",{"Total Pages":i,"File Name":c.name,Anonymous:!s});const g=await Xe({totalPages:i,title:u,token:s,timeoutMessage:"Import timed out after 10 minutes. Please try with a shorter PDF.",targetDocumentId:o,afterBlockId:r});return Ke({totalPages:i,preparePage:async m=>{const{blob:w,thumbnail:b}=await Z(a,m);return n({stage:"rasterizing",currentPage:m,totalPages:i,message:`Processing page ${m} of ${i}`,thumbnail:b}),{url:await Ve(w,m,s),mediaType:"image/png",pageNumber:m}},sendBatch:(m,w)=>Q({importId:g.importId,uploadToken:g.uploadToken,pages:m,final:w})}).catch(async m=>{const w=m instanceof Error?m.message:"Failed to prepare PDF pages";console.error("[PDF Import] Background page upload failed:",m),n({stage:"error",totalPages:i,message:w});try{await Q({importId:g.importId,uploadToken:g.uploadToken,error:w})}catch(b){console.error("[PDF Import] Failed to report page upload error:",b)}}),n({stage:"complete",totalPages:i,message:"Document created! Content is streaming..."}),M.track("PDF Import Completed",{"Document ID":g.documentId,"Total Pages":i,Anonymous:!s}),{documentId:g.documentId,title:g.title,pagesProcessed:i,inputTokens:0,outputTokens:0,streaming:!0}}function oe(e){const t=e.getMap("import-progress");let o=()=>{};const r=new Promise((n,a)=>{const s=()=>{const i=t.get("stage");i!=="complete"&&i!=="error"||(o(),i==="complete"?n():a(new Error(String(t.get("error")||"PDF import failed."))))},c=setTimeout(()=>{o(),a(new Error("PDF import timed out before content was ready."))},9e5);o=()=>{clearTimeout(c),t.unobserve(s)},t.observe(s)});return r.catch(()=>{}),{done:r,cancel:()=>o()}}async function Ze(e,t,o,r,n){const a=await ee(e,void 0,r),s=oe(o);try{const c=await te(a,r,t,n);return await s.done,c}catch(c){throw s.cancel(),c}}export{S as PdfLimitError,te as confirmPdfImport,Ze as importPdfIntoExistingDocument,ee as previewPdfForImport,oe as watchImportCompletion};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{A as P,B as w,a6 as q,a7 as K,a8 as U,a9 as G,aa as z,ab as _,I as Y}from"./index-2TBhRkX7.js";import{N as X,k as Z,h as $,g as J,r as T,t as k,i as Q,m as tt,d as et,s as st,b as rt,l as nt,f as it,j as at,a as ot,p as lt}from"./OfficeImportShared-Bvm-mOyj.js";const ct={65001:"utf-8",932:"shift_jis",936:"gb18030",949:"euc-kr",950:"big5",874:"windows-874",1e4:"macintosh",437:"windows-1252",850:"windows-1252"};function ht(a){const t=/\\ansicpg(\d+)/i.exec(a)?.[1];return t?C(t):/\\mac\b/.test(a)?"macintosh":"windows-1252"}function C(a){const t=String(a);return ct[t]??`windows-${t}`}const dt={77:1e4,128:932,129:949,134:936,136:950,161:1253,162:1254,163:1258,177:1255,178:1256,186:1257,204:1251,222:874,238:1250},j=new Map;function ut(a,t){let e=j.get(t);if(!e){try{e=new TextDecoder(t)}catch{e=new TextDecoder("windows-1252")}j.set(t,e)}return e.decode(a instanceof Uint8Array?a:new Uint8Array(a))}class L{constructor(t){this.kind=t,this.items=[],this.runs=[],this.runText="",this.runMarks={},this.paraId=w(),this.suppressEmptyPar=!1}}const pt=new Map([["emdash","—"],["endash","–"],["lquote","‘"],["rquote","’"],["ldblquote","“"],["rdblquote","”"],["bullet","•"],["emspace"," "],["enspace"," "],["qmspace"," "],["zwj",""],["zwnj",""],["ltrmark",""],["rtlmark",""]]),ft=new Set(["info","xmlnstbl","themedata","colorschememapping","latentstyles","datastore","generator","filetbl","rsidtbl","nonshppict","objdata","objclass","objname","shpinst","shptxt","userprops","docvar","pgdsctbl","mmathPr","bkmkstart","bkmkend","xe","tc","txe","template","private","passwordhash","wgrffmtfilter","defchp","defpap","listpicture","pnseclvl","protusertbl","fchars","lchars","aftnsep","aftnsepc","aftncn","ftnsep","ftnsepc","ftncn","blipuid","picprop","atnicn","atntime","do","falt","panose","fname","oldcprops","oldpprops","oldtprops","oldsprops","annotation-ignore"]),gt=new Set(["expandedcolortbl","listtable","listoverridetable","shppict","fldinst","annotation","atnauthor","atnid","atnref","atndate","atrfstart","atrfend","pn","revtbl","footnote"]),mt=new Set(["pict","footnote","annotation","fldinst","fldrslt","header","headerl","headerr","headerf","footer","footerl","footerr","footerf"]),bt=new Set(["ul","uld","uldash","uldashd","uldashdd","uldb","ulhwave","ulldash","ulth","ulthd","ulthdash","ulthdashd","ulthdashdd","ulthldash","ululdbwave","ulw","ulwave"]),W=new Map([["header","default"],["headerr","default"],["headerl","even"],["headerf","first"],["footer","default"],["footerr","default"],["footerl","even"],["footerf","first"]]);function E(a,t={}){return new kt(a,t).read()}class kt{constructor(t,e){this.rtf=t,this.options=e,this.defaultFont=0,this.fonts=new Map,this.colors=[],this.colorParts={r:0,g:0,b:0},this.colorHasValue=!1,this.expandedIndex=0,this.expandedParts=[],this.styles=new Map,this.currentStyle=null,this.lists=new Map,this.currentList=null,this.listOverrides=new Map,this.currentOverride=null,this.revAuthors=[],this.currentFontEntry=null,this.rowDefs=[],this.pendingCellDef={},this.rowIsHeader=!1,this.body=new L("body"),this.notes=new X("rtffn"),this.headers={},this.footers={},this.comments=[],this.openCommentRanges=[],this.commentMeta={},this.annotationCounter=0,this.commentRangeIds=new Map,this.commentIds=new Set,this.page={margins:{}},this.sectionSeen=!1,this.stack=[],this.marksVersion=0,this.cachedMarksVersion=-1,this.cachedMarks={},this.pendingBytes=[],this.pendingBytesEncoding="",this.chainsSeen=new Set,this.ansiEncoding=ht(t.slice(0,4096)),this.cocoa=/\\cocoartf/.test(t.slice(0,512)),this.state={dest:"body",chars:{},para:{borders:{}},unicodeSkip:1,storyRef:{story:this.body}}}read(){this.tokenize(),this.flushBytes();const t=this.body;this.flushRun(t),t.runs.some(i=>i.text.trim().length>0)&&this.flushParagraph(t);const e=this.buildBlocks(t.items,"body");O(e),e.length===0&&e.push(P());const s={type:"doc",children:e};this.notes.notes.length>0&&(s.notes=this.notes.notes),Object.keys(this.headers).length>0&&(s.headers=this.headers),Object.keys(this.footers).length>0&&(s.footers=this.footers);const r=Z(this.comments,[s.children,s.notes??[]]);r.length>0&&(s.comments=r);const n=this.pageLayout();return n&&(s.pageLayout=n),s}tokenize(){const t=this.rtf,e=t.length,s=/\\([a-zA-Z]{1,32})(-?\d{1,10})? ?/y;let r=0;for(;r<e;){const n=t.charCodeAt(r);if(n===123){this.flushBytes(),this.pushGroup(),r++;continue}if(n===125){this.flushBytes(),this.popGroup(),r++;continue}if(n===10||n===13){r++;continue}if(n!==92){let l=r+1;for(;l<e;){const f=t.charCodeAt(l);if(f===92||f===123||f===125||f===10||f===13)break;l++}this.literal(t.slice(r,l)),r=l;continue}const i=t[r+1];if(i===void 0)break;if(i==="\\"||i==="{"||i==="}"){this.flushBytes(),this.text(i),r+=2;continue}if(i==="'"){const l=parseInt(t.slice(r+2,r+4),16);r+=4,Number.isNaN(l)||this.byte(l);continue}if(this.flushBytes(),i==="*"){this.state.starred=!0,r+=2;continue}if(i==="~"){this.text(" "),r+=2;continue}if(i==="_"){this.text("‑"),r+=2;continue}if(i==="-"){r+=2;continue}if(i===`
|
|
2
|
+
`||i==="\r"){this.controlWord("par",null),r+=2;continue}s.lastIndex=r;const o=s.exec(t);if(!o){r+=2;continue}r+=o[0].length;const c=o[1],d=o[2]!==void 0?parseInt(o[2],10):null;if(c==="bin"&&d!==null&&d>0){this.binary(t.slice(r,r+d)),r+=d;continue}if(c==="u"&&d!==null){this.text(String.fromCharCode(d<0?d+65536:d));let l=this.state.unicodeSkip;for(;l>0&&r<e;){const f=t[r];if(f==="\\")if(t[r+1]==="'")r+=4;else{s.lastIndex=r;const m=s.exec(t);r+=m?m[0].length:2}else{if(f==="{"||f==="}")break;if(f===`
|
|
3
|
+
`||f==="\r"){r+=1;continue}else r+=1}l--}continue}this.controlWord(c,d)}}pushGroup(){const t=this.state;this.stack.push(t),this.state={dest:t.dest,chars:{...t.chars},para:{...t.para,borders:{...t.para.borders}},unicodeSkip:t.unicodeSkip,storyRef:t.storyRef,field:t.field,link:t.link,fieldKind:t.fieldKind,capture:void 0,metaKind:t.dest==="meta"?t.metaKind:void 0},(t.dest==="listtext"||t.dest==="fldinst"||t.dest==="meta")&&(this.state.capture=t.capture),this.marksVersion++}popGroup(){const t=this.state,e=this.stack.pop();e&&(this.endGroup(t,e),this.state=e,this.marksVersion++)}endGroup(t,e){switch(t.dest){case"pict":t.pict&&t.pict!==e.pict&&this.finishPicture(t.pict,t);break;case"fonttbl":t.capture&&t.capture!==e.capture&&this.finishFontName(t.capture.text);break;case"stylesheet":t.capture&&t.capture!==e.capture&&this.finishStyle(t.capture.text);break;case"listtext":e.dest!=="listtext"&&t.capture&&(t.storyRef.story.listText=t.capture.text);break;case"fldinst":e.dest!=="fldinst"&&t.capture&&t.field&&(t.field.instr=t.capture.text);break;case"meta":e.dest!=="meta"&&t.capture&&t.metaKind&&this.finishMeta(t.metaKind,t.capture.text.trim());break;case"revtbl":if(t.capture&&t.capture!==e.capture)for(const s of t.capture.text.split(";").slice(0,-1))this.revAuthors.push(s.trim());break}t.opensStory&&this.finishStory(t,e)}literal(t){const e=this.state;if(this.flushBytes(),e.dest==="pict"){e.pict?.hex.push(t);return}if(this.options.binary){let s=0;for(let r=0;r<t.length;r++)t.charCodeAt(r)>=128&&(r>s&&(this.flushBytes(),this.text(t.slice(s,r))),this.byte(t.charCodeAt(r)&255),s=r+1);s<t.length&&(this.flushBytes(),this.text(t.slice(s)));return}this.text(t)}byte(t){const e=this.currentEncoding();this.pendingBytes.length>0&&e!==this.pendingBytesEncoding&&this.flushBytes(),this.pendingBytesEncoding=e,this.pendingBytes.push(t)}flushBytes(){if(this.pendingBytes.length===0)return;const t=this.pendingBytes;this.pendingBytes=[],this.text(ut(t,this.pendingBytesEncoding))}currentEncoding(){const t=this.state.chars;return this.fonts.get(t.font??t.lochFont??this.defaultFont)?.encoding??this.ansiEncoding}binary(t){const e=this.state.pict;if(this.state.dest!=="pict"||!e)return;const s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r)&255;(e.binary??(e.binary=[])).push(s)}text(t){if(!t)return;const e=this.state;switch(e.dest){case"body":{const s=e.storyRef.story,r=this.effectiveMarks();J(r,s.runMarks)||(this.flushRun(s),s.runMarks=r),s.runText+=t,s.suppressEmptyPar=!1;return}case"fonttbl":case"stylesheet":case"listtext":case"fldinst":case"meta":e.capture&&(e.capture.text+=t),e.dest==="fonttbl"&&t.includes(";")&&this.fontTableSemicolons(t);return;case"colortbl":for(const s of t)s===";"&&(this.colors.push(this.colorHasValue?$(this.colorParts.r,this.colorParts.g,this.colorParts.b):void 0),this.colorParts={r:0,g:0,b:0},this.colorHasValue=!1);return;case"expandedcolortbl":for(const s of t){if(s!==";")continue;const r=this.expandedParts,n=i=>i/1e5*255;if(r.length>=3)this.colors[this.expandedIndex]=$(n(r[0]),n(r[1]),n(r[2]));else if(r.length===1){const i=n(r[0]);this.colors[this.expandedIndex]=$(i,i,i)}this.expandedParts=[],this.expandedIndex++}return;case"revtbl":e.capture?e.capture.text+=t:e.capture={text:t};return;default:return}}fontTableSemicolons(t){const e=this.state.capture;if(!e)return;const s=e.text.split(";");for(let r=0;r<s.length-1;r++)this.finishFontName(s[r]);e.text=s[s.length-1]}effectiveMarks(){if(this.cachedMarksVersion===this.marksVersion)return this.cachedMarks;const t=this.state,e=t.chars,s={};e.bold&&(s.bold=!0),e.italic&&(s.italic=!0),e.underline&&(s.underline=!0),e.strike&&(s.strikethrough=!0),e.dstrike&&(s.doubleStrikethrough=!0),e.superscript?s.superscript=!0:e.subscript&&(s.subscript=!0),e.caps&&(s.allCaps=!0),e.scaps&&(s.smallCaps=!0),e.hidden&&(s.hidden=!0);const r=this.fonts.get(e.font??e.lochFont??this.defaultFont)?.name;r&&(s.fontFamily=r),e.halfPoints&&e.halfPoints>0&&(s.fontSize=T(e.halfPoints/2*(96/72)));const n=e.color?this.colors[e.color]:void 0;n&&n!=="#000000"&&(s.color=n);const i=(e.highlight?this.colors[e.highlight]:void 0)??(e.background?this.colors[e.background]:void 0);return i&&i!=="#ffffff"&&(s.backgroundColor=i),e.expandTwips&&(s.letterSpacing=T(k(e.expandTwips))),t.link&&(s.link=t.link),t.fieldKind&&(s.field=t.fieldKind),this.openCommentRanges.length>0&&t.storyRef.story.kind!=="annotation"&&(s.comment=this.openCommentRanges.join(",")),e.deleted?Object.assign(s,this.revisionMarks("deletion",e.revAuthorDel??e.revAuthor,e.revTimeDel??e.revTime)):e.revised&&Object.assign(s,this.revisionMarks("insertion",e.revAuthor,e.revTime)),this.cachedMarks=s,this.cachedMarksVersion=this.marksVersion,s}revisionMarks(t,e,s){const r=e!==void 0?this.revAuthors[e]:void 0,n=s!==void 0?V(s):void 0;return Q(t,`rtfrev-${t==="insertion"?"ins":"del"}-${e??0}-${s??0}`,r&&r!=="Unknown"?r:void 0,n)}flushRun(t){t.runText&&(t.runs.push({type:"text",text:t.runText,marks:{...t.runMarks}}),t.runText="")}flushParagraph(t,e=!1){this.flushRun(t);const s=t.runs.filter(r=>r.text.length>0);if(t.runs=[],s.length===0&&t.suppressEmptyPar&&!e){t.suppressEmptyPar=!1,t.listText=void 0,t.paraId=w();return}t.items.push({kind:"para",id:t.paraId,runs:tt(s),para:{...this.state.para,borders:{...this.state.para.borders}},...t.listText!==void 0?{listText:t.listText}:{},...e?{forcedInTable:!0}:{}}),t.listText=void 0,t.suppressEmptyPar=!1,t.paraId=w()}controlWord(t,e){const s=this.state,r=s.starred;if(s.starred=!1,s.dest!=="skip"&&!this.startDestination(t)){if(r&&!gt.has(t)){s.dest="skip";return}if(ft.has(t)){s.dest="skip";return}switch(s.dest){case"fonttbl":this.fontTableWord(t,e);return;case"colortbl":this.colorTableWord(t,e);return;case"expandedcolortbl":t==="c"&&e!==null?this.expandedParts.push(e):(t==="cssrgb"||t==="csgray"||t==="csgenericrgb")&&(this.expandedParts=[]);return;case"stylesheet":this.styleSheetWord(t,e);return;case"listtable":this.listTableWord(t,e);return;case"listoverridetable":this.listOverrideWord(t,e);return;case"pict":this.pictWord(t,e);return;case"pn":this.pnWord(t,e);return;case"listtext":case"fldinst":case"meta":t==="tab"&&this.text(" ");return;case"revtbl":return}if(this.characterWord(t,e)){this.marksVersion++;return}this.paragraphWord(t,e)||this.structureWord(t,e)}}startDestination(t){const e=this.state;if(e.dest!=="body"&&mt.has(t))return e.dest="skip",!0;switch(t){case"fonttbl":return e.dest="fonttbl",e.capture={text:""},!0;case"colortbl":return e.dest="colortbl",this.colors=[],!0;case"expandedcolortbl":return e.dest="expandedcolortbl",this.expandedIndex=0,this.expandedParts=[],!0;case"stylesheet":return e.dest="stylesheet",!0;case"listtable":return e.dest="listtable",!0;case"listoverridetable":return e.dest="listoverridetable",!0;case"revtbl":return e.dest="revtbl",!0;case"pict":return e.dest="pict",e.pict={hex:[]},!0;case"shppict":case"shprslt":case"result":case"shp":case"object":case"field":return t==="field"&&(e.field={instr:""}),!0;case"fldinst":return e.dest="fldinst",e.capture={text:""},!0;case"fldrslt":{const s=e.field?.instr??"",r=/^\s*HYPERLINK\s+(?:\\[a-z]\s+)*"([^"]+)"/i.exec(s);return r&&!/^\s*HYPERLINK\s+\\l\b/i.test(s)&&(e.link=et(r[1])),/^\s*PAGE\b/i.test(s)&&(e.fieldKind="page"),/^\s*NUMPAGES\b/i.test(s)&&(e.fieldKind="numPages"),this.marksVersion++,!0}case"listtext":case"pntext":return e.dest="listtext",e.capture={text:""},!0;case"pn":return e.dest="pn",e.para.pn={kind:"number",level:0},!0;case"footnote":return this.openStory("footnote");case"annotation":return this.openStory("annotation");case"atnauthor":case"atnid":case"atnref":case"atndate":case"atrfstart":case"atrfend":return e.dest="meta",e.metaKind=t,e.capture={text:""},!0;default:return W.has(t)?(e.dest="body",e.opensStory=!0,e.storyRef={story:new L("header")},e.para={borders:{}},e.headerWord=t,!0):!1}}openStory(t){const e=this.state;return e.dest="body",e.opensStory=!0,e.storyRef={story:new L(t)},e.para={borders:{}},e.link=void 0,t==="annotation"&&(this.annotationRef=void 0,this.annotationDate=void 0),this.marksVersion++,!0}finishStory(t,e){const s=t.storyRef.story;if(this.flushRun(s),s.runs.some(i=>i.text.length>0)){const i=this.state;this.state=t,this.flushParagraph(s),this.state=i}const r=this.buildBlocks(s.items,s.kind);O(r);const n=e.storyRef.story;if(s.kind==="footnote"||s.kind==="endnote"){if(e.dest!=="body")return;this.flushRun(n),this.state=e,this.marksVersion++;const i=this.effectiveMarks(),o=this.notes.add(s.kind,r,i);n.runs.push(o),n.runMarks={},this.marksVersion++;return}if(s.kind==="header"){const i=t.headerWord??"header",o=W.get(i)??"default",c=r.filter(d=>d.type==="paragraph");if(c.some(d=>d.children.some(l=>l.text.trim()!==""||l.marks?.field))){const d=i.startsWith("footer")?this.footers:this.headers;d[o]=c}return}if(s.kind==="annotation"){const i=r.map(l=>l.type==="paragraph"?l.children.map(f=>f.text).join("").trim():"").filter(l=>l.length>0).join(`
|
|
4
|
+
|
|
5
|
+
`);this.annotationCounter++;const o=this.annotationRef;let c=`rtfcmt-${o??`point-${this.annotationCounter}`}`,d=o!==void 0&&this.commentRangeIds.has(o);if(this.commentIds.has(c)){d=!1;let l=this.annotationCounter;for(;this.commentIds.has(`${c}-${l}`);)l++;c=`${c}-${l}`}this.commentIds.add(c),this.comments.push({id:c,author:this.commentMeta.author||this.commentMeta.initials||"Unknown",...this.commentMeta.initials?{initials:this.commentMeta.initials}:{},createdAt:new Date(this.annotationDate!==void 0?V(this.annotationDate)??0:0).toISOString(),bodyMd:i,...d?{}:{anchorBlockId:n.paraId}}),this.commentMeta={}}}finishMeta(t,e){switch(t){case"atnauthor":this.commentMeta.author=e;break;case"atnid":this.commentMeta.initials=e;break;case"atnref":this.annotationRef=e;break;case"atndate":{const s=parseInt(e,10);Number.isFinite(s)&&(this.annotationDate=s);break}case"atrfstart":e&&(this.commentRangeIds.set(e,`rtfcmt-${e}`),this.openCommentRanges=[...this.openCommentRanges,`rtfcmt-${e}`],this.marksVersion++);break;case"atrfend":e&&(this.openCommentRanges=this.openCommentRanges.filter(s=>s!==`rtfcmt-${e}`),this.marksVersion++);break}}fontTableWord(t,e){if(t==="f"&&e!==null){const r=this.state.capture;r&&r.text.trim()&&this.currentFontEntry!==null&&this.finishFontName(r.text),this.currentFontEntry=e,this.fonts.has(e)||this.fonts.set(e,{name:""}),this.state.capture={text:""};return}const s=this.currentFontEntry!==null?this.fonts.get(this.currentFontEntry):void 0;if(s)if(t==="fcharset"&&e!==null){const r=dt[e];r&&(s.encoding=C(r)),e===2&&(s.encoding="windows-1252")}else t==="cpg"&&e!==null&&e>0&&(s.encoding=C(e))}finishFontName(t){if(this.currentFontEntry===null)return;const e=this.fonts.get(this.currentFontEntry),s=t.replace(/;$/,"").trim();e&&s&&!e.name&&(e.name=this.cocoa?St(s):s)}colorTableWord(t,e){if(e!==null){if(t==="red")this.colorParts.r=e;else if(t==="green")this.colorParts.g=e;else if(t==="blue")this.colorParts.b=e;else return;this.colorHasValue=!0}}styleSheetWord(t,e){const s=this.state;t==="s"&&e!==null?(this.currentStyle={index:e},s.capture={text:""}):t==="outlinelevel"&&e!==null&&this.currentStyle&&(this.currentStyle.outlineLevel=e)}finishStyle(t){if(!this.currentStyle)return;const e=t.replace(/;[\s\S]*$/,"").trim();this.styles.set(this.currentStyle.index,{name:e,outlineLevel:this.currentStyle.outlineLevel}),this.currentStyle=null}listTableWord(t,e){switch(t){case"list":this.currentList={def:{levels:[]}};break;case"listlevel":this.currentList?.def.levels.push({nfc:0,startAt:1});break;case"levelnfc":case"levelnfcn":{const s=this.currentList?.def.levels.at(-1);s&&e!==null&&(s.nfc=e);break}case"levelstartat":{const s=this.currentList?.def.levels.at(-1);s&&e!==null&&(s.startAt=e);break}case"listid":this.currentList&&e!==null&&(this.currentList.id=e,this.lists.set(e,this.currentList.def));break}}listOverrideWord(t,e){t==="listoverride"?this.currentOverride={}:t==="listid"&&this.currentOverride&&e!==null?this.currentOverride.listId=e:t==="ls"&&this.currentOverride&&e!==null&&(this.currentOverride.ls=e);const s=this.currentOverride;s?.listId!==void 0&&s.ls!==void 0&&this.listOverrides.set(s.ls,s.listId)}pnWord(t,e){const s=this.state.para.pn;if(!s)return;t==="pnlvlblt"?s.kind="bullet":/^pn(dec|ucltr|lcltr|ucrm|lcrm|ord|ordt|cardt)$/.test(t)?s.kind="number":t==="pnlvl"&&e!==null&&(s.level=Math.max(0,e-1));const r=this.stack[this.stack.length-1];r&&(r.para.pn={...s})}pictWord(t,e){const s=this.state.pict;if(s)switch(t){case"pngblip":s.format="png";break;case"jpegblip":s.format="jpeg";break;case"emfblip":s.format="emf";break;case"wmetafile":s.format="wmf";break;case"macpict":case"dibitmap":case"wbitmap":case"pmmetafile":s.format??(s.format="unsupported");break;case"picw":e!==null&&(s.picw=e);break;case"pich":e!==null&&(s.pich=e);break;case"picwgoal":e!==null&&(s.goalW=e);break;case"pichgoal":e!==null&&(s.goalH=e);break;case"picscalex":e!==null&&(s.scaleX=e);break;case"picscaley":e!==null&&(s.scaleY=e);break}}finishPicture(t,e){let s;if(t.binary&&t.binary.length>0){const b=t.binary.reduce((u,p)=>u+p.length,0);s=new Uint8Array(b);let h=0;for(const u of t.binary)s.set(u,h),h+=u.length}else s=vt(t.hex.join(""));if(s.length===0)return;const r=t.format&&t.format!=="unsupported"?t.format:void 0,n=st(s)??r;if(!n)return;const i=n==="emf"||n==="wmf",o=(t.scaleX??100)/100,c=(t.scaleY??100)/100,d=(b,h)=>b?k(b):h?i?h/2540*96:h:void 0,l=d(t.goalW,t.picw),f=d(t.goalH,t.pich),m=e.storyRef.story,M=e.para;if(this.flushRun(m),m.runs.some(b=>b.text.length>0)){const b=this.state;this.state=e,this.flushParagraph(m),this.state=b}else m.runs=[];const I=M.align==="justify"?void 0:M.align;m.items.push({kind:"image",image:rt(s,n,{width:l!==void 0?l*o:void 0,height:f!==void 0?f*c:void 0},{align:I}),inTable:!!M.inTable}),m.suppressEmptyPar=!0}characterWord(t,e){const s=this.state.chars,r=e!==0;if(bt.has(t))return s.underline=r,!0;switch(t){case"plain":{const{revised:n,deleted:i,revAuthor:o,revTime:c,revAuthorDel:d,revTimeDel:l}=s;return this.state.chars={revised:n,deleted:i,revAuthor:o,revTime:c,revAuthorDel:d,revTimeDel:l},!0}case"b":return s.bold=r,!0;case"i":return s.italic=r,!0;case"ulnone":return s.underline=!1,!0;case"strike":return s.strike=r,!0;case"striked":return s.dstrike=r,!0;case"super":return s.superscript=r,s.subscript=!1,!0;case"sub":return s.subscript=r,s.superscript=!1,!0;case"nosupersub":return s.superscript=!1,s.subscript=!1,!0;case"caps":return s.caps=r,!0;case"scaps":return s.scaps=r,!0;case"v":return s.hidden=r,!0;case"f":return e!==null&&(s.font=e),!0;case"loch":case"hich":case"dbch":return s.script=t,!0;case"rtlch":case"ltrch":return s.script=void 0,!0;case"af":return e!==null&&(s.script==="loch"||s.script==="hich")&&(s.lochFont=e),!0;case"fs":return e!==null&&(s.halfPoints=e),!0;case"fsmilli":return e!==null&&(s.halfPoints=e/1e3*2),!0;case"cf":return s.color=e??0,!0;case"highlight":return s.highlight=e??0,!0;case"cb":case"chcbpat":return s.background=e??0,!0;case"expndtw":return s.expandTwips=e??0,!0;case"expnd":return s.expandTwips===void 0&&e!==null&&(s.expandTwips=e*5),!0;case"revised":return s.revised=r,!0;case"deleted":return s.deleted=r,!0;case"revauth":return e!==null&&(s.revAuthor=e),!0;case"revdttm":return e!==null&&(s.revTime=e),!0;case"revauthdel":return e!==null&&(s.revAuthorDel=e),!0;case"revdttmdel":return e!==null&&(s.revTimeDel=e),!0;default:return!1}}paragraphWord(t,e){const s=this.state.para;switch(t){case"pard":return this.state.para={borders:{}},!0;case"qc":return s.align="center",!0;case"qr":return s.align="right",!0;case"qj":case"qd":return s.align="justify",!0;case"ql":return s.align=void 0,!0;case"li":case"lin":return e!==null&&(s.leftTwips=e),!0;case"fi":return e!==null&&(s.firstTwips=e),!0;case"sb":return e!==null&&(s.spaceBeforeTwips=e),!0;case"sa":return e!==null&&(s.spaceAfterTwips=e),!0;case"sl":return s.lineTwips=e??0,!0;case"slmult":return s.lineMultiple=e===1,!0;case"keepn":return s.keepNext=e!==0,!0;case"keep":return s.keepLines=e!==0,!0;case"rtlpar":return s.rtl=!0,!0;case"ltrpar":return s.rtl=!1,!0;case"s":return e!==null&&(s.style=e),!0;case"outlinelevel":return e!==null&&(s.outlineLevel=e),!0;case"intbl":return s.inTable=e!==0,!0;case"itap":return e!==null&&(s.inTable=e>0),!0;case"ls":return e!==null&&(s.ls=e),!0;case"ilvl":return e!==null&&(s.ilvl=e),!0;case"cbpat":return e!==null&&(s.shading=e),!0;case"pagebb":return s.pageBreakBefore=e!==0,!0;case"brdrt":case"brdrb":case"brdrl":case"brdrr":case"box":{const r=t==="box"?["top","bottom","left","right"]:[{brdrt:"top",brdrb:"bottom",brdrl:"left",brdrr:"right"}[t]];for(const n of r)s.borders[n]={style:"single",width:1,color:"#000000"};return s.borderTarget=t==="box"?"box":r[0],!0}case"brdrs":case"brdrth":case"brdrsh":case"brdrdb":case"brdrdash":case"brdrdashsm":case"brdrdot":case"brdrnone":case"brdrw":case"brdrcf":{const r=s.borderTarget;if(!r||r==="ignore")return!0;const n=r==="box"?["top","bottom","left","right"]:[r];for(const i of n){const o=s.borders[i];o&&(t==="brdrnone"?delete s.borders[i]:t==="brdrdb"?o.style="double":t==="brdrdash"||t==="brdrdashsm"?o.style="dashed":t==="brdrdot"?o.style="dotted":t==="brdrth"?(o.style="single",o.width=Math.max(o.width,2)):t==="brdrw"&&e!==null?o.width=Math.min(8,Math.max(1,Math.round(e/15))):t==="brdrcf"&&e!==null?o.color=this.colors[e]??o.color:(t==="brdrs"||t==="brdrsh")&&(o.style="single"))}return!0}default:return/^(tr|cl|pg)brdr[tblrhv]$|^brdrbtw$|^brdrbar$/.test(t)?(s.borderTarget="ignore",!(t.startsWith("cl")||t.startsWith("tr"))):!1}}structureWord(t,e){const s=this.state.storyRef.story,r=this.state.dest==="body";switch(t){case"par":r&&this.flushParagraph(s);return;case"sect":r&&(s.runs.length>0||s.runText)&&this.flushParagraph(s),this.sectionSeen=!0;return;case"line":this.text(`
|
|
6
|
+
`);return;case"tab":this.text(" ");return;case"page":if(!r||s.kind!=="body")return;this.flushRun(s),s.runs.some(n=>n.text.length>0)&&this.flushParagraph(s),s.runs=[],s.items.push({kind:"pagebreak",inTable:!!this.state.para.inTable}),s.suppressEmptyPar=!0;return;case"cell":case"nestcell":if(!r)return;this.flushParagraph(s,!0),t==="cell"&&s.items.push({kind:"cell"});return;case"row":if(!r)return;this.flushRun(s),s.runs.some(n=>n.text.length>0)&&(this.flushParagraph(s,!0),s.items.push({kind:"cell"})),s.runs=[],s.items.push({kind:"row",defs:this.rowDefs.slice(),header:this.rowIsHeader});return;case"trowd":this.rowDefs=[],this.pendingCellDef={},this.rowIsHeader=!1;return;case"trhdr":this.rowIsHeader=!0;return;case"clmgf":this.pendingCellDef.hmergeFirst=!0;return;case"clmrg":this.pendingCellDef.hmergeCont=!0;return;case"clvmgf":this.pendingCellDef.vmergeFirst=!0;return;case"clvmrg":this.pendingCellDef.vmergeCont=!0;return;case"clcbpat":e!==null&&(this.pendingCellDef.background=e);return;case"clvertalt":this.pendingCellDef.valign="top";return;case"clvertalc":this.pendingCellDef.valign="middle";return;case"clvertalb":this.pendingCellDef.valign="bottom";return;case"cellx":e!==null&&(this.rowDefs.push({right:e,...this.pendingCellDef}),this.pendingCellDef={});return;case"chftn":case"chatn":case"chpgn":t==="chpgn"&&r&&s.kind==="header"&&(this.state.fieldKind="page",this.marksVersion++,this.text("1"),this.state.fieldKind=void 0,this.marksVersion++);return;case"ftnalt":s.kind==="footnote"&&(s.kind="endnote");return;case"uc":this.state.unicodeSkip=e??1;return;case"deff":e!==null&&(this.defaultFont=e);return;case"paperw":case"pgwsxn":e!==null&&(!this.sectionSeen||this.page.widthTwips===void 0)&&(this.page.widthTwips=e);return;case"paperh":case"pghsxn":e!==null&&(!this.sectionSeen||this.page.heightTwips===void 0)&&(this.page.heightTwips=e);return;case"landscape":case"lndscpsxn":this.page.landscape=!0;return;case"margl":case"margr":case"margt":case"margb":case"marglsxn":case"margrsxn":case"margtsxn":case"margbsxn":{if(e===null)return;const n=t.slice(4,5);if(t.endsWith("sxn")&&this.sectionSeen)return;this.page.margins[n]=e;return}default:{const n=pt.get(t);n!==void 0&&this.text(n)}}}buildBlocks(t,e){const s=[],r=i=>i.kind==="cell"||i.kind==="row"||i.kind==="para"&&(!!i.para.inTable||!!i.forcedInTable)||(i.kind==="image"||i.kind==="pagebreak")&&i.inTable;let n=0;for(;n<t.length;){const i=t[n];if(e!=="header"&&r(i)){const o=n;for(;n<t.length&&r(t[n]);)n++;const c=this.buildTable(t.slice(o,n),e);c&&s.push(...c);continue}if(i.kind==="para"){const o=this.listInfo(i);if(o&&e!=="header"){const c=[{item:i,info:o}];for(n++;n<t.length;){const d=t[n];if(d.kind!=="para"||r(d))break;const l=this.listInfo(d);if(!l||l.key!==o.key)break;c.push({item:d,info:l}),n++}s.push(this.buildList(c));continue}i.para.pageBreakBefore&&e==="body"&&s.length>0&&s.push({type:"page-break",id:w()}),s.push(this.buildParagraph(i,e)),n++;continue}i.kind==="image"?s.push(i.image):i.kind==="pagebreak"&&s.push({type:"page-break",id:w()}),n++}return s}buildParagraph(t,e){const s=t.runs.length>0?t.runs:[{type:"text",text:"",marks:{}}],r=P(s);r.id=t.id;const n=t.para;if(n.align&&(r.align=n.align),n.rtl&&(r.direction="rtl"),e!=="header"){const i=this.headingLevel(n);if(i&&(r.heading=i),n.leftTwips!==void 0){const c=nt(k(n.leftTwips));c&&(r.leftIndent=c)}if(n.firstTwips!==void 0){const c=it(k(n.firstTwips));c&&(r.firstLineIndent=c)}n.spaceBeforeTwips!==void 0&&(r.spaceBefore=T(k(Math.max(0,n.spaceBeforeTwips)))),n.spaceAfterTwips!==void 0&&(r.spaceAfter=T(k(Math.max(0,n.spaceAfterTwips)))),n.lineMultiple&&n.lineTwips&&n.lineTwips>0&&(r.lineSpacing=T(n.lineTwips/240)),n.keepNext&&(r.keepNext=!0),n.keepLines&&(r.keepLines=!0);const o=n.shading?this.colors[n.shading]:void 0;o&&o!=="#ffffff"&&(r.shading=o),Object.keys(n.borders).length>0&&(r.borders=JSON.stringify(n.borders))}return r}headingLevel(t){let e;if(t.outlineLevel!==void 0&&t.outlineLevel<9&&(e=t.outlineLevel+1),e===void 0&&t.style!==void 0){const s=this.styles.get(t.style),r=s?.name&&/^heading\s*(\d)$/i.exec(s.name);r?e=parseInt(r[1],10):s?.outlineLevel!==void 0&&s.outlineLevel<9&&(e=s.outlineLevel+1)}if(!(!e||e<1))return Math.min(e,6)}listInfo(t){const e=t.para;if(!this.headingLevel(e)){if(e.ls!==void 0&&e.ls>0){const s=this.listOverrides.get(e.ls),r=s!==void 0?this.lists.get(s):void 0,n=Math.max(0,Math.min(8,e.ilvl??0));if(r){const i=r.levels[n]??r.levels[0];if(i&&i.nfc===255&&t.listText===void 0)return;const o=i?i.nfc!==23&&i.nfc!==255:!1;return{key:`ls${e.ls}`,ordered:o,level:n,startAt:r.levels[0]?.startAt??1,chain:`rtf-ls-${e.ls}`}}return{key:`ls${e.ls}`,ordered:t.listText!==void 0&&F(t.listText),level:n,startAt:1,chain:`rtf-ls-${e.ls}`}}if(e.pn)return{key:`pn-${e.pn.kind}`,ordered:e.pn.kind==="number",level:e.pn.level,startAt:1};if(t.listText!==void 0&&t.listText.trim()!==""){const s=F(t.listText);return{key:`lt-${s}`,ordered:s,level:0,startAt:1}}}}buildList(t){const e=t[0].info,s=t.map(({item:i,info:o})=>{const c=i.runs.length>0?i.runs:[{type:"text",text:"",marks:{}}];return{type:"list-item",id:i.id,children:c,...o.level>0?{indentLevel:o.level}:{},...i.para.rtl?{direction:"rtl"}:{}}}),r={type:"list",id:w(),variant:e.ordered?"ordered":"unordered",children:s};e.ordered&&e.chain?(r.numberingChainId=e.chain,this.chainsSeen.has(e.chain)||(this.chainsSeen.add(e.chain),e.startAt!==1&&(r.startNumber=e.startAt))):e.ordered&&e.startAt!==1&&(r.startNumber=e.startAt);const n=t[0].item.para;return n.spaceAfterTwips!==void 0&&(r.spaceAfter=T(k(Math.max(0,n.spaceAfterTwips)))),n.spaceBeforeTwips!==void 0&&(r.spaceBefore=T(k(Math.max(0,n.spaceBeforeTwips)))),n.lineMultiple&&n.lineTwips&&n.lineTwips>0&&(r.lineSpacing=T(n.lineTwips/240)),r}buildTable(t,e){const s=[];let r=[],n=[],i=[];for(const h of t)h.kind==="cell"?(r.push({items:n}),n=[]):h.kind==="row"?(n.length>0&&(r.push({items:n}),n=[]),s.push({cells:r,defs:h.defs.length>0?h.defs:i,header:h.header}),h.defs.length>0&&(i=h.defs),r=[]):n.push(h);if(n.length>0&&r.push({items:n}),r.length>0&&s.push({cells:r,defs:i,header:!1}),s.length===0)return null;const o=new Set([0]),c=s.map(h=>{const u=[];let p=0,g=0;const A=h.defs.length>0?h.defs[h.defs.length-1].right/Math.max(1,h.defs.length):1440;return h.cells.forEach((R,S)=>{const x=h.defs[S],v=x?x.right:g+Math.max(1,Math.round(A));if(x?.hmergeCont&&u.length>0){const N=u[u.length-1];N.right=v,N.items.push(...R.items.filter(H=>!wt(H)))}else u.push({left:p,right:Math.max(v,p+1),def:x,items:R.items});p=v,g=v}),u}),d=0;for(const h of c)for(const u of h)o.add(Math.max(d,u.left)),o.add(u.right);const l=xt(yt([...o].sort((h,u)=>h-u),30),at(c.length)),f=h=>{let u=0,p=l.length-1;for(;u<p;){const g=u+p>>1;l[g]<h?u=g+1:p=g}return u>0&&Math.abs(l[u-1]-h)<=Math.abs(l[u]-h)?u-1:u},m=[],M=new Map;c.forEach(h=>{const u=[];for(const p of h){const g=f(p.left),A=Math.max(g+1,f(p.right));if(p.def?.vmergeCont){const v=M.get(g);if(v){v.rowSpan=(v.rowSpan??1)+1;continue}}const R=this.buildBlocks(p.items.map(v=>Tt(v)),e);Mt(R);const S={type:"table-cell",id:w(),children:R.length>0?R:[P()]};A-g>1&&(S.colSpan=A-g);const x=p.def?.background?this.colors[p.def.background]:void 0;x&&x!=="#ffffff"&&(S.backgroundColor=x),p.def?.valign&&p.def.valign!=="top"&&(S.verticalAlign=p.def.valign),p.def?.vmergeFirst?M.set(g,S):M.delete(g),u.push(S)}m.push({type:"table-row",id:w(),children:u})});const I=[];for(let h=1;h<l.length;h++)I.push(l[h]-l[h-1]);const b=ot(m,{columnWidths:I,hasHeader:s[0]?.header});return b?[b]:null}pageLayout(){const t=this.page,e=s=>t.margins[s]!==void 0?k(t.margins[s]):void 0;return lt({widthPx:t.widthTwips?k(t.widthTwips):void 0,heightPx:t.heightTwips?k(t.heightTwips):void 0,landscape:t.landscape,marginTopPx:e("t"),marginRightPx:e("r"),marginBottomPx:e("b"),marginLeftPx:e("l")})}}function F(a){const t=a.replace(/[\t\s]+/g,"");return/^(\d+|[a-zA-Z]|[ivxlcdm]+|[IVXLCDM]+)[.)]?$/.test(t)&&t.length>0}function vt(a){const t=a.replace(/[^0-9a-fA-F]/g,""),e=new Uint8Array(t.length>>1);for(let s=0;s<e.length;s++)e[s]=parseInt(t.slice(s*2,s*2+2),16);return e}function yt(a,t){const e=[];for(const s of a)(e.length===0||s-e[e.length-1]>t)&&e.push(s);return e}function xt(a,t){if(a.length-1<=t)return a;const e=a.length-1,s=[];for(let r=0;r<=t;r++)s.push(a[Math.round(r*e/t)]);return s}function wt(a){return a.kind==="para"&&a.runs.every(t=>t.text.trim()==="")}function Tt(a){return a.kind==="para"?{...a,forcedInTable:!1,para:{...a.para,inTable:!1}}:a.kind==="image"||a.kind==="pagebreak"?{...a,inTable:!1}:a}function B(a){return a.type==="paragraph"&&!a.borders&&a.children.every(t=>t.text.trim()===""&&!t.marks?.footnoteRef)}function O(a){for(;a.length>0&&B(a[0]);)a.shift();for(;a.length>0&&B(a[a.length-1]);)a.pop()}function Mt(a){for(;a.length>1&&B(a[a.length-1]);)a.pop()}function V(a){const t=a>>>0;if(t===0)return;const e=t&63,s=t>>>6&31,r=t>>>11&31,n=t>>>16&15,i=(t>>>20&511)+1900;if(!(n<1||n>12||r<1))return Date.UTC(i,n-1,r,s,e)}function St(a){if(a.startsWith("."))return"";if(/\s/.test(a))return a;let t=a.replace(/-(Regular|Roman|Book|Bold|Italic|Oblique|BoldItalic|BoldOblique|Light|LightItalic|Medium|MediumItalic|Semibold|SemiBold|SemiboldItalic|Heavy|Black|Condensed|Thin|UltraLight)$/,"");return t=t.replace(/(PSMT|PS|MT)$/,""),t=t.replace(/([a-z])([A-Z])/g,"$1 $2"),t}const D=class{static async parseFile(t){const e=new Uint8Array(await t.arrayBuffer());let s="";const r=32768;for(let n=0;n<e.length;n+=r)s+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+r)));return E(s,{binary:!0})}static fromRtf(t){return E(t)}static toRtf(t){t=q(t),this.exportListNumbering=K(t);const e=[];for(const s of t.children){const r=this.blockToRtf(s,t);r!==null&&e.push(r)}return this.exportListNumbering=null,`{\\rtf1\\ansi\\ansicpg1252\\deff0\\uc1{\\fonttbl{\\f0\\froman Times New Roman;}{\\f1\\fmodern Courier New;}}
|
|
7
|
+
\\f0\\fs24
|
|
8
|
+
`+e.join(`
|
|
9
|
+
`)+`
|
|
10
|
+
}`}static blockToRtf(t,e){switch(t.type){case"paragraph":return z(t)?"\\pard\\brdrb\\brdrs\\brdrw15 \\par":this.paragraphToRtf(t);case"list":return this.listToRtf(t);case"table":return this.tableToRtf(t);case"code":return"\\pard{\\f1\\fs20 "+y(t.content).replace(/\n/g,"\\line ")+"}\\par";case"math":return"\\pard "+y(t.content)+"\\par";case"toc":{const s=U(e,G(t));return s.length===0?null:s.map(r=>`\\pard${t.direction==="rtl"?"\\rtlpar":"\\ltrpar"}${t.align==="justify"?"\\qj":t.align==="center"?"\\qc":(t.align??(t.direction==="rtl"?"right":"left"))==="right"?"\\qr":"\\ql"}\\${t.direction==="rtl"?"ri":"li"}${(r.level-1)*360} `+y(r.text)+"\\par").join(`
|
|
11
|
+
`)}case"image":return"\\pard{\\i [Image"+(t.alt?`: ${y(t.alt)}`:"")+"]}\\par";case"page-break":return"\\page";case"container":return t.children.map(s=>this.blockToRtf(s,e)).filter(s=>s!==null).join(`
|
|
12
|
+
`);default:return null}}static paragraphToRtf(t){let e="\\pard";t.align==="center"?e+="\\qc":t.align==="right"?e+="\\qr":t.align==="justify"&&(e+="\\qj");let s=this.inlineNodesToRtf(t.children);return t.heading&&(s=`{\\b\\fs${this.HEADING_HALF_POINTS[t.heading-1]} ${s}}`),`${e} ${s}\\par`}static listToRtf(t){const e=this.exportListNumbering?.get(t.id);let s=e?_(e):t.startNumber??1;const r=[];for(const n of t.children){if(n.type!=="list-item")continue;const i=((n.indentLevel??0)+1)*360;let o;t.variant==="ordered"?(o=`${s}. `,s++):t.variant==="todo"?o=n.checked?"[x] ":"[ ] ":o="\\bullet ",r.push(`\\pard\\li${i} ${o}`+this.inlineNodesToRtf(n.children)+"\\par")}return r.join(`
|
|
13
|
+
`)}static tableToRtf(t){if(!t.children||t.children.length===0)return"";const e=Y(t),s=9360,r=[];for(let n=0;n<e.rows;n++){const i=["\\trowd\\trgaph108"];for(let o=0;o<e.cols;o++)i.push(`\\cellx${Math.round(s*(o+1)/e.cols)}`);for(let o=0;o<e.cols;o++){const c=e.occupancy[n][o];let d="";c&&c.row===n&&c.col===o&&(d=c.cell.children.map(l=>l.type==="paragraph"?this.inlineNodesToRtf(l.children):l.type==="code"?y(l.content):"").filter(l=>l.length>0).join("\\line ")),i.push(`\\pard\\intbl ${d}\\cell`)}i.push("\\row"),r.push(i.join(""))}return r.join(`
|
|
14
|
+
`)+`
|
|
15
|
+
\\pard`}static inlineNodesToRtf(t){return t.map(e=>this.textNodeToRtf(e)).join("")}static textNodeToRtf(t){if(t.marks?.footnoteRef)return`{\\super ${y(t.text)}}`;const e=y(t.text).replace(/\n/g,"\\line ");if(!t.marks)return e;const s=[];t.marks.bold&&s.push("\\b"),t.marks.italic&&s.push("\\i"),t.marks.underline&&s.push("\\ul"),t.marks.strikethrough&&s.push("\\strike"),t.marks.superscript&&s.push("\\super"),t.marks.subscript&&s.push("\\sub"),t.marks.code&&s.push("\\f1");const r=s.length>0?`{${s.join("")} ${e}}`:e;return t.marks.link?`{\\field{\\*\\fldinst HYPERLINK "${y(t.marks.link)}"}{\\fldrslt ${r}}}`:r}};D.exportListNumbering=null,D.HEADING_HALF_POINTS=[32,28,26,24,22,22];let Rt=D;function y(a){let t="";for(let e=0;e<a.length;e++){const s=a[e];if(s==="\\"||s==="{"||s==="}"){t+="\\"+s;continue}const r=a.charCodeAt(e);if(r<128){t+=s;continue}t+=`\\u${r>32767?r-65536:r}?`}return t}export{Rt as RtfConverter,y as escapeRtfText};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{A as P,B as w,a6 as q,a7 as K,a8 as U,a9 as G,aa as z,ab as _,I as Y}from"./index-BwcX_r62.js";import{N as X,k as Z,h as $,g as J,r as T,t as k,i as Q,m as tt,d as et,s as st,b as rt,l as nt,f as it,j as at,a as ot,p as lt}from"./OfficeImportShared-BY6FdZ8d.js";const ct={65001:"utf-8",932:"shift_jis",936:"gb18030",949:"euc-kr",950:"big5",874:"windows-874",1e4:"macintosh",437:"windows-1252",850:"windows-1252"};function ht(a){const t=/\\ansicpg(\d+)/i.exec(a)?.[1];return t?C(t):/\\mac\b/.test(a)?"macintosh":"windows-1252"}function C(a){const t=String(a);return ct[t]??`windows-${t}`}const dt={77:1e4,128:932,129:949,134:936,136:950,161:1253,162:1254,163:1258,177:1255,178:1256,186:1257,204:1251,222:874,238:1250},j=new Map;function ut(a,t){let e=j.get(t);if(!e){try{e=new TextDecoder(t)}catch{e=new TextDecoder("windows-1252")}j.set(t,e)}return e.decode(a instanceof Uint8Array?a:new Uint8Array(a))}class L{constructor(t){this.kind=t,this.items=[],this.runs=[],this.runText="",this.runMarks={},this.paraId=w(),this.suppressEmptyPar=!1}}const pt=new Map([["emdash","—"],["endash","–"],["lquote","‘"],["rquote","’"],["ldblquote","“"],["rdblquote","”"],["bullet","•"],["emspace"," "],["enspace"," "],["qmspace"," "],["zwj",""],["zwnj",""],["ltrmark",""],["rtlmark",""]]),ft=new Set(["info","xmlnstbl","themedata","colorschememapping","latentstyles","datastore","generator","filetbl","rsidtbl","nonshppict","objdata","objclass","objname","shpinst","shptxt","userprops","docvar","pgdsctbl","mmathPr","bkmkstart","bkmkend","xe","tc","txe","template","private","passwordhash","wgrffmtfilter","defchp","defpap","listpicture","pnseclvl","protusertbl","fchars","lchars","aftnsep","aftnsepc","aftncn","ftnsep","ftnsepc","ftncn","blipuid","picprop","atnicn","atntime","do","falt","panose","fname","oldcprops","oldpprops","oldtprops","oldsprops","annotation-ignore"]),gt=new Set(["expandedcolortbl","listtable","listoverridetable","shppict","fldinst","annotation","atnauthor","atnid","atnref","atndate","atrfstart","atrfend","pn","revtbl","footnote"]),mt=new Set(["pict","footnote","annotation","fldinst","fldrslt","header","headerl","headerr","headerf","footer","footerl","footerr","footerf"]),bt=new Set(["ul","uld","uldash","uldashd","uldashdd","uldb","ulhwave","ulldash","ulth","ulthd","ulthdash","ulthdashd","ulthdashdd","ulthldash","ululdbwave","ulw","ulwave"]),W=new Map([["header","default"],["headerr","default"],["headerl","even"],["headerf","first"],["footer","default"],["footerr","default"],["footerl","even"],["footerf","first"]]);function E(a,t={}){return new kt(a,t).read()}class kt{constructor(t,e){this.rtf=t,this.options=e,this.defaultFont=0,this.fonts=new Map,this.colors=[],this.colorParts={r:0,g:0,b:0},this.colorHasValue=!1,this.expandedIndex=0,this.expandedParts=[],this.styles=new Map,this.currentStyle=null,this.lists=new Map,this.currentList=null,this.listOverrides=new Map,this.currentOverride=null,this.revAuthors=[],this.currentFontEntry=null,this.rowDefs=[],this.pendingCellDef={},this.rowIsHeader=!1,this.body=new L("body"),this.notes=new X("rtffn"),this.headers={},this.footers={},this.comments=[],this.openCommentRanges=[],this.commentMeta={},this.annotationCounter=0,this.commentRangeIds=new Map,this.commentIds=new Set,this.page={margins:{}},this.sectionSeen=!1,this.stack=[],this.marksVersion=0,this.cachedMarksVersion=-1,this.cachedMarks={},this.pendingBytes=[],this.pendingBytesEncoding="",this.chainsSeen=new Set,this.ansiEncoding=ht(t.slice(0,4096)),this.cocoa=/\\cocoartf/.test(t.slice(0,512)),this.state={dest:"body",chars:{},para:{borders:{}},unicodeSkip:1,storyRef:{story:this.body}}}read(){this.tokenize(),this.flushBytes();const t=this.body;this.flushRun(t),t.runs.some(i=>i.text.trim().length>0)&&this.flushParagraph(t);const e=this.buildBlocks(t.items,"body");O(e),e.length===0&&e.push(P());const s={type:"doc",children:e};this.notes.notes.length>0&&(s.notes=this.notes.notes),Object.keys(this.headers).length>0&&(s.headers=this.headers),Object.keys(this.footers).length>0&&(s.footers=this.footers);const r=Z(this.comments,[s.children,s.notes??[]]);r.length>0&&(s.comments=r);const n=this.pageLayout();return n&&(s.pageLayout=n),s}tokenize(){const t=this.rtf,e=t.length,s=/\\([a-zA-Z]{1,32})(-?\d{1,10})? ?/y;let r=0;for(;r<e;){const n=t.charCodeAt(r);if(n===123){this.flushBytes(),this.pushGroup(),r++;continue}if(n===125){this.flushBytes(),this.popGroup(),r++;continue}if(n===10||n===13){r++;continue}if(n!==92){let l=r+1;for(;l<e;){const f=t.charCodeAt(l);if(f===92||f===123||f===125||f===10||f===13)break;l++}this.literal(t.slice(r,l)),r=l;continue}const i=t[r+1];if(i===void 0)break;if(i==="\\"||i==="{"||i==="}"){this.flushBytes(),this.text(i),r+=2;continue}if(i==="'"){const l=parseInt(t.slice(r+2,r+4),16);r+=4,Number.isNaN(l)||this.byte(l);continue}if(this.flushBytes(),i==="*"){this.state.starred=!0,r+=2;continue}if(i==="~"){this.text(" "),r+=2;continue}if(i==="_"){this.text("‑"),r+=2;continue}if(i==="-"){r+=2;continue}if(i===`
|
|
2
|
+
`||i==="\r"){this.controlWord("par",null),r+=2;continue}s.lastIndex=r;const o=s.exec(t);if(!o){r+=2;continue}r+=o[0].length;const c=o[1],d=o[2]!==void 0?parseInt(o[2],10):null;if(c==="bin"&&d!==null&&d>0){this.binary(t.slice(r,r+d)),r+=d;continue}if(c==="u"&&d!==null){this.text(String.fromCharCode(d<0?d+65536:d));let l=this.state.unicodeSkip;for(;l>0&&r<e;){const f=t[r];if(f==="\\")if(t[r+1]==="'")r+=4;else{s.lastIndex=r;const m=s.exec(t);r+=m?m[0].length:2}else{if(f==="{"||f==="}")break;if(f===`
|
|
3
|
+
`||f==="\r"){r+=1;continue}else r+=1}l--}continue}this.controlWord(c,d)}}pushGroup(){const t=this.state;this.stack.push(t),this.state={dest:t.dest,chars:{...t.chars},para:{...t.para,borders:{...t.para.borders}},unicodeSkip:t.unicodeSkip,storyRef:t.storyRef,field:t.field,link:t.link,fieldKind:t.fieldKind,capture:void 0,metaKind:t.dest==="meta"?t.metaKind:void 0},(t.dest==="listtext"||t.dest==="fldinst"||t.dest==="meta")&&(this.state.capture=t.capture),this.marksVersion++}popGroup(){const t=this.state,e=this.stack.pop();e&&(this.endGroup(t,e),this.state=e,this.marksVersion++)}endGroup(t,e){switch(t.dest){case"pict":t.pict&&t.pict!==e.pict&&this.finishPicture(t.pict,t);break;case"fonttbl":t.capture&&t.capture!==e.capture&&this.finishFontName(t.capture.text);break;case"stylesheet":t.capture&&t.capture!==e.capture&&this.finishStyle(t.capture.text);break;case"listtext":e.dest!=="listtext"&&t.capture&&(t.storyRef.story.listText=t.capture.text);break;case"fldinst":e.dest!=="fldinst"&&t.capture&&t.field&&(t.field.instr=t.capture.text);break;case"meta":e.dest!=="meta"&&t.capture&&t.metaKind&&this.finishMeta(t.metaKind,t.capture.text.trim());break;case"revtbl":if(t.capture&&t.capture!==e.capture)for(const s of t.capture.text.split(";").slice(0,-1))this.revAuthors.push(s.trim());break}t.opensStory&&this.finishStory(t,e)}literal(t){const e=this.state;if(this.flushBytes(),e.dest==="pict"){e.pict?.hex.push(t);return}if(this.options.binary){let s=0;for(let r=0;r<t.length;r++)t.charCodeAt(r)>=128&&(r>s&&(this.flushBytes(),this.text(t.slice(s,r))),this.byte(t.charCodeAt(r)&255),s=r+1);s<t.length&&(this.flushBytes(),this.text(t.slice(s)));return}this.text(t)}byte(t){const e=this.currentEncoding();this.pendingBytes.length>0&&e!==this.pendingBytesEncoding&&this.flushBytes(),this.pendingBytesEncoding=e,this.pendingBytes.push(t)}flushBytes(){if(this.pendingBytes.length===0)return;const t=this.pendingBytes;this.pendingBytes=[],this.text(ut(t,this.pendingBytesEncoding))}currentEncoding(){const t=this.state.chars;return this.fonts.get(t.font??t.lochFont??this.defaultFont)?.encoding??this.ansiEncoding}binary(t){const e=this.state.pict;if(this.state.dest!=="pict"||!e)return;const s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r)&255;(e.binary??(e.binary=[])).push(s)}text(t){if(!t)return;const e=this.state;switch(e.dest){case"body":{const s=e.storyRef.story,r=this.effectiveMarks();J(r,s.runMarks)||(this.flushRun(s),s.runMarks=r),s.runText+=t,s.suppressEmptyPar=!1;return}case"fonttbl":case"stylesheet":case"listtext":case"fldinst":case"meta":e.capture&&(e.capture.text+=t),e.dest==="fonttbl"&&t.includes(";")&&this.fontTableSemicolons(t);return;case"colortbl":for(const s of t)s===";"&&(this.colors.push(this.colorHasValue?$(this.colorParts.r,this.colorParts.g,this.colorParts.b):void 0),this.colorParts={r:0,g:0,b:0},this.colorHasValue=!1);return;case"expandedcolortbl":for(const s of t){if(s!==";")continue;const r=this.expandedParts,n=i=>i/1e5*255;if(r.length>=3)this.colors[this.expandedIndex]=$(n(r[0]),n(r[1]),n(r[2]));else if(r.length===1){const i=n(r[0]);this.colors[this.expandedIndex]=$(i,i,i)}this.expandedParts=[],this.expandedIndex++}return;case"revtbl":e.capture?e.capture.text+=t:e.capture={text:t};return;default:return}}fontTableSemicolons(t){const e=this.state.capture;if(!e)return;const s=e.text.split(";");for(let r=0;r<s.length-1;r++)this.finishFontName(s[r]);e.text=s[s.length-1]}effectiveMarks(){if(this.cachedMarksVersion===this.marksVersion)return this.cachedMarks;const t=this.state,e=t.chars,s={};e.bold&&(s.bold=!0),e.italic&&(s.italic=!0),e.underline&&(s.underline=!0),e.strike&&(s.strikethrough=!0),e.dstrike&&(s.doubleStrikethrough=!0),e.superscript?s.superscript=!0:e.subscript&&(s.subscript=!0),e.caps&&(s.allCaps=!0),e.scaps&&(s.smallCaps=!0),e.hidden&&(s.hidden=!0);const r=this.fonts.get(e.font??e.lochFont??this.defaultFont)?.name;r&&(s.fontFamily=r),e.halfPoints&&e.halfPoints>0&&(s.fontSize=T(e.halfPoints/2*(96/72)));const n=e.color?this.colors[e.color]:void 0;n&&n!=="#000000"&&(s.color=n);const i=(e.highlight?this.colors[e.highlight]:void 0)??(e.background?this.colors[e.background]:void 0);return i&&i!=="#ffffff"&&(s.backgroundColor=i),e.expandTwips&&(s.letterSpacing=T(k(e.expandTwips))),t.link&&(s.link=t.link),t.fieldKind&&(s.field=t.fieldKind),this.openCommentRanges.length>0&&t.storyRef.story.kind!=="annotation"&&(s.comment=this.openCommentRanges.join(",")),e.deleted?Object.assign(s,this.revisionMarks("deletion",e.revAuthorDel??e.revAuthor,e.revTimeDel??e.revTime)):e.revised&&Object.assign(s,this.revisionMarks("insertion",e.revAuthor,e.revTime)),this.cachedMarks=s,this.cachedMarksVersion=this.marksVersion,s}revisionMarks(t,e,s){const r=e!==void 0?this.revAuthors[e]:void 0,n=s!==void 0?V(s):void 0;return Q(t,`rtfrev-${t==="insertion"?"ins":"del"}-${e??0}-${s??0}`,r&&r!=="Unknown"?r:void 0,n)}flushRun(t){t.runText&&(t.runs.push({type:"text",text:t.runText,marks:{...t.runMarks}}),t.runText="")}flushParagraph(t,e=!1){this.flushRun(t);const s=t.runs.filter(r=>r.text.length>0);if(t.runs=[],s.length===0&&t.suppressEmptyPar&&!e){t.suppressEmptyPar=!1,t.listText=void 0,t.paraId=w();return}t.items.push({kind:"para",id:t.paraId,runs:tt(s),para:{...this.state.para,borders:{...this.state.para.borders}},...t.listText!==void 0?{listText:t.listText}:{},...e?{forcedInTable:!0}:{}}),t.listText=void 0,t.suppressEmptyPar=!1,t.paraId=w()}controlWord(t,e){const s=this.state,r=s.starred;if(s.starred=!1,s.dest!=="skip"&&!this.startDestination(t)){if(r&&!gt.has(t)){s.dest="skip";return}if(ft.has(t)){s.dest="skip";return}switch(s.dest){case"fonttbl":this.fontTableWord(t,e);return;case"colortbl":this.colorTableWord(t,e);return;case"expandedcolortbl":t==="c"&&e!==null?this.expandedParts.push(e):(t==="cssrgb"||t==="csgray"||t==="csgenericrgb")&&(this.expandedParts=[]);return;case"stylesheet":this.styleSheetWord(t,e);return;case"listtable":this.listTableWord(t,e);return;case"listoverridetable":this.listOverrideWord(t,e);return;case"pict":this.pictWord(t,e);return;case"pn":this.pnWord(t,e);return;case"listtext":case"fldinst":case"meta":t==="tab"&&this.text(" ");return;case"revtbl":return}if(this.characterWord(t,e)){this.marksVersion++;return}this.paragraphWord(t,e)||this.structureWord(t,e)}}startDestination(t){const e=this.state;if(e.dest!=="body"&&mt.has(t))return e.dest="skip",!0;switch(t){case"fonttbl":return e.dest="fonttbl",e.capture={text:""},!0;case"colortbl":return e.dest="colortbl",this.colors=[],!0;case"expandedcolortbl":return e.dest="expandedcolortbl",this.expandedIndex=0,this.expandedParts=[],!0;case"stylesheet":return e.dest="stylesheet",!0;case"listtable":return e.dest="listtable",!0;case"listoverridetable":return e.dest="listoverridetable",!0;case"revtbl":return e.dest="revtbl",!0;case"pict":return e.dest="pict",e.pict={hex:[]},!0;case"shppict":case"shprslt":case"result":case"shp":case"object":case"field":return t==="field"&&(e.field={instr:""}),!0;case"fldinst":return e.dest="fldinst",e.capture={text:""},!0;case"fldrslt":{const s=e.field?.instr??"",r=/^\s*HYPERLINK\s+(?:\\[a-z]\s+)*"([^"]+)"/i.exec(s);return r&&!/^\s*HYPERLINK\s+\\l\b/i.test(s)&&(e.link=et(r[1])),/^\s*PAGE\b/i.test(s)&&(e.fieldKind="page"),/^\s*NUMPAGES\b/i.test(s)&&(e.fieldKind="numPages"),this.marksVersion++,!0}case"listtext":case"pntext":return e.dest="listtext",e.capture={text:""},!0;case"pn":return e.dest="pn",e.para.pn={kind:"number",level:0},!0;case"footnote":return this.openStory("footnote");case"annotation":return this.openStory("annotation");case"atnauthor":case"atnid":case"atnref":case"atndate":case"atrfstart":case"atrfend":return e.dest="meta",e.metaKind=t,e.capture={text:""},!0;default:return W.has(t)?(e.dest="body",e.opensStory=!0,e.storyRef={story:new L("header")},e.para={borders:{}},e.headerWord=t,!0):!1}}openStory(t){const e=this.state;return e.dest="body",e.opensStory=!0,e.storyRef={story:new L(t)},e.para={borders:{}},e.link=void 0,t==="annotation"&&(this.annotationRef=void 0,this.annotationDate=void 0),this.marksVersion++,!0}finishStory(t,e){const s=t.storyRef.story;if(this.flushRun(s),s.runs.some(i=>i.text.length>0)){const i=this.state;this.state=t,this.flushParagraph(s),this.state=i}const r=this.buildBlocks(s.items,s.kind);O(r);const n=e.storyRef.story;if(s.kind==="footnote"||s.kind==="endnote"){if(e.dest!=="body")return;this.flushRun(n),this.state=e,this.marksVersion++;const i=this.effectiveMarks(),o=this.notes.add(s.kind,r,i);n.runs.push(o),n.runMarks={},this.marksVersion++;return}if(s.kind==="header"){const i=t.headerWord??"header",o=W.get(i)??"default",c=r.filter(d=>d.type==="paragraph");if(c.some(d=>d.children.some(l=>l.text.trim()!==""||l.marks?.field))){const d=i.startsWith("footer")?this.footers:this.headers;d[o]=c}return}if(s.kind==="annotation"){const i=r.map(l=>l.type==="paragraph"?l.children.map(f=>f.text).join("").trim():"").filter(l=>l.length>0).join(`
|
|
4
|
+
|
|
5
|
+
`);this.annotationCounter++;const o=this.annotationRef;let c=`rtfcmt-${o??`point-${this.annotationCounter}`}`,d=o!==void 0&&this.commentRangeIds.has(o);if(this.commentIds.has(c)){d=!1;let l=this.annotationCounter;for(;this.commentIds.has(`${c}-${l}`);)l++;c=`${c}-${l}`}this.commentIds.add(c),this.comments.push({id:c,author:this.commentMeta.author||this.commentMeta.initials||"Unknown",...this.commentMeta.initials?{initials:this.commentMeta.initials}:{},createdAt:new Date(this.annotationDate!==void 0?V(this.annotationDate)??0:0).toISOString(),bodyMd:i,...d?{}:{anchorBlockId:n.paraId}}),this.commentMeta={}}}finishMeta(t,e){switch(t){case"atnauthor":this.commentMeta.author=e;break;case"atnid":this.commentMeta.initials=e;break;case"atnref":this.annotationRef=e;break;case"atndate":{const s=parseInt(e,10);Number.isFinite(s)&&(this.annotationDate=s);break}case"atrfstart":e&&(this.commentRangeIds.set(e,`rtfcmt-${e}`),this.openCommentRanges=[...this.openCommentRanges,`rtfcmt-${e}`],this.marksVersion++);break;case"atrfend":e&&(this.openCommentRanges=this.openCommentRanges.filter(s=>s!==`rtfcmt-${e}`),this.marksVersion++);break}}fontTableWord(t,e){if(t==="f"&&e!==null){const r=this.state.capture;r&&r.text.trim()&&this.currentFontEntry!==null&&this.finishFontName(r.text),this.currentFontEntry=e,this.fonts.has(e)||this.fonts.set(e,{name:""}),this.state.capture={text:""};return}const s=this.currentFontEntry!==null?this.fonts.get(this.currentFontEntry):void 0;if(s)if(t==="fcharset"&&e!==null){const r=dt[e];r&&(s.encoding=C(r)),e===2&&(s.encoding="windows-1252")}else t==="cpg"&&e!==null&&e>0&&(s.encoding=C(e))}finishFontName(t){if(this.currentFontEntry===null)return;const e=this.fonts.get(this.currentFontEntry),s=t.replace(/;$/,"").trim();e&&s&&!e.name&&(e.name=this.cocoa?St(s):s)}colorTableWord(t,e){if(e!==null){if(t==="red")this.colorParts.r=e;else if(t==="green")this.colorParts.g=e;else if(t==="blue")this.colorParts.b=e;else return;this.colorHasValue=!0}}styleSheetWord(t,e){const s=this.state;t==="s"&&e!==null?(this.currentStyle={index:e},s.capture={text:""}):t==="outlinelevel"&&e!==null&&this.currentStyle&&(this.currentStyle.outlineLevel=e)}finishStyle(t){if(!this.currentStyle)return;const e=t.replace(/;[\s\S]*$/,"").trim();this.styles.set(this.currentStyle.index,{name:e,outlineLevel:this.currentStyle.outlineLevel}),this.currentStyle=null}listTableWord(t,e){switch(t){case"list":this.currentList={def:{levels:[]}};break;case"listlevel":this.currentList?.def.levels.push({nfc:0,startAt:1});break;case"levelnfc":case"levelnfcn":{const s=this.currentList?.def.levels.at(-1);s&&e!==null&&(s.nfc=e);break}case"levelstartat":{const s=this.currentList?.def.levels.at(-1);s&&e!==null&&(s.startAt=e);break}case"listid":this.currentList&&e!==null&&(this.currentList.id=e,this.lists.set(e,this.currentList.def));break}}listOverrideWord(t,e){t==="listoverride"?this.currentOverride={}:t==="listid"&&this.currentOverride&&e!==null?this.currentOverride.listId=e:t==="ls"&&this.currentOverride&&e!==null&&(this.currentOverride.ls=e);const s=this.currentOverride;s?.listId!==void 0&&s.ls!==void 0&&this.listOverrides.set(s.ls,s.listId)}pnWord(t,e){const s=this.state.para.pn;if(!s)return;t==="pnlvlblt"?s.kind="bullet":/^pn(dec|ucltr|lcltr|ucrm|lcrm|ord|ordt|cardt)$/.test(t)?s.kind="number":t==="pnlvl"&&e!==null&&(s.level=Math.max(0,e-1));const r=this.stack[this.stack.length-1];r&&(r.para.pn={...s})}pictWord(t,e){const s=this.state.pict;if(s)switch(t){case"pngblip":s.format="png";break;case"jpegblip":s.format="jpeg";break;case"emfblip":s.format="emf";break;case"wmetafile":s.format="wmf";break;case"macpict":case"dibitmap":case"wbitmap":case"pmmetafile":s.format??(s.format="unsupported");break;case"picw":e!==null&&(s.picw=e);break;case"pich":e!==null&&(s.pich=e);break;case"picwgoal":e!==null&&(s.goalW=e);break;case"pichgoal":e!==null&&(s.goalH=e);break;case"picscalex":e!==null&&(s.scaleX=e);break;case"picscaley":e!==null&&(s.scaleY=e);break}}finishPicture(t,e){let s;if(t.binary&&t.binary.length>0){const b=t.binary.reduce((u,p)=>u+p.length,0);s=new Uint8Array(b);let h=0;for(const u of t.binary)s.set(u,h),h+=u.length}else s=vt(t.hex.join(""));if(s.length===0)return;const r=t.format&&t.format!=="unsupported"?t.format:void 0,n=st(s)??r;if(!n)return;const i=n==="emf"||n==="wmf",o=(t.scaleX??100)/100,c=(t.scaleY??100)/100,d=(b,h)=>b?k(b):h?i?h/2540*96:h:void 0,l=d(t.goalW,t.picw),f=d(t.goalH,t.pich),m=e.storyRef.story,M=e.para;if(this.flushRun(m),m.runs.some(b=>b.text.length>0)){const b=this.state;this.state=e,this.flushParagraph(m),this.state=b}else m.runs=[];const I=M.align==="justify"?void 0:M.align;m.items.push({kind:"image",image:rt(s,n,{width:l!==void 0?l*o:void 0,height:f!==void 0?f*c:void 0},{align:I}),inTable:!!M.inTable}),m.suppressEmptyPar=!0}characterWord(t,e){const s=this.state.chars,r=e!==0;if(bt.has(t))return s.underline=r,!0;switch(t){case"plain":{const{revised:n,deleted:i,revAuthor:o,revTime:c,revAuthorDel:d,revTimeDel:l}=s;return this.state.chars={revised:n,deleted:i,revAuthor:o,revTime:c,revAuthorDel:d,revTimeDel:l},!0}case"b":return s.bold=r,!0;case"i":return s.italic=r,!0;case"ulnone":return s.underline=!1,!0;case"strike":return s.strike=r,!0;case"striked":return s.dstrike=r,!0;case"super":return s.superscript=r,s.subscript=!1,!0;case"sub":return s.subscript=r,s.superscript=!1,!0;case"nosupersub":return s.superscript=!1,s.subscript=!1,!0;case"caps":return s.caps=r,!0;case"scaps":return s.scaps=r,!0;case"v":return s.hidden=r,!0;case"f":return e!==null&&(s.font=e),!0;case"loch":case"hich":case"dbch":return s.script=t,!0;case"rtlch":case"ltrch":return s.script=void 0,!0;case"af":return e!==null&&(s.script==="loch"||s.script==="hich")&&(s.lochFont=e),!0;case"fs":return e!==null&&(s.halfPoints=e),!0;case"fsmilli":return e!==null&&(s.halfPoints=e/1e3*2),!0;case"cf":return s.color=e??0,!0;case"highlight":return s.highlight=e??0,!0;case"cb":case"chcbpat":return s.background=e??0,!0;case"expndtw":return s.expandTwips=e??0,!0;case"expnd":return s.expandTwips===void 0&&e!==null&&(s.expandTwips=e*5),!0;case"revised":return s.revised=r,!0;case"deleted":return s.deleted=r,!0;case"revauth":return e!==null&&(s.revAuthor=e),!0;case"revdttm":return e!==null&&(s.revTime=e),!0;case"revauthdel":return e!==null&&(s.revAuthorDel=e),!0;case"revdttmdel":return e!==null&&(s.revTimeDel=e),!0;default:return!1}}paragraphWord(t,e){const s=this.state.para;switch(t){case"pard":return this.state.para={borders:{}},!0;case"qc":return s.align="center",!0;case"qr":return s.align="right",!0;case"qj":case"qd":return s.align="justify",!0;case"ql":return s.align=void 0,!0;case"li":case"lin":return e!==null&&(s.leftTwips=e),!0;case"fi":return e!==null&&(s.firstTwips=e),!0;case"sb":return e!==null&&(s.spaceBeforeTwips=e),!0;case"sa":return e!==null&&(s.spaceAfterTwips=e),!0;case"sl":return s.lineTwips=e??0,!0;case"slmult":return s.lineMultiple=e===1,!0;case"keepn":return s.keepNext=e!==0,!0;case"keep":return s.keepLines=e!==0,!0;case"rtlpar":return s.rtl=!0,!0;case"ltrpar":return s.rtl=!1,!0;case"s":return e!==null&&(s.style=e),!0;case"outlinelevel":return e!==null&&(s.outlineLevel=e),!0;case"intbl":return s.inTable=e!==0,!0;case"itap":return e!==null&&(s.inTable=e>0),!0;case"ls":return e!==null&&(s.ls=e),!0;case"ilvl":return e!==null&&(s.ilvl=e),!0;case"cbpat":return e!==null&&(s.shading=e),!0;case"pagebb":return s.pageBreakBefore=e!==0,!0;case"brdrt":case"brdrb":case"brdrl":case"brdrr":case"box":{const r=t==="box"?["top","bottom","left","right"]:[{brdrt:"top",brdrb:"bottom",brdrl:"left",brdrr:"right"}[t]];for(const n of r)s.borders[n]={style:"single",width:1,color:"#000000"};return s.borderTarget=t==="box"?"box":r[0],!0}case"brdrs":case"brdrth":case"brdrsh":case"brdrdb":case"brdrdash":case"brdrdashsm":case"brdrdot":case"brdrnone":case"brdrw":case"brdrcf":{const r=s.borderTarget;if(!r||r==="ignore")return!0;const n=r==="box"?["top","bottom","left","right"]:[r];for(const i of n){const o=s.borders[i];o&&(t==="brdrnone"?delete s.borders[i]:t==="brdrdb"?o.style="double":t==="brdrdash"||t==="brdrdashsm"?o.style="dashed":t==="brdrdot"?o.style="dotted":t==="brdrth"?(o.style="single",o.width=Math.max(o.width,2)):t==="brdrw"&&e!==null?o.width=Math.min(8,Math.max(1,Math.round(e/15))):t==="brdrcf"&&e!==null?o.color=this.colors[e]??o.color:(t==="brdrs"||t==="brdrsh")&&(o.style="single"))}return!0}default:return/^(tr|cl|pg)brdr[tblrhv]$|^brdrbtw$|^brdrbar$/.test(t)?(s.borderTarget="ignore",!(t.startsWith("cl")||t.startsWith("tr"))):!1}}structureWord(t,e){const s=this.state.storyRef.story,r=this.state.dest==="body";switch(t){case"par":r&&this.flushParagraph(s);return;case"sect":r&&(s.runs.length>0||s.runText)&&this.flushParagraph(s),this.sectionSeen=!0;return;case"line":this.text(`
|
|
6
|
+
`);return;case"tab":this.text(" ");return;case"page":if(!r||s.kind!=="body")return;this.flushRun(s),s.runs.some(n=>n.text.length>0)&&this.flushParagraph(s),s.runs=[],s.items.push({kind:"pagebreak",inTable:!!this.state.para.inTable}),s.suppressEmptyPar=!0;return;case"cell":case"nestcell":if(!r)return;this.flushParagraph(s,!0),t==="cell"&&s.items.push({kind:"cell"});return;case"row":if(!r)return;this.flushRun(s),s.runs.some(n=>n.text.length>0)&&(this.flushParagraph(s,!0),s.items.push({kind:"cell"})),s.runs=[],s.items.push({kind:"row",defs:this.rowDefs.slice(),header:this.rowIsHeader});return;case"trowd":this.rowDefs=[],this.pendingCellDef={},this.rowIsHeader=!1;return;case"trhdr":this.rowIsHeader=!0;return;case"clmgf":this.pendingCellDef.hmergeFirst=!0;return;case"clmrg":this.pendingCellDef.hmergeCont=!0;return;case"clvmgf":this.pendingCellDef.vmergeFirst=!0;return;case"clvmrg":this.pendingCellDef.vmergeCont=!0;return;case"clcbpat":e!==null&&(this.pendingCellDef.background=e);return;case"clvertalt":this.pendingCellDef.valign="top";return;case"clvertalc":this.pendingCellDef.valign="middle";return;case"clvertalb":this.pendingCellDef.valign="bottom";return;case"cellx":e!==null&&(this.rowDefs.push({right:e,...this.pendingCellDef}),this.pendingCellDef={});return;case"chftn":case"chatn":case"chpgn":t==="chpgn"&&r&&s.kind==="header"&&(this.state.fieldKind="page",this.marksVersion++,this.text("1"),this.state.fieldKind=void 0,this.marksVersion++);return;case"ftnalt":s.kind==="footnote"&&(s.kind="endnote");return;case"uc":this.state.unicodeSkip=e??1;return;case"deff":e!==null&&(this.defaultFont=e);return;case"paperw":case"pgwsxn":e!==null&&(!this.sectionSeen||this.page.widthTwips===void 0)&&(this.page.widthTwips=e);return;case"paperh":case"pghsxn":e!==null&&(!this.sectionSeen||this.page.heightTwips===void 0)&&(this.page.heightTwips=e);return;case"landscape":case"lndscpsxn":this.page.landscape=!0;return;case"margl":case"margr":case"margt":case"margb":case"marglsxn":case"margrsxn":case"margtsxn":case"margbsxn":{if(e===null)return;const n=t.slice(4,5);if(t.endsWith("sxn")&&this.sectionSeen)return;this.page.margins[n]=e;return}default:{const n=pt.get(t);n!==void 0&&this.text(n)}}}buildBlocks(t,e){const s=[],r=i=>i.kind==="cell"||i.kind==="row"||i.kind==="para"&&(!!i.para.inTable||!!i.forcedInTable)||(i.kind==="image"||i.kind==="pagebreak")&&i.inTable;let n=0;for(;n<t.length;){const i=t[n];if(e!=="header"&&r(i)){const o=n;for(;n<t.length&&r(t[n]);)n++;const c=this.buildTable(t.slice(o,n),e);c&&s.push(...c);continue}if(i.kind==="para"){const o=this.listInfo(i);if(o&&e!=="header"){const c=[{item:i,info:o}];for(n++;n<t.length;){const d=t[n];if(d.kind!=="para"||r(d))break;const l=this.listInfo(d);if(!l||l.key!==o.key)break;c.push({item:d,info:l}),n++}s.push(this.buildList(c));continue}i.para.pageBreakBefore&&e==="body"&&s.length>0&&s.push({type:"page-break",id:w()}),s.push(this.buildParagraph(i,e)),n++;continue}i.kind==="image"?s.push(i.image):i.kind==="pagebreak"&&s.push({type:"page-break",id:w()}),n++}return s}buildParagraph(t,e){const s=t.runs.length>0?t.runs:[{type:"text",text:"",marks:{}}],r=P(s);r.id=t.id;const n=t.para;if(n.align&&(r.align=n.align),n.rtl&&(r.direction="rtl"),e!=="header"){const i=this.headingLevel(n);if(i&&(r.heading=i),n.leftTwips!==void 0){const c=nt(k(n.leftTwips));c&&(r.leftIndent=c)}if(n.firstTwips!==void 0){const c=it(k(n.firstTwips));c&&(r.firstLineIndent=c)}n.spaceBeforeTwips!==void 0&&(r.spaceBefore=T(k(Math.max(0,n.spaceBeforeTwips)))),n.spaceAfterTwips!==void 0&&(r.spaceAfter=T(k(Math.max(0,n.spaceAfterTwips)))),n.lineMultiple&&n.lineTwips&&n.lineTwips>0&&(r.lineSpacing=T(n.lineTwips/240)),n.keepNext&&(r.keepNext=!0),n.keepLines&&(r.keepLines=!0);const o=n.shading?this.colors[n.shading]:void 0;o&&o!=="#ffffff"&&(r.shading=o),Object.keys(n.borders).length>0&&(r.borders=JSON.stringify(n.borders))}return r}headingLevel(t){let e;if(t.outlineLevel!==void 0&&t.outlineLevel<9&&(e=t.outlineLevel+1),e===void 0&&t.style!==void 0){const s=this.styles.get(t.style),r=s?.name&&/^heading\s*(\d)$/i.exec(s.name);r?e=parseInt(r[1],10):s?.outlineLevel!==void 0&&s.outlineLevel<9&&(e=s.outlineLevel+1)}if(!(!e||e<1))return Math.min(e,6)}listInfo(t){const e=t.para;if(!this.headingLevel(e)){if(e.ls!==void 0&&e.ls>0){const s=this.listOverrides.get(e.ls),r=s!==void 0?this.lists.get(s):void 0,n=Math.max(0,Math.min(8,e.ilvl??0));if(r){const i=r.levels[n]??r.levels[0];if(i&&i.nfc===255&&t.listText===void 0)return;const o=i?i.nfc!==23&&i.nfc!==255:!1;return{key:`ls${e.ls}`,ordered:o,level:n,startAt:r.levels[0]?.startAt??1,chain:`rtf-ls-${e.ls}`}}return{key:`ls${e.ls}`,ordered:t.listText!==void 0&&F(t.listText),level:n,startAt:1,chain:`rtf-ls-${e.ls}`}}if(e.pn)return{key:`pn-${e.pn.kind}`,ordered:e.pn.kind==="number",level:e.pn.level,startAt:1};if(t.listText!==void 0&&t.listText.trim()!==""){const s=F(t.listText);return{key:`lt-${s}`,ordered:s,level:0,startAt:1}}}}buildList(t){const e=t[0].info,s=t.map(({item:i,info:o})=>{const c=i.runs.length>0?i.runs:[{type:"text",text:"",marks:{}}];return{type:"list-item",id:i.id,children:c,...o.level>0?{indentLevel:o.level}:{},...i.para.rtl?{direction:"rtl"}:{}}}),r={type:"list",id:w(),variant:e.ordered?"ordered":"unordered",children:s};e.ordered&&e.chain?(r.numberingChainId=e.chain,this.chainsSeen.has(e.chain)||(this.chainsSeen.add(e.chain),e.startAt!==1&&(r.startNumber=e.startAt))):e.ordered&&e.startAt!==1&&(r.startNumber=e.startAt);const n=t[0].item.para;return n.spaceAfterTwips!==void 0&&(r.spaceAfter=T(k(Math.max(0,n.spaceAfterTwips)))),n.spaceBeforeTwips!==void 0&&(r.spaceBefore=T(k(Math.max(0,n.spaceBeforeTwips)))),n.lineMultiple&&n.lineTwips&&n.lineTwips>0&&(r.lineSpacing=T(n.lineTwips/240)),r}buildTable(t,e){const s=[];let r=[],n=[],i=[];for(const h of t)h.kind==="cell"?(r.push({items:n}),n=[]):h.kind==="row"?(n.length>0&&(r.push({items:n}),n=[]),s.push({cells:r,defs:h.defs.length>0?h.defs:i,header:h.header}),h.defs.length>0&&(i=h.defs),r=[]):n.push(h);if(n.length>0&&r.push({items:n}),r.length>0&&s.push({cells:r,defs:i,header:!1}),s.length===0)return null;const o=new Set([0]),c=s.map(h=>{const u=[];let p=0,g=0;const A=h.defs.length>0?h.defs[h.defs.length-1].right/Math.max(1,h.defs.length):1440;return h.cells.forEach((R,S)=>{const x=h.defs[S],v=x?x.right:g+Math.max(1,Math.round(A));if(x?.hmergeCont&&u.length>0){const N=u[u.length-1];N.right=v,N.items.push(...R.items.filter(H=>!wt(H)))}else u.push({left:p,right:Math.max(v,p+1),def:x,items:R.items});p=v,g=v}),u}),d=0;for(const h of c)for(const u of h)o.add(Math.max(d,u.left)),o.add(u.right);const l=xt(yt([...o].sort((h,u)=>h-u),30),at(c.length)),f=h=>{let u=0,p=l.length-1;for(;u<p;){const g=u+p>>1;l[g]<h?u=g+1:p=g}return u>0&&Math.abs(l[u-1]-h)<=Math.abs(l[u]-h)?u-1:u},m=[],M=new Map;c.forEach(h=>{const u=[];for(const p of h){const g=f(p.left),A=Math.max(g+1,f(p.right));if(p.def?.vmergeCont){const v=M.get(g);if(v){v.rowSpan=(v.rowSpan??1)+1;continue}}const R=this.buildBlocks(p.items.map(v=>Tt(v)),e);Mt(R);const S={type:"table-cell",id:w(),children:R.length>0?R:[P()]};A-g>1&&(S.colSpan=A-g);const x=p.def?.background?this.colors[p.def.background]:void 0;x&&x!=="#ffffff"&&(S.backgroundColor=x),p.def?.valign&&p.def.valign!=="top"&&(S.verticalAlign=p.def.valign),p.def?.vmergeFirst?M.set(g,S):M.delete(g),u.push(S)}m.push({type:"table-row",id:w(),children:u})});const I=[];for(let h=1;h<l.length;h++)I.push(l[h]-l[h-1]);const b=ot(m,{columnWidths:I,hasHeader:s[0]?.header});return b?[b]:null}pageLayout(){const t=this.page,e=s=>t.margins[s]!==void 0?k(t.margins[s]):void 0;return lt({widthPx:t.widthTwips?k(t.widthTwips):void 0,heightPx:t.heightTwips?k(t.heightTwips):void 0,landscape:t.landscape,marginTopPx:e("t"),marginRightPx:e("r"),marginBottomPx:e("b"),marginLeftPx:e("l")})}}function F(a){const t=a.replace(/[\t\s]+/g,"");return/^(\d+|[a-zA-Z]|[ivxlcdm]+|[IVXLCDM]+)[.)]?$/.test(t)&&t.length>0}function vt(a){const t=a.replace(/[^0-9a-fA-F]/g,""),e=new Uint8Array(t.length>>1);for(let s=0;s<e.length;s++)e[s]=parseInt(t.slice(s*2,s*2+2),16);return e}function yt(a,t){const e=[];for(const s of a)(e.length===0||s-e[e.length-1]>t)&&e.push(s);return e}function xt(a,t){if(a.length-1<=t)return a;const e=a.length-1,s=[];for(let r=0;r<=t;r++)s.push(a[Math.round(r*e/t)]);return s}function wt(a){return a.kind==="para"&&a.runs.every(t=>t.text.trim()==="")}function Tt(a){return a.kind==="para"?{...a,forcedInTable:!1,para:{...a.para,inTable:!1}}:a.kind==="image"||a.kind==="pagebreak"?{...a,inTable:!1}:a}function B(a){return a.type==="paragraph"&&!a.borders&&a.children.every(t=>t.text.trim()===""&&!t.marks?.footnoteRef)}function O(a){for(;a.length>0&&B(a[0]);)a.shift();for(;a.length>0&&B(a[a.length-1]);)a.pop()}function Mt(a){for(;a.length>1&&B(a[a.length-1]);)a.pop()}function V(a){const t=a>>>0;if(t===0)return;const e=t&63,s=t>>>6&31,r=t>>>11&31,n=t>>>16&15,i=(t>>>20&511)+1900;if(!(n<1||n>12||r<1))return Date.UTC(i,n-1,r,s,e)}function St(a){if(a.startsWith("."))return"";if(/\s/.test(a))return a;let t=a.replace(/-(Regular|Roman|Book|Bold|Italic|Oblique|BoldItalic|BoldOblique|Light|LightItalic|Medium|MediumItalic|Semibold|SemiBold|SemiboldItalic|Heavy|Black|Condensed|Thin|UltraLight)$/,"");return t=t.replace(/(PSMT|PS|MT)$/,""),t=t.replace(/([a-z])([A-Z])/g,"$1 $2"),t}const D=class{static async parseFile(t){const e=new Uint8Array(await t.arrayBuffer());let s="";const r=32768;for(let n=0;n<e.length;n+=r)s+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+r)));return E(s,{binary:!0})}static fromRtf(t){return E(t)}static toRtf(t){t=q(t),this.exportListNumbering=K(t);const e=[];for(const s of t.children){const r=this.blockToRtf(s,t);r!==null&&e.push(r)}return this.exportListNumbering=null,`{\\rtf1\\ansi\\ansicpg1252\\deff0\\uc1{\\fonttbl{\\f0\\froman Times New Roman;}{\\f1\\fmodern Courier New;}}
|
|
7
|
+
\\f0\\fs24
|
|
8
|
+
`+e.join(`
|
|
9
|
+
`)+`
|
|
10
|
+
}`}static blockToRtf(t,e){switch(t.type){case"paragraph":return z(t)?"\\pard\\brdrb\\brdrs\\brdrw15 \\par":this.paragraphToRtf(t);case"list":return this.listToRtf(t);case"table":return this.tableToRtf(t);case"code":return"\\pard{\\f1\\fs20 "+y(t.content).replace(/\n/g,"\\line ")+"}\\par";case"math":return"\\pard "+y(t.content)+"\\par";case"toc":{const s=U(e,G(t));return s.length===0?null:s.map(r=>`\\pard${t.direction==="rtl"?"\\rtlpar":"\\ltrpar"}${t.align==="justify"?"\\qj":t.align==="center"?"\\qc":(t.align??(t.direction==="rtl"?"right":"left"))==="right"?"\\qr":"\\ql"}\\${t.direction==="rtl"?"ri":"li"}${(r.level-1)*360} `+y(r.text)+"\\par").join(`
|
|
11
|
+
`)}case"image":return"\\pard{\\i [Image"+(t.alt?`: ${y(t.alt)}`:"")+"]}\\par";case"page-break":return"\\page";case"container":return t.children.map(s=>this.blockToRtf(s,e)).filter(s=>s!==null).join(`
|
|
12
|
+
`);default:return null}}static paragraphToRtf(t){let e="\\pard";t.align==="center"?e+="\\qc":t.align==="right"?e+="\\qr":t.align==="justify"&&(e+="\\qj");let s=this.inlineNodesToRtf(t.children);return t.heading&&(s=`{\\b\\fs${this.HEADING_HALF_POINTS[t.heading-1]} ${s}}`),`${e} ${s}\\par`}static listToRtf(t){const e=this.exportListNumbering?.get(t.id);let s=e?_(e):t.startNumber??1;const r=[];for(const n of t.children){if(n.type!=="list-item")continue;const i=((n.indentLevel??0)+1)*360;let o;t.variant==="ordered"?(o=`${s}. `,s++):t.variant==="todo"?o=n.checked?"[x] ":"[ ] ":o="\\bullet ",r.push(`\\pard\\li${i} ${o}`+this.inlineNodesToRtf(n.children)+"\\par")}return r.join(`
|
|
13
|
+
`)}static tableToRtf(t){if(!t.children||t.children.length===0)return"";const e=Y(t),s=9360,r=[];for(let n=0;n<e.rows;n++){const i=["\\trowd\\trgaph108"];for(let o=0;o<e.cols;o++)i.push(`\\cellx${Math.round(s*(o+1)/e.cols)}`);for(let o=0;o<e.cols;o++){const c=e.occupancy[n][o];let d="";c&&c.row===n&&c.col===o&&(d=c.cell.children.map(l=>l.type==="paragraph"?this.inlineNodesToRtf(l.children):l.type==="code"?y(l.content):"").filter(l=>l.length>0).join("\\line ")),i.push(`\\pard\\intbl ${d}\\cell`)}i.push("\\row"),r.push(i.join(""))}return r.join(`
|
|
14
|
+
`)+`
|
|
15
|
+
\\pard`}static inlineNodesToRtf(t){return t.map(e=>this.textNodeToRtf(e)).join("")}static textNodeToRtf(t){if(t.marks?.footnoteRef)return`{\\super ${y(t.text)}}`;const e=y(t.text).replace(/\n/g,"\\line ");if(!t.marks)return e;const s=[];t.marks.bold&&s.push("\\b"),t.marks.italic&&s.push("\\i"),t.marks.underline&&s.push("\\ul"),t.marks.strikethrough&&s.push("\\strike"),t.marks.superscript&&s.push("\\super"),t.marks.subscript&&s.push("\\sub"),t.marks.code&&s.push("\\f1");const r=s.length>0?`{${s.join("")} ${e}}`:e;return t.marks.link?`{\\field{\\*\\fldinst HYPERLINK "${y(t.marks.link)}"}{\\fldrslt ${r}}}`:r}};D.exportListNumbering=null,D.HEADING_HALF_POINTS=[32,28,26,24,22,22];let Rt=D;function y(a){let t="";for(let e=0;e<a.length;e++){const s=a[e];if(s==="\\"||s==="{"||s==="}"){t+="\\"+s;continue}const r=a.charCodeAt(e);if(r<128){t+=s;continue}t+=`\\u${r>32767?r-65536:r}?`}return t}export{Rt as RtfConverter,y as escapeRtfText};
|