revise 2.0.0 → 2.0.1

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.
Files changed (85) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/assets/{historyMaterializeWorker-CoAX9ZAi.js → historyMaterializeWorker-C4uxcZEh.js} +1 -1
  3. package/backend.d.ts +22 -0
  4. package/backend.js +1 -1
  5. package/chunks/AgentPageRenderer-BIf_Fza8.js +1 -0
  6. package/chunks/AgentPageRenderer-DT9sNxEn.js +1 -0
  7. package/chunks/{AttachmentDocumentImporter-dNMtkxrv.js → AttachmentDocumentImporter-BUavYRxO.js} +1 -1
  8. package/chunks/{AttachmentDocumentImporter-DSic_6At.js → AttachmentDocumentImporter-DGwfDJSH.js} +1 -1
  9. package/chunks/{BidiText-B4Hzrjg9.js → BidiText-D7LYTAUL.js} +1 -1
  10. package/chunks/DocumentMutator-CjN7Kk-X.js +31 -0
  11. package/chunks/DocumentScrubber-C9ZZEcYW.js +1 -0
  12. package/chunks/DocumentScrubber-DrgzBlx4.js +1 -0
  13. package/chunks/DocumentScrubber-W0EfGmL-.js +1 -0
  14. package/chunks/{DocxConverter-COV6CjUM.js → DocxConverter-Be3uPNcD.js} +3 -3
  15. package/chunks/{DocxConverter-B7P52lw7.js → DocxConverter-CGYMfz-j.js} +6 -6
  16. package/chunks/{DocxConverter-Cq_zCEJC.js → DocxConverter-DabDLfsu.js} +6 -6
  17. package/chunks/{DocxGraft-CJ12C9WP.js → DocxGraft-B6W7fbh4.js} +1 -1
  18. package/chunks/{DocxGraft-DcmFuUkd.js → DocxGraft-Cj7v78BO.js} +1 -1
  19. package/chunks/DocxGraft-Duvo2cpy.js +1 -0
  20. package/chunks/FileImporter-CjUX2S4s.js +1 -0
  21. package/chunks/FileImporter-DtkbI6rF.js +1 -0
  22. package/chunks/{HtmlConverter-JvRlkQM3.js → HtmlConverter-ikXImzTY.js} +1 -1
  23. package/chunks/{MarkdownConverter-B-tPY7X3.js → MarkdownConverter-CFrcLyO_.js} +2 -2
  24. package/chunks/{OdtConverter-DYHnR4E8.js → OdtConverter-BFT_P8SI.js} +1 -1
  25. package/chunks/OdtConverter-Cnda9T0q.js +1 -0
  26. package/chunks/OdtConverter-WdwwXKVM.js +1 -0
  27. package/chunks/PdfConverter-D7UM58vc.js +21 -0
  28. package/chunks/PdfConverter-TB-QPw29.js +21 -0
  29. package/chunks/PdfConverter-wVP63986.js +21 -0
  30. package/chunks/PdfImportService-Dj1-3L2B.js +2 -0
  31. package/chunks/PdfImportService-OE9G383I.js +2 -0
  32. package/chunks/{RtfConverter-oIwzoqCD.js → RtfConverter-D-oqPWNl.js} +5 -5
  33. package/chunks/{RtfConverter-BQGge3K-.js → RtfConverter-D9zhE07-.js} +5 -5
  34. package/chunks/{RtfConverter-CMfZ4olw.js → RtfConverter-DZgwU-_R.js} +1 -1
  35. package/chunks/{TableBorders-BLkZYt1k.js → TableBorders-BorZS8aZ.js} +1 -1
  36. package/chunks/{TxtConverter-C1lp6dBS.js → TxtConverter-BYazsp6P.js} +3 -3
  37. package/chunks/ar-C8zx2RwP.js +8 -0
  38. package/chunks/backend-MFpDFVrD.js +1 -0
  39. package/chunks/base64-BNMNG-lN.js +1 -0
  40. package/chunks/{browser-module-6b2Fq-5C.js → browser-module-BbaxnHNK.js} +1 -1
  41. package/chunks/{browser-module-CkO57IPL.js → browser-module-D2ixluMg.js} +1 -1
  42. package/chunks/capture-qC26xmfy.js +1 -0
  43. package/chunks/{carrier-WgcRSu7a.js → carrier-BWONvrA7.js} +1 -1
  44. package/chunks/de-ByQFqecF.js +8 -0
  45. package/chunks/es-PHpJXv5S.js +8 -0
  46. package/chunks/{footnoteFlatten-CW-DUcgK.js → footnoteFlatten-Bdnn_bz1.js} +1 -1
  47. package/chunks/{graftExport-CVg7PO2A.js → graftExport-CP3h2T88.js} +1 -1
  48. package/chunks/index-CjeGoI2g.js +351 -0
  49. package/chunks/index-D7V8zn4w.js +36 -0
  50. package/chunks/index-DyOcu9mD.js +351 -0
  51. package/chunks/{index.es-DOqegDGr.js → index.es-B97tjxvW.js} +1 -1
  52. package/chunks/{index.es-tXDO0RMv.js → index.es-mTU7Sl3w.js} +1 -1
  53. package/chunks/{jspdf.es.min-CzYti8jo.js → jspdf.es.min-DGiD4mlU.js} +1 -1
  54. package/chunks/{jspdf.es.min-ejWOGhkJ.js → jspdf.es.min-Mykp4BZO.js} +1 -1
  55. package/chunks/{pseudoLocale-CdBtPHRi.js → pseudoLocale-C90lXrPg.js} +1 -1
  56. package/chunks/{pseudoLocale-DEVWLkGC.js → pseudoLocale-UA_TkGrH.js} +1 -1
  57. package/chunks/serverDocumentSession-CRZSb5SO.js +11 -0
  58. package/chunks/signatures-CsL_TjvW.js +1 -0
  59. package/full.js +1 -1
  60. package/index.d.ts +27 -4
  61. package/index.js +1 -1
  62. package/package.json +2 -2
  63. package/root.js +2 -2
  64. package/style.css +1 -1
  65. package/chunks/AgentPageRenderer-C0n4EnuW.js +0 -1
  66. package/chunks/AgentPageRenderer-DURfmiu0.js +0 -1
  67. package/chunks/DocxGraft-CQpvFcYb.js +0 -1
  68. package/chunks/FileImporter-DVnYOJHp.js +0 -1
  69. package/chunks/FileImporter-q9mCch0J.js +0 -1
  70. package/chunks/OdtConverter-Br81BSoJ.js +0 -1
  71. package/chunks/OdtConverter-CQjh0vlo.js +0 -1
  72. package/chunks/PdfConverter-D26rXumc.js +0 -21
  73. package/chunks/PdfConverter-DGZpUSVf.js +0 -21
  74. package/chunks/PdfConverter-DZzVP0-B.js +0 -21
  75. package/chunks/PdfImportService-CBD8TL1k.js +0 -2
  76. package/chunks/PdfImportService-D6uUKGMf.js +0 -2
  77. package/chunks/ar-kgSWdrXF.js +0 -8
  78. package/chunks/backend-Cq-khfdG.js +0 -1
  79. package/chunks/base64-CfDUyGi8.js +0 -36
  80. package/chunks/capture-DU3MC7tb.js +0 -1
  81. package/chunks/de-C2QTHrqo.js +0 -8
  82. package/chunks/es-BKboUn4q.js +0 -8
  83. package/chunks/index-CLw_BlSL.js +0 -353
  84. package/chunks/index-F-kHIwWT.js +0 -353
  85. package/chunks/serverDocumentSession-DZrYbdpk.js +0 -42
@@ -0,0 +1,21 @@
1
+ import{b8 as re,b9 as ut,ba as Gt,bb as Nt,r as Ut,bc as It,Z as zt,a as Kt,t as se,bd as le,be as ce,bf as he,bg as ge,ai as jt,bh as et,aj as $t,aP as de,f as fe,bi as Yt,bj as me,bk as Bt,bl as Et,bm as ft,bn as Pe,bo as ue,bp as pe,bq as Te,C as St,br as xe,ad as be,a_ as ye,aa as vt}from"./backend-MFpDFVrD.js";import{b as _e,s as Fe,o as Se,p as Le,n as we}from"./ListNumbering-Qlu6AuRZ.js";import{y as Vt,z as qt,i as Oe,b as ke,c as Me,A as Ce,B as Re,D as Lt,C as Ne,E as Ie,F as Be,G as Jt,H as Zt,I as Ee,J as Qt,K as te,L as Dt,M as ve,S as ee}from"./index-D7V8zn4w.js";import{m as De,k as Ae,a as Xe,r as We,o as He,b as Ge,q as Ue}from"./TableBorders-BorZS8aZ.js";import{b as ze}from"./TableGrid-DVWaRZv0.js";import{i as Ke,l as je,s as $e,d as Ye}from"./HorizontalRuleOrnaments-gmUZ3R7Q.js";import{b as ae,c as Ve,p as At,K as ie,d as qe}from"./base64-BNMNG-lN.js";import{L as Je,F as yt,l as Xt,o as wt,r as Ze,p as oe,c as Qe,g as ta,q as ea,e as ne,s as aa,i as ia,u as oa}from"./BidiText-D7LYTAUL.js";import{r as Ct,o as na,e as ra,c as sa,a as la}from"./MathRenderer-B0Y1h1JU.js";const Rt=new Map;na(()=>Rt.clear());function ca(ot){const t=String.fromCharCode(...ot.subarray(0,4));return ot[0]===0&&ot[1]===1&&ot[2]===0&&ot[3]===0||t==="true"||t==="OTTO"}function ha(ot){let t="";for(let e=0;e<ot.length;e+=32768)t+=String.fromCharCode(...ot.subarray(e,e+32768));return btoa(t)}async function ga(ot){try{const t=await fetch(Ct(`fonts/${encodeURIComponent(ot)}`),{credentials:"omit"});if(!t.ok)return null;const e=new Uint8Array(await t.arrayBuffer());return ca(e)?ha(e):null}catch{return null}}async function da(ot){let t=Rt.get(ot);return t||(t=ga(ot),Rt.set(ot,t),t.then(e=>{e===null&&Rt.delete(ot)})),t}const J=ot=>({normal:ot,bold:ot}),fa={japanese:{family:"NotoSansJP",probeCodePoint:12354,charRegex:/[\p{Script=Hiragana}\p{Script=Katakana}]/u,files:J("NotoSansJP-Regular.ttf")},korean:{family:"NotoSansKR",probeCodePoint:54620,charRegex:/\p{Script=Hangul}/u,files:J("NotoSansKR-Regular.ttf")},devanagari:{family:"NotoSansDevanagari",probeCodePoint:2309,charRegex:/\p{Script=Devanagari}/u,files:J("NotoSansDevanagari-Regular.ttf"),shape:!0},bengali:{family:"NotoSansBengali",probeCodePoint:2437,charRegex:/\p{Script=Bengali}/u,files:J("NotoSansBengali-Regular.ttf"),shape:!0},gurmukhi:{family:"NotoSansGurmukhi",probeCodePoint:2565,charRegex:/\p{Script=Gurmukhi}/u,files:J("NotoSansGurmukhi-Regular.ttf"),shape:!0},gujarati:{family:"NotoSansGujarati",probeCodePoint:2693,charRegex:/\p{Script=Gujarati}/u,files:J("NotoSansGujarati-Regular.ttf"),shape:!0},oriya:{family:"NotoSansOriya",probeCodePoint:2821,charRegex:/\p{Script=Oriya}/u,files:J("NotoSansOriya-Regular.ttf"),shape:!0},tamil:{family:"NotoSansTamil",probeCodePoint:2949,charRegex:/\p{Script=Tamil}/u,files:J("NotoSansTamil-Regular.ttf"),shape:!0},telugu:{family:"NotoSansTelugu",probeCodePoint:3077,charRegex:/\p{Script=Telugu}/u,files:J("NotoSansTelugu-Regular.ttf"),shape:!0},kannada:{family:"NotoSansKannada",probeCodePoint:3205,charRegex:/\p{Script=Kannada}/u,files:J("NotoSansKannada-Regular.ttf"),shape:!0},malayalam:{family:"NotoSansMalayalam",probeCodePoint:3333,charRegex:/\p{Script=Malayalam}/u,files:J("NotoSansMalayalam-Regular.ttf"),shape:!0},sinhala:{family:"NotoSansSinhala",probeCodePoint:3461,charRegex:/\p{Script=Sinhala}/u,files:J("NotoSansSinhala-Regular.ttf"),shape:!0},thai:{family:"NotoSansThai",probeCodePoint:3585,charRegex:/\p{Script=Thai}/u,files:J("NotoSansThai-Regular.ttf"),shape:!0},lao:{family:"NotoSansLao",probeCodePoint:3713,charRegex:/\p{Script=Lao}/u,files:J("NotoSansLao-Regular.ttf"),shape:!0},khmer:{family:"NotoSansKhmer",probeCodePoint:6016,charRegex:/\p{Script=Khmer}/u,files:J("NotoSansKhmer-Regular.ttf"),shape:!0},myanmar:{family:"NotoSansMyanmar",probeCodePoint:4096,charRegex:/\p{Script=Myanmar}/u,files:J("NotoSansMyanmar-Regular.ttf"),shape:!0},tibetan:{family:"NotoSerifTibetan",probeCodePoint:3904,charRegex:/\p{Script=Tibetan}/u,files:J("NotoSerifTibetan-Regular.ttf"),shape:!0},ethiopic:{family:"NotoSansEthiopic",probeCodePoint:4608,charRegex:/\p{Script=Ethiopic}/u,files:J("NotoSansEthiopic-Regular.ttf")},armenian:{family:"NotoSansArmenian",probeCodePoint:1329,charRegex:/\p{Script=Armenian}/u,files:J("NotoSansArmenian-Regular.ttf")},georgian:{family:"NotoSansGeorgian",probeCodePoint:4304,charRegex:/\p{Script=Georgian}/u,files:J("NotoSansGeorgian-Regular.ttf")},syriac:{family:"NotoSansSyriac",probeCodePoint:1808,charRegex:/\p{Script=Syriac}/u,files:J("NotoSansSyriac-Regular.ttf"),shape:!0},thaana:{family:"NotoSansThaana",probeCodePoint:1920,charRegex:/\p{Script=Thaana}/u,files:J("NotoSansThaana-Regular.ttf"),shape:!0},arabic:{family:"NotoNaskhArabic",probeCodePoint:1575,charRegex:/[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/,files:{normal:"NotoNaskhArabic-Regular.ttf",bold:"NotoNaskhArabic-Bold.ttf"}},hebrew:{family:"NotoSansHebrew",probeCodePoint:1488,charRegex:/[\u0590-\u05FF\uFB1D-\uFB4F]/,files:{normal:"NotoSansHebrew-Regular.ttf",bold:"NotoSansHebrew-Bold.ttf"}},cjkExtensionB:{family:"HanExtBSubset",probeCodePoint:131079,charRegex:/[\u{20000}-\u{207FF}]/u,files:J("HanExtBSubset-Regular.ttf"),shape:!0},han:{family:"NotoSansSC",probeCodePoint:20013,charRegex:/[\p{Script=Han}\p{Script=Bopomofo}\u3000-\u303F\uFE30-\uFE4F\uFF00-\uFFEF]/u,files:J("NotoSansSC-Regular.ttf")},emoji:{family:"NotoEmoji",probeCodePoint:128512,charRegex:/[\p{Extended_Pictographic}\p{Regional_Indicator}]/u,files:J("NotoEmoji-Regular.ttf"),shape:!0},arrows:{family:"NotoSansSymbols",probeCodePoint:8592,charRegex:/[\u2190-\u21FF]/u,files:J("NotoSansSymbols-Regular.ttf")},symbols:{family:"NotoSansSymbols2",probeCodePoint:9728,charRegex:/[\u2300-\u23FF\u2460-\u24FF\u25A0-\u27BF\u2B00-\u2BFF\u{1F000}-\u{1F2FF}]/u,files:J("NotoSansSymbols2-Regular.ttf"),shape:!0}},R=class ct{static async ensureAllLatexRendered(t){const e=[],a=new Set,i=(o,l)=>{const n=`${l}:${o}`;!a.has(n)&&o.trim()&&(a.add(n),e.push({content:o,displayMode:l}))},r=o=>{if(!o||typeof o!="object")return;if(Array.isArray(o)){o.forEach(r);return}const l=o;l.type==="math"&&l.content?i(l.content,l.displayMode!=="inline"):l.type==="text"&&l.marks?.latex&&l.text&&i(l.text,!1),r(l.children)};r(t.children),r(t.chrome),r(t.notes),await Promise.all(e.map(o=>ra(o.content,o.displayMode)))}static getLatexSvgFromCache(t,e){return sa(t,e)}static async svgToPng(t,e,a,i=3){return new Promise(r=>{const o=new Image,l="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(t);o.onload=()=>{try{const n=document.createElement("canvas");n.width=e*i,n.height=a*i;const h=n.getContext("2d");if(!h){r(null);return}h.scale(i,i),h.drawImage(o,0,0,e,a),r(n.toDataURL("image/png"))}catch(n){console.error("Failed to convert SVG to PNG:",n),r(null)}},o.onerror=()=>{r(null)},o.src=l})}static async loadFontFile(t,e=!0){const a=this.fontFileData.get(t);if(a!==void 0)return a;let i=await da(t);try{if(!i){const r=await fetch(Ct(`fonts/${t}`));if(r.ok){const o=await r.arrayBuffer();Gt(new Uint8Array(o))==="ttf"&&(i=this.arrayBufferToBase64(o))}}}catch{}return i||(i=await this.readFontFromDisk(t)),!i&&e&&console.warn(`Failed to load font ${t}`),this.fontFileData.set(t,i),i}static async readFontFromDisk(t){try{const{readFile:e}=await import("fs/promises"),{join:a}=await import("path"),i=[a(process.cwd(),"public","fonts",t),a(process.cwd(),"frontend","public","fonts",t),a(process.cwd(),"..","frontend","public","fonts",t),a(process.cwd(),"..","..","frontend","public","fonts",t)];for(const r of i)try{return(await e(r)).toString("base64")}catch{}}catch{}return null}static async loadSourceCodePro(t){const e=await this.loadFontFile("SourceCodePro-Regular.ttf",!1);return e?(t.addFileToVFS("SourceCodePro-Regular.ttf",e),t.addFont("SourceCodePro-Regular.ttf","SourceCodePro","normal"),!0):!1}static async loadKaTeXMain(t){const e=[{file:"KaTeX_Main-Regular.ttf",style:"normal"},{file:"KaTeX_Main-Bold.ttf",style:"bold"},{file:"KaTeX_Main-Italic.ttf",style:"italic"},{file:"KaTeX_Main-BoldItalic.ttf",style:"bolditalic"}],a=await Promise.all(e.map(async i=>{const r=await this.loadFontFile(i.file);return r?{...i,base64:r}:null}));for(const i of a)i&&(t.addFileToVFS(i.file,i.base64),t.addFont(i.file,"KaTeX_Main",i.style));return a[0]!==null}static async embedBundledGenreFonts(t,e,a){this.bundledGenreFamilies.clear();const i=new Set,r=o=>{const l=this.mapFontFamilyToStandard(o);this.BUNDLED_GENRE_FONTS[l]&&i.add(l)};r(a);for(const o of Nt(e))r(o.value);for(const o of i){const l=this.BUNDLED_GENRE_FONTS[o],n=await Promise.all(Object.entries(l.files).map(async([h,s])=>({style:h,file:s,base64:await this.loadFontFile(s)})));if(!n.some(h=>!h.base64)){for(const{style:h,file:s,base64:g}of n)t.addFileToVFS(s,g),t.addFont(s,l.family,h);this.bundledGenreFamilies.set(o,l.family)}}}static documentFallbackScripts(t){const e=new Set,a=Object.keys(this.SCRIPT_FALLBACK_FONTS),i=r=>{if(e.size===a.length||!r||typeof r!="object")return;if(Array.isArray(r)){r.forEach(i);return}const o=r;if(typeof o.text=="string"&&o.text)for(const l of a)!e.has(l)&&this.SCRIPT_FALLBACK_FONTS[l].charRegex.test(o.text)&&e.add(l);i(o.children)};return i(t.children),i(t.chrome),i(t.notes),e}static splitDocumentFallbackRuns(t,e){const a=Object.entries(this.SCRIPT_FALLBACK_FONTS),i=s=>{const g=a.filter(([,P])=>P.charRegex.test(s)).map(([P])=>P);if(g.length>1&&e){const P=s.codePointAt(0)??0,c=g.find(d=>e(d,P));if(c)return c}return g[0]},r=/[\p{Letter}\p{Number}]/u,o=this.SCRIPT_FALLBACK_FONTS.japanese.charRegex,l=this.SCRIPT_FALLBACK_FONTS.korean.charRegex,n=s=>{const g=s.text??"";if(!g)return[{...s}];const P=[];let c="",d=null;for(const f of g.split(/(\s+)/)){const x=o.test(f)?"japanese":l.test(f)?"korean":null;for(const m of f){let b=i(m);if(b==="han"&&x&&(b=x),!b&&r.test(m)&&(b="base"),!b){d?d.text+=m:c+=m;continue}!d||d.key!==b?(d&&P.push(d),d={key:b,text:c+m},c=""):d.text+=m}}return d?(d.text+=c,P.push(d)):P.push({key:"base",text:c}),P.map(f=>{if(f.key==="base")return{...s,text:f.text};const x=this.SCRIPT_FALLBACK_FONTS[f.key];return{...s,text:f.text,marks:{...s.marks,fontFamily:x.family}}})},h=s=>Array.isArray(s)?s.flatMap(g=>g&&typeof g=="object"&&g.type==="text"?n(g):[h(g)]):!s||typeof s!="object"?s:Object.fromEntries(Object.entries(s).map(([g,P])=>[g,h(P)]));return h(t)}static async loadFallbackCoverage(t){const e=Object.entries(this.SCRIPT_FALLBACK_FONTS),a=new Set,i=new Set,r=l=>{if(!l||typeof l!="object")return;if(Array.isArray(l)){l.forEach(r);return}const n=l;if(typeof n.text=="string")for(const h of n.text){if(i.has(h)||h.charCodeAt(0)<128)continue;i.add(h);const s=e.filter(([,g])=>g.charRegex.test(h));s.length>1&&s.forEach(([g])=>a.add(g))}r(n.children)};r(t.children),r(t.chrome),r(t.notes);const o=new Map;for(const l of a){const n=this.SCRIPT_FALLBACK_FONTS[l].files.normal;let h=this.fallbackCharsetCache.get(n);if(h===void 0){h=null;const s=await this.loadFontFile(n,!1);if(s)try{const g=(await import("./browser-module-CFmqfGkE.js")).create(ae(s));h=new Set(g.characterSet??[])}catch{h=null}this.fallbackCharsetCache.set(n,h)}h&&o.set(l,h)}return(l,n)=>{const h=o.get(l);return h?h.has(n):!0}}static async embedScriptFallbackFonts(t,e){this.scriptFallbackFamilies.clear(),this.shapingFonts.clear();for(const a of this.documentFallbackScripts(e)){const i=await this.registerScriptFallbackFace(t,a);i&&this.scriptFallbackFamilies.set(a,i)}}static async registerScriptFallbackFace(t,e){const a=this.SCRIPT_FALLBACK_FONTS[e];if(!a)return null;const i=await this.loadFontFile(a.files.normal);if(!i)return null;const r=await this.loadFontFile(a.files.bold,!1);t.addFileToVFS(a.files.normal,i),r&&a.files.bold!==a.files.normal&&t.addFileToVFS(a.files.bold,r);const o=r?a.files.bold:a.files.normal;if(t.addFont(a.files.normal,a.family,"normal"),t.addFont(o,a.family,"bold"),t.addFont(a.files.normal,a.family,"italic"),t.addFont(o,a.family,"bolditalic"),a.shape&&!this.shapingFonts.has(a.family))try{const[l,n]=await Promise.all([import("./browser-module-CFmqfGkE.js"),import("./_revise-sdk-lazy-harfbuzz-CDWdjF9f.js")]),h=n,s=h.loadHarfBuzz?await h.loadHarfBuzz():n,g=ae(i),P=l.create(g),c=new s.Blob(g),d=new s.Face(c),f=new s.Font(d);this.shapingFonts.set(a.family,{unitsPerEm:d.upem,notdefPathCommands:P.getGlyph(0).path.commands,layout:x=>{const m=new s.Buffer;m.addText(x),m.guessSegmentProperties(),s.shape(f,m);const b=m.getGlyphInfosAndPositions(),_=b.map(y=>({xAdvance:y.xAdvance??0,yAdvance:y.yAdvance??0,xOffset:y.xOffset??0,yOffset:y.yOffset??0}));return{glyphs:b.map(y=>P.getGlyph(y.codepoint)),positions:_,advanceWidth:_.reduce((y,v)=>y+v.xAdvance,0)}}})}catch(l){console.warn(`Failed to initialize PDF shaping for ${a.family}:`,l)}return a.family}static fontCoversCodePoint(t,e,a){const i=`${e}:${a}`;let r=this.scriptFontCoverageCache.get(i);if(r===void 0){let o;try{o=t.getFont(e,"normal")}catch{o=void 0}r=!!o?.metadata?.cmap?.unicode?.codeMap?.[a],this.scriptFontCoverageCache.set(i,r)}return r}static fontCoversMatchedChars(t,e,a,i){let r=!1;for(const o of a)if(i.test(o)&&(r=!0,!this.fontCoversCodePoint(t,e,o.codePointAt(0)??0)))return!1;return r}static scriptFallbackFor(t,e,a){if(!e||this.scriptFallbackFamilies.size===0)return null;let i=null;for(const[r,o]of Object.entries(this.SCRIPT_FALLBACK_FONTS)){const l=this.scriptFallbackFamilies.get(r);if(l&&o.charRegex.test(e)&&!this.fontCoversCodePoint(t,a,o.probeCodePoint)&&!this.fontCoversMatchedChars(t,a,e,o.charRegex)){if(this.fontCoversMatchedChars(t,l,e,o.charRegex))return l;i??(i=l)}}return i}static async registerDocumentFonts(t,e,a){await this.embedLocalFonts(t,e),await this.embedBundledGenreFonts(t,e,a),await this.embedScriptFallbackFonts(t,e);const i=this.documentUsesSourceCodePro(e)?await this.loadSourceCodePro(t):!1;return this.inlineCodeFontFamily=i?"SourceCodePro":"courier",this.documentUsesKaTeXMain(e)&&await this.loadKaTeXMain(t),{hasSourceCodePro:i}}static async registerCurrentPdfFonts(t,e){for(const[a,i]of this.bundledGenreFamilies){const r=this.BUNDLED_GENRE_FONTS[a];if(!r||r.family!==i)continue;const o=await Promise.all(Object.entries(r.files).map(async([l,n])=>({style:l,file:n,base64:await this.loadFontFile(n)})));for(const{style:l,file:n,base64:h}of o)h&&(t.addFileToVFS(n,h),t.addFont(n,i,l))}for(const a of this.scriptFallbackFamilies.keys())await this.registerScriptFallbackFace(t,a);e&&await this.loadSourceCodePro(t)}static documentUsesKaTeXMain(t){return Nt(t).some(e=>{const a=e.family.toLowerCase();return a.includes("katex")||a.includes("computer modern")||a.includes("computermodern")})}static documentUsesSourceCodePro(t){const e=[...t.children];for(;e.length>0;){const a=e.pop();if(!a||typeof a!="object")continue;const i=a;if(i.type==="code"||i.type==="text"&&typeof i.marks=="object"&&i.marks!==null&&i.marks.code===!0)return!0;Array.isArray(i.children)&&e.push(...i.children)}return!1}static createCanvasTextContext(){if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;let e=null;return{measureText:a=>({width:Vt(a,e,i=>t.measureText(i).width)}),setFont:a=>{t.font=a,e=null},setMarkAdjustments:a=>{e=a}}}static resolveIndentStepPx(t){return this.resolvePdfLayoutMetrics(t).indentStepPx}static getDefaultPdfLayoutMetrics(){const t=Ut(void 0),e=Math.max(1,this.PAGE_WIDTH-this.MARGIN_LEFT-this.MARGIN_RIGHT);return{orientation:"portrait",pageWidthPt:this.PAGE_WIDTH,pageHeightPt:this.PAGE_HEIGHT,marginTopPt:this.MARGIN_TOP,marginRightPt:this.MARGIN_RIGHT,marginBottomPt:this.MARGIN_BOTTOM,marginLeftPt:this.MARGIN_LEFT,contentWidthPt:e,fullContentWidthPt:e,pageMarginLeftPt:this.MARGIN_LEFT,columnCount:1,columnGapPt:It(t.columnGapTwips),columnStridePt:qt(e,It(t.columnGapTwips)),blockSpacingPt:t.blockSpacingPx*this.PX_TO_PT,indentStepPx:t.indentStepPx,showPageNumbers:t.showPageNumbers,pageBorders:t.pageBorders,pageNumberPosition:t.pageNumberPosition,pageNumberStart:t.pageNumberStart,pageNumberFormat:t.pageNumberFormat,hyphenationEnabled:t.hyphenationEnabled,lineNumbering:t.lineNumbering}}static resolvePdfLayoutMetrics(t){return this.resolvePdfMetricsFromSettings(t?.pageLayout,t?.pageLayout,!1)}static resolvePdfMetricsFromSettings(t,e,a=!1){const i=zt(e,t),r=t,{pageWidth:o,pageHeight:l}=Kt(i),n=o*this.PX_TO_PT,h=l*this.PX_TO_PT,s=i.marginTopPx*this.PX_TO_PT,g=i.marginRightPx*this.PX_TO_PT,P=i.marginBottomPx*this.PX_TO_PT,c=i.marginLeftPx*this.PX_TO_PT,d=Math.max(1,n-c-g),f=Math.max(1,i.columnCount),x=It(i.columnGapTwips),m=Oe(d,f,x);return{orientation:i.orientation,pageWidthPt:n,pageHeightPt:h,marginTopPt:s,marginRightPt:g,marginBottomPt:P,marginLeftPt:c,contentWidthPt:m,fullContentWidthPt:d,pageMarginLeftPt:c,columnCount:f,columnGapPt:x,columnStridePt:qt(m,x),...f>1?{columnFlow:{index:0,topPt:s,pageOffset:0}}:{},blockSpacingPt:i.blockSpacingPx*this.PX_TO_PT,indentStepPx:i.indentStepPx,showPageNumbers:i.showPageNumbers,pageBorders:i.pageBorders,pageNumberPosition:i.pageNumberPosition,pageNumberStart:i.pageNumberStart,pageNumberStartExplicit:a&&r?.pageNumberStart!==void 0,pageNumberFormat:i.pageNumberFormat,hyphenationEnabled:i.hyphenationEnabled,lineNumbering:i.lineNumbering}}static physicalPageMetrics(t){return{...t,marginLeftPt:t.pageMarginLeftPt,contentWidthPt:t.fullContentWidthPt,columnFlow:void 0,reservedInsetForPage:void 0}}static computeEngineLayout(t){if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");if(!e)return null;const a=Ut(t.pageLayout),i=Kt(a),r=ke({pageWidth:i.pageWidth,pageHeight:i.pageHeight,pageMargin:a.marginLeftPx,pageMarginTop:a.marginTopPx,pageMarginRight:a.marginRightPx,pageMarginBottom:a.marginBottomPx,pageMarginLeft:a.marginLeftPx,availableWidth:Math.max(1,i.pageWidth-a.marginLeftPx-a.marginRightPx),textStartY:a.marginTopPx,indentStepPx:a.indentStepPx,blockSpacingPx:a.blockSpacingPx,hyphenationEnabled:a.hyphenationEnabled,lineNumbering:a.lineNumbering,columnCount:a.columnCount,columnGapPx:se(a.columnGapTwips),pageless:!1});try{return Ve(t,Me(e),r)}catch{return null}}static computeColumnBalanceTargets(t,e){const a=new Map,i=e.filter(g=>g.type==="section-break"),r=new Set;if(i.forEach((g,P)=>{const c=zt(t.pageLayout,g.layout);Ce(Math.max(1,c.columnCount),g.breakType==="continuous")&&r.add(P)}),r.size===0)return a;const o=this.computeEngineLayout(t);if(!o?.pageGeometries||o.pageGeometries.length===0)return a;const l=new Map(o.pageGeometries.map(g=>[g.pageIndex+1,g.pageTop])),n=(g,P)=>{if(!g||typeof g!="object")return;if(Array.isArray(g)){g.forEach(d=>n(d,P));return}const c=g;typeof c.id=="string"&&c.id&&P.add(c.id),n(c.children,P)},h=new Map;let s=0;for(const g of e){if(g.type==="section-break"){s+=1;continue}let P=h.get(s);P||(P=new Set,h.set(s,P)),n(g,P)}for(const g of r){const P=h.get(g);if(!P||P.size===0)continue;const c=o.fragments.filter(b=>!b.isChrome&&typeof b.pageNumber=="number"&&P.has(b.blockId));if(c.length===0)continue;let d=Number.POSITIVE_INFINITY,f=0;for(const b of c)d=Math.min(d,b.pageNumber),f=Math.max(f,b.pageNumber);const x=l.get(f);if(x===void 0)continue;let m=0;for(const b of c)b.pageNumber===f&&(m=Math.max(m,b.bounds.y+b.bounds.height-x));m<=0||a.set(g,{pageOffset:f-d,bottomPt:m*this.PX_TO_PT+this.COLUMN_BALANCE_SLACK_PT})}return a}static advancePdfColumnOrPage(t,e){const a=e.columnFlow;return!a||e.columnCount<=1?(t.addPage(),!0):a.index<e.columnCount-1?(a.index+=1,e.marginLeftPt=e.pageMarginLeftPt+a.index*e.columnStridePt,!1):(a.index=0,e.marginLeftPt=e.pageMarginLeftPt,t.addPage([e.pageWidthPt,e.pageHeightPt],e.orientation),a.topPt=e.marginTopPt,a.pageOffset+=1,!0)}static advancePdfFlowRegion(t,e){const a=this.advancePdfColumnOrPage(t,e);return{x:e.marginLeftPt,y:a?e.marginTopPt:e.columnFlow?.topPt??e.marginTopPt}}static declaredSpacingPx(t,e){const a=t?.[e];return typeof a=="number"&&Number.isFinite(a)?Math.max(0,a):void 0}static pdfSpaceBeforePt(t,e){const a=ct.declaredSpacingPx(t,"spaceBefore");return a!==void 0?a*ct.PX_TO_PT:e.blockSpacingPt}static pdfSpaceAfterPt(t){const e=ct.declaredSpacingPx(t,"spaceAfter");return e!==void 0?e*ct.PX_TO_PT:0}static syncPdfColumnOffset(t){const e=t.columnFlow;!e||t.columnCount<=1||(t.marginLeftPt=t.pageMarginLeftPt+e.index*t.columnStridePt)}static getPdfReservedInsetPt(t,e){return e.reservedInsetForPage?.get(this.getPdfCurrentPage(t))??0}static getPdfWritableBottomPt(t,e){return e.pageHeightPt-e.marginBottomPt-this.getPdfReservedInsetPt(t,e)}static getPdfFlowBottom(t,e){const a=this.getPdfWritableBottomPt(t,e),i=e.columnFlow;return!i?.balance||e.columnCount<=1||i.pageOffset!==i.balance.pageOffset?a:Math.min(a,i.balance.bottomPt)}static getPdfPageCount(t){return typeof t.getNumberOfPages=="function"?t.getNumberOfPages():typeof t.internal?.getNumberOfPages=="function"?t.internal.getNumberOfPages():1}static getPdfCurrentPage(t){return t.getCurrentPageInfo?.().pageNumber??this.getPdfPageCount(t)}static createPdfPageNumbering(t,e,a){const i=[...e?.keys()??[]].sort((n,h)=>n-h),r=n=>{let h=t;for(const s of i){if(s>n)break;h=e.get(s)}return h},o=[],l=n=>{const h=Math.max(1,Math.floor(n));for(let s=o.length+1;s<=h;s++){const g=r(s);o.push(s===1||a?.has(s)&&g.pageNumberStartExplicit?g.pageNumberStart:o[s-2]+1)}return o[h-1]};return{metricsForPage:r,numberForPage:l,labelForPage:n=>le(l(n),r(n).pageNumberFormat)}}static async renderHeaderFooterChrome(t,e,a,i,r,o){const l=this.getPdfPageCount(t),n=d=>{if(!r)return a;let f=a,x=0;for(const[m,b]of r)m<=d&&m>x&&(f=b,x=m);return f},h=d=>{if(!o)return 0;let f=0,x=0;for(const[m,b]of o)m<=d&&m>x&&(f=b,x=m);return f},s=d=>{if(!o)return 1;let f=1;for(const[x]of o)x<=d&&x>f&&(f=x);return f},g=this.createPdfPageNumbering(a,r,o).labelForPage,P=(d,f)=>{if(e.chrome&&e.chrome.length>0)return xe(e.chrome,d,f,h(f));const x=d==="header"?e.headers:e.footers;if(!x)return;const m=f===s(f)&&x.first?"first":f%2===0&&x.even?"even":"default",b=x[m];if(b)return be(d,m,ye(b),i)},c=async(d,f,x)=>{const m=n(x),b=d.children.slice(0,3).map((w,E)=>{const u=vt[E];return{...w,...u&&!w.align?{align:u}:{},children:w.children.map(p=>p.type!=="text"||!p.marks?.field?p:p.marks.field==="page"?{...p,text:g(x)}:{...p,text:String(l)})}});for(;b.length<3;){const w=b.length;b.push({type:"paragraph",id:`${d.id}-pdf-column-${w}`,children:[{type:"text",text:""}],...vt[w]?{align:vt[w]}:{}})}const _=this.createLayoutForWrapping(m.contentWidthPt,m.indentStepPx,m),y=this.createCanvasTextContext(),v=y?qe(d,y,_,e,b).map(w=>w*this.PX_TO_PT):[m.contentWidthPt/3,m.contentWidthPt/3,m.contentWidthPt/3],M=f?Math.max(10*this.PX_TO_PT,m.marginTopPt/2):m.pageHeightPt-Math.max(10*this.PX_TO_PT,m.marginBottomPt/2);let A=m.marginLeftPt;for(let w=0;w<3;w++){const E=b[w],u=v[w],p=this.measureParagraphLineAdvances(E,u,m.indentStepPx,m).reduce((L,X)=>L+X,0),S=M-p/2,O={...m,marginTopPt:S,marginLeftPt:A,marginRightPt:Math.max(0,m.pageWidthPt-A-u),contentWidthPt:Math.max(1,u)};await this.renderParagraph(t,E,S,u,i,1e9,m.indentStepPx,O),A+=u}};for(let d=0;d<l;d++){const f=d+1;t.setPage(f);const x=P("header",f),m=P("footer",f);x&&await c(x,!0,f),m&&await c(m,!1,f)}this.renderPageNumbers(t,a,i,n,g,(d,f)=>!!P(f,d));for(let d=1;d<=l;d++){const f=n(d),x=ce(f.pageBorders,f.pageWidthPt,f.pageHeightPt,{top:f.marginTopPt,right:f.marginRightPt,bottom:f.marginBottomPt,left:f.pageMarginLeftPt},d===s(d));if(!x.length)continue;t.setPage(d);const m=t.internal?.pages?.[d],b=m?.length??0;t.saveGraphicsState(),t.setLineCap?.("square");for(const _ of x){t.setDrawColor(_.color),t.setLineWidth(_.style==="double"?_.widthPt/3:_.widthPt),t.setLineDashPattern(_.style==="dotted"?[_.widthPt,_.widthPt*2]:_.style==="dashed"?[_.widthPt*4,_.widthPt*2]:[],0);for(const y of _.style==="double"?[-_.widthPt/3,_.widthPt/3]:[0]){const v=_.x1===_.x2?y:0,M=_.y1===_.y2?y:0;t.line(_.x1+v,_.y1+M,_.x2+v,_.y2+M)}}t.restoreGraphicsState(),f.pageBorders?.zOrder==="back"&&m&&m.unshift(...m.splice(b))}}static drawWatermarkOnPage(t,e,a,i){t.setFont("helvetica","normal");const r=De(e,a/this.PX_TO_PT,i/this.PX_TO_PT,(b,_)=>{t.setFontSize(_*this.PX_TO_PT);const y=t.getTextWidth(b);return typeof y=="number"?y/this.PX_TO_PT:0})*this.PX_TO_PT;t.setFontSize(r);const o=t.getTextWidth(e.text),l=this.hexToRgb(e.color);t.setTextColor(l.r,l.g,l.b);const n=typeof t.saveGraphicsState=="function"&&typeof t.setGState=="function"&&typeof t.GState=="function";n&&(t.saveGraphicsState(),t.setGState(new t.GState({opacity:e.opacity})));const h=e.diagonal?Math.atan2(i,a):0,s=Math.cos(h),g=Math.sin(h),P=a/2,c=i/2,d=o/2,f=-.35*r,x=P-(d*s+f*g),m=c-(-d*g+f*s);t.text(e.text,x,m,{...h!==0?{angle:h*180/Math.PI}:{}}),n&&t.restoreGraphicsState()}static installWatermarkUnderpaint(t,e){const a=()=>{const r=t.internal?.pageSize,o=typeof r?.getWidth=="function"?r.getWidth():r?.width,l=typeof r?.getHeight=="function"?r.getHeight():r?.height;!o||!l||this.drawWatermarkOnPage(t,e,o,l)},i=t.addPage.bind(t);t.addPage=(...r)=>{const o=i(...r);return a(),o},a()}static renderBodyLineNumbers(t,e,a,i){if(e.length===0)return;const r=h=>{let s,g=0;for(const[P,c]of a)P<=h&&P>g&&(s=c,g=P);return s??this.resolvePdfLayoutMetrics(i)},o=this.getPdfPageCount(t),l=o;let n=!1;for(let h=1;h<=o;h++){const s=r(h),g=s.lineNumbering;if(!g)continue;let P=g.start;if(g.restart==="continuous")for(const d of e)d.pageNumber<h&&P++;const c=s.marginLeftPt-(g.distancePx??12)*this.PX_TO_PT;t.setPage(h),t.setFont("helvetica","normal"),t.setFontSize(10*this.PX_TO_PT),t.setTextColor(115,115,115),n=!0;for(const d of e){if(d.pageNumber!==h)continue;const f=P++;f%g.countBy===0&&t.text(String(f),c,d.y+d.height/2,{align:"right",baseline:"middle"})}}n&&t.setPage(l)}static renderPageNumbers(t,e,a,i,r,o){const l=this.getPdfPageCount(t),n=12,h=n/2+6;t.setFont(this.mapFontFamily(a),"normal"),t.setFontSize(n),t.setTextColor(0,0,0);for(let s=0;s<l;s++){const g=i?.(s+1)??e;if(!g.showPageNumbers)continue;const P=s+1,c=g.pageNumberPosition.startsWith("top");if(o?.(P,c?"header":"footer"))continue;const d=g.pageNumberPosition.endsWith("right"),f=d?g.pageWidthPt-g.marginRightPt:g.marginLeftPt,x=c?Math.max(h,g.marginTopPt/2):g.pageHeightPt-Math.max(h,g.marginBottomPt/2);t.setPage(P),t.text(r?.(P)??he({pageNumberStart:e.pageNumberStart,pageNumberFormat:e.pageNumberFormat??"decimal"},s),f,x,{align:d?"right":"left"})}}static getParagraphLineIndentPt(t,e,a){return ge(t,e,a)*this.PX_TO_PT}static createLayoutForWrapping(t,e,a=this.getDefaultPdfLayoutMetrics()){const i=t/this.PX_TO_PT;return{pageWidth:a.pageWidthPt/this.PX_TO_PT,pageHeight:a.pageHeightPt/this.PX_TO_PT,pageMargin:a.marginLeftPt/this.PX_TO_PT,pageMarginTop:a.marginTopPt/this.PX_TO_PT,pageMarginRight:a.marginRightPt/this.PX_TO_PT,pageMarginBottom:a.marginBottomPt/this.PX_TO_PT,pageMarginLeft:a.marginLeftPt/this.PX_TO_PT,pageSpacing:0,paragraphSpacing:0,availableWidth:i,textStartY:a.marginTopPt/this.PX_TO_PT,fontSize:16,fontFamily:this.DEFAULT_BODY_FONT,lineHeight:16*1.4,indentStepPx:e,pageless:!1,hyphenationEnabled:a.hyphenationEnabled}}static buildNumberedNoteEntries(t){const e=new Map,a=s=>{if(!s||typeof s!="object")return;if(Array.isArray(s)){s.forEach(a);return}const g=s;g.type!=="footnote"&&(g.marks?.footnoteRef&&!e.has(g.marks.footnoteRef)&&e.set(g.marks.footnoteRef,g.text??""),a(g.children))};a(t.children.filter(s=>s.type!=="footnote"));const i=[...t.notes??[],...t.children.filter(s=>s.type==="footnote")],r={footnote:0,endnote:0},o=new Map,l=new Map;for(const s of i)l.set(s.id,s.noteKind==="endnote"?"endnote":"footnote");for(const[s]of e){const g=l.get(s)??"footnote";r[g]+=1,o.set(s,jt(r[g],g))}const n=i.map(s=>{const g=l.get(s.id)??"footnote",P=o.get(s.id)||jt(r[g]+=1,g);return{footnoteId:s.id,number:P,kind:g,blocks:s.children}}),h=s=>{const g=[...o.keys()],P=g.indexOf(s.footnoteId);return P===-1?g.length:P};return n.sort((s,g)=>h(s)-h(g))}static async renderNoteEntry(t,e,a,i,r,o,l,n,h){n&&this.drawNoteNumeral(t,e.number,i.marginLeftPt,a,r);const s=et.verticalPaddingPx*ct.PX_TO_PT,g=et.gutterPx*ct.PX_TO_PT,P=a+s,c={...i,marginTopPt:i.marginTopPt+s,marginLeftPt:i.marginLeftPt+g,contentWidthPt:Math.max(1,i.contentWidthPt-g),blockSpacingPt:et.blockSpacingPx*ct.PX_TO_PT};if(h){const d=c.marginTopPt;Object.defineProperty(c,"marginTopPt",{get:()=>h.get(this.getPdfCurrentPage(t))??d})}return(await this.renderBodyBlocks(t,e.blocks,c,o,l,r,void 0,void 0,void 0,P)).finalY+s}static drawNoteNumeral(t,e,a,i,r){t.setFont(this.mapFontFamily(r),"normal"),t.setFontSize($t*this.PX_TO_PT),t.setTextColor(0,0,0),t.text(e,a+1.5,i+(6+$t)*ct.PX_TO_PT)}static mapFootnoteRefBlocks(t){const e=new Map,a=(i,r)=>{if(!i||typeof i!="object")return;if(Array.isArray(i)){i.forEach(l=>a(l,r));return}const o=i;o.marks?.footnoteRef&&!e.has(o.marks.footnoteRef)&&e.set(o.marks.footnoteRef,r),a(o.children,r)};for(const i of t)a(i,i.id??"");return e}static async renderBodyBlocks(t,e,a,i,r,o,l,n,h,s,g){const P=new Map,c=new Map([[1,0]]),d=[],f=[],x=_e(e);let m=s??a.marginTopPt,b=a.contentWidthPt,_=a.indentStepPx,y=!0;const v=new Map([[1,this.physicalPageMetrics(a)]]),M=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages();let A=0;const w=E=>{if(A=E,!g)return;const u=a.columnFlow;!u||a.columnCount<=1||(u.index=0,u.topPt=m,u.pageOffset=0,u.balance=g.balanceBySection.get(E),a.marginLeftPt=a.pageMarginLeftPt)};w(0);for(let E=0;E<e.length;E++){this.syncPdfColumnOffset(a);const u=e[E],p=this.getPdfFlowBottom(t,a);if(u.type==="page-break"){!y&&a.blockSpacingPt>0&&(m+=a.blockSpacingPt),u.id&&P.set(u.id,M()),t.addPage([a.pageWidthPt,a.pageHeightPt],a.orientation),a.columnFlow&&(a.columnFlow.index=0,a.columnFlow.topPt=a.marginTopPt,a.columnFlow.pageOffset+=1,a.marginLeftPt=a.pageMarginLeftPt),m=a.marginTopPt,y=!0;continue}if(u.type==="docx-raw"){const G=Lt.heightPx*.75,k=a.pageWidthPt-a.marginLeftPt-a.marginRightPt,N=Re(u,k/.75)*.75;!y&&a.blockSpacingPt>0&&(m+=a.blockSpacingPt),m+G>p&&(m=this.advancePdfFlowRegion(t,a).y),u.id&&P.set(u.id,M());const H=a.marginLeftPt;t.setDrawColor(107,114,128),t.setFillColor(243,244,246),t.setLineWidth(.75),t.roundedRect(H,m,N,G,Lt.cornerRadiusPx*.75,Lt.cornerRadiusPx*.75,"FD"),t.setFont("courier","normal"),t.setFontSize(Lt.fontPx*.75),t.setTextColor(107,114,128),t.text(Ne(u),H+Lt.paddingXPx*.75,m+G/2,{baseline:"middle"}),t.setTextColor(0,0,0),m+=G,y=!1;continue}if(u.type==="section-break"){u.id&&P.set(u.id,M());const G=l?.get(u.id),k=G?n?.(G)??G:void 0;if(k){const H=Ie(u.breakType==="continuous",{width:a.pageWidthPt,height:a.pageHeightPt},{width:k.pageWidthPt,height:k.pageHeightPt});a=k,b=k.contentWidthPt,_=k.indentStepPx,H?(m=Be(m,a.blockSpacingPt,0,a.marginTopPt),m>this.getPdfWritableBottomPt(t,a)&&(t.addPage([a.pageWidthPt,a.pageHeightPt],a.orientation),m=a.marginTopPt)):(t.addPage([k.pageWidthPt,k.pageHeightPt],k.orientation),m=a.marginTopPt),v.set(M(),this.physicalPageMetrics(k))}else t.addPage(),m=a.marginTopPt;const N=h?.get(u.id);N!==void 0&&c.set(M(),N),w(A+1),y=!0;continue}if(u.type==="toc"){const G=a.blockSpacingPt;!y&&G>0&&(m+=G),y=!1,u.id&&P.set(u.id,M());const k=de({children:e.map(V=>V.type==="paragraph"?this.paragraphForPdfOutput(V):V)},fe(u)),N=(u.fontSize??16)*this.PX_TO_PT,H=N*1.4,z=Yt.paddingYPx*this.PX_TO_PT;t.setFont(this.mapFontFamily(u.fontFamily??o),"normal"),t.setFontSize(N);const j=this.hexToRgb(u.color??"#000000");t.setTextColor(j.r,j.g,j.b),m+=z,k.length===0&&(m+H>p&&(m=this.advancePdfFlowRegion(t,a).y),m+=H);for(const V of k)m+H>p&&(m=this.advancePdfFlowRegion(t,a).y),f.push({pdfPage:M(),headingBlockId:V.blockId,block:u,entry:V,baseline:m+N,left:a.marginLeftPt,width:a.contentWidthPt,fontName:this.mapFontFamily(u.fontFamily??o),fontSizePt:N}),m+=H;m+=z;continue}const S=ct.pdfSpaceBeforePt(u,a)+ct.pdfSpaceAfterPt(E>0?e[E-1]:void 0);if(!y&&S>0?m+=S:y&&E===0&&a.keepFirstBlockDeclaredSpaceBefore&&(m+=(ct.declaredSpacingPx(u,"spaceBefore")??0)*ct.PX_TO_PT),y=!1,u.id&&u.type!=="paragraph"&&P.set(u.id,M()),u.type==="container"){const G=await this.renderContainerBlock(t,u,m,b,o,i,r,a);m=G.nextY;for(const[k,N]of G.blockStartPages)P.set(k,N);d.push(...G.lineMarks);continue}if(u.type==="placeholder"){m=this.advancePlaceholderBlock(t,u,m,a);continue}if(u.type==="image"){const G=await this.renderImageBlock(t,u,m,b,a);G&&(m=G.nextY);continue}if(u.type==="math"){const G=u;m=(await this.renderMathBlock(t,G,m,b,p,a)).nextY;continue}if(u.type==="list"){m=await this.renderListBlock(t,u,m,b,o,a,x.get(u.id),d);continue}if(u.type==="table"){m=await this.renderTableBlock(t,u,m,b,o,i,r,a);continue}if(u.type==="code"){m=await this.renderCodeBlock(t,u,m,b,p,a.marginLeftPt,i,r,a,d);continue}if(u.type!=="paragraph")continue;const O=u,{required:L,firstLineAdvance:X}=this.getRequiredParagraphStartHeight(e,E,b,_,a);L>0&&m+L>p&&a.marginTopPt+L<=p&&m!==a.marginTopPt&&(m=this.advancePdfFlowRegion(t,a).y),m+X>p&&m!==a.marginTopPt&&(m=this.advancePdfFlowRegion(t,a).y),O.id&&P.set(O.id,M()),m=await this.renderParagraph(t,O,m,b,o,p,_,a,d)}if(f.length>0){const E=M(),u=this.createPdfPageNumbering(v.get(1)??a,v,c).labelForPage;for(const p of f){t.setPage(p.pdfPage),t.setFont(p.fontName,"normal"),t.setFontSize(p.fontSizePt);const S=this.hexToRgb(p.block.color??"#000000");t.setTextColor(S.r,S.g,S.b);const O=P.get(p.headingBlockId),L=O!==void 0?u(O):"",X=me(p.block,p.entry,p.left,p.width,L,G=>t.getTextWidth(G),this.PX_TO_PT);X.text&&t.text(X.text,X.textX,p.baseline,{align:X.align,...X.rtl?{isInputVisual:!1,isOutputVisual:!0,isInputRtl:!0,isOutputRtl:!1}:{}}),L&&X.leaderEnd-X.leaderStart>Yt.minimumLeaderWidthPx*this.PX_TO_PT&&(t.setDrawColor(150),typeof t.setLineDashPattern=="function"&&t.setLineDashPattern([.8,2.2],0),t.line(X.leaderStart,p.baseline,X.leaderEnd,p.baseline),typeof t.setLineDashPattern=="function"&&t.setLineDashPattern([],0),t.setDrawColor(0,0,0)),L&&t.text(L,X.numberX,p.baseline)}t.setPage(E)}return{blockStartPages:P,pageMetrics:v,pageSections:c,lineMarks:d,finalY:m}}static async renderContainerBlock(t,e,a,i,r,o,l,n){const h=Math.max(0,e.padding??Bt.paddingPx)*this.PX_TO_PT,s=this.getPdfFlowBottom(t,n);a+h>s&&a!==n.marginTopPt&&(a=this.advancePdfFlowRegion(t,n).y);const g=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages(),P=g(),c=n.columnFlow?.index??0,d=n.columnFlow?.topPt??n.marginTopPt,f={...n,keepFirstBlockDeclaredSpaceBefore:void 0,marginTopPt:n.marginTopPt+h,marginRightPt:n.marginRightPt+h,marginBottomPt:n.marginBottomPt+h,marginLeftPt:n.marginLeftPt+h,contentWidthPt:Math.max(1,i-h*2),pageMarginLeftPt:n.pageMarginLeftPt+h},x=await this.renderBodyBlocks(t,e.children,f,o,l,r,void 0,void 0,void 0,a+h);let m=x.finalY+h;this.syncPdfColumnOffset(n),m>s&&x.finalY!==f.marginTopPt&&(m=this.advancePdfFlowRegion(t,n).y+h);const b=g(),_=n.columnFlow?.index??0,y=b,v=this.hexToRgb(e.borderColor??Bt.borderColor);t.setDrawColor(v.r,v.g,v.b),t.setLineWidth(Bt.borderWidthPx*this.PX_TO_PT);let M=P,A=c;for(;M<b||M===b&&A<=_;){t.setPage(M);const w=M===P&&A===c,E=M===b&&A===_,u=w?a:M===P?d:n.marginTopPt,p=E?m:s;p>u&&t.rect(n.pageMarginLeftPt+A*n.columnStridePt,u,i,p-u,"S"),A+=1,A>=n.columnCount&&(A=0,M+=1)}return t.setPage(y),{nextY:m,blockStartPages:x.blockStartPages,lineMarks:x.lineMarks}}static advancePlaceholderBlock(t,e,a,i){const r=Math.max(0,e.height||100)*this.PX_TO_PT,o=this.getPdfFlowBottom(t,i);return a+r>o&&a!==i.marginTopPt&&(a=this.advancePdfFlowRegion(t,i).y),a+r}static async toBlob(t,e,a){class i extends this{}return i.bundledGenreFamilies=new Map,i.scriptFallbackFamilies=new Map,i.shapingFonts=new Map,i.embeddedFamilyNames=new Map,i.inlineCodeFontFamily="courier",i.renderDocument(t,e,a)}static async renderDocument(t,e,a){t=this.splitDocumentFallbackRuns(t,await this.loadFallbackCoverage(t));const i=a||{...Xt,background:wt.codeBackground,text:wt.codeText};await this.ensureAllLatexRendered(t);const r=this.resolvePdfLayoutMetrics(t),o=t.children.filter(S=>S.type==="section-break"),l=new Map,n=new Map,h=t.pageLayout?.pageNumberRestart===!0?{...r,pageNumberStartExplicit:!0}:r;o.forEach((S,O)=>{const L=o[O+1];l.set(S.id,L?.layout?this.resolvePdfMetricsFromSettings(L.layout,t.pageLayout,!0):L?r:h),n.set(S.id,O+1)});const s=o[0]?.layout?this.resolvePdfMetricsFromSettings(o[0].layout,t.pageLayout,!1):r,g=await import("./jspdf.es.min-DU74zN8b.js").then(S=>S.j),P=g.jsPDF??g.default,c=new P({orientation:s.orientation,unit:"pt",format:[s.pageWidthPt,s.pageHeightPt]}),d=this.DEFAULT_BODY_FONT,{hasSourceCodePro:f}=await this.registerDocumentFonts(c,t,d);e&&c.setProperties({title:e});const x=Ae(t.watermark);x&&this.installWatermarkUnderpaint(c,x);const m=[...t.children.filter(S=>S.type==="footnote"),...t.notes??[]],b=t.children.filter(S=>S.type!=="footnote"&&S.type!=="header-footer"),_={balanceBySection:this.computeColumnBalanceTargets(t,b)},y=m.length>0?this.buildNumberedNoteEntries(t):[],v=y.filter(S=>S.kind==="footnote"),M=y.filter(S=>S.kind==="endnote");let A=new Map([[1,s]]),w=new Map([[1,0]]),E=s.marginTopPt,u=[],p=new Map;if(v.length===0){const S=await this.renderBodyBlocks(c,b,s,i,f,d,l,void 0,n,void 0,_);A=S.pageMetrics,w=S.pageSections,u=S.lineMarks,E=S.finalY}else{const S=v,O=et.separatorSpacePx*this.PX_TO_PT,L=this.mapFootnoteRefBlocks(b),X=new P({orientation:s.orientation,unit:"pt",format:[s.pageWidthPt,s.pageHeightPt]});await this.registerDocumentFonts(X,t,d);const G=await this.renderBodyBlocks(X,b,s,i,f,d,l,void 0,void 0,void 0,_),k=C=>{let B=s,U=0;for(const[W,Y]of G.pageMetrics)W<=C&&W>U&&(B=Y,U=W);return B},N=new Map,H=X.getNumberOfPages();for(const C of S){const B=L.get(C.footnoteId),U=(B?G.blockStartPages.get(B):void 0)??H,W=N.get(U)??[];W.push(C),N.set(U,W)}const z=new P({orientation:r.orientation,unit:"pt",format:[r.pageWidthPt,1e4]});await this.registerDocumentFonts(z,t,d);const j=new Map;for(const[C,B]of N){const U=k(C);for(const W of B){const Y={...U,pageHeightPt:1e4,marginTopPt:0,marginBottomPt:0},q=await this.renderNoteEntry(z,W,0,Y,d,i,f,!1);j.set(W.footnoteId,Math.max(0,q))}}const V=new Map;for(const[C,B]of N){const U=k(C),W=O+B.reduce((tt,at)=>tt+(j.get(at.footnoteId)??0),0),Y=U.pageHeightPt-U.marginTopPt-U.marginBottomPt,q=G.lineMarks.filter(tt=>tt.pageNumber===C).sort((tt,at)=>tt.y-at.y).slice(0,et.minimumBodyLinesBeforeFootnotes),Z=this.getParagraphLineHeight({type:"paragraph",id:"__pdf_measure__",children:[]}),Q=(q.length>0?Math.max(0,Math.max(...q.map(tt=>tt.y+tt.height))-U.marginTopPt):Z*et.minimumBodyLinesBeforeFootnotes)+et.bodyKeepSlackPx*this.PX_TO_PT;V.set(C,Math.min(W,Math.max(0,Y-Q)))}p=V;const T=C=>({...C,reservedInsetForPage:V}),I=T(s),F=await this.renderBodyBlocks(c,b,I,i,f,d,l,T,n,void 0,_);A=F.pageMetrics,w=F.pageSections,u=F.lineMarks,E=F.finalY;const K=new Map;for(const C of F.lineMarks)K.set(C.pageNumber,Math.max(K.get(C.pageNumber)??0,C.y+C.height+et.separatorSpacePx*this.PX_TO_PT+et.verticalPaddingPx*this.PX_TO_PT));const D=c.getNumberOfPages();for(const[C,B]of[...N.entries()].sort((U,W)=>U[0]-W[0])){const U=Math.min(C,D);c.setPage(U);const W=k(C),Y=V.get(C)??0,q=W.pageHeightPt-W.marginBottomPt-Y+O;c.setDrawColor(120),c.setLineWidth(.75),c.line(W.marginLeftPt,q-7,W.marginLeftPt+Math.max(et.separatorWidthMinPx*this.PX_TO_PT,W.contentWidthPt*et.separatorWidthFraction),q-7);let Z=q;for(let Q=0;Q<B.length;Q++){Q>0&&(Z+=et.blockSpacingPx*this.PX_TO_PT);const tt=this.getPdfCurrentPage(c),at=c.addPage.bind(c),rt=[];c.addPage=(...st)=>{const lt=this.getPdfCurrentPage(c)+1;return lt<=D?c.setPage(lt):at(...st),rt.push(this.getPdfCurrentPage(c)),c};try{Z=await this.renderNoteEntry(c,B[Q],Z,W,d,i,f,!0,K)}finally{c.addPage=at}for(const st of rt){c.setPage(st),c.setDrawColor(120),c.setLineWidth(.75);const lt=(K.get(st)??W.marginTopPt)-et.verticalPaddingPx*this.PX_TO_PT*2;c.line(W.marginLeftPt,lt,W.marginLeftPt+W.contentWidthPt,lt)}c.setPage(rt[rt.length-1]??tt)}}c.setPage(this.getPdfPageCount(c))}if(M.length>0){const S=new P({orientation:r.orientation,unit:"pt",format:[r.pageWidthPt,1e4]});await this.registerDocumentFonts(S,t,d);let O=et.separatorToContentPx*this.PX_TO_PT;for(let z=0;z<M.length;z++){z>0&&(O+=et.blockSpacingPx*this.PX_TO_PT);const j={...r,pageHeightPt:1e4,marginTopPt:0,marginBottomPt:0};O+=await this.renderNoteEntry(S,M[z],0,j,d,i,f,!1)}const L=this.getPdfPageCount(c);let X=s,G=0;for(const[z,j]of A)z<=L&&z>=G&&(X=j,G=z);const k=E+et.inlineEndnoteGapPx*this.PX_TO_PT,N=k+O<=X.pageHeightPt-X.marginBottomPt-(p.get(L)??0);let H;N?(c.setPage(L),H=k):(c.addPage(),H=X.marginTopPt+et.newPageSeparatorOffsetPx*this.PX_TO_PT),c.setDrawColor(120),c.setLineWidth(.75),c.line(X.marginLeftPt,H,X.marginLeftPt+Math.max(et.separatorWidthMinPx*this.PX_TO_PT,X.contentWidthPt*et.separatorWidthFraction),H),H+=et.separatorToContentPx*this.PX_TO_PT;for(let z=0;z<M.length;z++)z>0&&(H+=et.blockSpacingPx*this.PX_TO_PT),H=await this.renderNoteEntry(c,M[z],H,X,d,i,f,!0)}return await this.renderHeaderFooterChrome(c,t,r,d,A,w),this.renderBodyLineNumbers(c,u,A,t),c.output("blob")}static measureLineAdvancePt(t,e,a,i){let r=0,o=0;for(const h of t)h.latexImage?o=Math.max(o,h.latexImage.contentHeight*this.PX_TO_PT):r=Math.max(r,h.marks?.fontSize?h.marks.fontSize*this.PX_TO_PT:e);r===0&&(r=e);const l=i??(a?this.LINE_HEIGHT_MULTIPLIERS.heading:this.LINE_HEIGHT_MULTIPLIERS.paragraph),n=r*l;return o>n*1.25?o:n}static parseParagraphDecoration(t){const e=t.shading&&t.shading!=="transparent"?t.shading:void 0;if(!e&&!t.borders)return null;let a;if(t.borders)try{a=JSON.parse(t.borders)}catch{a=void 0}return!e&&!a?null:{...e?{shading:e}:{},...a?{edges:a}:{}}}static drawParagraphDecorationSlice(t,e,a,i,r,o,l,n){if(e.shading){const f=this.hexToRgb(e.shading);t.setFillColor(f.r,f.g,f.b),t.rect(a,i,r,o+(n?0:.5),"F")}const h=e.edges;if(!h)return;const s=(f,x,m,b,_)=>{const y=h[f];if(!y||y.style==="none")return;const v=Math.max(.4,(y.width??1)*this.PX_TO_PT),M=m===_,A=this.hexToRgb(y.color??"#000000");if(t.setDrawColor(A.r,A.g,A.b),t.setLineWidth(v),M&&Ke(y.style)){const u=je(x,b,this.PX_TO_PT);for(const p of u.lines)t.line(p.from,m,p.to,m);t.setFillColor(A.r,A.g,A.b);for(const p of u.ornaments)if(y.style==="stars")for(const S of $e(p.cx,m,p.radius))t.line(S.x1,S.y1,S.x2,S.y2);else{const S=Ye(p.cx,m,p.radius);t.lines([[S[1].x-S[0].x,S[1].y-S[0].y],[S[2].x-S[1].x,S[2].y-S[1].y],[S[3].x-S[2].x,S[3].y-S[2].y]],S[0].x,S[0].y,[1,1],"F",!0)}return}const w=typeof t.setLineDashPattern=="function";w&&(y.style==="dashed"?t.setLineDashPattern([4.5,2.25],0):y.style==="dotted"?t.setLineDashPattern([1.5,1.5],0):t.setLineDashPattern([],0));const E=u=>{t.line(x+(M?0:u),m+(M?u:0),b+(M?0:u),_+(M?u:0))};y.style==="double"?(E(-v),E(v)):E(0),w&&t.setLineDashPattern([],0)},g=n?0:.5,P=f=>Math.max(0,h[f]?.space??0)*this.PX_TO_PT,c=a-P("left"),d=a+r+P("right");if(s("left",c,i,c,i+o+g),s("right",d,i,d,i+o+g),l){const f=i-P("top");s("top",a,f,a+r,f)}if(n){const f=i+o+P("bottom");s("bottom",a,f,a+r,f)}}static measureParagraphLineAdvances(t,e,a,i){const r=this.createCanvasTextContext();if(!r)return[this.getParagraphLineHeight(t)];const o=this.createLayoutForWrapping(e,a,i),l=Jt(this.paragraphForPdfOutput(t),r,o);if(l.length===0)return[this.getEmptyParagraphLineHeight(t)];const n=this.getParagraphFontSize(t),h=this.getLineSpacingMultiplier(t);return l.map(s=>this.measureLineAdvancePt(s.segments.map(g=>({marks:g.marks})),n,!!t.heading,h))}static paragraphForPdfOutput(t){const e=t.children.filter(a=>a.type!=="text"||!a.marks?.hidden||!!a.marks.footnoteRef);return e.length===t.children.length?t:{...t,children:e}}static getParagraphDirection(t){let e="";for(const a of t.children)e+=a.text??"";return Ze(t.direction,e)}static getEffectiveParagraphAlignment(t,e){return t.align||(e==="rtl"?"right":"left")}static getRequiredParagraphStartHeight(t,e,a,i,r){const o=t[e];if(!o||o.type!=="paragraph")return{required:0,firstLineAdvance:0};const l=At(o),n=this.measureParagraphLineAdvances(o,a,i,r),h=this.paragraphForPdfOutput(o).children.every(c=>c.type==="text"&&c.text==="")||n.length===0?this.getEmptyParagraphLineHeight(o):n[0],s=c=>c.reduce((d,f)=>d+Math.max(0,f),0);let g=0;if(l.keepLines?g=s(n):l.widowControl&&n.length>=2&&(g=n[0]+n[1]),!l.keepNext)return{required:g,firstLineAdvance:h};let P=0;for(let c=0;c<ie;c++){const d=t[e+c+1];if(!d||d.type!=="paragraph")break;const f=this.measureParagraphLineAdvances(d,a,i,r);if(f.length===0)break;P+=ct.pdfSpaceBeforePt(d,r);const x=At(d);if(x.keepNext&&c<ie-1){P+=s(f);continue}P+=f[0],x.widowControl&&f.length>=2&&(P+=f[1]);break}return{required:Math.max(g,s(n)+P),firstLineAdvance:h}}static async renderParagraph(t,e,a,i,r,o,l=this.resolveIndentStepPx(),n=this.getDefaultPdfLayoutMetrics(),h){let s=a;const g=this.paragraphForPdfOutput(e),P=this.getParagraphFontSize(e),c=this.getParagraphLineHeight(e),d=this.getLineSpacingMultiplier(e);let f=Number.isFinite(o)&&o>0?o:this.getPdfFlowBottom(t,n),x=n.marginLeftPt;const m=()=>{const w=this.advancePdfFlowRegion(t,n);s=w.y,x=w.x,f=this.getPdfFlowBottom(t,n)},b=(w=c)=>{if(s+w>f){if(s===n.marginTopPt)return;m()}},_=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages(),y=this.getParagraphDirection(g),v=this.getEffectiveParagraphAlignment(e,y),M=this.parseParagraphDecoration(e);if(g.children.length===0||g.children.length===1&&g.children[0].type==="text"&&g.children[0].text===""){const w=this.getEmptyParagraphLineHeight(e);return M&&(b(w),this.drawParagraphDecorationSlice(t,M,x,s,i,w,!0,!0)),s+w}const A=this.createCanvasTextContext();if(A){const w=this.createLayoutForWrapping(i,l,n),E=Jt(g,A,w),u=await this.prepareLatexImages(g,P),p=E.map(O=>O.segments.map(L=>L.marks?.latex?{text:L.text,marks:L.marks,latexImage:u.get(L.text)}:{text:L.text,marks:L.marks,font:L.marks?.fontFamily})),S=At(e);for(let O=0;O<E.length;O++){const L=E[O],X=p[O];if(X.length>0){const G=this.getParagraphLineIndentPt(e,O,l),k=Math.max(1,i-G),N=this.measureLineAdvancePt(X,P,!!e.heading,d),H=p[O+1];if(S.widowControl&&E.length>=3&&O===E.length-2&&H&&s+N<=f){const j=this.measureLineAdvancePt(H,P,!!e.heading,d);s+N+j>f&&s!==n.marginTopPt&&m()}b(N);const z=y==="rtl"?x:x+G;M&&this.drawParagraphDecorationSlice(t,M,x,s,i,N,O===0,O===E.length-1),h?.push({pageNumber:_(),y:s,height:N}),s=this.renderLine(t,X,s,z,k,v,P,r,!!e.heading,d,O===E.length-1,{direction:y,...L.tabLayout?{tabLayoutPx:L.tabLayout.segments,...L.tabLayout.rtl?{tabRtl:!0,tabWidthPx:L.tabLayout.width}:{}}:{},...L.hyphenTrailing?{hyphenTrailing:!0}:{}})}}return s}return this.renderParagraphWithJsPDFWrapping(t,g,a,i,r,o,l,n)}static async prepareLatexImages(t,e){const a=new Map;for(const i of t.children)if(i.type==="text"&&i.marks?.latex){const r=await this.renderLatexToImage(i.text,!1,e);r&&a.set(i.text,r)}return a}static async renderParagraphWithJsPDFWrapping(t,e,a,i,r,o,l=this.resolveIndentStepPx(),n=this.getDefaultPdfLayoutMetrics()){let h=a;const s=this.getParagraphFontSize(e),g=this.getParagraphLineHeight(e),P=this.getLineSpacingMultiplier(e);let c=Number.isFinite(o)&&o>0?o:this.getPdfFlowBottom(t,n),d=n.marginLeftPt;const f=()=>{if(h+g>c){if(h===n.marginTopPt)return;const w=this.advancePdfFlowRegion(t,n);h=w.y,d=w.x,c=this.getPdfFlowBottom(t,n)}},x=this.getParagraphDirection(e),m=this.getEffectiveParagraphAlignment(e,x),b=await this.processTextNodesWithLatex(e.children,s);if(b.length===0)return h+this.getEmptyParagraphLineHeight(e);let _=[],y=0,v=0;const M=()=>Math.max(1,i-this.getParagraphLineIndentPt(e,v,l)),A=(w=!1)=>{if(_.length===0)return;f();const E=this.getParagraphLineIndentPt(e,v,l);h=this.renderLine(t,_,h,x==="rtl"?d:d+E,Math.max(1,i-E),m,s,r,!!e.heading,P,w,{direction:x}),_=[],y=0,v+=1};if(b.length===1&&b[0].text==="")return a+this.getEmptyParagraphLineHeight(e);for(const w of b){if(w.latexImage){const u=w.latexImage.contentWidth*this.PX_TO_PT;y+u>M()&&_.length>0&&A(),_.push({text:w.text,marks:w.marks,font:w.font||w.marks?.fontFamily,latexImage:w.latexImage}),y+=u;continue}this.setRunFont(t,w,r),t.setFontSize(this.getRunEffectiveFontSizePt(w.marks,s));const E=w.text.split(`
2
+ `);for(let u=0;u<E.length;u++){const p=E[u];u>0&&_.length>0&&A();const S=p.split(/(\s+)/);for(const O of S){const L=this.measureRunDisplayWidthPt(t,O,w.marks);y+L>M()&&_.length>0&&A(),(O.trim()||_.length>0)&&(_.push({text:O,marks:w.marks,font:w.font||w.marks?.fontFamily}),y+=L)}}}return _.length>0&&A(!0),h}static getLineSpacingMultiplier(t){return oe(t)}static async renderListBlock(t,e,a,i,r,o=this.getDefaultPdfLayoutMetrics(),l,n){if(!e.children.length)return a;let h=a;const s=this.getPdfFlowBottom(t,o),g=l??Fe(e),P={...g.counters};let c;if(e.variant==="ordered"&&e.numberingFormat)try{t.setFont(this.mapFontFamily(r),"normal"),t.setFontSize(this.FONT_SIZES.normal);let d=0;for(const x of Se(e,g))d=Math.max(d,t.getTextWidth(x)/this.PX_TO_PT);const f=this.ORDERED_LIST_INDENT_PT/this.PX_TO_PT;c=Math.min(Math.max(f,Math.ceil(d)+10),240)*this.PX_TO_PT}catch{c=void 0}for(let d=0;d<e.children.length;d++){const f=e.children[d],x=this.getListIndentLevel(f);let m;e.variant==="ordered"?m={type:"ordered",label:this.computeOrderedMarkerLabel(P,x,g.start,Le(e.numberingFormat))}:e.variant==="todo"?m={type:"todo",checked:!!f.checked}:m={type:"bullet",indentLevel:x},h=await this.renderListItem(t,f,e,m,h,i,s,r,o,n,c)}return h}static async renderListItem(t,e,a,i,r,o,l,n,h=this.getDefaultPdfLayoutMetrics(),s,g){let P=r+Math.max(0,e.spaceBefore??0)*this.PX_TO_PT;const c=this.getListIndentLevel(e)*this.SUBLIST_INDENT_PT,d=n,f=this.FONT_SIZES.normal,x=this.mapFontFamily(d);t.setFont(x,"normal"),t.setFontSize(f);const m=g??this.getListIndentPt(a.variant);let b=h.marginLeftPt,_=b+c+m,y=l;const v=()=>{const T=this.advancePdfFlowRegion(t,h);P=T.y,b=T.x,_=b+c+m,y=this.getPdfFlowBottom(t,h)};let M=o-c-m;(!Number.isFinite(M)||M<=0)&&(M=Math.max(o*.3,o*.1));let A="";for(const T of e.children)A+=T.text??"";const w=Qe(A)??"ltr",E=w==="rtl",u=()=>E?b:_,p=()=>E?b+M:_,S=e.lineSpacing??a.lineSpacing??this.LINE_HEIGHT_MULTIPLIERS.paragraph,O=f*S,L=await this.processTextNodesWithLatex(e.children,f);let X=L.length>0?L:[{text:""}];a.variant==="todo"&&e.checked&&(X=X.map(T=>T.latexImage?T:{...T,marks:{...T.marks,strikethrough:!0,color:wt.todoCheckedText}}));const G=new Set(Object.values(this.SCRIPT_FALLBACK_FONTS).map(T=>T.family)),k=[...L].reverse().find(T=>!T.latexImage&&!T.marks?.latex&&T.text.length>0&&!G.has(T.marks?.fontFamily??""))?.marks;let N=[],H=0,z=!1;const j=()=>{z||(P+O>y&&P!==h.marginTopPt&&v(),this.drawListMarker(t,i,p(),P,O,f,d,n,E,k),z=!0)},V=()=>{N.length!==0&&(P+O>y&&P!==h.marginTopPt&&v(),j(),s?.push({pageNumber:t.getCurrentPageInfo?.().pageNumber??t.getNumberOfPages(),y:P,height:this.measureLineAdvancePt(N,f,!1,S)}),P=this.renderLine(t,N,P,u(),M,E?"right":"left",f,d,!1,S,!0,{direction:w}),N=[],H=0)};for(const T of X){if(T.latexImage){const F=T.latexImage.contentWidth*this.PX_TO_PT;H+F>M&&N.length>0&&V(),N.push({text:T.text,marks:T.marks,font:T.font,latexImage:T.latexImage}),H+=F;continue}this.setRunFont(t,T,d||n),t.setFontSize(this.getRunEffectiveFontSizePt(T.marks,f));const I=T.text.split(`
3
+ `);for(let F=0;F<I.length;F++){const K=I[F];F>0&&(N.length>0?V():(j(),P+=O));const D=K.split(/(\s+)/);for(const C of D){const B=this.measureRunDisplayWidthPt(t,C,T.marks);H+B>M&&N.length>0&&V(),(C.trim()||N.length>0)&&(N.push({text:C,marks:T.marks,font:T.font}),H+=B)}}}return N.length>0&&V(),z||(j(),P+=O),P+Math.max(0,e.spaceAfter??0)*this.PX_TO_PT}static drawListMarker(t,e,a,i,r,o,l,n,h,s){t.setDrawColor(0,0,0);const g=(d,f=0)=>h?2*a-d-f:d,P=a-this.BULLET_MARKER_WIDTH_PT,c=i+r/2;switch(e.type){case"bullet":{const d=g(P+this.BULLET_CENTER_OFFSET_PT),f=this.BULLET_RADIUS_PT;if(e.indentLevel<=0)t.circle(d,c,f,"F");else if(e.indentLevel===1)t.circle(d,c,f,"S");else{const x=this.BULLET_SQUARE_HALF_PT*2,m=g(P+this.BULLET_SQUARE_INSET_PT,x),b=c-this.BULLET_SQUARE_HALF_PT+this.BULLET_SQUARE_VERTICAL_ADJUST_PT;t.rect(m,b,x,x,"S")}break}case"todo":{const d=this.TODO_CHECKBOX_SIZE_PT,f=g(P-this.TODO_CHECKBOX_OFFSET_PT,d),x=c-d/2;t.setLineWidth(.8),typeof t.roundedRect=="function"?t.roundedRect(f,x,d,d,this.TODO_CHECKBOX_RADIUS_PT,this.TODO_CHECKBOX_RADIUS_PT,"S"):t.rect(f,x,d,d,"S"),e.checked&&(t.setLineWidth(1.2),t.line(f+d*.15,x+d*.55,f+d*.4,x+d*.75),t.line(f+d*.4,x+d*.75,f+d*.85,x+d*.25));break}case"ordered":{const d=e.label,f=s?{fontFamily:s.fontFamily,fontSize:s.fontSize,bold:s.bold,italic:s.italic,code:s.code,superscript:s.superscript,subscript:s.subscript}:void 0;this.setRunFont(t,{text:d,marks:f},l||n);const x=this.getRunEffectiveFontSizePt(f,o);t.setFontSize(x);const m=t.getTextWidth(d),b=h?a+this.ORDERED_LABEL_GAP_PT:a-this.ORDERED_LABEL_GAP_PT-m;t.text(d,b,i+x);break}}t.setLineWidth(.5),t.setTextColor(0,0,0)}static async renderTableBlock(t,e,a,i,r,o=Xt,l=!1,n=this.getDefaultPdfLayoutMetrics()){if(!e.children||e.children.length===0)return a;const h=this.getPdfFlowBottom(t,n);let s=a;const g=e.borderWidth??Et.borderWidthPx,P=e.borderColor??Et.borderColor,c=this.hexToRgb(P),d=Number.isFinite(e.cellPadding)?Math.max(0,Math.round(e.cellPadding)):Et.cellPaddingPx,f=d*this.PX_TO_PT,x=Xe(e.borders),m=ze(e),b=m.cols,_=Math.min(e.tableWidth?e.tableWidth*this.PX_TO_PT:i,i),y=e.align==="center"?(i-_)/2:e.align==="right"?i-_:0;let v=n.marginLeftPt+y;const M=(e.columnWidths||[]).map(T=>T/100*_),A=[];for(let T=0;T<b;T++)A.push(M[T]||_/b);const w=[0];for(let T=0;T<b;T++)w.push(w[T]+A[T]);const E=T=>w[Math.min(T.col+T.colSpan,b)]-w[T.col],u=new Map;for(const T of m.cells){const I=We(d,T.cell.padding),F={top:I.top*this.PX_TO_PT,right:I.right*this.PX_TO_PT,bottom:I.bottom*this.PX_TO_PT,left:I.left*this.PX_TO_PT},K=E(T)-F.left-F.right,D=this.extractCellBlocks(T.cell);let C=this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph;if(D.length>0){const U=await import("./jspdf.es.min-DU74zN8b.js").then(Z=>Z.j),W=U.jsPDF??U.default,Y=new W({orientation:"portrait",unit:"pt",format:[Math.max(72,K),this.UNBOUNDED_CELL_FLOW_BOTTOM_PT]});await this.registerCurrentPdfFonts(Y,l);const q={...n,keepFirstBlockDeclaredSpaceBefore:!0,pageWidthPt:Math.max(72,K),pageHeightPt:this.UNBOUNDED_CELL_FLOW_BOTTOM_PT,marginTopPt:0,marginRightPt:0,marginBottomPt:0,marginLeftPt:0,contentWidthPt:Math.max(1,K)};C=(await this.renderBodyBlocks(Y,D,q,o,l,r,void 0,void 0,void 0,0)).finalY}const B=F.top+C+F.bottom;u.set(T.cell.id,{blocks:D,width:K,flowHeight:C,contentHeight:B,pad:F})}const p=e.children.map((T,I)=>{let F=0;for(const K of T.children){const D=m.byId.get(K.id);D&&D.rowSpan>1||(F=Math.max(F,u.get(K.id)?.contentHeight??0))}return F}),S=m.cells.filter(T=>T.rowSpan>1).sort((T,I)=>T.rowSpan-I.rowSpan);for(const T of S){const I=u.get(T.cell.id);if(!I)continue;let F=0;for(let K=T.row;K<T.row+T.rowSpan;K++)F+=p[K];I.contentHeight>F&&(p[T.row+T.rowSpan-1]+=I.contentHeight-F)}const O=T=>{let I=0;for(let F=T.row;F<T.row+T.rowSpan;F++)I+=p[F];return I},L=[],X=()=>{if(L.length===0)return;const T=this.getPdfCurrentPage(t);for(const{page:I,draw:F}of L)t.setPage(I),F();L.length=0,t.setPage(T)},G=(T,I,F,K,D,C,B)=>{const U=T.backgroundColor?this.hexToRgb(T.backgroundColor):B?{r:249,g:250,b:251}:{r:255,g:255,b:255};(T.backgroundColor||B)&&(t.setFillColor(U.r,U.g,U.b),t.rect(F,D,K,C,"F"));const W=this.getPdfCurrentPage(t),Y=Ge(T.borders);if(x||Y){const q=Ue({tableBorders:x,cellBorders:Y,flags:{isTopRow:(I?.row??0)===0,isBottomRow:I?I.row+I.rowSpan===m.rows:!1,isLeftCol:(I?.col??0)===0,isRightCol:I?I.col+I.colSpan===m.cols:!1},fallback:{style:"single",width:g,color:P}}),Z=F+K,Q=D+C;L.push({page:W,draw:()=>{this.drawPdfBorderEdge(t,q.top,F,D,Z,D),this.drawPdfBorderEdge(t,q.bottom,F,Q,Z,Q),this.drawPdfBorderEdge(t,q.left,F,D,F,Q),this.drawPdfBorderEdge(t,q.right,Z,D,Z,Q)}})}else g>0&&L.push({page:W,draw:()=>{t.setDrawColor(c.r,c.g,c.b),t.setLineWidth(g*this.PX_TO_PT),t.rect(F,D,K,C,"S")}})},k=async(T,I,F,K)=>{const D=!!e.hasHeader&&I===0,C=p[I],B=this.getPdfCurrentPage(t);for(const U of T.children){t.setPage(B);const W=m.byId.get(U.id),Y=v+(W?w[W.col]:0),q=W?E(W):_/b,Z=K||!W?C:O(W);G(U,W,Y,q,F,Z,D);const Q=u.get(U.id),tt=Q?.blocks??this.extractCellBlocks(U),at=Q?.pad.left??f,rt=Q?.pad.right??f,st=Q?.pad.top??f,lt=Q?.pad.bottom??f,ht=Q?.width??q-at-rt,nt=Q?.flowHeight??this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph,mt=Math.max(0,Z-st-lt-nt),pt=U.verticalAlign==="bottom"?mt:U.verticalAlign==="middle"?mt/2:0,Ot=F+st+pt;if(tt.length>0){const kt={...n,keepFirstBlockDeclaredSpaceBefore:!0,columnCount:1,columnFlow:void 0,marginTopPt:Ot,marginRightPt:Math.max(0,n.pageWidthPt-(Y+at+ht)),marginBottomPt:n.pageHeightPt-this.UNBOUNDED_CELL_FLOW_BOTTOM_PT,marginLeftPt:Y+at,pageMarginLeftPt:Y+at,contentWidthPt:Math.max(1,ht),fullContentWidthPt:Math.max(1,ht),columnStridePt:Math.max(1,ht)};await this.renderBodyBlocks(t,tt,kt,o,l,r,void 0,void 0,void 0,Ot)}}t.setPage(B)},N=(T,I)=>T.idx!==I.idx?T.idx>I.idx?T:I:T.y>=I.y?T:I,H=async(T,I,F,K,D,C)=>{const B=u.get(I.id),U=B?.blocks??this.extractCellBlocks(I),W=B?.pad.left??f,Y=B?.pad.bottom??f,q=F?E(F):_/b,Z=B?.width??q-W-(B?.pad.right??f),Q=F?w[F.col]:0;let tt=K.idx;if(U.length===0){const nt=B?.flowHeight??this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph;return{idx:tt,y:Math.min(C,K.y+nt+Y)}}const at=(nt,mt)=>{const pt=nt.left+Q+W;mt.marginTopPt=nt.top,mt.marginLeftPt=pt,mt.pageMarginLeftPt=pt,mt.marginRightPt=Math.max(0,n.pageWidthPt-(pt+Z))},rt={...n,keepFirstBlockDeclaredSpaceBefore:!0,columnCount:1,columnFlow:void 0,marginBottomPt:n.pageHeightPt-C,reservedInsetForPage:void 0,contentWidthPt:Math.max(1,Z),fullContentWidthPt:Math.max(1,Z),columnStridePt:Math.max(1,Z)},st=D(tt);at(st,rt),T.setPage(st.page);const lt=T.addPage;T.addPage=()=>{tt+=1;const nt=D(tt);return at(nt,rt),T.setPage(nt.page),T};let ht=K.y;try{ht=(await this.renderBodyBlocks(T,U,rt,o,l,r,void 0,void 0,void 0,K.y)).finalY}finally{T.addPage=lt}return{idx:tt,y:Math.min(C,ht+Y)}},z=async(T,I,F)=>{const K=h,D=j&&T>0?p[0]:0,C=n.marginTopPt+D,B=await import("./jspdf.es.min-DU74zN8b.js").then($=>$.j),U=B.jsPDF??B.default,W=new U({orientation:n.orientation,unit:"pt",format:[n.pageWidthPt,n.pageHeightPt]});await this.registerCurrentPdfFonts(W,l);const Y=W.addPage.bind(W),q=[{page:1,top:n.marginTopPt,left:v}],Z=$=>{for(;q.length<=$;)Y(),q.push({page:q.length+1,top:C,left:v});return q[$]},Q=($,it)=>{let{idx:Tt,y:gt}=$,dt=it;for(;;){const Pt=Math.max(0,K-gt);if(dt<=Pt+.01)return{idx:Tt,y:gt+dt};dt-=Pt,Tt+=1,gt=C}},tt=[],at=[],rt=new Map,st=[];let lt={idx:0,y:F};for(let $=T;$<I;$++){const it=lt;tt[$-T]=it;for(const dt of e.children[$].children){const Pt=m.byId.get(dt.id),bt=u.get(dt.id)?.pad.top??f,Mt=it.y+bt>K+.01?{idx:it.idx+1,y:C+bt}:{idx:it.idx,y:it.y+bt};rt.set(dt.id,Mt);const xt=await H(W,dt,Pt,Mt,Z,K),_t=Math.min(I-1,$+(Pt?.rowSpan??1)-1),Ft=st[_t-T];st[_t-T]=Ft?N(Ft,xt):xt}const Tt=Q(it,p[$]),gt=st[$-T];lt=gt?N(Tt,gt):Tt,at[$-T]=lt}let ht=lt.idx;for(const $ of rt.values())ht=Math.max(ht,$.idx);ht=Math.max(ht,q.length-1);const nt=[{page:this.getPdfCurrentPage(t),top:n.marginTopPt,left:v}],mt=t.addPage,pt=()=>{const $=this.advancePdfFlowRegion(t,n);return v=$.x+y,{page:this.getPdfCurrentPage(t),top:$.y+D,left:v}};for(let $=1;$<=ht;$++){const it=pt();nt.push(it),D>0&&await k(e.children[0],0,it.top-D,!0)}const Ot=$=>{for(;nt.length<=$;){const it=t.addPage;t.addPage=mt;try{nt.push(pt())}finally{t.addPage=it}}return nt[$]};for(let $=T;$<I;$++){const it=!!e.hasHeader&&$===0;for(const Tt of e.children[$].children){const gt=m.byId.get(Tt.id),dt=Math.min(I-1,$+(gt?.rowSpan??1)-1),Pt=tt[$-T],bt=at[dt-T],Mt=gt?E(gt):_/b;for(let xt=Pt.idx;xt<=bt.idx;xt++){const _t=nt[xt],Ft=xt===Pt.idx?Pt.y:_t.top,Ht=xt===bt.idx?bt.y:K;Ht-Ft<=.01||(t.setPage(_t.page),G(Tt,gt,_t.left+(gt?w[gt.col]:0),Mt,Ft,Ht-Ft,it))}}}for(let $=T;$<I;$++)for(const it of e.children[$].children)await H(t,it,m.byId.get(it.id),rt.get(it.id),Ot,K);const kt=at[at.length-1],Wt=nt[Math.min(kt.idx,nt.length-1)];return t.setPage(Wt.page),v=Wt.left,kt.y},j=e.hasHeader===!0&&e.children.length>1&&!m.cells.some(T=>T.row===0&&T.rowSpan>1),V=e.children.map(()=>[]);for(const T of m.cells)V[T.row]?.push(T);for(let T=0;T<e.children.length;){let I=T+1,F=0;for(let B=T;B<I;B++){F+=p[B];for(const U of V[B])I=Math.min(e.children.length,Math.max(I,U.row+U.rowSpan))}const K=j&&T>0?p[0]:0,D=h-n.marginTopPt-K,C=F>D;if((C?s>=h-.01:s+F>h)&&s!==n.marginTopPt){const B=this.advancePdfFlowRegion(t,n);s=B.y,v=B.x+y,j&&T>0&&(await k(e.children[0],0,s,!0),s+=p[0])}if(C)s=await z(T,I,s);else for(let B=T;B<I;B++)await k(e.children[B],B,s,!1),s+=p[B];T=I}return X(),s}static async renderCodeBlock(t,e,a,i,r,o=this.MARGIN_LEFT,l=Xt,n=!1,h=this.getDefaultPdfLayoutMetrics(),s){const g=o-h.marginLeftPt;let P=o;const c=e.language||"",d=ta(c);if(d&&e.renderDiagram!==!1&&d)return this.renderDiagramCodeBlock(t,e,a,i,r,P,d,l,n,h);const f=n?"SourceCodePro":"courier",x=e.content||"",m=c?await ea(x,c,l):null,b=ft.fontSizePx*this.PX_TO_PT,_=b*ft.lineHeightMultiplier,y=ft.paddingPx*this.PX_TO_PT,v=ft.borderRadiusPx*this.PX_TO_PT,M=this.hexToRgb(l.background),A=this.hexToRgb(l.default);t.setFont(f,"normal"),t.setFontSize(b);const w=Math.max(1,i-y*2),E=Zt(x,k=>t.getTextWidth(k),w),u=[];let p=0;for(const k of m??[])u.push({start:p,end:p+k.text.length,color:k.color}),p+=k.text.length;const S=k=>{if(u.length===0)return[{text:k.text,color:l.default}];const N=[];for(const H of u){const z=Math.max(k.startCharOffset,H.start),j=Math.min(k.endCharOffset,H.end);j<=z||N.push({text:x.slice(z,j),color:H.color})}return N.length>0?N:[{text:k.text,color:l.default}]};let O=a,L=0,X=r;const G=()=>{const k=this.advancePdfFlowRegion(t,h);O=k.y,P=k.x+g,X=this.getPdfFlowBottom(t,h)};for(;L<E.length;){const k=L===0,N=k?y:0,H=N+_+(E.length===L+1?y:0);O+H>X&&O!==h.marginTopPt&&G();let z=L,j=N;for(;z<E.length;){const T=z===E.length-1,I=j+_+(T?y:0);if(O+I>X&&z>L)break;j+=_,z+=1}const V=z===E.length;V&&(j+=y),t.setFillColor(M.r,M.g,M.b),k&&V?this.drawRoundedRect(t,P,O,i,j,v):t.rect(P,O,i,j,"F"),t.setFont(f,"normal"),t.setFontSize(b);for(let T=L;T<z;T++){const I=T===0,F=T===E.length-1,K=O+N+(T-L)*_;s?.push({pageNumber:t.getCurrentPageInfo?.().pageNumber??t.getNumberOfPages(),y:K-(I?y:0),height:_+(I?y:0)+(F?y:0)});let D=P+y;const C=O+N+(T-L)*_+b;for(const B of S(E[T])){const U=B.color?this.hexToRgb(B.color):A;t.setTextColor(U.r,U.g,U.b),B.text&&t.text(B.text,D,C),D+=t.getTextWidth(B.text)}}O+=j,L=z,V||G()}return O}static async renderDiagramCodeBlock(t,e,a,i,r,o,l,n,h,s){const g=o-s.marginLeftPt;let P=o;const c=ft.paddingPx*this.PX_TO_PT,d=ft.diagramSourceGapPx*this.PX_TO_PT,f=ne(),x=Math.max(120,Math.round((i-c*2)/this.PX_TO_PT)),m=await aa({protocol:l,source:e.content||"",theme:f,maxWidth:x}),b=Math.max(1,m.width*this.PX_TO_PT),_=Math.max(ft.diagramMinHeightPx,m.height)*this.PX_TO_PT,y=_+c*2,v=e.showDiagramSource!==!1,M=h?"SourceCodePro":"courier",A=ft.fontSizePx*this.PX_TO_PT;t.setFont(M,"normal"),t.setFontSize(A);const w=Zt(e.content||"",N=>t.getTextWidth(N),Math.max(1,i-c*2)),E=c*2+w.length*A*ft.lineHeightMultiplier,u=(v?E+d:0)+y;let p=a;if(p+u>r&&p!==s.marginTopPt){const N=this.advancePdfFlowRegion(t,s);p=N.y,P=N.x+g}v&&(p=await this.renderCodeBlock(t,{...e,renderDiagram:!1},p,i,r,P,n,h,s),p+=d);const S=this.hexToRgb(f.codeBorder||"#e0e0e0"),O=ft.borderRadiusPx*this.PX_TO_PT;t.setDrawColor(S.r,S.g,S.b),t.setLineWidth(this.BLOCK_BORDER_WIDTH_PT),this.drawRoundedRect(t,P,p,i,y,O,"S");const L=Math.min(i-c*2,b),X=Math.min(y-c*2,_),G=P+(i-L)/2,k=p+(y-X)/2;if(m.svg){const N=await this.svgToPng(m.svg,Math.max(1,Math.round(m.width)),Math.max(1,Math.round(m.height)),2);if(N)return t.addImage(N,"PNG",G,k,L,X),p+y}return t.setTextColor(220,38,38),t.setFont("helvetica","normal"),t.setFontSize(10),t.text("Diagram unavailable",P+c,p+c+10),p+y}static renderCellParagraph(t,e,a,i,r,o,l=!1){const n=this.getParagraphFontSize(e),h=this.getParagraphDirection(e),s=this.getEffectiveParagraphAlignment(e,h),g=this.getLineSpacingMultiplier(e),P=this.processTextNodes(e.children);let c=i,d=[],f=0;const x=m=>{d.length!==0&&(l?c+=this.measureLineAdvancePt(d,n,!!e.heading,g):c=this.renderLine(t,d,c,a,r,s,n,o,!!e.heading,g,m,{direction:h}),d=[],f=0)};for(const m of P){this.setRunFont(t,m,o),t.setFontSize(this.getRunEffectiveFontSizePt(m.marks,n));const b=m.text.split(`
4
+ `);for(let _=0;_<b.length;_++){_>0&&x(!1);const y=b[_].split(/(\s+)/);for(const v of y){const M=this.measureRunDisplayWidthPt(t,v,m.marks);f+M>r&&d.length>0&&x(!1),(v.trim()||d.length>0)&&(d.push({text:v,marks:m.marks,font:m.marks?.fontFamily}),f+=M)}}}return x(!0),c===i&&(c+=this.getEmptyParagraphLineHeight(e)),c}static extractCellBlocks(t){return t.children}static drawRoundedRect(t,e,a,i,r,o,l="F"){const n=Math.min(o,i/2,r/2);t.roundedRect(e,a,i,r,n,n,l)}static getListIndentPt(t){switch(t){case"todo":return this.TODO_LIST_INDENT_PT;case"ordered":return this.ORDERED_LIST_INDENT_PT;case"unordered":default:return this.UNORDERED_LIST_INDENT_PT}}static getListIndentLevel(t){const e=t.indentLevel??0;if(!Number.isFinite(e))return 0;const a=Math.floor(e);return Math.max(0,Math.min(a,this.MAX_LIST_INDENT_LEVEL))}static computeOrderedMarkerLabel(t,e,a,i){return we(t,a,e,i)}static getRunLetterSpacingPt(t){return(typeof t?.letterSpacing=="number"&&Number.isFinite(t.letterSpacing)?t.letterSpacing:0)*this.PX_TO_PT}static getRunEffectiveFontSizePt(t,e){const a=t?.fontSize?t.fontSize*this.PX_TO_PT:e;return t?.superscript||t?.subscript?Math.round(a/this.PX_TO_PT*.7)*this.PX_TO_PT:a}static setRunFont(t,e,a){if(e.marks?.code){t.setFont(this.inlineCodeFontFamily,"normal");return}const i=this.mapFontFamily(e.font||e.marks?.fontFamily||a),r=this.resolveFontStyle(e.marks),o=this.scriptFallbackFor(t,e.text,i);if(o){t.setFont(o,r==="bold"||r==="bolditalic"?"bold":"normal");return}t.setFont(i,r)}static measureRunDisplayWidthPt(t,e,a){const i=o=>{const l=t.getFont?.()?.fontName,n=l?this.shapingFonts.get(l):void 0;return n?n.layout(o).advanceWidth*t.getFontSize()/n.unitsPerEm:t.getTextWidth(o)},r=Ee(a);return r?Vt(e,{...r,letterSpacingPx:this.getRunLetterSpacingPt(a)},i):i(e)}static drawShapedText(t,e,a,i,r,o,l){const n=t.getFont?.()?.fontName,h=n?this.shapingFonts.get(n):void 0;if(!h)return null;const s=h.layout(e);Array.from(e).every(f=>(f.codePointAt(0)??0)<=65535)&&t.text(e,a,i,{renderingMode:"invisible"}),t.setFillColor(l.r,l.g,l.b);const g=r/h.unitsPerEm;let P=0,c=0,d=0;for(let f=0;f<s.glyphs.length;f++){const x=s.glyphs[f],m=s.positions[f],b=[];let _=0,y=0;const v=A=>a+d+(P+m.xOffset+A)*g,M=A=>i-(c+m.yOffset+A)*g;for(const A of x.path.commands)if(A.command==="moveTo")[_,y]=A.args,b.push({op:"m",c:[v(_),M(y)]});else if(A.command==="lineTo")[_,y]=A.args,b.push({op:"l",c:[v(_),M(y)]});else if(A.command==="bezierCurveTo"){const[w,E,u,p,S,O]=A.args;b.push({op:"c",c:[v(w),M(E),v(u),M(p),v(S),M(O)]}),_=S,y=O}else if(A.command==="quadraticCurveTo"){const[w,E,u,p]=A.args,S=_+(w-_)*2/3,O=y+(E-y)*2/3,L=u+(w-u)*2/3,X=p+(E-p)*2/3;b.push({op:"c",c:[v(S),M(O),v(L),M(X),v(u),M(p)]}),_=u,y=p}else A.command==="closePath"&&b.push({op:"h",c:[]});b.length>0&&(t.path(b),t.fill()),P+=m.xAdvance,c+=m.yAdvance,d+=o*Math.max(1,x.codePoints?.length??1)}return s.advanceWidth*r/h.unitsPerEm+o*[...e].length}static renderLine(t,e,a,i,r,o,l,n,h,s,g=!0,P){e=e.filter(u=>!u.marks?.hidden||!!u.marks.footnoteRef);let c=P?.tabLayoutPx;const d=u=>u.marks?.fontSize?u.marks.fontSize*this.PX_TO_PT:l,f=P?.direction??"ltr";if(!c&&e.length>0&&!e.some(u=>u.latexImage||u.marks?.latex)){const u=e,p={segments:u.map(O=>({text:O.text}))},S=Qt(p,f);if(S){const O=(X,G)=>{let k=0,N=0;for(const H of u){const z=Math.max(X,N),j=Math.min(G,N+H.text.length);if(z<j){const V=H.text.slice(z-N,j-N);this.setRunFont(t,{...H,text:V},n),t.setFontSize(this.getRunEffectiveFontSizePt(H.marks,l)),k+=this.measureRunDisplayWidthPt(t,V,H.marks)}N+=H.text.length}return k},L=u.map(X=>X.text).join("");e=te(p,S,O,o==="justify"&&!g).map(X=>({...u[X.segmentIndex],text:L.slice(X.start,X.end),rtl:X.rtl}))}}if(P?.tabRtl&&c&&c.length>0){const u=e,p=c,S=[],O=[];let L=0;for(;L<u.length;){const X=u[L];if(X.text===" "){S.push(X),O.push(p[L]??{startX:0,endX:0}),L++;continue}const G=L;let k=Number.NEGATIVE_INFINITY;for(;L<u.length&&u[L].text!==" ";){const F=p[L];F&&(k=Math.max(k,F.endX)),L++}const N=u.slice(G,L),H=N.map(F=>F.text).join("");if(!H)continue;Number.isFinite(k)||(k=0);const z={segments:N.map(F=>({text:F.text}))},j=Qt(z,"rtl");if(!j){for(let F=G;F<L;F++)S.push(u[F]),O.push(p[F]??{startX:0,endX:0});continue}const V=te(z,j,(F,K)=>{let D=0,C=0;for(const B of N){const U=Math.max(F,C),W=Math.min(K,C+B.text.length);if(U<W){const Y=B.text.slice(U-C,W-C);this.setRunFont(t,{...B,text:Y},n),t.setFontSize(this.getRunEffectiveFontSizePt(B.marks,l)),D+=this.measureRunDisplayWidthPt(t,Y,B.marks)}C+=B.text.length}return D}),T=V.reduce((F,K)=>F+K.width,0),I=k*this.PX_TO_PT-T;for(const F of V)S.push({...N[F.segmentIndex],text:H.slice(F.start,F.end),rtl:F.rtl}),O.push({startX:(I+F.x)/this.PX_TO_PT,endX:(I+F.x+F.width)/this.PX_TO_PT})}e=S,c=O}let x=0,m=0;for(const u of e)if(u.latexImage){const p=u.latexImage.contentHeight*this.PX_TO_PT;p>m&&(m=p)}else{const p=d(u);p>x&&(x=p)}x===0&&(x=l);const b=a+x;let _=0;if(c&&c.length>0)_=P?.tabRtl?(P.tabWidthPx??Math.max(...c.map(u=>u.endX)))*this.PX_TO_PT:c[c.length-1].endX*this.PX_TO_PT;else for(const u of e)u.latexImage?_+=u.latexImage.contentWidth*this.PX_TO_PT:(this.setRunFont(t,u,n),t.setFontSize(this.getRunEffectiveFontSizePt(u.marks,l)),_+=this.measureRunDisplayWidthPt(t,u.text,u.marks));let y=i;o==="center"?y=i+(r-_)/2:(o==="right"||o==="justify"&&f==="rtl"&&(g||c))&&(y=i+r-_),P?.tabRtl&&c&&(y=i);let v=0;if(o==="justify"&&!g&&!c){let u=0;for(const p of e)p.latexImage||p.marks?.latex||(u+=(p.text.match(/ /g)||[]).length);u>0&&(v=Math.max(0,(r-_)/u))}const M=y;for(let u=0;u<e.length;u++){const p=e[u],S=c?.[u];if(S&&(y=M+S.startX*this.PX_TO_PT,p.text===" ")){if(S.leader){const D=this.getRunEffectiveFontSizePt(p.marks,l),C=p.marks?.color?this.hexToRgb(p.marks.color):{r:0,g:0,b:0};this.renderTabLeaderPdf(t,M+S.startX*this.PX_TO_PT,M+S.endX*this.PX_TO_PT,b,S.leader,D,C)}y=M+S.endX*this.PX_TO_PT;continue}if(p.latexImage){const D=p.latexImage.width*this.PX_TO_PT,C=p.latexImage.height*this.PX_TO_PT,B=p.latexImage.contentWidth*this.PX_TO_PT,U=p.latexImage.contentHeight*this.PX_TO_PT,W=(D-B)/2,Y=y-W,q=b-U*.7-W;try{t.addImage(p.latexImage.dataUrl,"PNG",Y,q,D,C)}catch(Z){console.error("Failed to add inline latex image to PDF:",Z)}y+=B;continue}this.setRunFont(t,p,n);const O=d(p),L=this.getRunEffectiveFontSizePt(p.marks,l),X=L/this.PX_TO_PT;t.setFontSize(L);const G=!!p.marks?.link;let k={r:0,g:0,b:0};G?k={r:37,g:99,b:235}:p.marks?.color?k=this.hexToRgb(p.marks.color):p.marks?.code&&(k=this.hexToRgb(wt.codeText)),t.setTextColor(k.r,k.g,k.b);const N=!!(p.marks?.smallCaps&&!p.marks?.allCaps),H=this.getRunLetterSpacingPt(p.marks),z=p.rtl?{isInputVisual:!1,isOutputVisual:!0,isInputRtl:!0,isOutputRtl:!1}:void 0,j=H!==0||z?{...H!==0?{charSpace:H}:{},...z}:void 0,V=this.measureRunDisplayWidthPt(t,p.text,p.marks),T=v>0?(p.text.match(/ /g)||[]).length:0,I=V+T*v;if(p.marks?.backgroundColor){const D=ia(p.marks.backgroundColor)??p.marks.backgroundColor,C=this.hexToRgb(D);t.setFillColor(C.r,C.g,C.b),t.rect(y,b-O*.8,I,O*1.1,"F"),t.setTextColor(k.r,k.g,k.b)}else if(p.marks?.code){const D=this.hexToRgb(wt.codeBackground);t.setFillColor(D.r,D.g,D.b),this.drawRoundedRect(t,y-2*this.PX_TO_PT,b-O*.93,I+4*this.PX_TO_PT,O+4*this.PX_TO_PT,3*this.PX_TO_PT),t.setTextColor(k.r,k.g,k.b)}let F=b;p.marks?.superscript?F=b-O*.4:p.marks?.subscript&&(F=b+O*.15),(p.marks?.underline||G)&&!p.marks?.code&&(G?t.setDrawColor(37,99,235):t.setDrawColor(0,0,0),t.setLineWidth(.5),t.line(y,F+2,y+I,F+2));const K=(D,C)=>{const B=p.marks?.allCaps?Dt(D,p.marks.lang):D,U=this.drawShapedText(t,B,C,F,L,H,k);if(U!==null)return U;if(N){let W=C;for(const Y of ve(D,p.marks?.lang)){const q=Y.lower?t.getTextWidth(Dt(Y.text,p.marks?.lang))*ee:t.getTextWidth(Y.text);Y.lower?(t.setFontSize(L*ee),t.text(Dt(Y.text,p.marks?.lang),W,F,j),t.setFontSize(L)):t.text(Y.text,W,F,j),W+=q+H*Y.text.length}return W-C}return t.text(B,C,F,j),this.measureRunDisplayWidthPt(t,D,p.marks)};if(v>0){let D=y;for(const C of p.text.split(/( +)/))C&&(D+=K(C,D),C[0]===" "&&(D+=v*C.length))}else K(p.text,y);if(p.marks?.strikethrough||p.marks?.doubleStrikethrough){t.setDrawColor(k.r,k.g,k.b),t.setLineWidth(Math.max(1,Math.round(X*.04))*this.PX_TO_PT);const D=C=>{const B=C-L*.3;t.line(y,B,y+I,B)};p.marks?.doubleStrikethrough?(D(F+L*.09),D(F-L*.09)):D(F)}if(G&&p.marks?.link){const D=b-O*.8,C=O*1.1;t.link(y,D,I,C,{url:p.marks.link})}y+=I}if(P?.hyphenTrailing){const u=e[e.length-1];if(u&&!u.marks?.latex){this.setRunFont(t,u,n),t.setFontSize(this.getRunEffectiveFontSizePt(u.marks,l));const p=u.marks?.color?this.hexToRgb(u.marks.color):{r:0,g:0,b:0};t.setTextColor(p.r,p.g,p.b),t.text("-",y,b)}}const A=s??(h?this.LINE_HEIGHT_MULTIPLIERS.heading:this.LINE_HEIGHT_MULTIPLIERS.paragraph),w=x*A,E=m>w*1.25?m:w;return a+E}static renderTabLeaderPdf(t,e,a,i,r,o,l){const n=Math.max(1.5,o*.12),h=e+n,s=a-n;if(s-h<1)return;if(t.setFillColor(l.r,l.g,l.b),r==="underscore"){const P=i+Math.max(1,o*.08),c=Math.max(.75,o*.055);t.rect(h,P,s-h,c,"F");return}const g=Math.max(2.25,o*.33);if(r==="dot"){const P=Math.max(.45,o*.045),c=i-P;for(let d=Math.ceil(h/g)*g;d<=s;d+=g)t.circle(d,c,P,"F")}else{const P=Math.max(1.5,o*.18),c=i-o*.28,d=Math.max(.75,o*.055);for(let f=Math.ceil(h/g)*g;f+P<=s;f+=g)t.rect(f,c,P,d,"F")}}static processTextNodes(t){const e=[];for(const a of t)if(a.type==="text"){const i=a;if(i.marks?.hidden&&!i.marks.footnoteRef)continue;e.push({text:i.text,marks:i.marks,font:i.marks?.fontFamily})}return e}static async processTextNodesWithLatex(t,e){const a=[];for(let o=0;o<t.length;o++){const l=t[o];if(l.type==="text"){const n=l;if(n.marks?.hidden&&!n.marks.footnoteRef)continue;n.marks?.latex?a.push({index:o,node:n,latexPromise:this.renderLatexToImage(n.text,!1,e)}):a.push({index:o,node:n})}}const i=await Promise.all(a.map(o=>o.latexPromise||Promise.resolve(null))),r=[];for(let o=0;o<a.length;o++){const{node:l}=a[o],n=i[o];r.push({text:l.text,marks:l.marks,font:l.marks?.fontFamily,latexImage:n||void 0})}return r}static getParagraphFontSize(t){return oa(t)*this.PX_TO_PT}static getParagraphLineHeight(t){return this.getParagraphFontSize(t)*oe(t)}static getEmptyParagraphLineHeight(t){return this.measureLineAdvancePt(this.paragraphForPdfOutput(t).children.map(e=>({marks:e.type==="text"?e.marks:void 0})),this.getParagraphFontSize(t),!!t.heading,this.getLineSpacingMultiplier(t))}static async embedLocalFonts(t,e){if(this.embeddedFamilyNames.clear(),typeof window>"u")return;const a=new Set(["sans-serif","sans","serif","monospace","system-ui","system ui","ui-sans-serif","ui-serif","ui-monospace"]),i=Nt(e).map(o=>o.family).filter(o=>{const l=o.toLowerCase();return!a.has(l)&&this.FONT_MAP[l]!=="KaTeX_Main"});if(i.length===0)return;let r;for(const o of i){const l=o.toLowerCase();let n=this.localFontFiles.get(l);if(n===void 0){if(r===void 0&&(r=await Pe().catch(()=>null)),!r)return;try{n=await this.buildLocalFontFiles(o,r)}catch{n=null}this.localFontFiles.set(l,n)}if(n)try{for(const h of n)t.addFileToVFS(h.vfsName,h.base64),t.addFont(h.vfsName,o,h.style);this.embeddedFamilyNames.set(l,o)}catch(h){console.warn(`Failed to embed font "${o}" in PDF:`,h),this.localFontFiles.set(l,null)}}}static async buildLocalFontFiles(t,e){const a=t.toLowerCase(),i=e.filter(c=>c.family?.trim().toLowerCase()===a&&c.blob);if(i.length===0)return null;const r=i.map(c=>({entry:c,...ue(c.style),specificity:(c.style??"").length})),o=(c,d)=>r.filter(f=>f.bold===c&&f.italic===d).sort((f,x)=>f.specificity-x.specificity)[0]?.entry,l=o(!1,!1)??r[0].entry,n=[{style:"normal",entry:l},{style:"bold",entry:o(!0,!1)??l},{style:"italic",entry:o(!1,!0)??l},{style:"bolditalic",entry:o(!0,!0)??o(!0,!1)??l}],h=new Map;for(const{entry:c}of n){if(h.has(c))continue;const d=await(await c.blob()).arrayBuffer(),f=Gt(new Uint8Array(d));h.set(c,f==="ttf"?this.arrayBufferToBase64(d):null)}if(!h.get(l))return null;const s=a.replace(/[^a-z0-9]+/g,"-"),g=new Map;let P=0;return n.map(({style:c,entry:d})=>{const f=h.get(d)?d:l;let x=g.get(f);return x||(x=`${s}-${P++}.ttf`,g.set(f,x)),{vfsName:x,base64:h.get(f),style:c}})}static mapFontFamily(t){const e=this.mapFontFamilyToStandard(t);return this.bundledGenreFamilies.get(e)??(e==="SourceSerif4"?"times":e)}static mapFontFamilyToStandard(t){if(!t)return"helvetica";const e=new Set(["helvetica","times","courier"]),a=t.split(",").map(r=>r.trim().replace(/^['"]|['"]$/g,"")).filter(r=>r.length>0);a.length===0&&a.push(t);for(const r of a){const o=r.toLowerCase(),l=this.embeddedFamilyNames.get(o);if(l)return l;if(e.has(o))return o;const n=this.FONT_MAP[o];if(n)return n}const i=pe(a[0]);return i==="serif"?"times":i==="monospace"?"courier":"helvetica"}static resolveFontStyle(t){const e=!!t?.bold,a=!!t?.italic;return e&&a?"bolditalic":e?"bold":a?"italic":"normal"}static drawPdfBorderEdge(t,e,a,i,r,o){if(e.style==="none"||e.width<=0)return;const l=this.hexToRgb(e.color);t.setDrawColor(l.r,l.g,l.b);const n=He(e).map(h=>h*this.PX_TO_PT);if(n.length>0&&typeof t.setLineDashPattern=="function"&&t.setLineDashPattern(n,0),e.style==="double"){const h=Math.max(e.width/3,.5)*this.PX_TO_PT,s=e.width*2/3/2*this.PX_TO_PT;t.setLineWidth(h);const g=i===o,P=g?0:s,c=g?s:0;t.line(a-P,i-c,r-P,o-c),t.line(a+P,i+c,r+P,o+c)}else t.setLineWidth(e.width*this.PX_TO_PT),t.line(a,i,r,o);n.length>0&&typeof t.setLineDashPattern=="function"&&t.setLineDashPattern([],0)}static hexToRgb(t){return Te(t)??{r:0,g:0,b:0}}static async renderImageBlock(t,e,a,i,r=this.getDefaultPdfLayoutMetrics()){if(!e.src)return{nextY:a};const o=this.getPdfFlowBottom(t,r);let l=Math.max(e.width||1,1)*this.PX_TO_PT,n=Math.max(e.height||1,1)*this.PX_TO_PT;if(l>i){const c=i/l;l=i,n*=c}(n<=0||!Number.isFinite(n))&&(n=72);let h=r.marginLeftPt;if(a+n>o&&a!==r.marginTopPt){const c=this.advancePdfFlowRegion(t,r);a=c.y,h=c.x}const s=e.align||"left";let g=h;if(s==="center"?g=h+(i-l)/2:s==="right"&&(g=h+i-l),e.originalFormat)return t.setFillColor(243,244,246),t.setDrawColor(209,213,219),t.setLineWidth(.75),t.rect(g,a,l,n,"FD"),t.setFont(this.mapFontFamily(void 0),"normal"),t.setFontSize(14*this.PX_TO_PT),t.setTextColor(107,114,128),t.text(`${e.originalFormat.toUpperCase()} image`,g+l/2,a+n/2,{align:"center",baseline:"middle"}),{nextY:a+n};const P=await this.resolveImageData(e.src);if(!P)return{nextY:a+n};try{t.addImage(P.data,P.format,g,a,l,n)}catch(c){return console.error("Failed to add image to PDF",c),{nextY:a+n}}return{nextY:a+n}}static async resolveImageData(t){const e=t.match(/^data:image\/([a-zA-Z0-9+.-]+);base64,/);if(e){const o=this.normalizeImageFormat(e[1]);return{data:t,format:o}}const a=await this.fetchImageAsBlob(t);if(!a)return null;const{blob:i,format:r}=a;return{data:await this.blobToDataUrl(i,r),format:r}}static async fetchImageAsBlob(t){try{const e=await fetch(t);if(!e.ok)throw new Error(`Failed to fetch image: ${e.status}`);const a=await e.blob(),i=this.extractImageFormat(a.type);return{blob:a,format:i}}catch(e){return console.error("Failed to load image for PDF export",e),null}}static async blobToDataUrl(t,e){const a=await t.arrayBuffer(),i=this.arrayBufferToBase64(a);return`data:${this.formatToMime(e)};base64,${i}`}static arrayBufferToBase64(t){const e=globalThis?.Buffer;if(e)return e.from(t).toString("base64");let a="";const i=new Uint8Array(t),r=32768;for(let o=0;o<i.length;o+=r){const l=i.subarray(o,o+r);a+=String.fromCharCode.apply(null,Array.from(l))}return btoa(a)}static formatToMime(t){const e=t.toLowerCase();return e==="jpeg"||e==="jpg"?"image/jpeg":e==="png"?"image/png":e==="webp"?"image/webp":`image/${e}`}static extractImageFormat(t){if(!t)return"PNG";const e=t.match(/^image\/([a-zA-Z0-9+.-]+)/);return e?this.normalizeImageFormat(e[1]):"PNG"}static normalizeImageFormat(t){const e=t.toLowerCase();return e==="jpg"||e==="jpeg"?"JPEG":e==="png"?"PNG":e==="webp"?"WEBP":e.toUpperCase()}static async renderMathBlock(t,e,a,i,r,o=this.getDefaultPdfLayoutMetrics()){if(!e.content||e.content.trim()==="")return{nextY:a};const l=e.displayMode!=="inline",n=await this.renderLatexToImage(e.content,l);if(!n)return{nextY:a+20};let h=n.width*this.PX_TO_PT,s=n.height*this.PX_TO_PT;const g=i-this.MATH_BLOCK_PADDING*2;if(h>g){const b=g/h;h=g,s*=b}const P=Math.max(this.MATH_BLOCK_MIN_HEIGHT,s)+this.MATH_BLOCK_PADDING*2;let c=o.marginLeftPt;if(a+P>r&&a!==o.marginTopPt){const b=this.advancePdfFlowRegion(t,o);a=b.y,c=b.x}const d=this.hexToRgb(ne().codeBorder||"#e0e0e0");t.setDrawColor(d.r,d.g,d.b),t.setLineWidth(this.BLOCK_BORDER_WIDTH_PT),typeof t.roundedRect=="function"?t.roundedRect(c,a,i,P,this.MATH_BLOCK_BORDER_RADIUS,this.MATH_BLOCK_BORDER_RADIUS,"S"):t.rect(c,a,i,P,"S");const f=e.align||"center";let x=c+this.MATH_BLOCK_PADDING;f==="center"?x=c+(i-h)/2:f==="right"&&(x=c+i-h-this.MATH_BLOCK_PADDING);const m=a+(P-s)/2;try{t.addImage(n.dataUrl,"PNG",x,m,h,s)}catch(b){console.error("Failed to add math image to PDF:",b)}return{nextY:a+P}}static async getHtml2Canvas(){return this.html2canvasModule?this.html2canvasModule:this.html2canvasLoading?this.html2canvasLoading:(this.html2canvasLoading=import("./html2canvas.esm-CntiHiYW.js").then(t=>(this.html2canvasModule=t.default,t.default)),this.html2canvasLoading)}static async renderLatexToImage(t,e,a=12){const i=this.getLatexSvgFromCache(t,e);if(i){const r=await this.svgToPng(i.svg,i.width,i.height,3);if(r){const o=e?1:this.INLINE_MATH_SCALE;return{dataUrl:r,width:i.width*o,height:i.height*o,contentWidth:i.contentWidth*o,contentHeight:i.contentHeight*o}}}try{const r=await this.getHtml2Canvas(),o=this.preprocessLaTeX(t),l=(await la()).renderToString(o,{displayMode:e,throwOnError:!1,errorColor:"#ef4444",trust:!1,strict:!1});this.ensureKaTeXStyles();const n=a/this.PX_TO_PT,h=e?20:n*this.INLINE_MATH_SCALE,s=4,g=document.createElement("div");g.style.cssText=`
5
+ position: fixed;
6
+ top: -9999px;
7
+ left: -9999px;
8
+ font-size: ${h}px;
9
+ line-height: 1.2;
10
+ background: transparent;
11
+ padding: ${s}px;
12
+ z-index: -9999;
13
+ `,g.innerHTML=l,document.body.appendChild(g),document.fonts?.ready&&await document.fonts.ready;const P=4,c=await r(g,{backgroundColor:null,scale:P,logging:!1,useCORS:!0,allowTaint:!1});document.body.removeChild(g);const d=c.toDataURL("image/png"),f=c.width/P,x=c.height/P,m=f-s*2,b=x-s*2;return{dataUrl:d,width:f,height:x,contentWidth:m,contentHeight:b}}catch(r){return console.error("Failed to render LaTeX for PDF:",r),null}}static preprocessLaTeX(t){if(!t.includes(`
14
+ `)||["align","aligned","gather","gathered","split","cases","matrix","pmatrix","bmatrix","array"].some(a=>t.includes(`\\begin{${a}}`)||t.includes(`\\begin{${a}*}`)))return t;const e=t.split(`
15
+ `).map(a=>a.trim()).filter(a=>a.length>0);return e.length<=1?t:`\\begin{gathered}
16
+ ${e.join(` \\\\
17
+ `)}
18
+ \\end{gathered}`}static ensureKaTeXStyles(){if(this.katexStylesLoaded)return;if(document.querySelector('link[href*="katex"]')){this.katexStylesLoaded=!0;return}const t=document.createElement("link");t.rel="stylesheet",t.href=Ct("katex.min.css"),document.head.appendChild(t),this.katexStylesLoaded=!0}static async parseFile(t){const e=await import("./pdf-BLWDCiFF.js");e.GlobalWorkerOptions.workerSrc=Ct("pdfjs/worker.js");const a=await t.arrayBuffer();try{const i=await e.getDocument(a).promise;let r="";for(let h=1;h<=i.numPages;h++){const s=(await(await i.getPage(h)).getTextContent()).items.map(g=>g.str).join(" ");r+=s+`
19
+
20
+ `}const o=r.trim().split(`
21
+ `),l=[];let n=[];for(let h=0;h<o.length;h++){const s=o[h].trim();if(s===""){if(n.length>0){const g=n.join(" ").trim();g&&l.push(St([{type:"text",text:g}])),n=[]}}else{const g=s.length<60,P=s===s.toUpperCase()&&/[A-Z]/.test(s),c=/[.!?]$/.test(s),d=h+1<o.length&&o[h+1].trim()==="";if(g&&(P||d&&!c)){if(n.length>0){const f=n.join(" ").trim();f&&l.push(St([{type:"text",text:f}])),n=[]}l.push(St([{type:"text",text:s}]))}else n.push(s)}}if(n.length>0){const h=n.join(" ").trim();h&&l.push(St([{type:"text",text:h}]))}return l.length===0&&l.push(St()),{type:"doc",children:l}}catch(i){throw console.error("Failed to parse PDF:",i),new Error(`Failed to parse PDF: ${i instanceof Error?i.message:"Unknown error"}`)}}};R.PAGE_WIDTH=612,R.PAGE_HEIGHT=792,R.MARGIN_LEFT=72,R.MARGIN_RIGHT=72,R.MARGIN_TOP=72,R.MARGIN_BOTTOM=72,R.PX_TO_PT=re,R.UNBOUNDED_CELL_FLOW_BOTTOM_PT=1e4,R.DEFAULT_BODY_FONT="Arial, sans-serif",R.LINE_HEIGHT_MULTIPLIERS=Je,R.FONT_SIZES={h1:yt.h1*R.PX_TO_PT,h2:yt.h2*R.PX_TO_PT,h3:yt.h3*R.PX_TO_PT,h4:yt.h4*R.PX_TO_PT,h5:yt.h5*R.PX_TO_PT,h6:yt.h6*R.PX_TO_PT,normal:yt.paragraph*R.PX_TO_PT},R.FONT_MAP={arial:"helvetica",helvetica:"helvetica","helvetica neue":"helvetica","times new roman":"times",georgia:"times","source serif 4":"SourceSerif4",times:"times",courier:"courier","courier new":"courier",monospace:"courier",verdana:"helvetica",tahoma:"helvetica",inter:"helvetica","system-ui":"helvetica","system ui":"helvetica","ui-sans-serif":"helvetica","ui-serif":"times","ui-monospace":"courier","sans-serif":"helvetica",sans:"helvetica",serif:"times",katex_main:"KaTeX_Main",computermodern:"KaTeX_Main","computer modern":"KaTeX_Main"},R.TODO_LIST_INDENT_PT=ut.variantIndentPx.todo*R.PX_TO_PT,R.ORDERED_LIST_INDENT_PT=ut.variantIndentPx.ordered*R.PX_TO_PT,R.UNORDERED_LIST_INDENT_PT=ut.variantIndentPx.unordered*R.PX_TO_PT,R.SUBLIST_INDENT_PT=ut.sublistIndentPx*R.PX_TO_PT,R.BULLET_MARKER_WIDTH_PT=ut.markerWidthPx*R.PX_TO_PT,R.BULLET_CENTER_OFFSET_PT=8*R.PX_TO_PT,R.BULLET_RADIUS_PT=2.5*R.PX_TO_PT,R.BULLET_SQUARE_INSET_PT=5*R.PX_TO_PT,R.BULLET_SQUARE_HALF_PT=5*R.PX_TO_PT,R.BULLET_SQUARE_VERTICAL_ADJUST_PT=1*R.PX_TO_PT,R.ORDERED_LABEL_GAP_PT=6*R.PX_TO_PT,R.TODO_CHECKBOX_SIZE_PT=ut.todoCheckboxSizePx*R.PX_TO_PT,R.TODO_CHECKBOX_RADIUS_PT=ut.todoCheckboxRadiusPx*R.PX_TO_PT,R.TODO_CHECKBOX_OFFSET_PT=ut.todoCheckboxOffsetPx*R.PX_TO_PT,R.MAX_LIST_INDENT_LEVEL=ut.maxIndentLevel,R.MATH_BLOCK_PADDING=16*R.PX_TO_PT,R.MATH_BLOCK_MIN_HEIGHT=40*R.PX_TO_PT,R.MATH_BLOCK_BORDER_RADIUS=4*R.PX_TO_PT,R.BLOCK_BORDER_WIDTH_PT=1*R.PX_TO_PT,R.INLINE_MATH_SCALE=.85,R.BUNDLED_GENRE_FONTS={SourceSerif4:{family:"SourceSerif4",files:{normal:"SourceSerif4-Regular.ttf",bold:"SourceSerif4-Bold.ttf",italic:"SourceSerif4-It.ttf",bolditalic:"SourceSerif4-BoldIt.ttf"}},helvetica:{family:"LiberationSans",files:{normal:"LiberationSans-Regular.ttf",bold:"LiberationSans-Bold.ttf",italic:"LiberationSans-Italic.ttf",bolditalic:"LiberationSans-BoldItalic.ttf"}},times:{family:"LiberationSerif",files:{normal:"LiberationSerif-Regular.ttf",bold:"LiberationSerif-Bold.ttf",italic:"LiberationSerif-Italic.ttf",bolditalic:"LiberationSerif-BoldItalic.ttf"}},courier:{family:"LiberationMono",files:{normal:"LiberationMono-Regular.ttf",bold:"LiberationMono-Bold.ttf",italic:"LiberationMono-Italic.ttf",bolditalic:"LiberationMono-BoldItalic.ttf"}}},R.bundledGenreFamilies=new Map,R.SCRIPT_FALLBACK_FONTS=fa,R.scriptFallbackFamilies=new Map,R.scriptFontCoverageCache=new Map,R.fallbackCharsetCache=new Map,R.shapingFonts=new Map,R.inlineCodeFontFamily="courier",R.fontFileData=new Map,R.localFontFiles=new Map,R.embeddedFamilyNames=new Map,R.COLUMN_BALANCE_SLACK_PT=1.5,R.html2canvasModule=null,R.html2canvasLoading=null,R.katexStylesLoaded=!1;let ma=R;export{ma as PdfConverter};
@@ -0,0 +1,21 @@
1
+ import{aX as Ct,aY as re,aZ as se,an as le,a7 as yt,a_ as ut,I as ce,a$ as he,b0 as Gt,b1 as Nt,b2 as Ut,b3 as zt,af as Kt,b4 as jt,b5 as It,b6 as $t,av as Yt,b7 as ge,b8 as de,b9 as fe,ba as me,B as Pe,bb as ue,bc as pe,bd as Te,be as xe,bf as be,bg as ye,aN as Vt,bh as et,bi as Zt,bj as _e,bk as Fe,bl as St,bm as Se,bn as Le,bo as we,Y as Oe,Z as Me,bp as Jt,bq as ke,br as Bt,bs as Lt,aD as Et,K as Ce,bt as qt,bu as Re,bv as vt,bw as Qt,bx as te,by as Ne,bz as Ie,bA as Be,al as Ee,bB as Dt,aU as ve,a0 as De,bC as Xe,aH as Ae,bD as We,bE as ft,bF as ee,A as ae,bG as He,bH as Ge,bI as Ue,bJ as ie,bK as oe,bL as ze,bM as Ke,bN as je,bO as $e,bP as Ye,bQ as Ve,bR as Ze,au as Je,V as wt,bS as qe,ab as Qe,ac as ta,bT as Xt,bU as ea,bV as aa,bW as ia,bX as oa,bY as na,bZ as At,b_ as ra,b$ as ne,aV as sa,c0 as la}from"./index-CjeGoI2g.js";const Rt=new Map;re(()=>Rt.clear());function ca(ot){const t=String.fromCharCode(...ot.subarray(0,4));return ot[0]===0&&ot[1]===1&&ot[2]===0&&ot[3]===0||t==="true"||t==="OTTO"}function ha(ot){let t="";for(let e=0;e<ot.length;e+=32768)t+=String.fromCharCode(...ot.subarray(e,e+32768));return btoa(t)}async function ga(ot){try{const t=await fetch(Ct(`fonts/${encodeURIComponent(ot)}`),{credentials:"omit"});if(!t.ok)return null;const e=new Uint8Array(await t.arrayBuffer());return ca(e)?ha(e):null}catch{return null}}async function da(ot){let t=Rt.get(ot);return t||(t=ga(ot),Rt.set(ot,t),t.then(e=>{e===null&&Rt.delete(ot)})),t}const J=ot=>({normal:ot,bold:ot}),fa={japanese:{family:"NotoSansJP",probeCodePoint:12354,charRegex:/[\p{Script=Hiragana}\p{Script=Katakana}]/u,files:J("NotoSansJP-Regular.ttf")},korean:{family:"NotoSansKR",probeCodePoint:54620,charRegex:/\p{Script=Hangul}/u,files:J("NotoSansKR-Regular.ttf")},devanagari:{family:"NotoSansDevanagari",probeCodePoint:2309,charRegex:/\p{Script=Devanagari}/u,files:J("NotoSansDevanagari-Regular.ttf"),shape:!0},bengali:{family:"NotoSansBengali",probeCodePoint:2437,charRegex:/\p{Script=Bengali}/u,files:J("NotoSansBengali-Regular.ttf"),shape:!0},gurmukhi:{family:"NotoSansGurmukhi",probeCodePoint:2565,charRegex:/\p{Script=Gurmukhi}/u,files:J("NotoSansGurmukhi-Regular.ttf"),shape:!0},gujarati:{family:"NotoSansGujarati",probeCodePoint:2693,charRegex:/\p{Script=Gujarati}/u,files:J("NotoSansGujarati-Regular.ttf"),shape:!0},oriya:{family:"NotoSansOriya",probeCodePoint:2821,charRegex:/\p{Script=Oriya}/u,files:J("NotoSansOriya-Regular.ttf"),shape:!0},tamil:{family:"NotoSansTamil",probeCodePoint:2949,charRegex:/\p{Script=Tamil}/u,files:J("NotoSansTamil-Regular.ttf"),shape:!0},telugu:{family:"NotoSansTelugu",probeCodePoint:3077,charRegex:/\p{Script=Telugu}/u,files:J("NotoSansTelugu-Regular.ttf"),shape:!0},kannada:{family:"NotoSansKannada",probeCodePoint:3205,charRegex:/\p{Script=Kannada}/u,files:J("NotoSansKannada-Regular.ttf"),shape:!0},malayalam:{family:"NotoSansMalayalam",probeCodePoint:3333,charRegex:/\p{Script=Malayalam}/u,files:J("NotoSansMalayalam-Regular.ttf"),shape:!0},sinhala:{family:"NotoSansSinhala",probeCodePoint:3461,charRegex:/\p{Script=Sinhala}/u,files:J("NotoSansSinhala-Regular.ttf"),shape:!0},thai:{family:"NotoSansThai",probeCodePoint:3585,charRegex:/\p{Script=Thai}/u,files:J("NotoSansThai-Regular.ttf"),shape:!0},lao:{family:"NotoSansLao",probeCodePoint:3713,charRegex:/\p{Script=Lao}/u,files:J("NotoSansLao-Regular.ttf"),shape:!0},khmer:{family:"NotoSansKhmer",probeCodePoint:6016,charRegex:/\p{Script=Khmer}/u,files:J("NotoSansKhmer-Regular.ttf"),shape:!0},myanmar:{family:"NotoSansMyanmar",probeCodePoint:4096,charRegex:/\p{Script=Myanmar}/u,files:J("NotoSansMyanmar-Regular.ttf"),shape:!0},tibetan:{family:"NotoSerifTibetan",probeCodePoint:3904,charRegex:/\p{Script=Tibetan}/u,files:J("NotoSerifTibetan-Regular.ttf"),shape:!0},ethiopic:{family:"NotoSansEthiopic",probeCodePoint:4608,charRegex:/\p{Script=Ethiopic}/u,files:J("NotoSansEthiopic-Regular.ttf")},armenian:{family:"NotoSansArmenian",probeCodePoint:1329,charRegex:/\p{Script=Armenian}/u,files:J("NotoSansArmenian-Regular.ttf")},georgian:{family:"NotoSansGeorgian",probeCodePoint:4304,charRegex:/\p{Script=Georgian}/u,files:J("NotoSansGeorgian-Regular.ttf")},syriac:{family:"NotoSansSyriac",probeCodePoint:1808,charRegex:/\p{Script=Syriac}/u,files:J("NotoSansSyriac-Regular.ttf"),shape:!0},thaana:{family:"NotoSansThaana",probeCodePoint:1920,charRegex:/\p{Script=Thaana}/u,files:J("NotoSansThaana-Regular.ttf"),shape:!0},arabic:{family:"NotoNaskhArabic",probeCodePoint:1575,charRegex:/[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/,files:{normal:"NotoNaskhArabic-Regular.ttf",bold:"NotoNaskhArabic-Bold.ttf"}},hebrew:{family:"NotoSansHebrew",probeCodePoint:1488,charRegex:/[\u0590-\u05FF\uFB1D-\uFB4F]/,files:{normal:"NotoSansHebrew-Regular.ttf",bold:"NotoSansHebrew-Bold.ttf"}},cjkExtensionB:{family:"HanExtBSubset",probeCodePoint:131079,charRegex:/[\u{20000}-\u{207FF}]/u,files:J("HanExtBSubset-Regular.ttf"),shape:!0},han:{family:"NotoSansSC",probeCodePoint:20013,charRegex:/[\p{Script=Han}\p{Script=Bopomofo}\u3000-\u303F\uFE30-\uFE4F\uFF00-\uFFEF]/u,files:J("NotoSansSC-Regular.ttf")},emoji:{family:"NotoEmoji",probeCodePoint:128512,charRegex:/[\p{Extended_Pictographic}\p{Regional_Indicator}]/u,files:J("NotoEmoji-Regular.ttf"),shape:!0},arrows:{family:"NotoSansSymbols",probeCodePoint:8592,charRegex:/[\u2190-\u21FF]/u,files:J("NotoSansSymbols-Regular.ttf")},symbols:{family:"NotoSansSymbols2",probeCodePoint:9728,charRegex:/[\u2300-\u23FF\u2460-\u24FF\u25A0-\u27BF\u2B00-\u2BFF\u{1F000}-\u{1F2FF}]/u,files:J("NotoSansSymbols2-Regular.ttf"),shape:!0}},R=class ct{static async ensureAllLatexRendered(t){const e=[],a=new Set,i=(o,l)=>{const n=`${l}:${o}`;!a.has(n)&&o.trim()&&(a.add(n),e.push({content:o,displayMode:l}))},r=o=>{if(!o||typeof o!="object")return;if(Array.isArray(o)){o.forEach(r);return}const l=o;l.type==="math"&&l.content?i(l.content,l.displayMode!=="inline"):l.type==="text"&&l.marks?.latex&&l.text&&i(l.text,!1),r(l.children)};r(t.children),r(t.chrome),r(t.notes),await Promise.all(e.map(o=>ce(o.content,o.displayMode)))}static getLatexSvgFromCache(t,e){return he(t,e)}static async svgToPng(t,e,a,i=3){return new Promise(r=>{const o=new Image,l="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(t);o.onload=()=>{try{const n=document.createElement("canvas");n.width=e*i,n.height=a*i;const h=n.getContext("2d");if(!h){r(null);return}h.scale(i,i),h.drawImage(o,0,0,e,a),r(n.toDataURL("image/png"))}catch(n){console.error("Failed to convert SVG to PNG:",n),r(null)}},o.onerror=()=>{r(null)},o.src=l})}static async loadFontFile(t,e=!0){const a=this.fontFileData.get(t);if(a!==void 0)return a;let i=await da(t);try{if(!i){const r=await fetch(Ct(`fonts/${t}`));if(r.ok){const o=await r.arrayBuffer();Gt(new Uint8Array(o))==="ttf"&&(i=this.arrayBufferToBase64(o))}}}catch{}return i||(i=await this.readFontFromDisk(t)),!i&&e&&console.warn(`Failed to load font ${t}`),this.fontFileData.set(t,i),i}static async readFontFromDisk(t){try{const{readFile:e}=await import("./__vite-browser-external-l0sNRNKZ.js"),{join:a}=await import("./__vite-browser-external-l0sNRNKZ.js"),i=[a(process.cwd(),"public","fonts",t),a(process.cwd(),"frontend","public","fonts",t),a(process.cwd(),"..","frontend","public","fonts",t),a(process.cwd(),"..","..","frontend","public","fonts",t)];for(const r of i)try{return(await e(r)).toString("base64")}catch{}}catch{}return null}static async loadSourceCodePro(t){const e=await this.loadFontFile("SourceCodePro-Regular.ttf",!1);return e?(t.addFileToVFS("SourceCodePro-Regular.ttf",e),t.addFont("SourceCodePro-Regular.ttf","SourceCodePro","normal"),!0):!1}static async loadKaTeXMain(t){const e=[{file:"KaTeX_Main-Regular.ttf",style:"normal"},{file:"KaTeX_Main-Bold.ttf",style:"bold"},{file:"KaTeX_Main-Italic.ttf",style:"italic"},{file:"KaTeX_Main-BoldItalic.ttf",style:"bolditalic"}],a=await Promise.all(e.map(async i=>{const r=await this.loadFontFile(i.file);return r?{...i,base64:r}:null}));for(const i of a)i&&(t.addFileToVFS(i.file,i.base64),t.addFont(i.file,"KaTeX_Main",i.style));return a[0]!==null}static async embedBundledGenreFonts(t,e,a){this.bundledGenreFamilies.clear();const i=new Set,r=o=>{const l=this.mapFontFamilyToStandard(o);this.BUNDLED_GENRE_FONTS[l]&&i.add(l)};r(a);for(const o of Nt(e))r(o.value);for(const o of i){const l=this.BUNDLED_GENRE_FONTS[o],n=await Promise.all(Object.entries(l.files).map(async([h,s])=>({style:h,file:s,base64:await this.loadFontFile(s)})));if(!n.some(h=>!h.base64)){for(const{style:h,file:s,base64:g}of n)t.addFileToVFS(s,g),t.addFont(s,l.family,h);this.bundledGenreFamilies.set(o,l.family)}}}static documentFallbackScripts(t){const e=new Set,a=Object.keys(this.SCRIPT_FALLBACK_FONTS),i=r=>{if(e.size===a.length||!r||typeof r!="object")return;if(Array.isArray(r)){r.forEach(i);return}const o=r;if(typeof o.text=="string"&&o.text)for(const l of a)!e.has(l)&&this.SCRIPT_FALLBACK_FONTS[l].charRegex.test(o.text)&&e.add(l);i(o.children)};return i(t.children),i(t.chrome),i(t.notes),e}static splitDocumentFallbackRuns(t,e){const a=Object.entries(this.SCRIPT_FALLBACK_FONTS),i=s=>{const g=a.filter(([,P])=>P.charRegex.test(s)).map(([P])=>P);if(g.length>1&&e){const P=s.codePointAt(0)??0,c=g.find(d=>e(d,P));if(c)return c}return g[0]},r=/[\p{Letter}\p{Number}]/u,o=this.SCRIPT_FALLBACK_FONTS.japanese.charRegex,l=this.SCRIPT_FALLBACK_FONTS.korean.charRegex,n=s=>{const g=s.text??"";if(!g)return[{...s}];const P=[];let c="",d=null;for(const f of g.split(/(\s+)/)){const x=o.test(f)?"japanese":l.test(f)?"korean":null;for(const m of f){let b=i(m);if(b==="han"&&x&&(b=x),!b&&r.test(m)&&(b="base"),!b){d?d.text+=m:c+=m;continue}!d||d.key!==b?(d&&P.push(d),d={key:b,text:c+m},c=""):d.text+=m}}return d?(d.text+=c,P.push(d)):P.push({key:"base",text:c}),P.map(f=>{if(f.key==="base")return{...s,text:f.text};const x=this.SCRIPT_FALLBACK_FONTS[f.key];return{...s,text:f.text,marks:{...s.marks,fontFamily:x.family}}})},h=s=>Array.isArray(s)?s.flatMap(g=>g&&typeof g=="object"&&g.type==="text"?n(g):[h(g)]):!s||typeof s!="object"?s:Object.fromEntries(Object.entries(s).map(([g,P])=>[g,h(P)]));return h(t)}static async loadFallbackCoverage(t){const e=Object.entries(this.SCRIPT_FALLBACK_FONTS),a=new Set,i=new Set,r=l=>{if(!l||typeof l!="object")return;if(Array.isArray(l)){l.forEach(r);return}const n=l;if(typeof n.text=="string")for(const h of n.text){if(i.has(h)||h.charCodeAt(0)<128)continue;i.add(h);const s=e.filter(([,g])=>g.charRegex.test(h));s.length>1&&s.forEach(([g])=>a.add(g))}r(n.children)};r(t.children),r(t.chrome),r(t.notes);const o=new Map;for(const l of a){const n=this.SCRIPT_FALLBACK_FONTS[l].files.normal;let h=this.fallbackCharsetCache.get(n);if(h===void 0){h=null;const s=await this.loadFontFile(n,!1);if(s)try{const g=(await import("./browser-module-D2ixluMg.js")).create(Ut(s));h=new Set(g.characterSet??[])}catch{h=null}this.fallbackCharsetCache.set(n,h)}h&&o.set(l,h)}return(l,n)=>{const h=o.get(l);return h?h.has(n):!0}}static async embedScriptFallbackFonts(t,e){this.scriptFallbackFamilies.clear(),this.shapingFonts.clear();for(const a of this.documentFallbackScripts(e)){const i=await this.registerScriptFallbackFace(t,a);i&&this.scriptFallbackFamilies.set(a,i)}}static async registerScriptFallbackFace(t,e){const a=this.SCRIPT_FALLBACK_FONTS[e];if(!a)return null;const i=await this.loadFontFile(a.files.normal);if(!i)return null;const r=await this.loadFontFile(a.files.bold,!1);t.addFileToVFS(a.files.normal,i),r&&a.files.bold!==a.files.normal&&t.addFileToVFS(a.files.bold,r);const o=r?a.files.bold:a.files.normal;if(t.addFont(a.files.normal,a.family,"normal"),t.addFont(o,a.family,"bold"),t.addFont(a.files.normal,a.family,"italic"),t.addFont(o,a.family,"bolditalic"),a.shape&&!this.shapingFonts.has(a.family))try{const[l,n]=await Promise.all([import("./browser-module-D2ixluMg.js"),import("./_revise-sdk-lazy-harfbuzz-X8gnYTZL.js")]),h=n,s=h.loadHarfBuzz?await h.loadHarfBuzz():n,g=Ut(i),P=l.create(g),c=new s.Blob(g),d=new s.Face(c),f=new s.Font(d);this.shapingFonts.set(a.family,{unitsPerEm:d.upem,notdefPathCommands:P.getGlyph(0).path.commands,layout:x=>{const m=new s.Buffer;m.addText(x),m.guessSegmentProperties(),s.shape(f,m);const b=m.getGlyphInfosAndPositions(),_=b.map(y=>({xAdvance:y.xAdvance??0,yAdvance:y.yAdvance??0,xOffset:y.xOffset??0,yOffset:y.yOffset??0}));return{glyphs:b.map(y=>P.getGlyph(y.codepoint)),positions:_,advanceWidth:_.reduce((y,v)=>y+v.xAdvance,0)}}})}catch(l){console.warn(`Failed to initialize PDF shaping for ${a.family}:`,l)}return a.family}static fontCoversCodePoint(t,e,a){const i=`${e}:${a}`;let r=this.scriptFontCoverageCache.get(i);if(r===void 0){let o;try{o=t.getFont(e,"normal")}catch{o=void 0}r=!!o?.metadata?.cmap?.unicode?.codeMap?.[a],this.scriptFontCoverageCache.set(i,r)}return r}static fontCoversMatchedChars(t,e,a,i){let r=!1;for(const o of a)if(i.test(o)&&(r=!0,!this.fontCoversCodePoint(t,e,o.codePointAt(0)??0)))return!1;return r}static scriptFallbackFor(t,e,a){if(!e||this.scriptFallbackFamilies.size===0)return null;let i=null;for(const[r,o]of Object.entries(this.SCRIPT_FALLBACK_FONTS)){const l=this.scriptFallbackFamilies.get(r);if(l&&o.charRegex.test(e)&&!this.fontCoversCodePoint(t,a,o.probeCodePoint)&&!this.fontCoversMatchedChars(t,a,e,o.charRegex)){if(this.fontCoversMatchedChars(t,l,e,o.charRegex))return l;i??(i=l)}}return i}static async registerDocumentFonts(t,e,a){await this.embedLocalFonts(t,e),await this.embedBundledGenreFonts(t,e,a),await this.embedScriptFallbackFonts(t,e);const i=this.documentUsesSourceCodePro(e)?await this.loadSourceCodePro(t):!1;return this.inlineCodeFontFamily=i?"SourceCodePro":"courier",this.documentUsesKaTeXMain(e)&&await this.loadKaTeXMain(t),{hasSourceCodePro:i}}static async registerCurrentPdfFonts(t,e){for(const[a,i]of this.bundledGenreFamilies){const r=this.BUNDLED_GENRE_FONTS[a];if(!r||r.family!==i)continue;const o=await Promise.all(Object.entries(r.files).map(async([l,n])=>({style:l,file:n,base64:await this.loadFontFile(n)})));for(const{style:l,file:n,base64:h}of o)h&&(t.addFileToVFS(n,h),t.addFont(n,i,l))}for(const a of this.scriptFallbackFamilies.keys())await this.registerScriptFallbackFace(t,a);e&&await this.loadSourceCodePro(t)}static documentUsesKaTeXMain(t){return Nt(t).some(e=>{const a=e.family.toLowerCase();return a.includes("katex")||a.includes("computer modern")||a.includes("computermodern")})}static documentUsesSourceCodePro(t){const e=[...t.children];for(;e.length>0;){const a=e.pop();if(!a||typeof a!="object")continue;const i=a;if(i.type==="code"||i.type==="text"&&typeof i.marks=="object"&&i.marks!==null&&i.marks.code===!0)return!0;Array.isArray(i.children)&&e.push(...i.children)}return!1}static createCanvasTextContext(){if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;let e=null;return{measureText:a=>({width:zt(a,e,i=>t.measureText(i).width)}),setFont:a=>{t.font=a,e=null},setMarkAdjustments:a=>{e=a}}}static resolveIndentStepPx(t){return this.resolvePdfLayoutMetrics(t).indentStepPx}static getDefaultPdfLayoutMetrics(){const t=Kt(void 0),e=Math.max(1,this.PAGE_WIDTH-this.MARGIN_LEFT-this.MARGIN_RIGHT);return{orientation:"portrait",pageWidthPt:this.PAGE_WIDTH,pageHeightPt:this.PAGE_HEIGHT,marginTopPt:this.MARGIN_TOP,marginRightPt:this.MARGIN_RIGHT,marginBottomPt:this.MARGIN_BOTTOM,marginLeftPt:this.MARGIN_LEFT,contentWidthPt:e,fullContentWidthPt:e,pageMarginLeftPt:this.MARGIN_LEFT,columnCount:1,columnGapPt:It(t.columnGapTwips),columnStridePt:jt(e,It(t.columnGapTwips)),blockSpacingPt:t.blockSpacingPx*this.PX_TO_PT,indentStepPx:t.indentStepPx,showPageNumbers:t.showPageNumbers,pageBorders:t.pageBorders,pageNumberPosition:t.pageNumberPosition,pageNumberStart:t.pageNumberStart,pageNumberFormat:t.pageNumberFormat,hyphenationEnabled:t.hyphenationEnabled,lineNumbering:t.lineNumbering}}static resolvePdfLayoutMetrics(t){return this.resolvePdfMetricsFromSettings(t?.pageLayout,t?.pageLayout,!1)}static resolvePdfMetricsFromSettings(t,e,a=!1){const i=$t(e,t),r=t,{pageWidth:o,pageHeight:l}=Yt(i),n=o*this.PX_TO_PT,h=l*this.PX_TO_PT,s=i.marginTopPx*this.PX_TO_PT,g=i.marginRightPx*this.PX_TO_PT,P=i.marginBottomPx*this.PX_TO_PT,c=i.marginLeftPx*this.PX_TO_PT,d=Math.max(1,n-c-g),f=Math.max(1,i.columnCount),x=It(i.columnGapTwips),m=ge(d,f,x);return{orientation:i.orientation,pageWidthPt:n,pageHeightPt:h,marginTopPt:s,marginRightPt:g,marginBottomPt:P,marginLeftPt:c,contentWidthPt:m,fullContentWidthPt:d,pageMarginLeftPt:c,columnCount:f,columnGapPt:x,columnStridePt:jt(m,x),...f>1?{columnFlow:{index:0,topPt:s,pageOffset:0}}:{},blockSpacingPt:i.blockSpacingPx*this.PX_TO_PT,indentStepPx:i.indentStepPx,showPageNumbers:i.showPageNumbers,pageBorders:i.pageBorders,pageNumberPosition:i.pageNumberPosition,pageNumberStart:i.pageNumberStart,pageNumberStartExplicit:a&&r?.pageNumberStart!==void 0,pageNumberFormat:i.pageNumberFormat,hyphenationEnabled:i.hyphenationEnabled,lineNumbering:i.lineNumbering}}static physicalPageMetrics(t){return{...t,marginLeftPt:t.pageMarginLeftPt,contentWidthPt:t.fullContentWidthPt,columnFlow:void 0,reservedInsetForPage:void 0}}static computeEngineLayout(t){if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");if(!e)return null;const a=Kt(t.pageLayout),i=Yt(a),r=de({pageWidth:i.pageWidth,pageHeight:i.pageHeight,pageMargin:a.marginLeftPx,pageMarginTop:a.marginTopPx,pageMarginRight:a.marginRightPx,pageMarginBottom:a.marginBottomPx,pageMarginLeft:a.marginLeftPx,availableWidth:Math.max(1,i.pageWidth-a.marginLeftPx-a.marginRightPx),textStartY:a.marginTopPx,indentStepPx:a.indentStepPx,blockSpacingPx:a.blockSpacingPx,hyphenationEnabled:a.hyphenationEnabled,lineNumbering:a.lineNumbering,columnCount:a.columnCount,columnGapPx:fe(a.columnGapTwips),pageless:!1});try{return me(t,Pe(e),r)}catch{return null}}static computeColumnBalanceTargets(t,e){const a=new Map,i=e.filter(g=>g.type==="section-break"),r=new Set;if(i.forEach((g,P)=>{const c=$t(t.pageLayout,g.layout);ue(Math.max(1,c.columnCount),g.breakType==="continuous")&&r.add(P)}),r.size===0)return a;const o=this.computeEngineLayout(t);if(!o?.pageGeometries||o.pageGeometries.length===0)return a;const l=new Map(o.pageGeometries.map(g=>[g.pageIndex+1,g.pageTop])),n=(g,P)=>{if(!g||typeof g!="object")return;if(Array.isArray(g)){g.forEach(d=>n(d,P));return}const c=g;typeof c.id=="string"&&c.id&&P.add(c.id),n(c.children,P)},h=new Map;let s=0;for(const g of e){if(g.type==="section-break"){s+=1;continue}let P=h.get(s);P||(P=new Set,h.set(s,P)),n(g,P)}for(const g of r){const P=h.get(g);if(!P||P.size===0)continue;const c=o.fragments.filter(b=>!b.isChrome&&typeof b.pageNumber=="number"&&P.has(b.blockId));if(c.length===0)continue;let d=Number.POSITIVE_INFINITY,f=0;for(const b of c)d=Math.min(d,b.pageNumber),f=Math.max(f,b.pageNumber);const x=l.get(f);if(x===void 0)continue;let m=0;for(const b of c)b.pageNumber===f&&(m=Math.max(m,b.bounds.y+b.bounds.height-x));m<=0||a.set(g,{pageOffset:f-d,bottomPt:m*this.PX_TO_PT+this.COLUMN_BALANCE_SLACK_PT})}return a}static advancePdfColumnOrPage(t,e){const a=e.columnFlow;return!a||e.columnCount<=1?(t.addPage(),!0):a.index<e.columnCount-1?(a.index+=1,e.marginLeftPt=e.pageMarginLeftPt+a.index*e.columnStridePt,!1):(a.index=0,e.marginLeftPt=e.pageMarginLeftPt,t.addPage([e.pageWidthPt,e.pageHeightPt],e.orientation),a.topPt=e.marginTopPt,a.pageOffset+=1,!0)}static advancePdfFlowRegion(t,e){const a=this.advancePdfColumnOrPage(t,e);return{x:e.marginLeftPt,y:a?e.marginTopPt:e.columnFlow?.topPt??e.marginTopPt}}static declaredSpacingPx(t,e){const a=t?.[e];return typeof a=="number"&&Number.isFinite(a)?Math.max(0,a):void 0}static pdfSpaceBeforePt(t,e){const a=ct.declaredSpacingPx(t,"spaceBefore");return a!==void 0?a*ct.PX_TO_PT:e.blockSpacingPt}static pdfSpaceAfterPt(t){const e=ct.declaredSpacingPx(t,"spaceAfter");return e!==void 0?e*ct.PX_TO_PT:0}static syncPdfColumnOffset(t){const e=t.columnFlow;!e||t.columnCount<=1||(t.marginLeftPt=t.pageMarginLeftPt+e.index*t.columnStridePt)}static getPdfReservedInsetPt(t,e){return e.reservedInsetForPage?.get(this.getPdfCurrentPage(t))??0}static getPdfWritableBottomPt(t,e){return e.pageHeightPt-e.marginBottomPt-this.getPdfReservedInsetPt(t,e)}static getPdfFlowBottom(t,e){const a=this.getPdfWritableBottomPt(t,e),i=e.columnFlow;return!i?.balance||e.columnCount<=1||i.pageOffset!==i.balance.pageOffset?a:Math.min(a,i.balance.bottomPt)}static getPdfPageCount(t){return typeof t.getNumberOfPages=="function"?t.getNumberOfPages():typeof t.internal?.getNumberOfPages=="function"?t.internal.getNumberOfPages():1}static getPdfCurrentPage(t){return t.getCurrentPageInfo?.().pageNumber??this.getPdfPageCount(t)}static createPdfPageNumbering(t,e,a){const i=[...e?.keys()??[]].sort((n,h)=>n-h),r=n=>{let h=t;for(const s of i){if(s>n)break;h=e.get(s)}return h},o=[],l=n=>{const h=Math.max(1,Math.floor(n));for(let s=o.length+1;s<=h;s++){const g=r(s);o.push(s===1||a?.has(s)&&g.pageNumberStartExplicit?g.pageNumberStart:o[s-2]+1)}return o[h-1]};return{metricsForPage:r,numberForPage:l,labelForPage:n=>pe(l(n),r(n).pageNumberFormat)}}static async renderHeaderFooterChrome(t,e,a,i,r,o){const l=this.getPdfPageCount(t),n=d=>{if(!r)return a;let f=a,x=0;for(const[m,b]of r)m<=d&&m>x&&(f=b,x=m);return f},h=d=>{if(!o)return 0;let f=0,x=0;for(const[m,b]of o)m<=d&&m>x&&(f=b,x=m);return f},s=d=>{if(!o)return 1;let f=1;for(const[x]of o)x<=d&&x>f&&(f=x);return f},g=this.createPdfPageNumbering(a,r,o).labelForPage,P=(d,f)=>{if(e.chrome&&e.chrome.length>0)return qe(e.chrome,d,f,h(f));const x=d==="header"?e.headers:e.footers;if(!x)return;const m=f===s(f)&&x.first?"first":f%2===0&&x.even?"even":"default",b=x[m];if(b)return Qe(d,m,ta(b),i)},c=async(d,f,x)=>{const m=n(x),b=d.children.slice(0,3).map((w,E)=>{const u=Xt[E];return{...w,...u&&!w.align?{align:u}:{},children:w.children.map(p=>p.type!=="text"||!p.marks?.field?p:p.marks.field==="page"?{...p,text:g(x)}:{...p,text:String(l)})}});for(;b.length<3;){const w=b.length;b.push({type:"paragraph",id:`${d.id}-pdf-column-${w}`,children:[{type:"text",text:""}],...Xt[w]?{align:Xt[w]}:{}})}const _=this.createLayoutForWrapping(m.contentWidthPt,m.indentStepPx,m),y=this.createCanvasTextContext(),v=y?ea(d,y,_,e,b).map(w=>w*this.PX_TO_PT):[m.contentWidthPt/3,m.contentWidthPt/3,m.contentWidthPt/3],k=f?Math.max(10*this.PX_TO_PT,m.marginTopPt/2):m.pageHeightPt-Math.max(10*this.PX_TO_PT,m.marginBottomPt/2);let X=m.marginLeftPt;for(let w=0;w<3;w++){const E=b[w],u=v[w],p=this.measureParagraphLineAdvances(E,u,m.indentStepPx,m).reduce((L,A)=>L+A,0),S=k-p/2,O={...m,marginTopPt:S,marginLeftPt:X,marginRightPt:Math.max(0,m.pageWidthPt-X-u),contentWidthPt:Math.max(1,u)};await this.renderParagraph(t,E,S,u,i,1e9,m.indentStepPx,O),X+=u}};for(let d=0;d<l;d++){const f=d+1;t.setPage(f);const x=P("header",f),m=P("footer",f);x&&await c(x,!0,f),m&&await c(m,!1,f)}this.renderPageNumbers(t,a,i,n,g,(d,f)=>!!P(f,d));for(let d=1;d<=l;d++){const f=n(d),x=Te(f.pageBorders,f.pageWidthPt,f.pageHeightPt,{top:f.marginTopPt,right:f.marginRightPt,bottom:f.marginBottomPt,left:f.pageMarginLeftPt},d===s(d));if(!x.length)continue;t.setPage(d);const m=t.internal?.pages?.[d],b=m?.length??0;t.saveGraphicsState(),t.setLineCap?.("square");for(const _ of x){t.setDrawColor(_.color),t.setLineWidth(_.style==="double"?_.widthPt/3:_.widthPt),t.setLineDashPattern(_.style==="dotted"?[_.widthPt,_.widthPt*2]:_.style==="dashed"?[_.widthPt*4,_.widthPt*2]:[],0);for(const y of _.style==="double"?[-_.widthPt/3,_.widthPt/3]:[0]){const v=_.x1===_.x2?y:0,k=_.y1===_.y2?y:0;t.line(_.x1+v,_.y1+k,_.x2+v,_.y2+k)}}t.restoreGraphicsState(),f.pageBorders?.zOrder==="back"&&m&&m.unshift(...m.splice(b))}}static drawWatermarkOnPage(t,e,a,i){t.setFont("helvetica","normal");const r=xe(e,a/this.PX_TO_PT,i/this.PX_TO_PT,(b,_)=>{t.setFontSize(_*this.PX_TO_PT);const y=t.getTextWidth(b);return typeof y=="number"?y/this.PX_TO_PT:0})*this.PX_TO_PT;t.setFontSize(r);const o=t.getTextWidth(e.text),l=this.hexToRgb(e.color);t.setTextColor(l.r,l.g,l.b);const n=typeof t.saveGraphicsState=="function"&&typeof t.setGState=="function"&&typeof t.GState=="function";n&&(t.saveGraphicsState(),t.setGState(new t.GState({opacity:e.opacity})));const h=e.diagonal?Math.atan2(i,a):0,s=Math.cos(h),g=Math.sin(h),P=a/2,c=i/2,d=o/2,f=-.35*r,x=P-(d*s+f*g),m=c-(-d*g+f*s);t.text(e.text,x,m,{...h!==0?{angle:h*180/Math.PI}:{}}),n&&t.restoreGraphicsState()}static installWatermarkUnderpaint(t,e){const a=()=>{const r=t.internal?.pageSize,o=typeof r?.getWidth=="function"?r.getWidth():r?.width,l=typeof r?.getHeight=="function"?r.getHeight():r?.height;!o||!l||this.drawWatermarkOnPage(t,e,o,l)},i=t.addPage.bind(t);t.addPage=(...r)=>{const o=i(...r);return a(),o},a()}static renderBodyLineNumbers(t,e,a,i){if(e.length===0)return;const r=h=>{let s,g=0;for(const[P,c]of a)P<=h&&P>g&&(s=c,g=P);return s??this.resolvePdfLayoutMetrics(i)},o=this.getPdfPageCount(t),l=o;let n=!1;for(let h=1;h<=o;h++){const s=r(h),g=s.lineNumbering;if(!g)continue;let P=g.start;if(g.restart==="continuous")for(const d of e)d.pageNumber<h&&P++;const c=s.marginLeftPt-(g.distancePx??12)*this.PX_TO_PT;t.setPage(h),t.setFont("helvetica","normal"),t.setFontSize(10*this.PX_TO_PT),t.setTextColor(115,115,115),n=!0;for(const d of e){if(d.pageNumber!==h)continue;const f=P++;f%g.countBy===0&&t.text(String(f),c,d.y+d.height/2,{align:"right",baseline:"middle"})}}n&&t.setPage(l)}static renderPageNumbers(t,e,a,i,r,o){const l=this.getPdfPageCount(t),n=12,h=n/2+6;t.setFont(this.mapFontFamily(a),"normal"),t.setFontSize(n),t.setTextColor(0,0,0);for(let s=0;s<l;s++){const g=i?.(s+1)??e;if(!g.showPageNumbers)continue;const P=s+1,c=g.pageNumberPosition.startsWith("top");if(o?.(P,c?"header":"footer"))continue;const d=g.pageNumberPosition.endsWith("right"),f=d?g.pageWidthPt-g.marginRightPt:g.marginLeftPt,x=c?Math.max(h,g.marginTopPt/2):g.pageHeightPt-Math.max(h,g.marginBottomPt/2);t.setPage(P),t.text(r?.(P)??be({pageNumberStart:e.pageNumberStart,pageNumberFormat:e.pageNumberFormat??"decimal"},s),f,x,{align:d?"right":"left"})}}static getParagraphLineIndentPt(t,e,a){return ye(t,e,a)*this.PX_TO_PT}static createLayoutForWrapping(t,e,a=this.getDefaultPdfLayoutMetrics()){const i=t/this.PX_TO_PT;return{pageWidth:a.pageWidthPt/this.PX_TO_PT,pageHeight:a.pageHeightPt/this.PX_TO_PT,pageMargin:a.marginLeftPt/this.PX_TO_PT,pageMarginTop:a.marginTopPt/this.PX_TO_PT,pageMarginRight:a.marginRightPt/this.PX_TO_PT,pageMarginBottom:a.marginBottomPt/this.PX_TO_PT,pageMarginLeft:a.marginLeftPt/this.PX_TO_PT,pageSpacing:0,paragraphSpacing:0,availableWidth:i,textStartY:a.marginTopPt/this.PX_TO_PT,fontSize:16,fontFamily:this.DEFAULT_BODY_FONT,lineHeight:16*1.4,indentStepPx:e,pageless:!1,hyphenationEnabled:a.hyphenationEnabled}}static buildNumberedNoteEntries(t){const e=new Map,a=s=>{if(!s||typeof s!="object")return;if(Array.isArray(s)){s.forEach(a);return}const g=s;g.type!=="footnote"&&(g.marks?.footnoteRef&&!e.has(g.marks.footnoteRef)&&e.set(g.marks.footnoteRef,g.text??""),a(g.children))};a(t.children.filter(s=>s.type!=="footnote"));const i=[...t.notes??[],...t.children.filter(s=>s.type==="footnote")],r={footnote:0,endnote:0},o=new Map,l=new Map;for(const s of i)l.set(s.id,s.noteKind==="endnote"?"endnote":"footnote");for(const[s]of e){const g=l.get(s)??"footnote";r[g]+=1,o.set(s,Vt(r[g],g))}const n=i.map(s=>{const g=l.get(s.id)??"footnote",P=o.get(s.id)||Vt(r[g]+=1,g);return{footnoteId:s.id,number:P,kind:g,blocks:s.children}}),h=s=>{const g=[...o.keys()],P=g.indexOf(s.footnoteId);return P===-1?g.length:P};return n.sort((s,g)=>h(s)-h(g))}static async renderNoteEntry(t,e,a,i,r,o,l,n,h){n&&this.drawNoteNumeral(t,e.number,i.marginLeftPt,a,r);const s=et.verticalPaddingPx*ct.PX_TO_PT,g=et.gutterPx*ct.PX_TO_PT,P=a+s,c={...i,marginTopPt:i.marginTopPt+s,marginLeftPt:i.marginLeftPt+g,contentWidthPt:Math.max(1,i.contentWidthPt-g),blockSpacingPt:et.blockSpacingPx*ct.PX_TO_PT};if(h){const d=c.marginTopPt;Object.defineProperty(c,"marginTopPt",{get:()=>h.get(this.getPdfCurrentPage(t))??d})}return(await this.renderBodyBlocks(t,e.blocks,c,o,l,r,void 0,void 0,void 0,P)).finalY+s}static drawNoteNumeral(t,e,a,i,r){t.setFont(this.mapFontFamily(r),"normal"),t.setFontSize(Zt*this.PX_TO_PT),t.setTextColor(0,0,0),t.text(e,a+1.5,i+(6+Zt)*ct.PX_TO_PT)}static mapFootnoteRefBlocks(t){const e=new Map,a=(i,r)=>{if(!i||typeof i!="object")return;if(Array.isArray(i)){i.forEach(l=>a(l,r));return}const o=i;o.marks?.footnoteRef&&!e.has(o.marks.footnoteRef)&&e.set(o.marks.footnoteRef,r),a(o.children,r)};for(const i of t)a(i,i.id??"");return e}static async renderBodyBlocks(t,e,a,i,r,o,l,n,h,s,g){const P=new Map,c=new Map([[1,0]]),d=[],f=[],x=_e(e);let m=s??a.marginTopPt,b=a.contentWidthPt,_=a.indentStepPx,y=!0;const v=new Map([[1,this.physicalPageMetrics(a)]]),k=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages();let X=0;const w=E=>{if(X=E,!g)return;const u=a.columnFlow;!u||a.columnCount<=1||(u.index=0,u.topPt=m,u.pageOffset=0,u.balance=g.balanceBySection.get(E),a.marginLeftPt=a.pageMarginLeftPt)};w(0);for(let E=0;E<e.length;E++){this.syncPdfColumnOffset(a);const u=e[E],p=this.getPdfFlowBottom(t,a);if(u.type==="page-break"){!y&&a.blockSpacingPt>0&&(m+=a.blockSpacingPt),u.id&&P.set(u.id,k()),t.addPage([a.pageWidthPt,a.pageHeightPt],a.orientation),a.columnFlow&&(a.columnFlow.index=0,a.columnFlow.topPt=a.marginTopPt,a.columnFlow.pageOffset+=1,a.marginLeftPt=a.pageMarginLeftPt),m=a.marginTopPt,y=!0;continue}if(u.type==="docx-raw"){const G=St.heightPx*.75,M=a.pageWidthPt-a.marginLeftPt-a.marginRightPt,N=Fe(u,M/.75)*.75;!y&&a.blockSpacingPt>0&&(m+=a.blockSpacingPt),m+G>p&&(m=this.advancePdfFlowRegion(t,a).y),u.id&&P.set(u.id,k());const H=a.marginLeftPt;t.setDrawColor(107,114,128),t.setFillColor(243,244,246),t.setLineWidth(.75),t.roundedRect(H,m,N,G,St.cornerRadiusPx*.75,St.cornerRadiusPx*.75,"FD"),t.setFont("courier","normal"),t.setFontSize(St.fontPx*.75),t.setTextColor(107,114,128),t.text(Se(u),H+St.paddingXPx*.75,m+G/2,{baseline:"middle"}),t.setTextColor(0,0,0),m+=G,y=!1;continue}if(u.type==="section-break"){u.id&&P.set(u.id,k());const G=l?.get(u.id),M=G?n?.(G)??G:void 0;if(M){const H=Le(u.breakType==="continuous",{width:a.pageWidthPt,height:a.pageHeightPt},{width:M.pageWidthPt,height:M.pageHeightPt});a=M,b=M.contentWidthPt,_=M.indentStepPx,H?(m=we(m,a.blockSpacingPt,0,a.marginTopPt),m>this.getPdfWritableBottomPt(t,a)&&(t.addPage([a.pageWidthPt,a.pageHeightPt],a.orientation),m=a.marginTopPt)):(t.addPage([M.pageWidthPt,M.pageHeightPt],M.orientation),m=a.marginTopPt),v.set(k(),this.physicalPageMetrics(M))}else t.addPage(),m=a.marginTopPt;const N=h?.get(u.id);N!==void 0&&c.set(k(),N),w(X+1),y=!0;continue}if(u.type==="toc"){const G=a.blockSpacingPt;!y&&G>0&&(m+=G),y=!1,u.id&&P.set(u.id,k());const M=Oe({children:e.map(V=>V.type==="paragraph"?this.paragraphForPdfOutput(V):V)},Me(u)),N=(u.fontSize??16)*this.PX_TO_PT,H=N*1.4,z=Jt.paddingYPx*this.PX_TO_PT;t.setFont(this.mapFontFamily(u.fontFamily??o),"normal"),t.setFontSize(N);const j=this.hexToRgb(u.color??"#000000");t.setTextColor(j.r,j.g,j.b),m+=z,M.length===0&&(m+H>p&&(m=this.advancePdfFlowRegion(t,a).y),m+=H);for(const V of M)m+H>p&&(m=this.advancePdfFlowRegion(t,a).y),f.push({pdfPage:k(),headingBlockId:V.blockId,block:u,entry:V,baseline:m+N,left:a.marginLeftPt,width:a.contentWidthPt,fontName:this.mapFontFamily(u.fontFamily??o),fontSizePt:N}),m+=H;m+=z;continue}const S=ct.pdfSpaceBeforePt(u,a)+ct.pdfSpaceAfterPt(E>0?e[E-1]:void 0);if(!y&&S>0?m+=S:y&&E===0&&a.keepFirstBlockDeclaredSpaceBefore&&(m+=(ct.declaredSpacingPx(u,"spaceBefore")??0)*ct.PX_TO_PT),y=!1,u.id&&u.type!=="paragraph"&&P.set(u.id,k()),u.type==="container"){const G=await this.renderContainerBlock(t,u,m,b,o,i,r,a);m=G.nextY;for(const[M,N]of G.blockStartPages)P.set(M,N);d.push(...G.lineMarks);continue}if(u.type==="placeholder"){m=this.advancePlaceholderBlock(t,u,m,a);continue}if(u.type==="image"){const G=await this.renderImageBlock(t,u,m,b,a);G&&(m=G.nextY);continue}if(u.type==="math"){const G=u;m=(await this.renderMathBlock(t,G,m,b,p,a)).nextY;continue}if(u.type==="list"){m=await this.renderListBlock(t,u,m,b,o,a,x.get(u.id),d);continue}if(u.type==="table"){m=await this.renderTableBlock(t,u,m,b,o,i,r,a);continue}if(u.type==="code"){m=await this.renderCodeBlock(t,u,m,b,p,a.marginLeftPt,i,r,a,d);continue}if(u.type!=="paragraph")continue;const O=u,{required:L,firstLineAdvance:A}=this.getRequiredParagraphStartHeight(e,E,b,_,a);L>0&&m+L>p&&a.marginTopPt+L<=p&&m!==a.marginTopPt&&(m=this.advancePdfFlowRegion(t,a).y),m+A>p&&m!==a.marginTopPt&&(m=this.advancePdfFlowRegion(t,a).y),O.id&&P.set(O.id,k()),m=await this.renderParagraph(t,O,m,b,o,p,_,a,d)}if(f.length>0){const E=k(),u=this.createPdfPageNumbering(v.get(1)??a,v,c).labelForPage;for(const p of f){t.setPage(p.pdfPage),t.setFont(p.fontName,"normal"),t.setFontSize(p.fontSizePt);const S=this.hexToRgb(p.block.color??"#000000");t.setTextColor(S.r,S.g,S.b);const O=P.get(p.headingBlockId),L=O!==void 0?u(O):"",A=ke(p.block,p.entry,p.left,p.width,L,G=>t.getTextWidth(G),this.PX_TO_PT);A.text&&t.text(A.text,A.textX,p.baseline,{align:A.align,...A.rtl?{isInputVisual:!1,isOutputVisual:!0,isInputRtl:!0,isOutputRtl:!1}:{}}),L&&A.leaderEnd-A.leaderStart>Jt.minimumLeaderWidthPx*this.PX_TO_PT&&(t.setDrawColor(150),typeof t.setLineDashPattern=="function"&&t.setLineDashPattern([.8,2.2],0),t.line(A.leaderStart,p.baseline,A.leaderEnd,p.baseline),typeof t.setLineDashPattern=="function"&&t.setLineDashPattern([],0),t.setDrawColor(0,0,0)),L&&t.text(L,A.numberX,p.baseline)}t.setPage(E)}return{blockStartPages:P,pageMetrics:v,pageSections:c,lineMarks:d,finalY:m}}static async renderContainerBlock(t,e,a,i,r,o,l,n){const h=Math.max(0,e.padding??Bt.paddingPx)*this.PX_TO_PT,s=this.getPdfFlowBottom(t,n);a+h>s&&a!==n.marginTopPt&&(a=this.advancePdfFlowRegion(t,n).y);const g=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages(),P=g(),c=n.columnFlow?.index??0,d=n.columnFlow?.topPt??n.marginTopPt,f={...n,keepFirstBlockDeclaredSpaceBefore:void 0,marginTopPt:n.marginTopPt+h,marginRightPt:n.marginRightPt+h,marginBottomPt:n.marginBottomPt+h,marginLeftPt:n.marginLeftPt+h,contentWidthPt:Math.max(1,i-h*2),pageMarginLeftPt:n.pageMarginLeftPt+h},x=await this.renderBodyBlocks(t,e.children,f,o,l,r,void 0,void 0,void 0,a+h);let m=x.finalY+h;this.syncPdfColumnOffset(n),m>s&&x.finalY!==f.marginTopPt&&(m=this.advancePdfFlowRegion(t,n).y+h);const b=g(),_=n.columnFlow?.index??0,y=b,v=this.hexToRgb(e.borderColor??Bt.borderColor);t.setDrawColor(v.r,v.g,v.b),t.setLineWidth(Bt.borderWidthPx*this.PX_TO_PT);let k=P,X=c;for(;k<b||k===b&&X<=_;){t.setPage(k);const w=k===P&&X===c,E=k===b&&X===_,u=w?a:k===P?d:n.marginTopPt,p=E?m:s;p>u&&t.rect(n.pageMarginLeftPt+X*n.columnStridePt,u,i,p-u,"S"),X+=1,X>=n.columnCount&&(X=0,k+=1)}return t.setPage(y),{nextY:m,blockStartPages:x.blockStartPages,lineMarks:x.lineMarks}}static advancePlaceholderBlock(t,e,a,i){const r=Math.max(0,e.height||100)*this.PX_TO_PT,o=this.getPdfFlowBottom(t,i);return a+r>o&&a!==i.marginTopPt&&(a=this.advancePdfFlowRegion(t,i).y),a+r}static async toBlob(t,e,a){class i extends this{}return i.bundledGenreFamilies=new Map,i.scriptFallbackFamilies=new Map,i.shapingFonts=new Map,i.embeddedFamilyNames=new Map,i.inlineCodeFontFamily="courier",i.renderDocument(t,e,a)}static async renderDocument(t,e,a){t=this.splitDocumentFallbackRuns(t,await this.loadFallbackCoverage(t));const i=a||{...Et,background:Lt.codeBackground,text:Lt.codeText};await this.ensureAllLatexRendered(t);const r=this.resolvePdfLayoutMetrics(t),o=t.children.filter(S=>S.type==="section-break"),l=new Map,n=new Map,h=t.pageLayout?.pageNumberRestart===!0?{...r,pageNumberStartExplicit:!0}:r;o.forEach((S,O)=>{const L=o[O+1];l.set(S.id,L?.layout?this.resolvePdfMetricsFromSettings(L.layout,t.pageLayout,!0):L?r:h),n.set(S.id,O+1)});const s=o[0]?.layout?this.resolvePdfMetricsFromSettings(o[0].layout,t.pageLayout,!1):r,g=await import("./jspdf.es.min-Mykp4BZO.js").then(S=>S.j),P=g.jsPDF??g.default,c=new P({orientation:s.orientation,unit:"pt",format:[s.pageWidthPt,s.pageHeightPt]}),d=this.DEFAULT_BODY_FONT,{hasSourceCodePro:f}=await this.registerDocumentFonts(c,t,d);e&&c.setProperties({title:e});const x=Ce(t.watermark);x&&this.installWatermarkUnderpaint(c,x);const m=[...t.children.filter(S=>S.type==="footnote"),...t.notes??[]],b=t.children.filter(S=>S.type!=="footnote"&&S.type!=="header-footer"),_={balanceBySection:this.computeColumnBalanceTargets(t,b)},y=m.length>0?this.buildNumberedNoteEntries(t):[],v=y.filter(S=>S.kind==="footnote"),k=y.filter(S=>S.kind==="endnote");let X=new Map([[1,s]]),w=new Map([[1,0]]),E=s.marginTopPt,u=[],p=new Map;if(v.length===0){const S=await this.renderBodyBlocks(c,b,s,i,f,d,l,void 0,n,void 0,_);X=S.pageMetrics,w=S.pageSections,u=S.lineMarks,E=S.finalY}else{const S=v,O=et.separatorSpacePx*this.PX_TO_PT,L=this.mapFootnoteRefBlocks(b),A=new P({orientation:s.orientation,unit:"pt",format:[s.pageWidthPt,s.pageHeightPt]});await this.registerDocumentFonts(A,t,d);const G=await this.renderBodyBlocks(A,b,s,i,f,d,l,void 0,void 0,void 0,_),M=C=>{let B=s,U=0;for(const[W,Y]of G.pageMetrics)W<=C&&W>U&&(B=Y,U=W);return B},N=new Map,H=A.getNumberOfPages();for(const C of S){const B=L.get(C.footnoteId),U=(B?G.blockStartPages.get(B):void 0)??H,W=N.get(U)??[];W.push(C),N.set(U,W)}const z=new P({orientation:r.orientation,unit:"pt",format:[r.pageWidthPt,1e4]});await this.registerDocumentFonts(z,t,d);const j=new Map;for(const[C,B]of N){const U=M(C);for(const W of B){const Y={...U,pageHeightPt:1e4,marginTopPt:0,marginBottomPt:0},Z=await this.renderNoteEntry(z,W,0,Y,d,i,f,!1);j.set(W.footnoteId,Math.max(0,Z))}}const V=new Map;for(const[C,B]of N){const U=M(C),W=O+B.reduce((tt,at)=>tt+(j.get(at.footnoteId)??0),0),Y=U.pageHeightPt-U.marginTopPt-U.marginBottomPt,Z=G.lineMarks.filter(tt=>tt.pageNumber===C).sort((tt,at)=>tt.y-at.y).slice(0,et.minimumBodyLinesBeforeFootnotes),q=this.getParagraphLineHeight({type:"paragraph",id:"__pdf_measure__",children:[]}),Q=(Z.length>0?Math.max(0,Math.max(...Z.map(tt=>tt.y+tt.height))-U.marginTopPt):q*et.minimumBodyLinesBeforeFootnotes)+et.bodyKeepSlackPx*this.PX_TO_PT;V.set(C,Math.min(W,Math.max(0,Y-Q)))}p=V;const T=C=>({...C,reservedInsetForPage:V}),I=T(s),F=await this.renderBodyBlocks(c,b,I,i,f,d,l,T,n,void 0,_);X=F.pageMetrics,w=F.pageSections,u=F.lineMarks,E=F.finalY;const K=new Map;for(const C of F.lineMarks)K.set(C.pageNumber,Math.max(K.get(C.pageNumber)??0,C.y+C.height+et.separatorSpacePx*this.PX_TO_PT+et.verticalPaddingPx*this.PX_TO_PT));const D=c.getNumberOfPages();for(const[C,B]of[...N.entries()].sort((U,W)=>U[0]-W[0])){const U=Math.min(C,D);c.setPage(U);const W=M(C),Y=V.get(C)??0,Z=W.pageHeightPt-W.marginBottomPt-Y+O;c.setDrawColor(120),c.setLineWidth(.75),c.line(W.marginLeftPt,Z-7,W.marginLeftPt+Math.max(et.separatorWidthMinPx*this.PX_TO_PT,W.contentWidthPt*et.separatorWidthFraction),Z-7);let q=Z;for(let Q=0;Q<B.length;Q++){Q>0&&(q+=et.blockSpacingPx*this.PX_TO_PT);const tt=this.getPdfCurrentPage(c),at=c.addPage.bind(c),rt=[];c.addPage=(...st)=>{const lt=this.getPdfCurrentPage(c)+1;return lt<=D?c.setPage(lt):at(...st),rt.push(this.getPdfCurrentPage(c)),c};try{q=await this.renderNoteEntry(c,B[Q],q,W,d,i,f,!0,K)}finally{c.addPage=at}for(const st of rt){c.setPage(st),c.setDrawColor(120),c.setLineWidth(.75);const lt=(K.get(st)??W.marginTopPt)-et.verticalPaddingPx*this.PX_TO_PT*2;c.line(W.marginLeftPt,lt,W.marginLeftPt+W.contentWidthPt,lt)}c.setPage(rt[rt.length-1]??tt)}}c.setPage(this.getPdfPageCount(c))}if(k.length>0){const S=new P({orientation:r.orientation,unit:"pt",format:[r.pageWidthPt,1e4]});await this.registerDocumentFonts(S,t,d);let O=et.separatorToContentPx*this.PX_TO_PT;for(let z=0;z<k.length;z++){z>0&&(O+=et.blockSpacingPx*this.PX_TO_PT);const j={...r,pageHeightPt:1e4,marginTopPt:0,marginBottomPt:0};O+=await this.renderNoteEntry(S,k[z],0,j,d,i,f,!1)}const L=this.getPdfPageCount(c);let A=s,G=0;for(const[z,j]of X)z<=L&&z>=G&&(A=j,G=z);const M=E+et.inlineEndnoteGapPx*this.PX_TO_PT,N=M+O<=A.pageHeightPt-A.marginBottomPt-(p.get(L)??0);let H;N?(c.setPage(L),H=M):(c.addPage(),H=A.marginTopPt+et.newPageSeparatorOffsetPx*this.PX_TO_PT),c.setDrawColor(120),c.setLineWidth(.75),c.line(A.marginLeftPt,H,A.marginLeftPt+Math.max(et.separatorWidthMinPx*this.PX_TO_PT,A.contentWidthPt*et.separatorWidthFraction),H),H+=et.separatorToContentPx*this.PX_TO_PT;for(let z=0;z<k.length;z++)z>0&&(H+=et.blockSpacingPx*this.PX_TO_PT),H=await this.renderNoteEntry(c,k[z],H,A,d,i,f,!0)}return await this.renderHeaderFooterChrome(c,t,r,d,X,w),this.renderBodyLineNumbers(c,u,X,t),c.output("blob")}static measureLineAdvancePt(t,e,a,i){let r=0,o=0;for(const h of t)h.latexImage?o=Math.max(o,h.latexImage.contentHeight*this.PX_TO_PT):r=Math.max(r,h.marks?.fontSize?h.marks.fontSize*this.PX_TO_PT:e);r===0&&(r=e);const l=i??(a?this.LINE_HEIGHT_MULTIPLIERS.heading:this.LINE_HEIGHT_MULTIPLIERS.paragraph),n=r*l;return o>n*1.25?o:n}static parseParagraphDecoration(t){const e=t.shading&&t.shading!=="transparent"?t.shading:void 0;if(!e&&!t.borders)return null;let a;if(t.borders)try{a=JSON.parse(t.borders)}catch{a=void 0}return!e&&!a?null:{...e?{shading:e}:{},...a?{edges:a}:{}}}static drawParagraphDecorationSlice(t,e,a,i,r,o,l,n){if(e.shading){const f=this.hexToRgb(e.shading);t.setFillColor(f.r,f.g,f.b),t.rect(a,i,r,o+(n?0:.5),"F")}const h=e.edges;if(!h)return;const s=(f,x,m,b,_)=>{const y=h[f];if(!y||y.style==="none")return;const v=Math.max(.4,(y.width??1)*this.PX_TO_PT),k=m===_,X=this.hexToRgb(y.color??"#000000");if(t.setDrawColor(X.r,X.g,X.b),t.setLineWidth(v),k&&aa(y.style)){const u=ia(x,b,this.PX_TO_PT);for(const p of u.lines)t.line(p.from,m,p.to,m);t.setFillColor(X.r,X.g,X.b);for(const p of u.ornaments)if(y.style==="stars")for(const S of oa(p.cx,m,p.radius))t.line(S.x1,S.y1,S.x2,S.y2);else{const S=na(p.cx,m,p.radius);t.lines([[S[1].x-S[0].x,S[1].y-S[0].y],[S[2].x-S[1].x,S[2].y-S[1].y],[S[3].x-S[2].x,S[3].y-S[2].y]],S[0].x,S[0].y,[1,1],"F",!0)}return}const w=typeof t.setLineDashPattern=="function";w&&(y.style==="dashed"?t.setLineDashPattern([4.5,2.25],0):y.style==="dotted"?t.setLineDashPattern([1.5,1.5],0):t.setLineDashPattern([],0));const E=u=>{t.line(x+(k?0:u),m+(k?u:0),b+(k?0:u),_+(k?u:0))};y.style==="double"?(E(-v),E(v)):E(0),w&&t.setLineDashPattern([],0)},g=n?0:.5,P=f=>Math.max(0,h[f]?.space??0)*this.PX_TO_PT,c=a-P("left"),d=a+r+P("right");if(s("left",c,i,c,i+o+g),s("right",d,i,d,i+o+g),l){const f=i-P("top");s("top",a,f,a+r,f)}if(n){const f=i+o+P("bottom");s("bottom",a,f,a+r,f)}}static measureParagraphLineAdvances(t,e,a,i){const r=this.createCanvasTextContext();if(!r)return[this.getParagraphLineHeight(t)];const o=this.createLayoutForWrapping(e,a,i),l=qt(this.paragraphForPdfOutput(t),r,o);if(l.length===0)return[this.getEmptyParagraphLineHeight(t)];const n=this.getParagraphFontSize(t),h=this.getLineSpacingMultiplier(t);return l.map(s=>this.measureLineAdvancePt(s.segments.map(g=>({marks:g.marks})),n,!!t.heading,h))}static paragraphForPdfOutput(t){const e=t.children.filter(a=>a.type!=="text"||!a.marks?.hidden||!!a.marks.footnoteRef);return e.length===t.children.length?t:{...t,children:e}}static getParagraphDirection(t){let e="";for(const a of t.children)e+=a.text??"";return Re(t.direction,e)}static getEffectiveParagraphAlignment(t,e){return t.align||(e==="rtl"?"right":"left")}static getRequiredParagraphStartHeight(t,e,a,i,r){const o=t[e];if(!o||o.type!=="paragraph")return{required:0,firstLineAdvance:0};const l=vt(o),n=this.measureParagraphLineAdvances(o,a,i,r),h=this.paragraphForPdfOutput(o).children.every(c=>c.type==="text"&&c.text==="")||n.length===0?this.getEmptyParagraphLineHeight(o):n[0],s=c=>c.reduce((d,f)=>d+Math.max(0,f),0);let g=0;if(l.keepLines?g=s(n):l.widowControl&&n.length>=2&&(g=n[0]+n[1]),!l.keepNext)return{required:g,firstLineAdvance:h};let P=0;for(let c=0;c<Qt;c++){const d=t[e+c+1];if(!d||d.type!=="paragraph")break;const f=this.measureParagraphLineAdvances(d,a,i,r);if(f.length===0)break;P+=ct.pdfSpaceBeforePt(d,r);const x=vt(d);if(x.keepNext&&c<Qt-1){P+=s(f);continue}P+=f[0],x.widowControl&&f.length>=2&&(P+=f[1]);break}return{required:Math.max(g,s(n)+P),firstLineAdvance:h}}static async renderParagraph(t,e,a,i,r,o,l=this.resolveIndentStepPx(),n=this.getDefaultPdfLayoutMetrics(),h){let s=a;const g=this.paragraphForPdfOutput(e),P=this.getParagraphFontSize(e),c=this.getParagraphLineHeight(e),d=this.getLineSpacingMultiplier(e);let f=Number.isFinite(o)&&o>0?o:this.getPdfFlowBottom(t,n),x=n.marginLeftPt;const m=()=>{const w=this.advancePdfFlowRegion(t,n);s=w.y,x=w.x,f=this.getPdfFlowBottom(t,n)},b=(w=c)=>{if(s+w>f){if(s===n.marginTopPt)return;m()}},_=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages(),y=this.getParagraphDirection(g),v=this.getEffectiveParagraphAlignment(e,y),k=this.parseParagraphDecoration(e);if(g.children.length===0||g.children.length===1&&g.children[0].type==="text"&&g.children[0].text===""){const w=this.getEmptyParagraphLineHeight(e);return k&&(b(w),this.drawParagraphDecorationSlice(t,k,x,s,i,w,!0,!0)),s+w}const X=this.createCanvasTextContext();if(X){const w=this.createLayoutForWrapping(i,l,n),E=qt(g,X,w),u=await this.prepareLatexImages(g,P),p=E.map(O=>O.segments.map(L=>L.marks?.latex?{text:L.text,marks:L.marks,latexImage:u.get(L.text)}:{text:L.text,marks:L.marks,font:L.marks?.fontFamily})),S=vt(e);for(let O=0;O<E.length;O++){const L=E[O],A=p[O];if(A.length>0){const G=this.getParagraphLineIndentPt(e,O,l),M=Math.max(1,i-G),N=this.measureLineAdvancePt(A,P,!!e.heading,d),H=p[O+1];if(S.widowControl&&E.length>=3&&O===E.length-2&&H&&s+N<=f){const j=this.measureLineAdvancePt(H,P,!!e.heading,d);s+N+j>f&&s!==n.marginTopPt&&m()}b(N);const z=y==="rtl"?x:x+G;k&&this.drawParagraphDecorationSlice(t,k,x,s,i,N,O===0,O===E.length-1),h?.push({pageNumber:_(),y:s,height:N}),s=this.renderLine(t,A,s,z,M,v,P,r,!!e.heading,d,O===E.length-1,{direction:y,...L.tabLayout?{tabLayoutPx:L.tabLayout.segments,...L.tabLayout.rtl?{tabRtl:!0,tabWidthPx:L.tabLayout.width}:{}}:{},...L.hyphenTrailing?{hyphenTrailing:!0}:{}})}}return s}return this.renderParagraphWithJsPDFWrapping(t,g,a,i,r,o,l,n)}static async prepareLatexImages(t,e){const a=new Map;for(const i of t.children)if(i.type==="text"&&i.marks?.latex){const r=await this.renderLatexToImage(i.text,!1,e);r&&a.set(i.text,r)}return a}static async renderParagraphWithJsPDFWrapping(t,e,a,i,r,o,l=this.resolveIndentStepPx(),n=this.getDefaultPdfLayoutMetrics()){let h=a;const s=this.getParagraphFontSize(e),g=this.getParagraphLineHeight(e),P=this.getLineSpacingMultiplier(e);let c=Number.isFinite(o)&&o>0?o:this.getPdfFlowBottom(t,n),d=n.marginLeftPt;const f=()=>{if(h+g>c){if(h===n.marginTopPt)return;const w=this.advancePdfFlowRegion(t,n);h=w.y,d=w.x,c=this.getPdfFlowBottom(t,n)}},x=this.getParagraphDirection(e),m=this.getEffectiveParagraphAlignment(e,x),b=await this.processTextNodesWithLatex(e.children,s);if(b.length===0)return h+this.getEmptyParagraphLineHeight(e);let _=[],y=0,v=0;const k=()=>Math.max(1,i-this.getParagraphLineIndentPt(e,v,l)),X=(w=!1)=>{if(_.length===0)return;f();const E=this.getParagraphLineIndentPt(e,v,l);h=this.renderLine(t,_,h,x==="rtl"?d:d+E,Math.max(1,i-E),m,s,r,!!e.heading,P,w,{direction:x}),_=[],y=0,v+=1};if(b.length===1&&b[0].text==="")return a+this.getEmptyParagraphLineHeight(e);for(const w of b){if(w.latexImage){const u=w.latexImage.contentWidth*this.PX_TO_PT;y+u>k()&&_.length>0&&X(),_.push({text:w.text,marks:w.marks,font:w.font||w.marks?.fontFamily,latexImage:w.latexImage}),y+=u;continue}this.setRunFont(t,w,r),t.setFontSize(this.getRunEffectiveFontSizePt(w.marks,s));const E=w.text.split(`
2
+ `);for(let u=0;u<E.length;u++){const p=E[u];u>0&&_.length>0&&X();const S=p.split(/(\s+)/);for(const O of S){const L=this.measureRunDisplayWidthPt(t,O,w.marks);y+L>k()&&_.length>0&&X(),(O.trim()||_.length>0)&&(_.push({text:O,marks:w.marks,font:w.font||w.marks?.fontFamily}),y+=L)}}}return _.length>0&&X(!0),h}static getLineSpacingMultiplier(t){return te(t)}static async renderListBlock(t,e,a,i,r,o=this.getDefaultPdfLayoutMetrics(),l,n){if(!e.children.length)return a;let h=a;const s=this.getPdfFlowBottom(t,o),g=l??Ne(e),P={...g.counters};let c;if(e.variant==="ordered"&&e.numberingFormat)try{t.setFont(this.mapFontFamily(r),"normal"),t.setFontSize(this.FONT_SIZES.normal);let d=0;for(const x of Ie(e,g))d=Math.max(d,t.getTextWidth(x)/this.PX_TO_PT);const f=this.ORDERED_LIST_INDENT_PT/this.PX_TO_PT;c=Math.min(Math.max(f,Math.ceil(d)+10),240)*this.PX_TO_PT}catch{c=void 0}for(let d=0;d<e.children.length;d++){const f=e.children[d],x=this.getListIndentLevel(f);let m;e.variant==="ordered"?m={type:"ordered",label:this.computeOrderedMarkerLabel(P,x,g.start,Be(e.numberingFormat))}:e.variant==="todo"?m={type:"todo",checked:!!f.checked}:m={type:"bullet",indentLevel:x},h=await this.renderListItem(t,f,e,m,h,i,s,r,o,n,c)}return h}static async renderListItem(t,e,a,i,r,o,l,n,h=this.getDefaultPdfLayoutMetrics(),s,g){let P=r+Math.max(0,e.spaceBefore??0)*this.PX_TO_PT;const c=this.getListIndentLevel(e)*this.SUBLIST_INDENT_PT,d=n,f=this.FONT_SIZES.normal,x=this.mapFontFamily(d);t.setFont(x,"normal"),t.setFontSize(f);const m=g??this.getListIndentPt(a.variant);let b=h.marginLeftPt,_=b+c+m,y=l;const v=()=>{const T=this.advancePdfFlowRegion(t,h);P=T.y,b=T.x,_=b+c+m,y=this.getPdfFlowBottom(t,h)};let k=o-c-m;(!Number.isFinite(k)||k<=0)&&(k=Math.max(o*.3,o*.1));let X="";for(const T of e.children)X+=T.text??"";const w=Ee(X)??"ltr",E=w==="rtl",u=()=>E?b:_,p=()=>E?b+k:_,S=e.lineSpacing??a.lineSpacing??this.LINE_HEIGHT_MULTIPLIERS.paragraph,O=f*S,L=await this.processTextNodesWithLatex(e.children,f);let A=L.length>0?L:[{text:""}];a.variant==="todo"&&e.checked&&(A=A.map(T=>T.latexImage?T:{...T,marks:{...T.marks,strikethrough:!0,color:Lt.todoCheckedText}}));const G=new Set(Object.values(this.SCRIPT_FALLBACK_FONTS).map(T=>T.family)),M=[...L].reverse().find(T=>!T.latexImage&&!T.marks?.latex&&T.text.length>0&&!G.has(T.marks?.fontFamily??""))?.marks;let N=[],H=0,z=!1;const j=()=>{z||(P+O>y&&P!==h.marginTopPt&&v(),this.drawListMarker(t,i,p(),P,O,f,d,n,E,M),z=!0)},V=()=>{N.length!==0&&(P+O>y&&P!==h.marginTopPt&&v(),j(),s?.push({pageNumber:t.getCurrentPageInfo?.().pageNumber??t.getNumberOfPages(),y:P,height:this.measureLineAdvancePt(N,f,!1,S)}),P=this.renderLine(t,N,P,u(),k,E?"right":"left",f,d,!1,S,!0,{direction:w}),N=[],H=0)};for(const T of A){if(T.latexImage){const F=T.latexImage.contentWidth*this.PX_TO_PT;H+F>k&&N.length>0&&V(),N.push({text:T.text,marks:T.marks,font:T.font,latexImage:T.latexImage}),H+=F;continue}this.setRunFont(t,T,d||n),t.setFontSize(this.getRunEffectiveFontSizePt(T.marks,f));const I=T.text.split(`
3
+ `);for(let F=0;F<I.length;F++){const K=I[F];F>0&&(N.length>0?V():(j(),P+=O));const D=K.split(/(\s+)/);for(const C of D){const B=this.measureRunDisplayWidthPt(t,C,T.marks);H+B>k&&N.length>0&&V(),(C.trim()||N.length>0)&&(N.push({text:C,marks:T.marks,font:T.font}),H+=B)}}}return N.length>0&&V(),z||(j(),P+=O),P+Math.max(0,e.spaceAfter??0)*this.PX_TO_PT}static drawListMarker(t,e,a,i,r,o,l,n,h,s){t.setDrawColor(0,0,0);const g=(d,f=0)=>h?2*a-d-f:d,P=a-this.BULLET_MARKER_WIDTH_PT,c=i+r/2;switch(e.type){case"bullet":{const d=g(P+this.BULLET_CENTER_OFFSET_PT),f=this.BULLET_RADIUS_PT;if(e.indentLevel<=0)t.circle(d,c,f,"F");else if(e.indentLevel===1)t.circle(d,c,f,"S");else{const x=this.BULLET_SQUARE_HALF_PT*2,m=g(P+this.BULLET_SQUARE_INSET_PT,x),b=c-this.BULLET_SQUARE_HALF_PT+this.BULLET_SQUARE_VERTICAL_ADJUST_PT;t.rect(m,b,x,x,"S")}break}case"todo":{const d=this.TODO_CHECKBOX_SIZE_PT,f=g(P-this.TODO_CHECKBOX_OFFSET_PT,d),x=c-d/2;t.setLineWidth(.8),typeof t.roundedRect=="function"?t.roundedRect(f,x,d,d,this.TODO_CHECKBOX_RADIUS_PT,this.TODO_CHECKBOX_RADIUS_PT,"S"):t.rect(f,x,d,d,"S"),e.checked&&(t.setLineWidth(1.2),t.line(f+d*.15,x+d*.55,f+d*.4,x+d*.75),t.line(f+d*.4,x+d*.75,f+d*.85,x+d*.25));break}case"ordered":{const d=e.label,f=s?{fontFamily:s.fontFamily,fontSize:s.fontSize,bold:s.bold,italic:s.italic,code:s.code,superscript:s.superscript,subscript:s.subscript}:void 0;this.setRunFont(t,{text:d,marks:f},l||n);const x=this.getRunEffectiveFontSizePt(f,o);t.setFontSize(x);const m=t.getTextWidth(d),b=h?a+this.ORDERED_LABEL_GAP_PT:a-this.ORDERED_LABEL_GAP_PT-m;t.text(d,b,i+x);break}}t.setLineWidth(.5),t.setTextColor(0,0,0)}static async renderTableBlock(t,e,a,i,r,o=Et,l=!1,n=this.getDefaultPdfLayoutMetrics()){if(!e.children||e.children.length===0)return a;const h=this.getPdfFlowBottom(t,n);let s=a;const g=e.borderWidth??Dt.borderWidthPx,P=e.borderColor??Dt.borderColor,c=this.hexToRgb(P),d=Number.isFinite(e.cellPadding)?Math.max(0,Math.round(e.cellPadding)):Dt.cellPaddingPx,f=d*this.PX_TO_PT,x=ve(e.borders),m=De(e),b=m.cols,_=Math.min(e.tableWidth?e.tableWidth*this.PX_TO_PT:i,i),y=e.align==="center"?(i-_)/2:e.align==="right"?i-_:0;let v=n.marginLeftPt+y;const k=(e.columnWidths||[]).map(T=>T/100*_),X=[];for(let T=0;T<b;T++)X.push(k[T]||_/b);const w=[0];for(let T=0;T<b;T++)w.push(w[T]+X[T]);const E=T=>w[Math.min(T.col+T.colSpan,b)]-w[T.col],u=new Map;for(const T of m.cells){const I=Xe(d,T.cell.padding),F={top:I.top*this.PX_TO_PT,right:I.right*this.PX_TO_PT,bottom:I.bottom*this.PX_TO_PT,left:I.left*this.PX_TO_PT},K=E(T)-F.left-F.right,D=this.extractCellBlocks(T.cell);let C=this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph;if(D.length>0){const U=await import("./jspdf.es.min-Mykp4BZO.js").then(q=>q.j),W=U.jsPDF??U.default,Y=new W({orientation:"portrait",unit:"pt",format:[Math.max(72,K),this.UNBOUNDED_CELL_FLOW_BOTTOM_PT]});await this.registerCurrentPdfFonts(Y,l);const Z={...n,keepFirstBlockDeclaredSpaceBefore:!0,pageWidthPt:Math.max(72,K),pageHeightPt:this.UNBOUNDED_CELL_FLOW_BOTTOM_PT,marginTopPt:0,marginRightPt:0,marginBottomPt:0,marginLeftPt:0,contentWidthPt:Math.max(1,K)};C=(await this.renderBodyBlocks(Y,D,Z,o,l,r,void 0,void 0,void 0,0)).finalY}const B=F.top+C+F.bottom;u.set(T.cell.id,{blocks:D,width:K,flowHeight:C,contentHeight:B,pad:F})}const p=e.children.map((T,I)=>{let F=0;for(const K of T.children){const D=m.byId.get(K.id);D&&D.rowSpan>1||(F=Math.max(F,u.get(K.id)?.contentHeight??0))}return F}),S=m.cells.filter(T=>T.rowSpan>1).sort((T,I)=>T.rowSpan-I.rowSpan);for(const T of S){const I=u.get(T.cell.id);if(!I)continue;let F=0;for(let K=T.row;K<T.row+T.rowSpan;K++)F+=p[K];I.contentHeight>F&&(p[T.row+T.rowSpan-1]+=I.contentHeight-F)}const O=T=>{let I=0;for(let F=T.row;F<T.row+T.rowSpan;F++)I+=p[F];return I},L=[],A=()=>{if(L.length===0)return;const T=this.getPdfCurrentPage(t);for(const{page:I,draw:F}of L)t.setPage(I),F();L.length=0,t.setPage(T)},G=(T,I,F,K,D,C,B)=>{const U=T.backgroundColor?this.hexToRgb(T.backgroundColor):B?{r:249,g:250,b:251}:{r:255,g:255,b:255};(T.backgroundColor||B)&&(t.setFillColor(U.r,U.g,U.b),t.rect(F,D,K,C,"F"));const W=this.getPdfCurrentPage(t),Y=sa(T.borders);if(x||Y){const Z=la({tableBorders:x,cellBorders:Y,flags:{isTopRow:(I?.row??0)===0,isBottomRow:I?I.row+I.rowSpan===m.rows:!1,isLeftCol:(I?.col??0)===0,isRightCol:I?I.col+I.colSpan===m.cols:!1},fallback:{style:"single",width:g,color:P}}),q=F+K,Q=D+C;L.push({page:W,draw:()=>{this.drawPdfBorderEdge(t,Z.top,F,D,q,D),this.drawPdfBorderEdge(t,Z.bottom,F,Q,q,Q),this.drawPdfBorderEdge(t,Z.left,F,D,F,Q),this.drawPdfBorderEdge(t,Z.right,q,D,q,Q)}})}else g>0&&L.push({page:W,draw:()=>{t.setDrawColor(c.r,c.g,c.b),t.setLineWidth(g*this.PX_TO_PT),t.rect(F,D,K,C,"S")}})},M=async(T,I,F,K)=>{const D=!!e.hasHeader&&I===0,C=p[I],B=this.getPdfCurrentPage(t);for(const U of T.children){t.setPage(B);const W=m.byId.get(U.id),Y=v+(W?w[W.col]:0),Z=W?E(W):_/b,q=K||!W?C:O(W);G(U,W,Y,Z,F,q,D);const Q=u.get(U.id),tt=Q?.blocks??this.extractCellBlocks(U),at=Q?.pad.left??f,rt=Q?.pad.right??f,st=Q?.pad.top??f,lt=Q?.pad.bottom??f,ht=Q?.width??Z-at-rt,nt=Q?.flowHeight??this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph,mt=Math.max(0,q-st-lt-nt),pt=U.verticalAlign==="bottom"?mt:U.verticalAlign==="middle"?mt/2:0,Ot=F+st+pt;if(tt.length>0){const Mt={...n,keepFirstBlockDeclaredSpaceBefore:!0,columnCount:1,columnFlow:void 0,marginTopPt:Ot,marginRightPt:Math.max(0,n.pageWidthPt-(Y+at+ht)),marginBottomPt:n.pageHeightPt-this.UNBOUNDED_CELL_FLOW_BOTTOM_PT,marginLeftPt:Y+at,pageMarginLeftPt:Y+at,contentWidthPt:Math.max(1,ht),fullContentWidthPt:Math.max(1,ht),columnStridePt:Math.max(1,ht)};await this.renderBodyBlocks(t,tt,Mt,o,l,r,void 0,void 0,void 0,Ot)}}t.setPage(B)},N=(T,I)=>T.idx!==I.idx?T.idx>I.idx?T:I:T.y>=I.y?T:I,H=async(T,I,F,K,D,C)=>{const B=u.get(I.id),U=B?.blocks??this.extractCellBlocks(I),W=B?.pad.left??f,Y=B?.pad.bottom??f,Z=F?E(F):_/b,q=B?.width??Z-W-(B?.pad.right??f),Q=F?w[F.col]:0;let tt=K.idx;if(U.length===0){const nt=B?.flowHeight??this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph;return{idx:tt,y:Math.min(C,K.y+nt+Y)}}const at=(nt,mt)=>{const pt=nt.left+Q+W;mt.marginTopPt=nt.top,mt.marginLeftPt=pt,mt.pageMarginLeftPt=pt,mt.marginRightPt=Math.max(0,n.pageWidthPt-(pt+q))},rt={...n,keepFirstBlockDeclaredSpaceBefore:!0,columnCount:1,columnFlow:void 0,marginBottomPt:n.pageHeightPt-C,reservedInsetForPage:void 0,contentWidthPt:Math.max(1,q),fullContentWidthPt:Math.max(1,q),columnStridePt:Math.max(1,q)},st=D(tt);at(st,rt),T.setPage(st.page);const lt=T.addPage;T.addPage=()=>{tt+=1;const nt=D(tt);return at(nt,rt),T.setPage(nt.page),T};let ht=K.y;try{ht=(await this.renderBodyBlocks(T,U,rt,o,l,r,void 0,void 0,void 0,K.y)).finalY}finally{T.addPage=lt}return{idx:tt,y:Math.min(C,ht+Y)}},z=async(T,I,F)=>{const K=h,D=j&&T>0?p[0]:0,C=n.marginTopPt+D,B=await import("./jspdf.es.min-Mykp4BZO.js").then($=>$.j),U=B.jsPDF??B.default,W=new U({orientation:n.orientation,unit:"pt",format:[n.pageWidthPt,n.pageHeightPt]});await this.registerCurrentPdfFonts(W,l);const Y=W.addPage.bind(W),Z=[{page:1,top:n.marginTopPt,left:v}],q=$=>{for(;Z.length<=$;)Y(),Z.push({page:Z.length+1,top:C,left:v});return Z[$]},Q=($,it)=>{let{idx:Tt,y:gt}=$,dt=it;for(;;){const Pt=Math.max(0,K-gt);if(dt<=Pt+.01)return{idx:Tt,y:gt+dt};dt-=Pt,Tt+=1,gt=C}},tt=[],at=[],rt=new Map,st=[];let lt={idx:0,y:F};for(let $=T;$<I;$++){const it=lt;tt[$-T]=it;for(const dt of e.children[$].children){const Pt=m.byId.get(dt.id),bt=u.get(dt.id)?.pad.top??f,kt=it.y+bt>K+.01?{idx:it.idx+1,y:C+bt}:{idx:it.idx,y:it.y+bt};rt.set(dt.id,kt);const xt=await H(W,dt,Pt,kt,q,K),_t=Math.min(I-1,$+(Pt?.rowSpan??1)-1),Ft=st[_t-T];st[_t-T]=Ft?N(Ft,xt):xt}const Tt=Q(it,p[$]),gt=st[$-T];lt=gt?N(Tt,gt):Tt,at[$-T]=lt}let ht=lt.idx;for(const $ of rt.values())ht=Math.max(ht,$.idx);ht=Math.max(ht,Z.length-1);const nt=[{page:this.getPdfCurrentPage(t),top:n.marginTopPt,left:v}],mt=t.addPage,pt=()=>{const $=this.advancePdfFlowRegion(t,n);return v=$.x+y,{page:this.getPdfCurrentPage(t),top:$.y+D,left:v}};for(let $=1;$<=ht;$++){const it=pt();nt.push(it),D>0&&await M(e.children[0],0,it.top-D,!0)}const Ot=$=>{for(;nt.length<=$;){const it=t.addPage;t.addPage=mt;try{nt.push(pt())}finally{t.addPage=it}}return nt[$]};for(let $=T;$<I;$++){const it=!!e.hasHeader&&$===0;for(const Tt of e.children[$].children){const gt=m.byId.get(Tt.id),dt=Math.min(I-1,$+(gt?.rowSpan??1)-1),Pt=tt[$-T],bt=at[dt-T],kt=gt?E(gt):_/b;for(let xt=Pt.idx;xt<=bt.idx;xt++){const _t=nt[xt],Ft=xt===Pt.idx?Pt.y:_t.top,Ht=xt===bt.idx?bt.y:K;Ht-Ft<=.01||(t.setPage(_t.page),G(Tt,gt,_t.left+(gt?w[gt.col]:0),kt,Ft,Ht-Ft,it))}}}for(let $=T;$<I;$++)for(const it of e.children[$].children)await H(t,it,m.byId.get(it.id),rt.get(it.id),Ot,K);const Mt=at[at.length-1],Wt=nt[Math.min(Mt.idx,nt.length-1)];return t.setPage(Wt.page),v=Wt.left,Mt.y},j=e.hasHeader===!0&&e.children.length>1&&!m.cells.some(T=>T.row===0&&T.rowSpan>1),V=e.children.map(()=>[]);for(const T of m.cells)V[T.row]?.push(T);for(let T=0;T<e.children.length;){let I=T+1,F=0;for(let B=T;B<I;B++){F+=p[B];for(const U of V[B])I=Math.min(e.children.length,Math.max(I,U.row+U.rowSpan))}const K=j&&T>0?p[0]:0,D=h-n.marginTopPt-K,C=F>D;if((C?s>=h-.01:s+F>h)&&s!==n.marginTopPt){const B=this.advancePdfFlowRegion(t,n);s=B.y,v=B.x+y,j&&T>0&&(await M(e.children[0],0,s,!0),s+=p[0])}if(C)s=await z(T,I,s);else for(let B=T;B<I;B++)await M(e.children[B],B,s,!1),s+=p[B];T=I}return A(),s}static async renderCodeBlock(t,e,a,i,r,o=this.MARGIN_LEFT,l=Et,n=!1,h=this.getDefaultPdfLayoutMetrics(),s){const g=o-h.marginLeftPt;let P=o;const c=e.language||"",d=Ae(c);if(d&&e.renderDiagram!==!1&&d)return this.renderDiagramCodeBlock(t,e,a,i,r,P,d,l,n,h);const f=n?"SourceCodePro":"courier",x=e.content||"",m=c?await We(x,c,l):null,b=ft.fontSizePx*this.PX_TO_PT,_=b*ft.lineHeightMultiplier,y=ft.paddingPx*this.PX_TO_PT,v=ft.borderRadiusPx*this.PX_TO_PT,k=this.hexToRgb(l.background),X=this.hexToRgb(l.default);t.setFont(f,"normal"),t.setFontSize(b);const w=Math.max(1,i-y*2),E=ee(x,M=>t.getTextWidth(M),w),u=[];let p=0;for(const M of m??[])u.push({start:p,end:p+M.text.length,color:M.color}),p+=M.text.length;const S=M=>{if(u.length===0)return[{text:M.text,color:l.default}];const N=[];for(const H of u){const z=Math.max(M.startCharOffset,H.start),j=Math.min(M.endCharOffset,H.end);j<=z||N.push({text:x.slice(z,j),color:H.color})}return N.length>0?N:[{text:M.text,color:l.default}]};let O=a,L=0,A=r;const G=()=>{const M=this.advancePdfFlowRegion(t,h);O=M.y,P=M.x+g,A=this.getPdfFlowBottom(t,h)};for(;L<E.length;){const M=L===0,N=M?y:0,H=N+_+(E.length===L+1?y:0);O+H>A&&O!==h.marginTopPt&&G();let z=L,j=N;for(;z<E.length;){const T=z===E.length-1,I=j+_+(T?y:0);if(O+I>A&&z>L)break;j+=_,z+=1}const V=z===E.length;V&&(j+=y),t.setFillColor(k.r,k.g,k.b),M&&V?this.drawRoundedRect(t,P,O,i,j,v):t.rect(P,O,i,j,"F"),t.setFont(f,"normal"),t.setFontSize(b);for(let T=L;T<z;T++){const I=T===0,F=T===E.length-1,K=O+N+(T-L)*_;s?.push({pageNumber:t.getCurrentPageInfo?.().pageNumber??t.getNumberOfPages(),y:K-(I?y:0),height:_+(I?y:0)+(F?y:0)});let D=P+y;const C=O+N+(T-L)*_+b;for(const B of S(E[T])){const U=B.color?this.hexToRgb(B.color):X;t.setTextColor(U.r,U.g,U.b),B.text&&t.text(B.text,D,C),D+=t.getTextWidth(B.text)}}O+=j,L=z,V||G()}return O}static async renderDiagramCodeBlock(t,e,a,i,r,o,l,n,h,s){const g=o-s.marginLeftPt;let P=o;const c=ft.paddingPx*this.PX_TO_PT,d=ft.diagramSourceGapPx*this.PX_TO_PT,f=ae(),x=Math.max(120,Math.round((i-c*2)/this.PX_TO_PT)),m=await He({protocol:l,source:e.content||"",theme:f,maxWidth:x}),b=Math.max(1,m.width*this.PX_TO_PT),_=Math.max(ft.diagramMinHeightPx,m.height)*this.PX_TO_PT,y=_+c*2,v=e.showDiagramSource!==!1,k=h?"SourceCodePro":"courier",X=ft.fontSizePx*this.PX_TO_PT;t.setFont(k,"normal"),t.setFontSize(X);const w=ee(e.content||"",N=>t.getTextWidth(N),Math.max(1,i-c*2)),E=c*2+w.length*X*ft.lineHeightMultiplier,u=(v?E+d:0)+y;let p=a;if(p+u>r&&p!==s.marginTopPt){const N=this.advancePdfFlowRegion(t,s);p=N.y,P=N.x+g}v&&(p=await this.renderCodeBlock(t,{...e,renderDiagram:!1},p,i,r,P,n,h,s),p+=d);const S=this.hexToRgb(f.codeBorder||"#e0e0e0"),O=ft.borderRadiusPx*this.PX_TO_PT;t.setDrawColor(S.r,S.g,S.b),t.setLineWidth(this.BLOCK_BORDER_WIDTH_PT),this.drawRoundedRect(t,P,p,i,y,O,"S");const L=Math.min(i-c*2,b),A=Math.min(y-c*2,_),G=P+(i-L)/2,M=p+(y-A)/2;if(m.svg){const N=await this.svgToPng(m.svg,Math.max(1,Math.round(m.width)),Math.max(1,Math.round(m.height)),2);if(N)return t.addImage(N,"PNG",G,M,L,A),p+y}return t.setTextColor(220,38,38),t.setFont("helvetica","normal"),t.setFontSize(10),t.text("Diagram unavailable",P+c,p+c+10),p+y}static renderCellParagraph(t,e,a,i,r,o,l=!1){const n=this.getParagraphFontSize(e),h=this.getParagraphDirection(e),s=this.getEffectiveParagraphAlignment(e,h),g=this.getLineSpacingMultiplier(e),P=this.processTextNodes(e.children);let c=i,d=[],f=0;const x=m=>{d.length!==0&&(l?c+=this.measureLineAdvancePt(d,n,!!e.heading,g):c=this.renderLine(t,d,c,a,r,s,n,o,!!e.heading,g,m,{direction:h}),d=[],f=0)};for(const m of P){this.setRunFont(t,m,o),t.setFontSize(this.getRunEffectiveFontSizePt(m.marks,n));const b=m.text.split(`
4
+ `);for(let _=0;_<b.length;_++){_>0&&x(!1);const y=b[_].split(/(\s+)/);for(const v of y){const k=this.measureRunDisplayWidthPt(t,v,m.marks);f+k>r&&d.length>0&&x(!1),(v.trim()||d.length>0)&&(d.push({text:v,marks:m.marks,font:m.marks?.fontFamily}),f+=k)}}}return x(!0),c===i&&(c+=this.getEmptyParagraphLineHeight(e)),c}static extractCellBlocks(t){return t.children}static drawRoundedRect(t,e,a,i,r,o,l="F"){const n=Math.min(o,i/2,r/2);t.roundedRect(e,a,i,r,n,n,l)}static getListIndentPt(t){switch(t){case"todo":return this.TODO_LIST_INDENT_PT;case"ordered":return this.ORDERED_LIST_INDENT_PT;case"unordered":default:return this.UNORDERED_LIST_INDENT_PT}}static getListIndentLevel(t){const e=t.indentLevel??0;if(!Number.isFinite(e))return 0;const a=Math.floor(e);return Math.max(0,Math.min(a,this.MAX_LIST_INDENT_LEVEL))}static computeOrderedMarkerLabel(t,e,a,i){return Ge(t,a,e,i)}static getRunLetterSpacingPt(t){return(typeof t?.letterSpacing=="number"&&Number.isFinite(t.letterSpacing)?t.letterSpacing:0)*this.PX_TO_PT}static getRunEffectiveFontSizePt(t,e){const a=t?.fontSize?t.fontSize*this.PX_TO_PT:e;return t?.superscript||t?.subscript?Math.round(a/this.PX_TO_PT*.7)*this.PX_TO_PT:a}static setRunFont(t,e,a){if(e.marks?.code){t.setFont(this.inlineCodeFontFamily,"normal");return}const i=this.mapFontFamily(e.font||e.marks?.fontFamily||a),r=this.resolveFontStyle(e.marks),o=this.scriptFallbackFor(t,e.text,i);if(o){t.setFont(o,r==="bold"||r==="bolditalic"?"bold":"normal");return}t.setFont(i,r)}static measureRunDisplayWidthPt(t,e,a){const i=o=>{const l=t.getFont?.()?.fontName,n=l?this.shapingFonts.get(l):void 0;return n?n.layout(o).advanceWidth*t.getFontSize()/n.unitsPerEm:t.getTextWidth(o)},r=Ue(a);return r?zt(e,{...r,letterSpacingPx:this.getRunLetterSpacingPt(a)},i):i(e)}static drawShapedText(t,e,a,i,r,o,l){const n=t.getFont?.()?.fontName,h=n?this.shapingFonts.get(n):void 0;if(!h)return null;const s=h.layout(e);Array.from(e).every(f=>(f.codePointAt(0)??0)<=65535)&&t.text(e,a,i,{renderingMode:"invisible"}),t.setFillColor(l.r,l.g,l.b);const g=r/h.unitsPerEm;let P=0,c=0,d=0;for(let f=0;f<s.glyphs.length;f++){const x=s.glyphs[f],m=s.positions[f],b=[];let _=0,y=0;const v=X=>a+d+(P+m.xOffset+X)*g,k=X=>i-(c+m.yOffset+X)*g;for(const X of x.path.commands)if(X.command==="moveTo")[_,y]=X.args,b.push({op:"m",c:[v(_),k(y)]});else if(X.command==="lineTo")[_,y]=X.args,b.push({op:"l",c:[v(_),k(y)]});else if(X.command==="bezierCurveTo"){const[w,E,u,p,S,O]=X.args;b.push({op:"c",c:[v(w),k(E),v(u),k(p),v(S),k(O)]}),_=S,y=O}else if(X.command==="quadraticCurveTo"){const[w,E,u,p]=X.args,S=_+(w-_)*2/3,O=y+(E-y)*2/3,L=u+(w-u)*2/3,A=p+(E-p)*2/3;b.push({op:"c",c:[v(S),k(O),v(L),k(A),v(u),k(p)]}),_=u,y=p}else X.command==="closePath"&&b.push({op:"h",c:[]});b.length>0&&(t.path(b),t.fill()),P+=m.xAdvance,c+=m.yAdvance,d+=o*Math.max(1,x.codePoints?.length??1)}return s.advanceWidth*r/h.unitsPerEm+o*[...e].length}static renderLine(t,e,a,i,r,o,l,n,h,s,g=!0,P){e=e.filter(u=>!u.marks?.hidden||!!u.marks.footnoteRef);let c=P?.tabLayoutPx;const d=u=>u.marks?.fontSize?u.marks.fontSize*this.PX_TO_PT:l,f=P?.direction??"ltr";if(!c&&e.length>0&&!e.some(u=>u.latexImage||u.marks?.latex)){const u=e,p={segments:u.map(O=>({text:O.text}))},S=ie(p,f);if(S){const O=(A,G)=>{let M=0,N=0;for(const H of u){const z=Math.max(A,N),j=Math.min(G,N+H.text.length);if(z<j){const V=H.text.slice(z-N,j-N);this.setRunFont(t,{...H,text:V},n),t.setFontSize(this.getRunEffectiveFontSizePt(H.marks,l)),M+=this.measureRunDisplayWidthPt(t,V,H.marks)}N+=H.text.length}return M},L=u.map(A=>A.text).join("");e=oe(p,S,O,o==="justify"&&!g).map(A=>({...u[A.segmentIndex],text:L.slice(A.start,A.end),rtl:A.rtl}))}}if(P?.tabRtl&&c&&c.length>0){const u=e,p=c,S=[],O=[];let L=0;for(;L<u.length;){const A=u[L];if(A.text===" "){S.push(A),O.push(p[L]??{startX:0,endX:0}),L++;continue}const G=L;let M=Number.NEGATIVE_INFINITY;for(;L<u.length&&u[L].text!==" ";){const F=p[L];F&&(M=Math.max(M,F.endX)),L++}const N=u.slice(G,L),H=N.map(F=>F.text).join("");if(!H)continue;Number.isFinite(M)||(M=0);const z={segments:N.map(F=>({text:F.text}))},j=ie(z,"rtl");if(!j){for(let F=G;F<L;F++)S.push(u[F]),O.push(p[F]??{startX:0,endX:0});continue}const V=oe(z,j,(F,K)=>{let D=0,C=0;for(const B of N){const U=Math.max(F,C),W=Math.min(K,C+B.text.length);if(U<W){const Y=B.text.slice(U-C,W-C);this.setRunFont(t,{...B,text:Y},n),t.setFontSize(this.getRunEffectiveFontSizePt(B.marks,l)),D+=this.measureRunDisplayWidthPt(t,Y,B.marks)}C+=B.text.length}return D}),T=V.reduce((F,K)=>F+K.width,0),I=M*this.PX_TO_PT-T;for(const F of V)S.push({...N[F.segmentIndex],text:H.slice(F.start,F.end),rtl:F.rtl}),O.push({startX:(I+F.x)/this.PX_TO_PT,endX:(I+F.x+F.width)/this.PX_TO_PT})}e=S,c=O}let x=0,m=0;for(const u of e)if(u.latexImage){const p=u.latexImage.contentHeight*this.PX_TO_PT;p>m&&(m=p)}else{const p=d(u);p>x&&(x=p)}x===0&&(x=l);const b=a+x;let _=0;if(c&&c.length>0)_=P?.tabRtl?(P.tabWidthPx??Math.max(...c.map(u=>u.endX)))*this.PX_TO_PT:c[c.length-1].endX*this.PX_TO_PT;else for(const u of e)u.latexImage?_+=u.latexImage.contentWidth*this.PX_TO_PT:(this.setRunFont(t,u,n),t.setFontSize(this.getRunEffectiveFontSizePt(u.marks,l)),_+=this.measureRunDisplayWidthPt(t,u.text,u.marks));let y=i;o==="center"?y=i+(r-_)/2:(o==="right"||o==="justify"&&f==="rtl"&&(g||c))&&(y=i+r-_),P?.tabRtl&&c&&(y=i);let v=0;if(o==="justify"&&!g&&!c){let u=0;for(const p of e)p.latexImage||p.marks?.latex||(u+=(p.text.match(/ /g)||[]).length);u>0&&(v=Math.max(0,(r-_)/u))}const k=y;for(let u=0;u<e.length;u++){const p=e[u],S=c?.[u];if(S&&(y=k+S.startX*this.PX_TO_PT,p.text===" ")){if(S.leader){const D=this.getRunEffectiveFontSizePt(p.marks,l),C=p.marks?.color?this.hexToRgb(p.marks.color):{r:0,g:0,b:0};this.renderTabLeaderPdf(t,k+S.startX*this.PX_TO_PT,k+S.endX*this.PX_TO_PT,b,S.leader,D,C)}y=k+S.endX*this.PX_TO_PT;continue}if(p.latexImage){const D=p.latexImage.width*this.PX_TO_PT,C=p.latexImage.height*this.PX_TO_PT,B=p.latexImage.contentWidth*this.PX_TO_PT,U=p.latexImage.contentHeight*this.PX_TO_PT,W=(D-B)/2,Y=y-W,Z=b-U*.7-W;try{t.addImage(p.latexImage.dataUrl,"PNG",Y,Z,D,C)}catch(q){console.error("Failed to add inline latex image to PDF:",q)}y+=B;continue}this.setRunFont(t,p,n);const O=d(p),L=this.getRunEffectiveFontSizePt(p.marks,l),A=L/this.PX_TO_PT;t.setFontSize(L);const G=!!p.marks?.link;let M={r:0,g:0,b:0};G?M={r:37,g:99,b:235}:p.marks?.color?M=this.hexToRgb(p.marks.color):p.marks?.code&&(M=this.hexToRgb(Lt.codeText)),t.setTextColor(M.r,M.g,M.b);const N=!!(p.marks?.smallCaps&&!p.marks?.allCaps),H=this.getRunLetterSpacingPt(p.marks),z=p.rtl?{isInputVisual:!1,isOutputVisual:!0,isInputRtl:!0,isOutputRtl:!1}:void 0,j=H!==0||z?{...H!==0?{charSpace:H}:{},...z}:void 0,V=this.measureRunDisplayWidthPt(t,p.text,p.marks),T=v>0?(p.text.match(/ /g)||[]).length:0,I=V+T*v;if(p.marks?.backgroundColor){const D=ze(p.marks.backgroundColor)??p.marks.backgroundColor,C=this.hexToRgb(D);t.setFillColor(C.r,C.g,C.b),t.rect(y,b-O*.8,I,O*1.1,"F"),t.setTextColor(M.r,M.g,M.b)}else if(p.marks?.code){const D=this.hexToRgb(Lt.codeBackground);t.setFillColor(D.r,D.g,D.b),this.drawRoundedRect(t,y-2*this.PX_TO_PT,b-O*.93,I+4*this.PX_TO_PT,O+4*this.PX_TO_PT,3*this.PX_TO_PT),t.setTextColor(M.r,M.g,M.b)}let F=b;p.marks?.superscript?F=b-O*.4:p.marks?.subscript&&(F=b+O*.15),(p.marks?.underline||G)&&!p.marks?.code&&(G?t.setDrawColor(37,99,235):t.setDrawColor(0,0,0),t.setLineWidth(.5),t.line(y,F+2,y+I,F+2));const K=(D,C)=>{const B=p.marks?.allCaps?At(D,p.marks.lang):D,U=this.drawShapedText(t,B,C,F,L,H,M);if(U!==null)return U;if(N){let W=C;for(const Y of ra(D,p.marks?.lang)){const Z=Y.lower?t.getTextWidth(At(Y.text,p.marks?.lang))*ne:t.getTextWidth(Y.text);Y.lower?(t.setFontSize(L*ne),t.text(At(Y.text,p.marks?.lang),W,F,j),t.setFontSize(L)):t.text(Y.text,W,F,j),W+=Z+H*Y.text.length}return W-C}return t.text(B,C,F,j),this.measureRunDisplayWidthPt(t,D,p.marks)};if(v>0){let D=y;for(const C of p.text.split(/( +)/))C&&(D+=K(C,D),C[0]===" "&&(D+=v*C.length))}else K(p.text,y);if(p.marks?.strikethrough||p.marks?.doubleStrikethrough){t.setDrawColor(M.r,M.g,M.b),t.setLineWidth(Math.max(1,Math.round(A*.04))*this.PX_TO_PT);const D=C=>{const B=C-L*.3;t.line(y,B,y+I,B)};p.marks?.doubleStrikethrough?(D(F+L*.09),D(F-L*.09)):D(F)}if(G&&p.marks?.link){const D=b-O*.8,C=O*1.1;t.link(y,D,I,C,{url:p.marks.link})}y+=I}if(P?.hyphenTrailing){const u=e[e.length-1];if(u&&!u.marks?.latex){this.setRunFont(t,u,n),t.setFontSize(this.getRunEffectiveFontSizePt(u.marks,l));const p=u.marks?.color?this.hexToRgb(u.marks.color):{r:0,g:0,b:0};t.setTextColor(p.r,p.g,p.b),t.text("-",y,b)}}const X=s??(h?this.LINE_HEIGHT_MULTIPLIERS.heading:this.LINE_HEIGHT_MULTIPLIERS.paragraph),w=x*X,E=m>w*1.25?m:w;return a+E}static renderTabLeaderPdf(t,e,a,i,r,o,l){const n=Math.max(1.5,o*.12),h=e+n,s=a-n;if(s-h<1)return;if(t.setFillColor(l.r,l.g,l.b),r==="underscore"){const P=i+Math.max(1,o*.08),c=Math.max(.75,o*.055);t.rect(h,P,s-h,c,"F");return}const g=Math.max(2.25,o*.33);if(r==="dot"){const P=Math.max(.45,o*.045),c=i-P;for(let d=Math.ceil(h/g)*g;d<=s;d+=g)t.circle(d,c,P,"F")}else{const P=Math.max(1.5,o*.18),c=i-o*.28,d=Math.max(.75,o*.055);for(let f=Math.ceil(h/g)*g;f+P<=s;f+=g)t.rect(f,c,P,d,"F")}}static processTextNodes(t){const e=[];for(const a of t)if(a.type==="text"){const i=a;if(i.marks?.hidden&&!i.marks.footnoteRef)continue;e.push({text:i.text,marks:i.marks,font:i.marks?.fontFamily})}return e}static async processTextNodesWithLatex(t,e){const a=[];for(let o=0;o<t.length;o++){const l=t[o];if(l.type==="text"){const n=l;if(n.marks?.hidden&&!n.marks.footnoteRef)continue;n.marks?.latex?a.push({index:o,node:n,latexPromise:this.renderLatexToImage(n.text,!1,e)}):a.push({index:o,node:n})}}const i=await Promise.all(a.map(o=>o.latexPromise||Promise.resolve(null))),r=[];for(let o=0;o<a.length;o++){const{node:l}=a[o],n=i[o];r.push({text:l.text,marks:l.marks,font:l.marks?.fontFamily,latexImage:n||void 0})}return r}static getParagraphFontSize(t){return Ke(t)*this.PX_TO_PT}static getParagraphLineHeight(t){return this.getParagraphFontSize(t)*te(t)}static getEmptyParagraphLineHeight(t){return this.measureLineAdvancePt(this.paragraphForPdfOutput(t).children.map(e=>({marks:e.type==="text"?e.marks:void 0})),this.getParagraphFontSize(t),!!t.heading,this.getLineSpacingMultiplier(t))}static async embedLocalFonts(t,e){if(this.embeddedFamilyNames.clear(),typeof window>"u")return;const a=new Set(["sans-serif","sans","serif","monospace","system-ui","system ui","ui-sans-serif","ui-serif","ui-monospace"]),i=Nt(e).map(o=>o.family).filter(o=>{const l=o.toLowerCase();return!a.has(l)&&this.FONT_MAP[l]!=="KaTeX_Main"});if(i.length===0)return;let r;for(const o of i){const l=o.toLowerCase();let n=this.localFontFiles.get(l);if(n===void 0){if(r===void 0&&(r=await je().catch(()=>null)),!r)return;try{n=await this.buildLocalFontFiles(o,r)}catch{n=null}this.localFontFiles.set(l,n)}if(n)try{for(const h of n)t.addFileToVFS(h.vfsName,h.base64),t.addFont(h.vfsName,o,h.style);this.embeddedFamilyNames.set(l,o)}catch(h){console.warn(`Failed to embed font "${o}" in PDF:`,h),this.localFontFiles.set(l,null)}}}static async buildLocalFontFiles(t,e){const a=t.toLowerCase(),i=e.filter(c=>c.family?.trim().toLowerCase()===a&&c.blob);if(i.length===0)return null;const r=i.map(c=>({entry:c,...$e(c.style),specificity:(c.style??"").length})),o=(c,d)=>r.filter(f=>f.bold===c&&f.italic===d).sort((f,x)=>f.specificity-x.specificity)[0]?.entry,l=o(!1,!1)??r[0].entry,n=[{style:"normal",entry:l},{style:"bold",entry:o(!0,!1)??l},{style:"italic",entry:o(!1,!0)??l},{style:"bolditalic",entry:o(!0,!0)??o(!0,!1)??l}],h=new Map;for(const{entry:c}of n){if(h.has(c))continue;const d=await(await c.blob()).arrayBuffer(),f=Gt(new Uint8Array(d));h.set(c,f==="ttf"?this.arrayBufferToBase64(d):null)}if(!h.get(l))return null;const s=a.replace(/[^a-z0-9]+/g,"-"),g=new Map;let P=0;return n.map(({style:c,entry:d})=>{const f=h.get(d)?d:l;let x=g.get(f);return x||(x=`${s}-${P++}.ttf`,g.set(f,x)),{vfsName:x,base64:h.get(f),style:c}})}static mapFontFamily(t){const e=this.mapFontFamilyToStandard(t);return this.bundledGenreFamilies.get(e)??(e==="SourceSerif4"?"times":e)}static mapFontFamilyToStandard(t){if(!t)return"helvetica";const e=new Set(["helvetica","times","courier"]),a=t.split(",").map(r=>r.trim().replace(/^['"]|['"]$/g,"")).filter(r=>r.length>0);a.length===0&&a.push(t);for(const r of a){const o=r.toLowerCase(),l=this.embeddedFamilyNames.get(o);if(l)return l;if(e.has(o))return o;const n=this.FONT_MAP[o];if(n)return n}const i=Ye(a[0]);return i==="serif"?"times":i==="monospace"?"courier":"helvetica"}static resolveFontStyle(t){const e=!!t?.bold,a=!!t?.italic;return e&&a?"bolditalic":e?"bold":a?"italic":"normal"}static drawPdfBorderEdge(t,e,a,i,r,o){if(e.style==="none"||e.width<=0)return;const l=this.hexToRgb(e.color);t.setDrawColor(l.r,l.g,l.b);const n=Ve(e).map(h=>h*this.PX_TO_PT);if(n.length>0&&typeof t.setLineDashPattern=="function"&&t.setLineDashPattern(n,0),e.style==="double"){const h=Math.max(e.width/3,.5)*this.PX_TO_PT,s=e.width*2/3/2*this.PX_TO_PT;t.setLineWidth(h);const g=i===o,P=g?0:s,c=g?s:0;t.line(a-P,i-c,r-P,o-c),t.line(a+P,i+c,r+P,o+c)}else t.setLineWidth(e.width*this.PX_TO_PT),t.line(a,i,r,o);n.length>0&&typeof t.setLineDashPattern=="function"&&t.setLineDashPattern([],0)}static hexToRgb(t){return Ze(t)??{r:0,g:0,b:0}}static async renderImageBlock(t,e,a,i,r=this.getDefaultPdfLayoutMetrics()){if(!e.src)return{nextY:a};const o=this.getPdfFlowBottom(t,r);let l=Math.max(e.width||1,1)*this.PX_TO_PT,n=Math.max(e.height||1,1)*this.PX_TO_PT;if(l>i){const c=i/l;l=i,n*=c}(n<=0||!Number.isFinite(n))&&(n=72);let h=r.marginLeftPt;if(a+n>o&&a!==r.marginTopPt){const c=this.advancePdfFlowRegion(t,r);a=c.y,h=c.x}const s=e.align||"left";let g=h;if(s==="center"?g=h+(i-l)/2:s==="right"&&(g=h+i-l),e.originalFormat)return t.setFillColor(243,244,246),t.setDrawColor(209,213,219),t.setLineWidth(.75),t.rect(g,a,l,n,"FD"),t.setFont(this.mapFontFamily(void 0),"normal"),t.setFontSize(14*this.PX_TO_PT),t.setTextColor(107,114,128),t.text(`${e.originalFormat.toUpperCase()} image`,g+l/2,a+n/2,{align:"center",baseline:"middle"}),{nextY:a+n};const P=await this.resolveImageData(e.src);if(!P)return{nextY:a+n};try{t.addImage(P.data,P.format,g,a,l,n)}catch(c){return console.error("Failed to add image to PDF",c),{nextY:a+n}}return{nextY:a+n}}static async resolveImageData(t){const e=t.match(/^data:image\/([a-zA-Z0-9+.-]+);base64,/);if(e){const o=this.normalizeImageFormat(e[1]);return{data:t,format:o}}const a=await this.fetchImageAsBlob(t);if(!a)return null;const{blob:i,format:r}=a;return{data:await this.blobToDataUrl(i,r),format:r}}static async fetchImageAsBlob(t){try{const e=await fetch(t);if(!e.ok)throw new Error(`Failed to fetch image: ${e.status}`);const a=await e.blob(),i=this.extractImageFormat(a.type);return{blob:a,format:i}}catch(e){return console.error("Failed to load image for PDF export",e),null}}static async blobToDataUrl(t,e){const a=await t.arrayBuffer(),i=this.arrayBufferToBase64(a);return`data:${this.formatToMime(e)};base64,${i}`}static arrayBufferToBase64(t){const e=globalThis?.Buffer;if(e)return e.from(t).toString("base64");let a="";const i=new Uint8Array(t),r=32768;for(let o=0;o<i.length;o+=r){const l=i.subarray(o,o+r);a+=String.fromCharCode.apply(null,Array.from(l))}return btoa(a)}static formatToMime(t){const e=t.toLowerCase();return e==="jpeg"||e==="jpg"?"image/jpeg":e==="png"?"image/png":e==="webp"?"image/webp":`image/${e}`}static extractImageFormat(t){if(!t)return"PNG";const e=t.match(/^image\/([a-zA-Z0-9+.-]+)/);return e?this.normalizeImageFormat(e[1]):"PNG"}static normalizeImageFormat(t){const e=t.toLowerCase();return e==="jpg"||e==="jpeg"?"JPEG":e==="png"?"PNG":e==="webp"?"WEBP":e.toUpperCase()}static async renderMathBlock(t,e,a,i,r,o=this.getDefaultPdfLayoutMetrics()){if(!e.content||e.content.trim()==="")return{nextY:a};const l=e.displayMode!=="inline",n=await this.renderLatexToImage(e.content,l);if(!n)return{nextY:a+20};let h=n.width*this.PX_TO_PT,s=n.height*this.PX_TO_PT;const g=i-this.MATH_BLOCK_PADDING*2;if(h>g){const b=g/h;h=g,s*=b}const P=Math.max(this.MATH_BLOCK_MIN_HEIGHT,s)+this.MATH_BLOCK_PADDING*2;let c=o.marginLeftPt;if(a+P>r&&a!==o.marginTopPt){const b=this.advancePdfFlowRegion(t,o);a=b.y,c=b.x}const d=this.hexToRgb(ae().codeBorder||"#e0e0e0");t.setDrawColor(d.r,d.g,d.b),t.setLineWidth(this.BLOCK_BORDER_WIDTH_PT),typeof t.roundedRect=="function"?t.roundedRect(c,a,i,P,this.MATH_BLOCK_BORDER_RADIUS,this.MATH_BLOCK_BORDER_RADIUS,"S"):t.rect(c,a,i,P,"S");const f=e.align||"center";let x=c+this.MATH_BLOCK_PADDING;f==="center"?x=c+(i-h)/2:f==="right"&&(x=c+i-h-this.MATH_BLOCK_PADDING);const m=a+(P-s)/2;try{t.addImage(n.dataUrl,"PNG",x,m,h,s)}catch(b){console.error("Failed to add math image to PDF:",b)}return{nextY:a+P}}static async getHtml2Canvas(){return this.html2canvasModule?this.html2canvasModule:this.html2canvasLoading?this.html2canvasLoading:(this.html2canvasLoading=import("./html2canvas.esm-CntiHiYW.js").then(t=>(this.html2canvasModule=t.default,t.default)),this.html2canvasLoading)}static async renderLatexToImage(t,e,a=12){const i=this.getLatexSvgFromCache(t,e);if(i){const r=await this.svgToPng(i.svg,i.width,i.height,3);if(r){const o=e?1:this.INLINE_MATH_SCALE;return{dataUrl:r,width:i.width*o,height:i.height*o,contentWidth:i.contentWidth*o,contentHeight:i.contentHeight*o}}}try{const r=await this.getHtml2Canvas(),o=this.preprocessLaTeX(t),l=(await Je()).renderToString(o,{displayMode:e,throwOnError:!1,errorColor:"#ef4444",trust:!1,strict:!1});this.ensureKaTeXStyles();const n=a/this.PX_TO_PT,h=e?20:n*this.INLINE_MATH_SCALE,s=4,g=document.createElement("div");g.style.cssText=`
5
+ position: fixed;
6
+ top: -9999px;
7
+ left: -9999px;
8
+ font-size: ${h}px;
9
+ line-height: 1.2;
10
+ background: transparent;
11
+ padding: ${s}px;
12
+ z-index: -9999;
13
+ `,g.innerHTML=l,document.body.appendChild(g),document.fonts?.ready&&await document.fonts.ready;const P=4,c=await r(g,{backgroundColor:null,scale:P,logging:!1,useCORS:!0,allowTaint:!1});document.body.removeChild(g);const d=c.toDataURL("image/png"),f=c.width/P,x=c.height/P,m=f-s*2,b=x-s*2;return{dataUrl:d,width:f,height:x,contentWidth:m,contentHeight:b}}catch(r){return console.error("Failed to render LaTeX for PDF:",r),null}}static preprocessLaTeX(t){if(!t.includes(`
14
+ `)||["align","aligned","gather","gathered","split","cases","matrix","pmatrix","bmatrix","array"].some(a=>t.includes(`\\begin{${a}}`)||t.includes(`\\begin{${a}*}`)))return t;const e=t.split(`
15
+ `).map(a=>a.trim()).filter(a=>a.length>0);return e.length<=1?t:`\\begin{gathered}
16
+ ${e.join(` \\\\
17
+ `)}
18
+ \\end{gathered}`}static ensureKaTeXStyles(){if(this.katexStylesLoaded)return;if(document.querySelector('link[href*="katex"]')){this.katexStylesLoaded=!0;return}const t=document.createElement("link");t.rel="stylesheet",t.href=Ct("katex.min.css"),document.head.appendChild(t),this.katexStylesLoaded=!0}static async parseFile(t){const e=await import("./pdf-BLWDCiFF.js");e.GlobalWorkerOptions.workerSrc=Ct("pdfjs/worker.js");const a=await t.arrayBuffer();try{const i=await e.getDocument(a).promise;let r="";for(let h=1;h<=i.numPages;h++){const s=(await(await i.getPage(h)).getTextContent()).items.map(g=>g.str).join(" ");r+=s+`
19
+
20
+ `}const o=r.trim().split(`
21
+ `),l=[];let n=[];for(let h=0;h<o.length;h++){const s=o[h].trim();if(s===""){if(n.length>0){const g=n.join(" ").trim();g&&l.push(wt([{type:"text",text:g}])),n=[]}}else{const g=s.length<60,P=s===s.toUpperCase()&&/[A-Z]/.test(s),c=/[.!?]$/.test(s),d=h+1<o.length&&o[h+1].trim()==="";if(g&&(P||d&&!c)){if(n.length>0){const f=n.join(" ").trim();f&&l.push(wt([{type:"text",text:f}])),n=[]}l.push(wt([{type:"text",text:s}]))}else n.push(s)}}if(n.length>0){const h=n.join(" ").trim();h&&l.push(wt([{type:"text",text:h}]))}return l.length===0&&l.push(wt()),{type:"doc",children:l}}catch(i){throw console.error("Failed to parse PDF:",i),new Error(`Failed to parse PDF: ${i instanceof Error?i.message:"Unknown error"}`)}}};R.PAGE_WIDTH=612,R.PAGE_HEIGHT=792,R.MARGIN_LEFT=72,R.MARGIN_RIGHT=72,R.MARGIN_TOP=72,R.MARGIN_BOTTOM=72,R.PX_TO_PT=se,R.UNBOUNDED_CELL_FLOW_BOTTOM_PT=1e4,R.DEFAULT_BODY_FONT="Arial, sans-serif",R.LINE_HEIGHT_MULTIPLIERS=le,R.FONT_SIZES={h1:yt.h1*R.PX_TO_PT,h2:yt.h2*R.PX_TO_PT,h3:yt.h3*R.PX_TO_PT,h4:yt.h4*R.PX_TO_PT,h5:yt.h5*R.PX_TO_PT,h6:yt.h6*R.PX_TO_PT,normal:yt.paragraph*R.PX_TO_PT},R.FONT_MAP={arial:"helvetica",helvetica:"helvetica","helvetica neue":"helvetica","times new roman":"times",georgia:"times","source serif 4":"SourceSerif4",times:"times",courier:"courier","courier new":"courier",monospace:"courier",verdana:"helvetica",tahoma:"helvetica",inter:"helvetica","system-ui":"helvetica","system ui":"helvetica","ui-sans-serif":"helvetica","ui-serif":"times","ui-monospace":"courier","sans-serif":"helvetica",sans:"helvetica",serif:"times",katex_main:"KaTeX_Main",computermodern:"KaTeX_Main","computer modern":"KaTeX_Main"},R.TODO_LIST_INDENT_PT=ut.variantIndentPx.todo*R.PX_TO_PT,R.ORDERED_LIST_INDENT_PT=ut.variantIndentPx.ordered*R.PX_TO_PT,R.UNORDERED_LIST_INDENT_PT=ut.variantIndentPx.unordered*R.PX_TO_PT,R.SUBLIST_INDENT_PT=ut.sublistIndentPx*R.PX_TO_PT,R.BULLET_MARKER_WIDTH_PT=ut.markerWidthPx*R.PX_TO_PT,R.BULLET_CENTER_OFFSET_PT=8*R.PX_TO_PT,R.BULLET_RADIUS_PT=2.5*R.PX_TO_PT,R.BULLET_SQUARE_INSET_PT=5*R.PX_TO_PT,R.BULLET_SQUARE_HALF_PT=5*R.PX_TO_PT,R.BULLET_SQUARE_VERTICAL_ADJUST_PT=1*R.PX_TO_PT,R.ORDERED_LABEL_GAP_PT=6*R.PX_TO_PT,R.TODO_CHECKBOX_SIZE_PT=ut.todoCheckboxSizePx*R.PX_TO_PT,R.TODO_CHECKBOX_RADIUS_PT=ut.todoCheckboxRadiusPx*R.PX_TO_PT,R.TODO_CHECKBOX_OFFSET_PT=ut.todoCheckboxOffsetPx*R.PX_TO_PT,R.MAX_LIST_INDENT_LEVEL=ut.maxIndentLevel,R.MATH_BLOCK_PADDING=16*R.PX_TO_PT,R.MATH_BLOCK_MIN_HEIGHT=40*R.PX_TO_PT,R.MATH_BLOCK_BORDER_RADIUS=4*R.PX_TO_PT,R.BLOCK_BORDER_WIDTH_PT=1*R.PX_TO_PT,R.INLINE_MATH_SCALE=.85,R.BUNDLED_GENRE_FONTS={SourceSerif4:{family:"SourceSerif4",files:{normal:"SourceSerif4-Regular.ttf",bold:"SourceSerif4-Bold.ttf",italic:"SourceSerif4-It.ttf",bolditalic:"SourceSerif4-BoldIt.ttf"}},helvetica:{family:"LiberationSans",files:{normal:"LiberationSans-Regular.ttf",bold:"LiberationSans-Bold.ttf",italic:"LiberationSans-Italic.ttf",bolditalic:"LiberationSans-BoldItalic.ttf"}},times:{family:"LiberationSerif",files:{normal:"LiberationSerif-Regular.ttf",bold:"LiberationSerif-Bold.ttf",italic:"LiberationSerif-Italic.ttf",bolditalic:"LiberationSerif-BoldItalic.ttf"}},courier:{family:"LiberationMono",files:{normal:"LiberationMono-Regular.ttf",bold:"LiberationMono-Bold.ttf",italic:"LiberationMono-Italic.ttf",bolditalic:"LiberationMono-BoldItalic.ttf"}}},R.bundledGenreFamilies=new Map,R.SCRIPT_FALLBACK_FONTS=fa,R.scriptFallbackFamilies=new Map,R.scriptFontCoverageCache=new Map,R.fallbackCharsetCache=new Map,R.shapingFonts=new Map,R.inlineCodeFontFamily="courier",R.fontFileData=new Map,R.localFontFiles=new Map,R.embeddedFamilyNames=new Map,R.COLUMN_BALANCE_SLACK_PT=1.5,R.html2canvasModule=null,R.html2canvasLoading=null,R.katexStylesLoaded=!1;let ma=R;export{ma as PdfConverter};
@@ -0,0 +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 Xe(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 Ve({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 qe(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,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 Xe(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 Ve({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 qe(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};