@namahapdf/react 0.1.0 → 0.1.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.
- package/README.md +11 -1
- package/dist/index.cjs +63 -62
- package/dist/index.d.cts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.js +33 -32
- package/dist/styles.css +1 -1
- package/package.json +17 -4
package/dist/index.js
CHANGED
|
@@ -1,43 +1,44 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import"./chunk-R5KFRMXF.js";import*as El from"react";import Pm,{useCallback as wl,useEffect as wt,useMemo as vl,useRef as we,useState as ae}from"react";var Qo=class{constructor(){this.processors=new Map}registerProcessor(e){this.processors.set(e.name,e),console.log(`[AvniEngine] Registered processor: ${e.name}`)}async runPipeline(e,n){let r=[],o=e;for(let i of n.tasks){let s=this.processors.get(i.processorName);if(!s)throw new Error(`Processor ${i.processorName} not found`);console.log(`[AvniEngine] Executing ${s.name}...`);let a=Date.now(),c=await s.process(o,i.params),l=Date.now();if(c.metrics={duration:l-a,originalSize:o.size,newSize:c.document.size},r.push(c),!c.success){console.error(`[AvniEngine] Pipeline failed at ${s.name}: ${c.error}`);break}o=c.document}return r}getAvailableProcessors(){return Array.from(this.processors.keys())}},_n=new Qo;import{degrees as Bu,rgb as dr,PDFDocument as tc,PDFRef as Mi,StandardFonts as lt,TextAlignment as Ri}from"pdf-lib";var ei=t=>({type:"name",value:t.startsWith("/")?t.slice(1):t}),ti=()=>({type:"null"}),Xn=t=>({type:"boolean",value:t}),ni=t=>({type:"integer",value:t}),ri=t=>({type:"real",value:t}),Xr=(t,e)=>({type:"string",value:t,encoding:e}),oi=(t,e=0)=>({type:"ref",objNum:t,genNum:e});var zr=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="integer",Zs=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="real",ii=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="string",Z=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="dict",me=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="stream",Be=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="ref",he=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="array",Yr=t=>zr(t)||Zs(t),K=t=>!t||typeof t!="object"||!("type"in t)?null:t.type==="integer"||t.type==="real"?t.value:null;import Qs from"zlib";function ea(t){return!t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null}function Nd(t){if(!t)return[];let e=ea(t);return e?[e]:he(t)?t.items.map(n=>ea(n)).filter(n=>n!==null):[]}function ta(t){return t&&Z(t)?t:null}function Ed(t,e){if(e<=0)return[];if(!t)return new Array(e).fill(null);let n=ta(t);if(n)return new Array(e).fill(n);if(he(t)){let r=t.items.map(o=>ta(o));return r.length>=e?r.slice(0,e):[...r,...new Array(e-r.length).fill(null)]}return new Array(e).fill(null)}function sn(t,e){return t?K(t.entries.get(e)):null}function Td(t){let e=new TextDecoder("latin1").decode(t),n=e.indexOf(">"),r=(n>=0?e.slice(0,n):e).replace(/\s+/g,"");if(r.length===0)return new Uint8Array(0);let o=r.length%2===0?r:`${r}0`,i=new Uint8Array(o.length/2);for(let s=0;s<i.length;s++){let a=Number.parseInt(o.slice(s*2,s*2+2),16);if(Number.isNaN(a))throw new Error("Invalid ASCIIHex stream data");i[s]=a}return i}function Od(t){let e=new TextDecoder("latin1").decode(t),n=[],r=[];for(let o=0;o<e.length;o++){let i=e[o];if(i==="~"&&e[o+1]===">")break;if(/\s/.test(i))continue;if(i==="z"){if(r.length!==0)throw new Error("Invalid ASCII85 stream data");n.push(0,0,0,0);continue}let s=i.charCodeAt(0);if(!(s<33||s>117)&&(r.push(s-33),r.length===5)){let a=0;for(let c of r)a=a*85+c;n.push(a>>>24&255,a>>>16&255,a>>>8&255,a&255),r=[]}}if(r.length>0){let o=r.length;for(;r.length<5;)r.push(84);let i=0;for(let a of r)i=i*85+a;let s=[i>>>24&255,i>>>16&255,i>>>8&255,i&255];n.push(...s.slice(0,o-1))}return new Uint8Array(n)}function Id(t){let e=[];for(let n=0;n<t.length;){let r=t[n++];if(r===128)break;if(r<128){let s=r+1;for(let a=0;a<s&&n<t.length;a++)e.push(t[n++]);continue}let o=257-r;if(n>=t.length)break;let i=t[n++];for(let s=0;s<o;s++)e.push(i)}return new Uint8Array(e)}function jd(t,e,n){let r=t+e-n,o=Math.abs(r-t),i=Math.abs(r-e),s=Math.abs(r-n);return o<=i&&o<=s?t:i<=s?e:n}function na(t,e,n,r){let o=Math.max(1,Math.ceil(e*n/8)),i=Math.ceil(r*e*n/8);if(i<=0)return t;let s=i+1,a=Math.floor(t.length/s);if(a<=0)return t;let c=new Uint8Array(a*i),l=new Uint8Array(i);for(let d=0;d<a;d++){let m=t[d*s],h=t.subarray(d*s+1,d*s+1+i),f=c.subarray(d*i,(d+1)*i);switch(m){case 0:{f.set(h);break}case 1:{for(let p=0;p<i;p++){let w=p>=o?f[p-o]:0;f[p]=h[p]+w&255}break}case 2:{for(let p=0;p<i;p++)f[p]=h[p]+l[p]&255;break}case 3:{for(let p=0;p<i;p++){let w=p>=o?f[p-o]:0,b=l[p];f[p]=h[p]+Math.floor((w+b)/2)&255}break}case 4:{for(let p=0;p<i;p++){let w=p>=o?f[p-o]:0,b=l[p],y=p>=o?l[p-o]:0;f[p]=h[p]+jd(w,b,y)&255}break}default:{f.set(h);break}}l=f.slice()}return c}function $d(t){let e=[{bytes:t,trimmed:0,skippedHeader:!1}];t.length>2&&e.push({bytes:t.subarray(2),trimmed:0,skippedHeader:!0});let n=Math.min(64,Math.max(0,t.length-1));for(let r=1;r<=n;r++){let o=t.subarray(0,t.length-r);e.push({bytes:o,trimmed:r,skippedHeader:!1}),o.length>2&&e.push({bytes:o.subarray(2),trimmed:r,skippedHeader:!0})}for(let r of e){try{return{inflated:new Uint8Array(Qs.inflateSync(Buffer.from(r.bytes))),mode:"zlib",trimmed:r.trimmed,skippedHeader:r.skippedHeader}}catch{}try{return{inflated:new Uint8Array(Qs.inflateRawSync(Buffer.from(r.bytes))),mode:"raw",trimmed:r.trimmed,skippedHeader:r.skippedHeader}}catch{}}return null}function Bd(t,e){var i,s,a,c;let n=$d(t);if(!n){let l=Array.from(t.subarray(0,Math.min(8,t.length))).map(h=>`0x${h.toString(16).padStart(2,"0")}`).join(" "),d=Math.max(0,t.length-8),m=Array.from(t.subarray(d)).map(h=>`0x${h.toString(16).padStart(2,"0")}`).join(" ");throw new Error(`FlateDecode failed after zlib/raw retries (including tail-trim recovery). len=${t.length} first=[${l}] last=[${m}]`)}let r=n.inflated;if(n.trimmed>0||n.skippedHeader){let l=[];n.trimmed>0&&l.push(`trimmed ${n.trimmed} byte(s)`),n.skippedHeader&&l.push("skipped first 2 header byte(s)"),console.warn(`[StreamDecoder] FlateDecode recovered (${l.join(", ")}) using ${n.mode} mode`)}if(((i=sn(e,"Predictor"))!=null?i:1)>=10){let l=(s=sn(e,"Colors"))!=null?s:1,d=(a=sn(e,"BitsPerComponent"))!=null?a:8,m=(c=sn(e,"Columns"))!=null?c:1;return na(r,l,d,m)}return r}function Ld(t,e){var w,b,y,k;let i=0,s=9,a=258,c=[];for(let C=0;C<256;C++)c[C]=[C];let l=()=>{if(Math.floor(i/8)>=t.length)return null;let S=0;for(let F=0;F<s;F++){let O=i+F,I=t[Math.floor(O/8)]>>7-O%8&1;S=S<<1|I}return i+=s,S},d=()=>{c.length=0;for(let C=0;C<256;C++)c[C]=[C];s=9,a=258},m=[],h=null;for(;;){let C=l();if(C===null||C===257)break;if(C===256){d(),h=null;continue}let S;if(c[C])S=c[C];else if(h)S=[...h,h[0]];else break;m.push(...S),h&&(c[a++]=[...h,S[0]],a===1<<s&&s<12&&s++),h=S}let f=new Uint8Array(m);if(((w=sn(e,"Predictor"))!=null?w:1)>=10){let C=(b=sn(e,"Colors"))!=null?b:1,S=(y=sn(e,"BitsPerComponent"))!=null?y:8,F=(k=sn(e,"Columns"))!=null?k:1;return na(f,C,S,F)}return f}var ve=class{static async decodeStream(e){return this.decodeStreamSync(e)}static decodeStreamSync(e){var c,l;let n=e.dict.entries.get("Filter"),r=e.dict.entries.get("DecodeParms"),o=Nd(n),i=Ed(r,o.length),s=(c=e.rawBytes)!=null?c:e.data;if(!s)throw new Error("Stream has no byte payload");if(o.length===0)return s;let a=s;for(let d=0;d<o.length;d++)a=this.applyFilterSync(o[d],a,(l=i[d])!=null?l:null);return a}static createLazyDecoder(e,n){return async()=>{let r={type:"stream",dict:e,rawBytes:n,decode:async()=>n};return this.decodeStreamSync(r)}}static applyFilterSync(e,n,r){switch(e){case"FlateDecode":case"Fl":return Bd(n,r);case"ASCII85Decode":case"A85":return Od(n);case"ASCIIHexDecode":case"AHx":return Td(n);case"LZWDecode":case"LZW":return Ld(n,r);case"DCTDecode":case"DCT":return n;case"JPXDecode":return console.warn("[StreamDecoder] JPXDecode not yet supported; returning raw bytes"),n;case"RunLengthDecode":case"RL":return Id(n);case"CCITTFaxDecode":case"CCF":return console.warn("[StreamDecoder] CCITTFaxDecode not yet supported; returning raw bytes"),n;case"Crypt":return n;default:return console.warn(`[StreamDecoder] Unknown filter: ${e}; returning raw bytes`),n}}};var Ht=class{constructor(e){this.pos=0;this.bytes=e}skipWhitespace(){for(;this.pos<this.bytes.length;){let e=this.bytes[this.pos];if(e===0||e===9||e===10||e===12||e===13||e===32)this.pos++;else if(e===37)for(;this.pos<this.bytes.length&&this.bytes[this.pos]!==10&&this.bytes[this.pos]!==13;)this.pos++;else break}}peek(){return this.skipWhitespace(),this.pos<this.bytes.length?this.bytes[this.pos]:void 0}peekRaw(e=0){let n=this.pos+e;return n<this.bytes.length?this.bytes[n]:void 0}read(){return this.skipWhitespace(),this.pos<this.bytes.length?this.bytes[this.pos++]:void 0}readRaw(){return this.pos<this.bytes.length?this.bytes[this.pos++]:void 0}readWord(){this.skipWhitespace();let e=this.pos;for(;this.pos<this.bytes.length;){let n=this.bytes[this.pos];if(n===0||n===9||n===10||n===12||n===13||n===32||n===60||n===62||n===40||n===41||n===123||n===125||n===91||n===93||n===47||n===37)break;this.pos++}return new TextDecoder().decode(this.bytes.subarray(e,this.pos))}readUntil(e){let n=this.pos,r=new TextEncoder().encode(e),o=r.length;for(;this.pos<=this.bytes.length-o;){let i=!0;for(let s=0;s<o;s++)if(this.bytes[this.pos+s]!==r[s]){i=!1;break}if(i){let s=this.bytes.subarray(n,this.pos);return this.pos+=o,s}this.pos++}throw new Error(`Could not find sequence: ${e}`)}getRemainingBytes(){return this.bytes.subarray(this.pos)}getBytes(){return this.bytes}getPosition(){return this.pos}setPosition(e){this.pos=e}};function Ud(t){let e=t.peekRaw(),n=t.peekRaw(1);if(e===13&&n===10){t.readRaw(),t.readRaw();return}if(e===10||e===13){t.readRaw();return}console.warn(`[WARN] No newline after 'stream' keyword at tokenizer position ${t.getPosition()}`)}function _d(t){let e=t.getBytes(),n=t.getPosition(),r=[101,110,100,115,116,114,101,97,109];for(let o=n;o<=e.length-r.length;o++){let i=!0;for(let m=0;m<r.length;m++)if(e[o+m]!==r[m]){i=!1;break}if(!i)continue;let s=o>0?e[o-1]:10,a=o+r.length<e.length?e[o+r.length]:10;if(!(s===10||s===13||s===32||s===9)||!(a===10||a===13||a===32||a===9||a===62))continue;let d=o;return d>n&&e[d-1]===10&&(d-=1),d>n&&e[d-1]===13&&(d-=1),t.setPosition(o+r.length),e.subarray(n,d)}throw new Error("Could not find 'endstream' marker for stream object")}function ra(t){let e=t.readWord();return parseFloat(e)}function Xd(t){if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(t))throw new Error(`Invalid numeric token: ${t}`);let e=parseFloat(t);if(!Number.isFinite(e))throw new Error(`Invalid numeric value: ${t}`);return/^[+-]?\d+$/.test(t)?ni(e):ri(e)}function zd(t){t.skipWhitespace();let e=t.readWord(),n=Xd(e);if(!zr(n))return n;let r=t.getPosition();try{t.skipWhitespace();let o=t.readWord();if(!/^[+-]?\d+$/.test(o))return t.setPosition(r),n;if(t.skipWhitespace(),t.readWord()==="R")return oi(n.value,parseInt(o,10))}catch{return t.setPosition(r),n}return t.setPosition(r),n}function oa(t){let e=t.peek();if(e===40){t.read();let n=[],r=1;for(;r>0&&t.peekRaw()!==void 0;){let o=t.readRaw();if(o===40)r++;else if(o===41){if(r--,r===0)break;n.push(o)}else if(o===92){let i=t.peekRaw();if(i===void 0)break;if(i>=48&&i<=55){let s="";for(let a=0;a<3;a++){let c=t.peekRaw();if(c!==void 0&&c>=48&&c<=55)s+=String.fromCharCode(t.readRaw());else break}n.push(parseInt(s,8)&255);continue}t.readRaw(),i===110?n.push(10):i===114?n.push(13):i===116?n.push(9):i===98?n.push(8):i===102?n.push(12):i===40?n.push(40):i===41?n.push(41):i===92?n.push(92):i===10||(i===13?t.peekRaw()===10&&t.readRaw():n.push(i))}else n.push(o)}return Xr(new Uint8Array(n),"literal")}else if(e===60){t.read();let n=[];for(;t.peekRaw()!==62;){let o=t.readRaw();if(o===void 0)throw new Error("Unexpected EOF in hex string");if(o===0||o===9||o===10||o===12||o===13||o===32)continue;let i=Yd(o);i!==-1&&n.push(i)}t.readRaw(),n.length%2===1&&n.push(0);let r=new Uint8Array(n.length/2);for(let o=0,i=0;o<n.length;o+=2,i++)r[i]=n[o]<<4|n[o+1];return Xr(r,"hex")}throw new Error("Invalid string format")}function Yd(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1}function Wd(t){if(t.peek()!==47)throw new Error("Expected / for name");t.read();let n=t.readWord();return ei(n)}function Hd(t){if(t.peek()!==91)throw new Error("Expected [ for array");t.read();let n=[];for(;t.peek()!==93;)n.push(gt(t));return t.read(),{type:"array",items:n}}function Gd(t){if(t.peek()!==60)throw new Error("Expected < for dict");if(t.read(),t.peek()!==60)throw new Error("Expected << for dict");t.read();let n=new Map;for(;;){if(t.skipWhitespace(),t.peekRaw()===62&&t.peekRaw(1)===62){t.readRaw(),t.readRaw();break}let r=gt(t);if(!r||typeof r!="object"||r.type!=="name")throw new Error("Dictionary key must be a name");let o=r.value,i=gt(t);n.set(o,i)}return{type:"dict",entries:n}}function gt(t){let e=t.peek();if(e===void 0)throw new Error("Unexpected EOF while reading object");if(e===110){let n=t.readWord();if(n==="null")return ti();if(n==="true")return Xn(!0);if(n==="false")return Xn(!1);throw new Error("Unknown keyword: "+n)}if(e===116||e===102){let n=t.readWord();if(n==="true")return Xn(!0);if(n==="false")return Xn(!1)}if(e===45||e===43||e===46||e>=48&&e<=57)return zd(t);if(e===40)return oa(t);if(e===47)return Wd(t);if(e===91)return Hd(t);if(e===60){if(t.peekRaw(1)!==60)return oa(t);let r=Gd(t),o=t.getPosition();try{if(t.skipWhitespace(),t.readWord()==="stream"){Ud(t);let s,a=r.entries.get("Length"),c=K(a);if(typeof c=="number"){let l=t.getPosition();s=t.getRemainingBytes().subarray(0,c),t.setPosition(l+c),t.skipWhitespace();let d=t.readWord();d!=="endstream"&&console.warn(`[WARN] Expected 'endstream' but got '${d}' - stream may be malformed`)}else s=_d(t);return{type:"stream",dict:r,rawBytes:s,data:s,decode:ve.createLazyDecoder(r,s)}}else return t.setPosition(o),r}catch{return t.setPosition(o),r}}throw new Error(`Unknown object type at byte ${e}`)}function ia(t){let e=ra(t),n=ra(t);if(t.readWord()!=="obj")throw new Error("Expected obj keyword");let o=gt(t),i=t.readWord();if(i!=="endobj"){let s=t.getRemainingBytes(),a=s.subarray(0,Math.min(8192,s.length)),c=new TextDecoder("latin1").decode(a),l=c.search(/\bendobj\b/);if(l===-1){let d=c.replace(/[\r\n\t]+/g," ").slice(0,220);throw new Error(`Expected endobj keyword (got '${i||"<EOF>"}'). Nearby: "${d}"`)}t.setPosition(t.getPosition()+l+6),console.warn(`[ObjectReader] Recovered non-immediate endobj for ${Math.floor(e)} ${Math.floor(n)} obj (first token: '${i||"<EOF>"}')`)}return{objNum:Math.floor(e),genNum:Math.floor(n),object:o}}function Wr(t,e,n){let r=new TextDecoder("latin1");if(!Number.isFinite(e)||e<0||e>=t.length)throw new Error(`Invalid object offset ${e} (file size: ${t.length})`);let o=4096,i=8192,s=Math.max(0,e-o),a=Math.min(t.length,e+i),c=t.subarray(s,a),l=r.decode(c),d=/(\d+)\s+(\d+)\s+obj\b/g,m,h=[];for(;(m=d.exec(l))!==null;){let k=s+m.index,C=Math.abs(k-e),S=parseInt(m[1],10);h.push({absolutePos:k,matched:m[0],distance:C,objNum:S})}if(h.length===0){let k=Math.max(0,e-64),C=Math.min(t.length,e+128),S=r.decode(t.subarray(k,C)).replace(/[\r\n\t]+/g," ").slice(0,220);throw new Error(`Could not find object header near offset ${e} (searched ${s}-${a}). Snippet: "${S}"`)}if(n!==void 0&&!h.some(k=>k.objNum===n)){let k=r.decode(t),C=String(n),S=new RegExp(`(?<![0-9])${C}\\s+\\d+\\s+obj\\b`,"g"),F;for(;(F=S.exec(k))!==null;){let O=F.index;if(h.some(I=>I.absolutePos===O))continue;let N=Math.abs(O-e);h.push({absolutePos:O,matched:F[0].trim(),distance:N,objNum:n})}}h.sort((k,C)=>{let S=n!==void 0&&k.objNum===n?0:1,F=n!==void 0&&C.objNum===n?0:1;return S!==F?S-F:k.distance-C.distance});let f=Math.min(12,h.length),p=[];for(let k=0;k<f;k++){let C=h[k];try{let S=new Ht(t.subarray(C.absolutePos)),F=ia(S);if(n!==void 0&&F.objNum!==n)throw new Error(`Parsed object ${F.objNum} but expected ${n}`);return k>0&&console.warn(`[ObjectReader] Offset ${e} resolved via fallback candidate #${k+1}: ${C.matched} at ${C.absolutePos}`),{...F,objectOffset:C.absolutePos}}catch(S){let F=S instanceof Error?S.message:String(S);p.push(`#${k+1} ${C.matched} @${C.absolutePos}: ${F}`)}}let w=Math.max(0,e-64),b=Math.min(t.length,e+256),y=r.decode(t.subarray(w,b)).replace(/[\r\n\t]+/g," ").slice(0,280);throw new Error(`Failed to read indirect object near offset ${e}. Tried ${f}/${h.length} candidates. Errors: ${p.join(" || ")}. Snippet: "${y}"`)}function si(t){let e=K(t.entries.get("XRefStm"));return e===null?null:Math.floor(e)}function Kd(t){return t===0||t===9||t===10||t===12||t===13||t===32}function Hr(t,e){let n=e;for(;n<t.length&&Kd(t[n]);)n++;return n}function sa(t,e){let n=e;for(;n<t.length&&t[n]!==10&&t[n]!==13;)n++;let r=new TextDecoder("latin1").decode(t.subarray(e,n));return n<t.length&&t[n]===13&&n++,n<t.length&&t[n]===10&&n++,{line:r,next:n}}function ci(t,e,n){e:for(let r=n;r<=t.length-e.length;r++){for(let o=0;o<e.length;o++)if(t[r+o]!==e[o])continue e;return r}return-1}function aa(t){return t===void 0?!0:t===0||t===9||t===10||t===12||t===13||t===32||t===60||t===62||t===40||t===41||t===91||t===93||t===123||t===125||t===47||t===37}function li(t,e,n){if(e<0||e+n.length>t.length)return!1;for(let i=0;i<n.length;i++)if(t[e+i]!==n[i])return!1;let r=e>0?t[e-1]:void 0,o=e+n.length<t.length?t[e+n.length]:void 0;return aa(r)&&aa(o)}function ua(t,e,n){let r=Math.max(0,n);for(;r<=t.length-e.length;){let o=ci(t,e,r);if(o===-1)return-1;if(li(t,o,e))return o;r=o+1}return-1}function Vd(t,e,n,r){let o=[],i=Math.max(0,n),s=Math.min(t.length-e.length,Math.max(i,r));for(;i<=s;){let a=ci(t,e,i);if(a===-1||a>s)break;li(t,a,e)&&o.push(a),i=a+1}return o}function ca(t,e,n,r){let o=Math.max(0,n-r),i=Math.min(t.length,n+r),s=Vd(t,e,o,i);return s.length===0?-1:(s.sort((a,c)=>Math.abs(a-n)-Math.abs(c-n)),s[0])}function qd(t,e,n,r){let o=Math.min(r,t.length);for(let i=Math.max(n,0);i<=o-e.length;i++){let s=!0;for(let a=0;a<e.length;a++)if(t[i+a]!==e[a]){s=!1;break}if(s){let a=i;for(let c=i+1;c<=o-e.length;c++){let l=!0;for(let d=0;d<e.length;d++)if(t[c+d]!==e[d]){l=!1;break}l&&(a=c)}return a}}return-1}function ai(t,e){let n=new Ht(t.subarray(e)),r=gt(n);if(!Z(r))throw new Error("Trailer object is not a dictionary");return r}function Dn(t){if(t===null)return"null";if(t===void 0)return"undefined";if(Array.isArray(t))return`Array(len=${t.length})`;if(typeof t=="number")return"number";if(typeof t!="object")return typeof t;let e=t;return typeof e.type=="string"?Array.isArray(e.items)?`PDFObject(type=${e.type}, items=${e.items.length})`:typeof e.value!="undefined"?`PDFObject(type=${e.type}, value=${String(e.value)})`:`PDFObject(type=${e.type})`:"object"}function Jd(t){return!t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null}function ha(t,e){console.debug("[XRefTable]",t,e!=null?e:{})}function la(t,e){console.warn("[XRefTable]",t,e!=null?e:{})}function da(t,e){if(!t)throw new Error(`/${e} missing`);if(he(t)){let o=[];for(let i of t.items){let s=K(i);if(s===null)throw new Error(`/${e} must contain only numbers`);o.push(Math.floor(s))}return o}if(Array.isArray(t))return t.map(o=>Math.floor(Number(o)||0));if(typeof t=="number")return[Math.floor(t)];let n=K(t);if(n!==null)return[Math.floor(n)];let r=t;if(Array.isArray(r.items))return r.items.map(o=>Math.floor(Number(o)||0));throw new Error(`/${e} must be an array, got ${Dn(t)}`)}function fa(t){let e=t.length,n=Math.min(1024*1024,e),r=new TextDecoder("latin1").decode(t.subarray(e-n,e)),o=r.lastIndexOf("startxref");if(o!==-1){let i=r.slice(o+9).match(/\d+/);if(i)return parseInt(i[0],10)}throw new Error("PDF missing startxref offset")}function ir(t,e){let n=new TextDecoder("latin1"),r=new Uint8Array([120,114,101,102]),o=e,i=ua(t,r,o);if(i===-1||i-e>32){let a=n.decode(t.subarray(e,Math.min(e+20,t.length)));throw new Error(`Expected 'xref' keyword near offset ${e}, found: ${a}`)}for(o=i+r.length;o<t.length&&(t[o]===13||t[o]===10);)o++;let s=new Map;for(;o<t.length;){for(;o<t.length&&(t[o]===13||t[o]===10);)o++;let a=o;for(;o<t.length&&t[o]!==13&&t[o]!==10;)o++;let c=n.decode(t.subarray(a,o)).trim();for(;o<t.length&&(t[o]===13||t[o]===10);)o++;if(!c)continue;if(c==="trailer"||c.startsWith("trailer")||c==="railer"||c.startsWith("railer")){let h=c.startsWith("railer")?Math.max(0,a-1):a,f=Hr(t,h+7),p=ai(t,f),w=p.entries.get("Prev"),b=K(w),y=b===null?null:Math.floor(b),k=si(p);if(s.size===0&&y===null&&k===null)throw new Error("No valid xref entries found");return{entries:s,trailer:p,prevXRefOffset:y,offset:e,xrefStmOffset:k}}if(c==="%%EOF"||c.startsWith("startxref")){let h=new Uint8Array([116,114,97,105,108,101,114]),f=qd(t,h,e,a);if(f!==-1){let p=Hr(t,f+7),w=ai(t,p),b=w.entries.get("Prev"),y=K(b),k=y===null?null:Math.floor(y),C=si(w);if(s.size===0&&k===null&&C===null)throw new Error("No valid xref entries found");return{entries:s,trailer:w,prevXRefOffset:k,offset:e,xrefStmOffset:C}}throw new Error("Reached EOF before trailer in traditional xref section")}let l=c.match(/^(\d+)\s+(\d+)$/);if(!l){if(/^\d+$/.test(c)){let h=new Uint8Array([116,114,97,105,108,101,114]),f=ci(t,h,Math.max(0,a-1));if(f!==-1&&f-a<=256){let p=Hr(t,f+7),w=ai(t,p),b=w.entries.get("Prev"),y=K(b),k=y===null?null:Math.floor(y),C=si(w);if(s.size===0&&k===null&&C===null)throw new Error("No valid xref entries found");return{entries:s,trailer:w,prevXRefOffset:k,offset:e,xrefStmOffset:C}}continue}throw new Error(`Invalid xref subsection header: ${c}`)}let d=parseInt(l[1],10),m=parseInt(l[2],10);for(let h=0;h<m;h++){if(o+20>t.length)throw new Error(`Truncated xref at entry ${d+h}`);let f=o,p=n.decode(t.subarray(o,o+20));o+=20;let w=p.substring(0,10),b=p.substring(11,16),y=p[17],k=0,C=0,S="f";if(/^\d{10}$/.test(w)&&/^\d{5}$/.test(b)&&(y==="n"||y==="f"))k=parseInt(w,10),C=parseInt(b,10),S=y;else{o=f;let F=sa(t,o);o=F.next;let O=0;for(;O<3&&F.line.trim()==="";)F=sa(t,o),o=F.next,O++;let N=F.line.match(/^\s*(\d{10})\s+(\d{5})\s+([nf])\b/);if(!N)throw new Error(`Malformed fixed-width xref entry: ${p}`);k=parseInt(N[1],10),C=parseInt(N[2],10),S=N[3]}s.set(d+h,{type:"uncompressed",offset:k,genNum:C,inUse:S==="n"})}}throw new Error("trailer keyword not found after xref entries")}function Zd(t,e){let{stream:n,resolvedObj:r}=Qd(t,e),o=n.dict,i=Jd(o.entries.get("Type"));i!=="XRef"&&la("Resolved stream is not /Type /XRef",{offset:e,resolvedObj:r,type:i}),ha("Parsing xref stream",{offset:e,resolvedObj:r,type:i,wShape:Dn(o.entries.get("W")),indexShape:Dn(o.entries.get("Index")),sizeShape:Dn(o.entries.get("Size"))});let s,a;{let F=o.entries.get("W"),O=o.entries.get("Size"),N=K(O),I=o.entries.get("Index");try{if(s=da(F,"W"),s.length!==3)throw new Error("/W must contain three integers");if(N===null)throw new Error("XRef stream missing /Size");if(a=I?da(I,"Index"):[0,Math.floor(N)],a.length%2!==0)throw new Error("/Index must have even number of elements")}catch(R){let H=R instanceof Error?R.message:String(R);throw la("Failed parsing /W or /Index in xref stream",{offset:e,resolvedObj:r,error:H,wShape:Dn(F),indexShape:Dn(I),sizeShape:Dn(O)}),R}}let c=new Map,[l,d,m]=s,h=l+d+m,f=ve.decodeStreamSync(n),p=0;for(let F=0;F<a.length;F+=2){let O=a[F],N=a[F+1];for(let I=0;I<N;I++){if(p+h>f.length)throw new Error("XRef stream data is shorter than expected from /W and /Index");let R=se=>{let fe=0;for(let pe=0;pe<se;pe++)fe=fe<<8|f[p++];return fe},H=l===0?1:R(l),te=R(d),T=R(m),ce=O+I;H===0?c.set(ce,{type:"uncompressed",offset:0,genNum:T,inUse:!1}):H===1?c.set(ce,{type:"uncompressed",offset:te,genNum:T,inUse:!0}):H===2&&c.set(ce,{type:"compressed",streamNum:te,indexNum:T,genNum:0,inUse:!0})}}let w=o.entries.get("Prev"),b=K(w),y=b===null?null:Math.floor(b),k=new Map(o.entries),C=new Set(["W","Index","Filter","DecodeParms","Length","Columns","Predictor","Type","DL"]);for(let F of C)k.delete(F);return{entries:c,trailer:{type:"dict",entries:k},prevXRefOffset:y,offset:e}}function Qd(t,e){let n=[0,-64,64,-256,256,-1024,1024,-4096,4096,-8192,8192],r=new Set,o=[],i=[];for(let s of n){let a=e+s;if(!(a<0||a>=t.length))try{let c=Wr(t,a),l=`${c.objNum}.${c.genNum}`;if(r.has(l))continue;if(r.add(l),!me(c.object)){o.push(`offset ${a}: ${l} is not a stream`);continue}let d=c.object,m=d.dict.entries.has("W"),h=d.dict.entries.has("Size"),f=d.dict.entries.get("Type"),p=f&&typeof f=="object"&&"type"in f&&f.type==="name"?f.value:null,w=p==="XRef";if(m&&h)return ha("Resolved xref stream candidate",{requestedOffset:e,probeOffset:a,object:`${c.objNum} ${c.genNum} obj`,type:p}),{stream:d,resolvedObj:`${c.objNum} ${c.genNum} obj`};i.push(`offset ${a}: ${l} stream type=${p!=null?p:"unknown"} hasW=${m} hasSize=${h} isTypeXRef=${w}`)}catch(c){let l=c instanceof Error?c.message:String(c);o.push(`offset ${a}: ${l}`)}}throw new Error(`Could not resolve xref stream with /W and /Size near startxref ${e}. Non-xref streams: ${i.join(" || ")||"none"}. Failures: ${o.join(" || ")||"none"}`)}function ma(t,e){let n=new Uint8Array([120,114,101,102]),r=Hr(t,e);if(li(t,r,n))return ir(t,r);let o=ua(t,n,Math.max(0,e));if(o!==-1&&o-e<=2048)return ir(t,o);let i=ca(t,n,e,32768);if(i!==-1)return ir(t,i);if(new TextDecoder("latin1").decode(t.subarray(e,Math.min(e+64,t.length))).trimStart().startsWith("xref"))return ir(t,e);try{return Zd(t,e)}catch(a){let c=ca(t,n,e,131072);if(c!==-1)return ir(t,c);throw a}}function di(t){let e=[],n=new Set,r=[fa(t)];for(;r.length>0;){let o=r.shift();if(o===null||n.has(o))continue;n.add(o);let i=ma(t,o);e.push(i),i.xrefStmOffset!=null&&r.push(i.xrefStmOffset),i.prevXRefOffset!=null&&r.push(i.prevXRefOffset)}return e}var eu=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);function ui(t){let e=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],n=[3614090360,3905402710,606105819,3250441966,4118548399,1200080426,2821735955,4249261313,1770035416,2336552879,4294925233,2304563134,1804603682,4254626195,2792965006,1236535329,4129170786,3225465664,643717713,3921069994,3593408605,38016083,3634488961,3889429448,568446438,3275163606,4107603335,1163531501,2850285829,4243563512,1735328473,2368359562,4294588738,2272392833,1839030562,4259657740,2763975236,1272893353,4139469664,3200236656,681279174,3936430074,3572445317,76029189,3654602809,3873151461,530742520,3299628645,4096336452,1126891415,2878612391,4237533241,1700485571,2399980690,4293915773,2240044497,1873313359,4264355552,2734768916,1309151649,4149444226,3174756917,718787259,3951481745],r=1732584193,o=4023233417,i=2562383102,s=271733878,a=t.length,c=(56-(a+1)%64+64)%64,l=new Uint8Array(a+1+c+8);l.set(t),l[a]=128;let d=a*8;l[l.length-8]=d&255,l[l.length-7]=d>>>8&255,l[l.length-6]=d>>>16&255,l[l.length-5]=d>>>24&255;let m=new DataView(l.buffer);for(let p=0;p<l.length;p+=64){let w=r,b=o,y=i,k=s,C=new Uint32Array(16);for(let S=0;S<16;S++)C[S]=m.getUint32(p+S*4,!0);for(let S=0;S<64;S++){let F,O;S<16?(F=b&y|~b&k,O=S):S<32?(F=k&b|~k&y,O=(5*S+1)%16):S<48?(F=b^y^k,O=(3*S+5)%16):(F=y^(b|~k),O=7*S%16);let N=k;k=y,y=b;let I=w+F+n[S]+C[O]|0;b=b+(I<<e[S]|I>>>32-e[S])|0,w=N}r=r+w|0,o=o+b|0,i=i+y|0,s=s+k|0}let h=new Uint8Array(16),f=new DataView(h.buffer);return f.setUint32(0,r,!0),f.setUint32(4,o,!0),f.setUint32(8,i,!0),f.setUint32(12,s,!0),h}function tu(t,e){let n=new Uint8Array(256);for(let s=0;s<256;s++)n[s]=s;let r=0;for(let s=0;s<256;s++){r=(r+n[s]+t[s%t.length])%256;let a=n[s];n[s]=n[r],n[r]=a}let o=new Uint8Array(e.length),i=0;r=0;for(let s=0;s<e.length;s++){i=(i+1)%256,r=(r+n[i])%256;let a=n[i];n[i]=n[r],n[r]=a,o[s]=e[s]^n[(n[i]+n[r])%256]}return o}var an=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),nu=new Uint8Array([82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125]);function ru(t){let e=t.length/4,n=e+6,r=new Uint32Array(4*(n+1));for(let i=0;i<e;i++)r[i]=t[4*i]<<24|t[4*i+1]<<16|t[4*i+2]<<8|t[4*i+3];let o=[0,1,2,4,8,16,32,64,128,27,54];for(let i=e;i<4*(n+1);i++){let s=r[i-1];if(i%e===0){let a=s>>>24&255,c=s>>>16&255,l=s>>>8&255,d=s&255;s=an[c]<<24|an[l]<<16|an[d]<<8|an[a],s^=o[i/e]<<24}else if(e>6&&i%e===4){let a=s>>>24&255,c=s>>>16&255,l=s>>>8&255,d=s&255;s=an[a]<<24|an[c]<<16|an[l]<<8|an[d]}r[i]=r[i-e]^s}return r}function pa(t){for(let e=0;e<16;e++)t[e]=nu[t[e]]}function ga(t){let e;e=t[13],t[13]=t[9],t[9]=t[5],t[5]=t[1],t[1]=e,e=t[2],t[2]=t[10],t[10]=e,e=t[6],t[6]=t[14],t[14]=e,e=t[3],t[3]=t[7],t[7]=t[11],t[11]=t[15],t[15]=e}var ou=t=>(t<<1^(t>>>7&1)*27)&255;function nt(t,e){let n=0,r=t;for(let o=0;o<8;o++)e>>>o&1&&(n^=r),r=ou(r);return n}function iu(t){for(let e=0;e<4;e++){let n=e*4,r=t[n],o=t[n+1],i=t[n+2],s=t[n+3];t[n]=nt(r,14)^nt(o,11)^nt(i,13)^nt(s,9),t[n+1]=nt(r,9)^nt(o,14)^nt(i,11)^nt(s,13),t[n+2]=nt(r,13)^nt(o,9)^nt(i,14)^nt(s,11),t[n+3]=nt(r,11)^nt(o,13)^nt(i,9)^nt(s,14)}}function hi(t,e,n){for(let r=0;r<4;r++){let o=e[n*4+r];t[r*4]^=o>>>24&255,t[r*4+1]^=o>>>16&255,t[r*4+2]^=o>>>8&255,t[r*4+3]^=o&255}}function su(t,e,n){let r=new Uint8Array(16);r.set(t),hi(r,e,n);for(let o=n-1;o>=1;o--)ga(r),pa(r),hi(r,e,o),iu(r);return ga(r),pa(r),hi(r,e,0),r}function au(t,e){if(e.length<16)return e;let n=ru(t),r=t.length/4+6,o=e.subarray(0,16),i=e.subarray(16),s=i.length/16,a=new Uint8Array(i.length),c=o;for(let d=0;d<s;d++){let m=d*16,h=i.subarray(m,m+16),f=su(h,n,r);for(let p=0;p<16;p++)a[m+p]=f[p]^c[p];c=h}let l=a[a.length-1];if(l>0&&l<=16){let d=!0;for(let m=a.length-l;m<a.length;m++)if(a[m]!==l){d=!1;break}if(d)return a.subarray(0,a.length-l)}return a}var Gr=class{constructor(e,n){this.fileKey=new Uint8Array(0);this.v=0;this.r=0;this.isAes=!1;this.parseEncryptDict(e,n)}parseEncryptDict(e,n){var k,C,S,F;let r=e.entries.get("V"),o=e.entries.get("R"),i=e.entries.get("Length"),s=e.entries.get("O"),a=e.entries.get("U"),c=e.entries.get("P"),l=e.entries.get("EncryptMetadata");this.v=(k=K(r))!=null?k:0,this.r=(C=K(o))!=null?C:0;let m=((S=K(i))!=null?S:40)/8,h=s&&"value"in s&&s.value instanceof Uint8Array?s.value:new Uint8Array(0),f=a&&"value"in a&&a.value instanceof Uint8Array?a.value:new Uint8Array(0),p=(F=K(c))!=null?F:0,w=l&&"value"in l?l.value:!0,b=e.entries.get("CF"),y=e.entries.get("StmF");if(y&&"value"in y&&y.value==="AESV2")this.isAes=!0;else if(b&&Z(b)){let O=b.entries.get("StdCF");if(O&&Z(O)){let N=O.entries.get("CFM");N&&"value"in N&&N.value==="AESV2"&&(this.isAes=!0)}}(this.v===5||this.r===5||this.r===6)&&(this.isAes=!0),this.fileKey=this.deriveFileKey(new Uint8Array(0),m,h,f,p,n,w)}deriveFileKey(e,n,r,o,i,s,a=!0){let c=new Uint8Array(32);c.set(e.subarray(0,Math.min(32,e.length))),e.length<32&&c.set(eu.subarray(0,32-e.length),e.length);let l=[];l.push(...c),l.push(...r),l.push(i&255),l.push(i>>>8&255),l.push(i>>>16&255),l.push(i>>>24&255),s&&s.length>0&&l.push(...s),this.r>=3&&!a&&l.push(255,255,255,255);let d=ui(new Uint8Array(l));if(this.r>=3){let h=d.subarray(0,n);for(let f=0;f<50;f++)h=ui(h).subarray(0,n);return h}return d.subarray(0,n)}deriveObjectKey(e,n){let r=new Uint8Array(5);r[0]=e&255,r[1]=e>>>8&255,r[2]=e>>>16&255,r[3]=n&255,r[4]=n>>>8&255;let o=new Uint8Array(this.fileKey.length+r.length+(this.isAes?4:0));o.set(this.fileKey),o.set(r,this.fileKey.length),this.isAes&&o.set([115,65,108,84],this.fileKey.length+r.length);let i=ui(o),s=Math.min(16,this.fileKey.length+5);return i.subarray(0,s)}decrypt(e,n,r){return this.isAes?au(this.deriveObjectKey(n,r),e):tu(this.deriveObjectKey(n,r),e)}};var Gt=class{constructor(e){this.document=null;this.objectStreamCache=new Map;this.encryptRef=null;this.decryptionHandler=null;this.bytes=e}parse(){if(this.document)return this.document;try{let e=this.extractVersion(),n=this.parseXRefTables();if(n.length===0)throw new Error("No valid xref tables found in PDF");let r=new Map;for(let a=n.length-1;a>=0;a--)for(let[c,l]of n[a].entries)r.set(c,l);let o=n[0].trailer,i=this.extractRootRef(o);this.document={rawBytes:this.bytes,xrefTables:new Map([[0,r]]),objectCache:new Map,rootRef:i,trailer:o,version:e};let s=o.entries.get("Encrypt");if(s){let a=null;if(Be(s)){this.encryptRef=s;let c=this.loadObject(s);Z(c)&&(a=c)}else Z(s)&&(a=s);if(a){let c,l=o.entries.get("ID");if(l&&he(l)&&l.items.length>0){let d=l.items[0];ii(d)&&(c=d.value)}this.decryptionHandler=new Gr(a,c)}}return this.document}catch(e){throw console.error("[ERROR] Parse failed:",e),e}}extractVersion(){let r=new TextDecoder().decode(this.bytes.subarray(0,20)).match(/%PDF-(\d+\.\d+)/);if(!r)throw new Error("Invalid PDF header - no %PDF-X.Y found");return r[1]}parseXRefTables(){return di(this.bytes)}extractRootRef(e){let n=e.entries.get("Root");if(!n)throw console.error("[ERROR] Trailer has no Root entry. Trailer entries:",Array.from(e.entries.keys())),new Error("Trailer missing /Root reference");if(typeof n!="object"||n.type!=="ref")throw console.error("[ERROR] Root is not a reference object:",n),new Error("Trailer /Root is not a valid reference");return n}loadObject(e){if(!this.document)throw new Error("Parse PDF first");let n=`${e.objNum}.${e.genNum}`;if(this.document.objectCache.has(n))return this.document.objectCache.get(n);let r=this.document.xrefTables.get(0);if(!r)throw new Error("No xref table found");let o=r.get(e.objNum);if(!o)throw new Error(`Object ${e.objNum} not found in xref`);if(o.type==="uncompressed"){if(!o.inUse)throw new Error(`Object ${e.objNum} is marked free in xref`);if(o.offset===0){let i={type:"dict",entries:new Map};throw this.document.objectCache.set(n,i),new Error(`Object ${e.objNum} has ghost xref entry (offset 0)`)}try{let{object:i,objectOffset:s}=Wr(this.bytes,o.offset,e.objNum),a=me(i)?this.repairStreamBytesFromLengthRef(i,s):i,c=this.decryptObject(a,e.objNum,e.genNum);return this.document.objectCache.set(n,c),c}catch(i){console.warn(`[PDFParser] Failed to load object ${e.objNum}: ${i}`);let s={type:"dict",entries:new Map};throw this.document.objectCache.set(n,s),i}}else{if(!o.inUse)throw new Error(`Object ${e.objNum} is marked free in compressed xref entry`);let i=o.streamNum;if(!this.objectStreamCache.has(i)){let a=this.loadObjectStream(i,r);this.objectStreamCache.set(i,a)}let s=this.document.objectCache.get(n);if(!s)throw new Error(`Object ${e.objNum} not found in object stream ${i}`);return s}}loadObjectStream(e,n){var b,y;let r=n.get(e);if(!r||r.type!=="uncompressed"||!r.inUse)throw new Error(`Object stream ${e} not found or not in-use/uncompressed`);let o={type:"ref",objNum:e,genNum:0},i=this.loadObject(o);if(!me(i))throw new Error(`Object ${e} is not a stream`);let s=i.dict.entries.get("Type");if(!s||s.type!=="name"||s.value!=="ObjStm")throw new Error(`Object ${e} is not an /ObjStm`);let a=i.dict.entries.get("N"),c=i.dict.entries.get("First");if(!a||!Yr(a)||!c||!Yr(c))throw new Error(`Object stream ${e} missing numeric /N or /First`);let l=Math.floor(a.value),d=Math.floor(c.value);if(l<0||d<0)throw new Error(`Object stream ${e} has invalid /N or /First values`);let m=i,h;try{h=ve.decodeStreamSync(m)}catch(k){let C=m.dict.entries.get("Filter"),S=m.dict.entries.get("Length"),F=(y=(b=m.rawBytes)!=null?b:m.data)!=null?y:new Uint8Array(0),O=Array.from(F.subarray(0,8)).map(H=>H.toString(16).padStart(2,"0")).join(" "),N=Math.max(0,F.length-8),I=Array.from(F.subarray(N)).map(H=>H.toString(16).padStart(2,"0")).join(" "),R=k instanceof Error?k.message:String(k);throw new Error(`Object stream ${e} decode failed: ${R}; Filter=${JSON.stringify(C)} Length=${JSON.stringify(S)} rawLen=${F.length} first8=[${O}] last8=[${I}]`)}if(d>h.length)throw new Error(`Object stream ${e} /First (${d}) exceeds decoded length (${h.length})`);let p=new TextDecoder("latin1").decode(h.subarray(0,d)).match(/\d+/g)||[];if(p.length<l*2)throw new Error(`Object stream ${e} header has ${p.length} numbers, expected at least ${l*2}`);let w=new Map;for(let k=0;k<l;k++){let C=parseInt(p[k*2],10),S=parseInt(p[k*2+1],10),F=d+S;if(!(!Number.isFinite(C)||!Number.isFinite(S)||S<0||F>h.length))try{let O=new Ht(h.subarray(F)),N=gt(O);w.set(C,N),this.document.objectCache.set(`${C}.0`,N)}catch(O){console.warn(`[WARN] Failed to parse object ${C} from object stream ${e}:`,O)}}return w}repairStreamBytesFromLengthRef(e,n){var l,d;let r=e.dict.entries.get("Length");if(!r||!Be(r))return e;let o=null;try{let m=this.loadObject(r);o=K(m)}catch{return e}if(o===null)return e;let i=Math.max(0,Math.floor(o)),s=this.findStreamDataStart(n);if(s<0||s+i>this.bytes.length)return e;let a=(l=e.rawBytes)!=null?l:e.data;if(a&&a.length===i)return e;let c=this.bytes.subarray(s,s+i);return console.warn(`[PDFParser] Repaired stream bytes via indirect /Length at offset ${n}: resolved length=${i}, previous length=${(d=a==null?void 0:a.length)!=null?d:0}`),{type:"stream",dict:e.dict,rawBytes:c,data:c,decode:ve.createLazyDecoder(e.dict,c)}}findStreamDataStart(e){let n=[115,116,114,101,97,109],r=Math.min(this.bytes.length-n.length,e+1024*1024);for(let o=Math.max(0,e);o<=r;o++){let i=!0;for(let m=0;m<n.length;m++)if(this.bytes[o+m]!==n[m]){i=!1;break}if(!i)continue;let s=o>0?this.bytes[o-1]:32,a=this.bytes[o+n.length];if(!(s===10||s===13||s===32||s===9||s===62)||!(a===10||a===13||a===32||a===9))continue;let d=o+n.length;return this.bytes[d]===13&&this.bytes[d+1]===10?d+=2:(this.bytes[d]===10||this.bytes[d]===13)&&(d+=1),d}return-1}decryptObject(e,n,r){return!this.decryptionHandler||this.encryptRef&&n===this.encryptRef.objNum?e:this.decryptObjectRecursive(e,n,r)}decryptObjectRecursive(e,n,r){var o,i;if(!this.decryptionHandler)return e;if(e.type==="string"){let s=this.decryptionHandler.decrypt(e.value,n,r);return{...e,value:s}}if(e.type==="array")return{...e,items:e.items.map(s=>this.decryptObjectRecursive(s,n,r))};if(e.type==="dict"){let s=new Map;for(let[a,c]of e.entries)s.set(a,this.decryptObjectRecursive(c,n,r));return{...e,entries:s}}if(e.type==="stream"){let s=(i=(o=e.rawBytes)!=null?o:e.data)!=null?i:new Uint8Array(0),a=s.length>0?this.decryptionHandler.decrypt(s,n,r):s,c=this.decryptObjectRecursive(e.dict,n,r);return{type:"stream",dict:c,rawBytes:a,data:a,decode:ve.createLazyDecoder(c,a)}}return e}};function sr(t){if(!t)return[];if(Be(t))return[t];if(he(t)){let e=[];for(let n of t.items)e.push(...sr(n));return e}return[]}function cu(t){if(t.length===0)return new Uint8Array(0);let e=Math.max(0,t.length-1),n=t.reduce((i,s)=>i+s.length,0)+e,r=new Uint8Array(n),o=0;for(let i=0;i<t.length;i++)r.set(t[i],o),o+=t[i].length,i<t.length-1&&(r[o]=32,o+=1);return r}async function fi(t,e){let n=sr(t);if(n.length===0)return{combinedBytes:new Uint8Array(0),streamCount:0,streamByteLengths:[]};let r=[];for(let o of n){let i=await Promise.resolve(e(o));if(!me(i)){console.warn(`[WARN] Contents ref ${o.objNum} ${o.genNum} R is not a stream, skipping`);continue}try{let s=i.decode?await i.decode():await ve.decodeStream(i);r.push(s)}catch(s){throw console.error(`[ContentStreamLoader] Failed to decode stream ${o.objNum} ${o.genNum} R:`,s),s}}return{combinedBytes:cu(r),streamCount:r.length,streamByteLengths:r.map(o=>o.length)}}function Vt(t){return zn(t).commands}function zn(t){let e=new Ht(t),n=[],r=[],o=[],i=-1;for(;e.skipWhitespace(),!(e.getPosition()>=t.length);){let s=e.getPosition(),a=t[s];if(ya(a)){let c=e.readWord();if(!c)break;if(c==="BI"){let d=du(e,t);d?(n.push(d.command),r.push({start:s,end:d.end})):(n.push({op:"unknown",keyword:"BI",operands:[]}),r.push({start:s,end:e.getPosition()})),o.length=0,i=-1;continue}let l=uu(c,o);l&&(n.push(l),r.push({start:i>=0?i:s,end:e.getPosition()})),o.length=0,i=-1}else{i<0&&(i=s);try{let c=gt(e);o.push(c)}catch{e.setPosition(s+1)}}}return{commands:n,ranges:r}}function ya(t){return t>=65&&t<=90||t>=97&&t<=122||t===39||t===34}var Kr=t=>t===32||t===10||t===13||t===9||t===12||t===0,xa=t=>t===47||t===60||t===62||t===91||t===93||t===40||t===41||t===37||t===123||t===125,lu=t=>{var r,o;let e=(r=t.entries.get("IM"))!=null?r:t.entries.get("ImageMask");if(e&&"type"in e&&e.type==="boolean"&&e.value)return 1;let n=(o=t.entries.get("CS"))!=null?o:t.entries.get("ColorSpace");if(!n||!("type"in n)||n.type!=="name")return 1;switch(n.value){case"RGB":case"DeviceRGB":case"CalRGB":return 3;case"CMYK":case"DeviceCMYK":return 4;default:return 1}};function du(t,e){var n,r,o,i,s;try{let a=new Map;for(;;){t.skipWhitespace();let y=t.getPosition();if(y>=e.length)return null;let k=e[y];if(k===47){let C=gt(t);if(!C||!("type"in C)||C.type!=="name")return null;t.skipWhitespace(),a.set(C.value,gt(t))}else if(ya(k)){if(t.readWord()==="ID")break;return null}else return null}let c={type:"dict",entries:a},l=t.getPosition();Kr(e[l])&&(l+=e[l]===13&&e[l+1]===10?2:1);let d=(n=a.get("L"))!=null?n:a.get("Length"),m=K(d),h=a.has("F")||a.has("Filter"),f=-1;if(m!==null&&m>=0&&l+m<=e.length)f=l+m;else if(!h){let y=K((r=a.get("W"))!=null?r:a.get("Width")),k=K((o=a.get("H"))!=null?o:a.get("Height")),C=(s=K((i=a.get("BPC"))!=null?i:a.get("BitsPerComponent")))!=null?s:8;if(y!==null&&k!==null&&y>0&&k>0){let S=Math.ceil(y*C*lu(c)/8)*k;l+S<=e.length&&(f=l+S)}}if(f<0){for(let y=l;y+1<e.length;y++){if(e[y]!==69||e[y+1]!==73||y>l&&!Kr(e[y-1]))continue;let k=e[y+2];if(!(k!==void 0&&!Kr(k)&&!xa(k))){f=Math.max(l,y-1);break}}if(f<0)return null}let p=new Uint8Array(e.subarray(l,f));t.setPosition(f),t.skipWhitespace();let w=t.getPosition();if(e[w]!==69||e[w+1]!==73)return null;let b=e[w+2];return b!==void 0&&!Kr(b)&&!xa(b)?null:(t.setPosition(w+2),{command:{op:"inline_image",params:c,data:p},end:w+2})}catch{return null}}function uu(t,e){switch(t){case"q":return{op:"save_state"};case"Q":return{op:"restore_state"};case"cm":return{op:"set_ctm",matrix:ba(e)};case"w":return{op:"set_line_width",width:re(e,0)};case"J":return{op:"set_line_cap",cap:Math.floor(re(e,0))};case"j":return{op:"set_line_join",join:Math.floor(re(e,0))};case"M":return{op:"set_miter_limit",limit:re(e,0)};case"d":return{op:"set_dash",array:hu(e,0),phase:re(e,1)};case"ri":return{op:"set_rendering_intent",intent:Kt(e,0)};case"gs":return{op:"set_graphics_state",name:Kt(e,0)};case"rg":return{op:"set_fill_color_rgb",r:re(e,0),g:re(e,1),b:re(e,2)};case"RG":return{op:"set_stroke_color_rgb",r:re(e,0),g:re(e,1),b:re(e,2)};case"g":return{op:"set_fill_gray",gray:re(e,0)};case"G":return{op:"set_stroke_gray",gray:re(e,0)};case"k":return{op:"set_fill_cmyk",c:re(e,0),m:re(e,1),y:re(e,2),k:re(e,3)};case"K":return{op:"set_stroke_cmyk",c:re(e,0),m:re(e,1),y:re(e,2),k:re(e,3)};case"cs":return{op:"set_fill_color_space",name:Kt(e,0)};case"CS":return{op:"set_stroke_color_space",name:Kt(e,0)};case"sc":case"scn":{let n=e[e.length-1],r=n&&typeof n=="object"&&"type"in n&&n.type==="name"?n.value:void 0;return{op:"set_fill_color",values:(r?e.slice(0,-1):e).map(Vr),patternName:r}}case"SC":case"SCN":{let n=e[e.length-1],r=n&&typeof n=="object"&&"type"in n&&n.type==="name"?n.value:void 0;return{op:"set_stroke_color",values:(r?e.slice(0,-1):e).map(Vr),patternName:r}}case"m":return{op:"move_to",x:re(e,0),y:re(e,1)};case"l":return{op:"line_to",x:re(e,0),y:re(e,1)};case"c":return{op:"curve_to",x1:re(e,0),y1:re(e,1),x2:re(e,2),y2:re(e,3),x3:re(e,4),y3:re(e,5)};case"v":return{op:"curve_to_v",x2:re(e,0),y2:re(e,1),x3:re(e,2),y3:re(e,3)};case"y":return{op:"curve_to",x1:re(e,0),y1:re(e,1),x2:re(e,2),y2:re(e,3),x3:re(e,2),y3:re(e,3)};case"re":return{op:"rect",x:re(e,0),y:re(e,1),w:re(e,2),h:re(e,3)};case"h":return{op:"close_path"};case"S":return{op:"stroke"};case"s":return{op:"close_stroke"};case"f":case"F":return{op:"fill"};case"f*":return{op:"fill_even_odd"};case"B":return{op:"fill_stroke"};case"B*":return{op:"fill_stroke_even_odd"};case"b":return{op:"close_fill_stroke"};case"b*":return{op:"close_fill_stroke_even_odd"};case"n":return{op:"end_path"};case"W":return{op:"clip"};case"W*":return{op:"clip_even_odd"};case"BT":return{op:"begin_text"};case"ET":return{op:"end_text"};case"Tf":return{op:"set_font",name:Kt(e,0),size:re(e,1)};case"Td":return{op:"move_text",tx:re(e,0),ty:re(e,1)};case"TD":return{op:"move_text_set_leading",tx:re(e,0),ty:re(e,1)};case"Tm":return{op:"set_text_matrix",matrix:ba(e)};case"T*":return{op:"next_line"};case"Tc":return{op:"set_char_spacing",spacing:re(e,0)};case"Tw":return{op:"set_word_spacing",spacing:re(e,0)};case"Tz":return{op:"set_horiz_scale",scale:re(e,0)};case"TL":return{op:"set_leading",leading:re(e,0)};case"Tr":return{op:"set_text_render",mode:re(e,0)};case"Ts":return{op:"set_text_rise",rise:re(e,0)};case"Tj":return{op:"show_string",data:mi(e,0)};case"TJ":return{op:"show_strings",items:fu(e,0)};case"'":return{op:"next_line_show_string",data:mi(e,0)};case'"':return{op:"set_spacing_next_line_show_string",wordSpacing:re(e,0),charSpacing:re(e,1),data:mi(e,2)};case"d0":return{op:"type3_glyph_width",wx:re(e,0),wy:re(e,1)};case"d1":return{op:"type3_glyph_width",wx:re(e,0),wy:re(e,1)};case"sh":return{op:"shade",name:Kt(e,0)};case"Do":return{op:"xobject",name:Kt(e,0)};case"BMC":return{op:"begin_marked_content",tag:Kt(e,0)};case"BDC":{let n=e[1];return{op:"begin_marked_content",tag:Kt(e,0),properties:Z(n)?n:void 0}}case"EMC":return{op:"end_marked_content"};case"MP":case"DP":case"BX":case"EX":return null;default:return{op:"unknown",keyword:t,operands:[...e]}}}function re(t,e){return Vr(t[e])}function Vr(t){let e=K(t);return e===null?0:e}function Kt(t,e){let n=t[e];return n&&typeof n=="object"&&"type"in n&&n.type==="name"?n.value:""}function mi(t,e){let n=t[e];return n&&typeof n=="object"&&"type"in n&&n.type==="string"?n.value:new Uint8Array(0)}function hu(t,e){let n=t[e];return he(n)?n.items.map(Vr):[]}function fu(t,e){let n=t[e];return he(n)?n.items.map(r=>{let o=K(r);return o!==null?o:r&&typeof r=="object"&&"type"in r&&r.type==="string"?r.value:0}):[]}function ba(t){return[re(t,0),re(t,1),re(t,2),re(t,3),re(t,4),re(t,5)]}var qr=t=>t.map(e=>e.text).join(""),wa=(t,e={})=>{let n=Cn(t);return n.length>1?!0:n.length===0?!1:cn(n[0].style)!==cn(e)},mu=t=>t?`${t.r.toFixed(4)},${t.g.toFixed(4)},${t.b.toFixed(4)}`:"-",cn=t=>{var e;return[t.bold?1:0,t.italic?1:0,t.underline?1:0,t.strikethrough?1:0,(e=t.sizePt)!=null?e:"-",mu(t.color)].join("|")},Cn=t=>{let e=[];for(let n of t){if(n.text.length===0)continue;let r=e[e.length-1];r&&cn(r.style)===cn(n.style)?r.text+=n.text:e.push({text:n.text,style:{...n.style}})}return e},pu=[[/times|serif|georgia|cambria|garamond|minion/,"Times"],[/courier|mono|consol/,"Courier"]],va=(t,e={})=>{let n=(t!=null?t:"").replace(/^[A-Z]{6}\+/,"").replace(/[#,\s]/g,"").toLowerCase(),r="Helvetica";for(let[i,s]of pu)if(i.test(n)){r=s;break}let o=`${e.bold?"Bold":""}${e.italic?"Italic":""}`;return o?`${r}-${o}`:r};var Jr=(t,e,n,r=.5)=>{let o=t.y+t.height,i=t.y,s=t.x+t.width,a=f=>{let p=f.pdfX+f.width/2,w=f.pdfY+f.height/2;if(p>=t.x&&p<=s&&w>=i&&w<=o)return!0;let b=Math.max(0,Math.min(s,f.pdfX+f.width)-Math.max(t.x,f.pdfX)),y=Math.max(0,Math.min(o,f.pdfY+f.height)-Math.max(i,f.pdfY)),k=f.width*f.height;return k>0&&b*y/k>=.6},c=e.filter(f=>!a(f)),l={},d,m;for(let f of c)if(!(f.pdfX+f.width<=t.x||f.pdfX>=n)){if(f.pdfY>=o)d=d===void 0?f.pdfY:Math.min(d,f.pdfY);else if(f.pdfY+f.height<=i){let p=f.pdfY+f.height;m=m===void 0?p:Math.max(m,p)}}d!==void 0&&(l.maxY=Math.max(o,d-r)),m!==void 0&&(l.minY=Math.min(i,m+r));let h;for(let f of c)Math.min(o,f.pdfY+f.height)-Math.max(i,f.pdfY)<=0||f.pdfX<s||(h=h===void 0?f.pdfX:Math.min(h,f.pdfX));return h!==void 0&&(l.maxRight=Math.max(s,h-r)),l},Zr=(t,e)=>{let n=t.y+t.height,r=t.y,o=t.x+t.width;return e.maxY!==void 0&&e.maxY<n&&e.maxY>r&&(n=e.maxY),e.minY!==void 0&&e.minY>r&&e.minY<n&&(r=e.minY),e.maxRight!==void 0&&e.maxRight<o&&e.maxRight>t.x&&(o=e.maxRight),{x:t.x,y:r,width:Math.max(0,o-t.x),height:Math.max(0,n-r)}};var Yn=class{static getAllPages(e,n={}){let r=[],o=[];try{r.push("[TRAVERSE] Starting page tree traversal...");let i=e.rootRef;r.push(`[CATALOG] Root reference: ${i.objNum} ${i.genNum} R`);let s=`${i.objNum}.${i.genNum}`,a=e.objectCache.get(s);if((!a||!Z(a))&&n.objectLoader)try{a=n.objectLoader(i),r.push("[CATALOG] Loaded root catalog from file")}catch(p){let w=p instanceof Error?p.message:String(p);r.push(`[WARN] Failed to load root catalog: ${w}`)}if(!a||!Z(a))return r.push(`[ERROR] Root catalog not found in object cache at ${s}`),{pages:o,logs:r};let c=a;r.push("[CATALOG] \u2713 Found catalog in cache");let l=c.entries.get("Pages");if(!l)return r.push("[ERROR] /Pages reference not found in catalog"),{pages:o,logs:r};if(!Be(l))return r.push("[ERROR] /Pages is not an indirect reference"),{pages:o,logs:r};let d=l;r.push(`[PAGES] Pages tree root: ${d.objNum} ${d.genNum} R`);let m=`${d.objNum}.${d.genNum}`,h=e.objectCache.get(m);if((!h||!Z(h))&&n.objectLoader)try{h=n.objectLoader(d),r.push("[PAGES] Loaded pages tree root from file")}catch(p){let w=p instanceof Error?p.message:String(p);r.push(`[WARN] Failed to load pages tree root: ${w}`)}if(!h||!Z(h))return r.push(`[ERROR] Pages tree object not in cache at ${m}`),r.push("[NOTE] Page tree object must be loaded before traversal can begin"),r.push("[NEXT STEP] Implement ObjectReader.resolveRef() to load from file"),{pages:o,logs:r};let f=h;return r.push("[PAGES] \u2713 Found pages tree root"),this.walkPageTree(f,d,e,o,r,n,1),r.push(`[TRAVERSE] \u2713 Complete. Found ${o.length} page(s)`),{pages:o,logs:r}}catch(i){let s=i instanceof Error?i.message:String(i);return r.push(`[ERROR] Traversal failed: ${s}`),{pages:o,logs:r}}}static walkPageTree(e,n,r,o,i,s,a){let c=e.entries.get("Type"),l=this.extractName(c);if(l==="Pages"){let d=e.entries.get("Kids");if(!d)return i.push(`[WARN] Pages node has no /Kids at ${n.objNum} ${n.genNum} R`),a;let m=this.extractArray(d);if(!m)return i.push("[WARN] /Kids is not an array"),a;i.push(`[NODE] Pages node with ${m.length} child(ren) at ${n.objNum}`);for(let h of m){if(!Be(h)){i.push("[WARN] /Kids contains non-reference");continue}let f=h,p=`${f.objNum}.${f.genNum}`,w=r.objectCache.get(p);if((!w||!Z(w))&&s.objectLoader)try{w=s.objectLoader(f),i.push(`[NODE] Loaded child page node ${f.objNum} ${f.genNum} R from file`)}catch(b){let y=b instanceof Error?b.message:String(b);i.push(`[WARN] Failed to load child node: ${y}`)}if(!w||!Z(w)){i.push(`[SKIP] Child page node not in cache: ${f.objNum} ${f.genNum} R`),i.push("[NOTE] Would need ObjectReader to load from file");continue}if(a=this.walkPageTree(w,f,r,o,i,s,a),s.maxPages&&o.length>=s.maxPages)return a}return a}else if(l==="Page"){i.push(`[PAGE ${a}] Found at ${n.objNum} ${n.genNum} R`);let d=this.extractContentStreams(e,r,i,s);i.push(`[PAGE ${a}] \u2713 Found ${d.length} stream(s)`);let m=this.extractMediaBox(e),h=this.extractResources(e,r,i,s),f=this.extractNumber(e.entries.get("Rotate"));return o.push({pageNum:a,ref:n,dict:e,contentStreams:d,mediaBox:m||[0,0,612,792],resources:h,rotate:f||0}),a+1}else return i.push(`[WARN] Unknown node type: ${l}`),a}static extractContentStreams(e,n,r,o){let i=[];try{let s=e.entries.get("Contents");if(!s)return r.push("[WARN] Page has no /Contents"),i;if(me(s))i.push(s);else if(Be(s)){let a=s,c=`${a.objNum}.${a.genNum}`,l=n.objectCache.get(c);if((!l||!me(l))&&o.objectLoader)try{l=o.objectLoader(a),r.push(`[STREAM] Loaded content stream ${a.objNum} ${a.genNum} R from file`)}catch(d){let m=d instanceof Error?d.message:String(d);r.push(`[WARN] Failed to load content stream ${a.objNum} ${a.genNum} R: ${m}`)}l&&me(l)?i.push(l):r.push(`[STREAM] Content stream reference not cached: ${a.objNum} ${a.genNum} R`)}else if(he(s)){let a=this.extractArray(s);if(a){for(let c of a)if(me(c))i.push(c);else if(Be(c)){let l=c,d=`${l.objNum}.${l.genNum}`,m=n.objectCache.get(d);if((!m||!me(m))&&o.objectLoader)try{m=o.objectLoader(l),r.push(`[STREAM] Loaded content stream ${l.objNum} ${l.genNum} R from file`)}catch(h){let f=h instanceof Error?h.message:String(h);r.push(`[WARN] Failed to load content stream ${l.objNum} ${l.genNum} R: ${f}`)}m&&me(m)?i.push(m):r.push(`[STREAM] Content stream reference not cached: ${l.objNum} ${l.genNum} R`)}}}}catch(s){r.push(`[ERROR] Failed to extract content streams: ${s instanceof Error?s.message:String(s)}`)}return i}static extractMediaBox(e){let n=e.entries.get("MediaBox");if(n&&he(n)){let r=this.extractArray(n);if(r&&r.length>=4){let o=r.slice(0,4).map(i=>this.extractNumber(i));if(o.every(i=>i!==null))return o}}return null}static extractResources(e,n,r,o){let i=e.entries.get("Resources");if(i&&Z(i))return i;if(i&&Be(i)){let s=i,a=`${s.objNum}.${s.genNum}`,c=n.objectCache.get(a);if((!c||!Z(c))&&o.objectLoader)try{c=o.objectLoader(s),r.push(`[RESOURCES] Loaded resources ${s.objNum} ${s.genNum} R from file`)}catch(l){let d=l instanceof Error?l.message:String(l);r.push(`[WARN] Failed to load resources ${s.objNum} ${s.genNum} R: ${d}`)}if(c&&Z(c))return c;r.push(`[RESOURCES] Reference to resources not in cache: ${s.objNum} ${s.genNum} R`)}}static extractName(e){return!e||typeof e!="object"||!("type"in e)?null:e.type==="name"?e.value:null}static extractArray(e){return!e||typeof e!="object"||!("type"in e)?null:e.type==="array"?e.items||[]:null}static extractNumber(e){return K(e)}};var ka=new Set(["show_string","show_strings","next_line_show_string"]),Pa=t=>t==="show_string"?"() Tj":t==="show_strings"?"[] TJ":"() '",Sa=(t,e)=>{if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0};async function pi(t,e){let n=new Gt(t),r=n.parse(),i=Yn.getAllPages(r,{objectLoader:h=>n.loadObject(h)}).pages[e];if(!i)throw new Error(`Page ${e+1} not found`);let s=sr(i.dict.entries.get("Contents"));if(s.length===0)throw new Error("Page has no content streams");let a=[];for(let h of s){let f=n.loadObject(h);if(!me(f))continue;let p=f.decode?await f.decode():await ve.decodeStream(f);a.push({objNum:h.objNum,genNum:h.genNum,bytes:p})}if(a.length===0)throw new Error("Page content streams could not be decoded");let c=a.reduce((h,f)=>h+f.bytes.length,0)+Math.max(0,a.length-1),l=new Uint8Array(c),d=[],m=0;for(let h=0;h<a.length;h++)l.set(a[h].bytes,m),d.push({start:m,end:m+a[h].bytes.length}),m+=a[h].bytes.length,h<a.length-1&&(l[m]=32,m+=1);return{chunks:a,pristine:l,chunkSpans:d}}var Da=(t,e)=>t.chunks.map((n,r)=>{let o=new Uint8Array(e.subarray(t.chunkSpans[r].start,t.chunkSpans[r].end));return{objNum:n.objNum,genNum:n.genNum,bytes:o,changed:!Sa(o,n.bytes)}});async function Ca(t,e,n,r){let o=await pi(t,e);if(r&&r.length!==o.pristine.length)throw new Error("Stale rewrite state for page");let{commands:i,ranges:s}=zn(o.pristine),a=new Uint8Array(r!=null?r:o.pristine);for(let c of n){let l=i[c],d=s[c];if(!l||!d)throw new Error(`No operator at index ${c}`);if(!ka.has(l.op))throw new Error(`Operator ${l.op} at index ${c} is not rewritable`);if(!o.chunkSpans.some(f=>d.start>=f.start&&d.end<=f.end))throw new Error(`Operator at index ${c} spans multiple content streams`);let h=Pa(l.op);if(d.end-d.start<h.length)throw new Error(`Operator span too small at index ${c}`);a.fill(32,d.start,d.end);for(let f=0;f<h.length;f++)a[d.start+f]=h.charCodeAt(f)}return{streams:Da(o,a),combined:a}}var gu=t=>{let e=t.toFixed(6).replace(/\.?0+$/,"");return e===""||e==="-"?"0":e};async function Fa(t,e,n,r,o){var k;let i=await pi(t,e);if(o&&o.length!==i.pristine.length)throw new Error("Stale rewrite state for page");if(!r.every(Number.isFinite))throw new Error("Non-finite transform matrix");let{commands:s,ranges:a}=zn(i.pristine);if(n.start<0||n.end<n.start||n.end>=s.length)throw new Error(`Invalid operator span ${n.start}..${n.end}`);let c=0;for(let C=n.start;C<=n.end;C++){let S=(k=s[C])==null?void 0:k.op;if(S==="save_state")c+=1;else if(S==="restore_state"&&(c-=1,c<0))throw new Error("Span restores state it did not save")}if(c!==0)throw new Error("Span has unbalanced q/Q");let l=a[n.start].start,d=a[n.end].end,m=i.chunkSpans.findIndex(C=>l>=C.start&&d<=C.end);if(m<0)throw new Error("Span crosses content-stream chunk boundaries");let h=o!=null?o:i.pristine,f=new TextEncoder().encode(`
|
|
3
|
-
q ${r.map(
|
|
2
|
+
import"./chunk-R5KFRMXF.js";import*as Tl from"react";import Cm,{useCallback as vl,useEffect as wt,useMemo as kl,useRef as be,useState as se}from"react";var ei=class{constructor(){this.processors=new Map}registerProcessor(e){this.processors.set(e.name,e),console.log(`[AvniEngine] Registered processor: ${e.name}`)}async runPipeline(e,n){let r=[],o=e;for(let i of n.tasks){let s=this.processors.get(i.processorName);if(!s)throw new Error(`Processor ${i.processorName} not found`);console.log(`[AvniEngine] Executing ${s.name}...`);let a=Date.now(),c=await s.process(o,i.params),l=Date.now();if(c.metrics={duration:l-a,originalSize:o.size,newSize:c.document.size},r.push(c),!c.success){console.error(`[AvniEngine] Pipeline failed at ${s.name}: ${c.error}`);break}o=c.document}return r}getAvailableProcessors(){return Array.from(this.processors.keys())}},Xn=new ei;import{degrees as Lu,rgb as ur,PDFDocument as nc,PDFRef as Ri,StandardFonts as dt,TextAlignment as Ai}from"pdf-lib";var ti=t=>({type:"name",value:t.startsWith("/")?t.slice(1):t}),ni=()=>({type:"null"}),zn=t=>({type:"boolean",value:t}),ri=t=>({type:"integer",value:t}),oi=t=>({type:"real",value:t}),zr=(t,e)=>({type:"string",value:t,encoding:e}),ii=(t,e=0)=>({type:"ref",objNum:t,genNum:e});var Yr=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="integer",Qs=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="real",si=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="string",Q=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="dict",fe=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="stream",Be=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="ref",he=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="array",Wr=t=>Yr(t)||Qs(t),q=t=>!t||typeof t!="object"||!("type"in t)?null:t.type==="integer"||t.type==="real"?t.value:null;import ea from"zlib";function ta(t){return!t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null}function Ed(t){if(!t)return[];let e=ta(t);return e?[e]:he(t)?t.items.map(n=>ta(n)).filter(n=>n!==null):[]}function na(t){return t&&Q(t)?t:null}function Td(t,e){if(e<=0)return[];if(!t)return new Array(e).fill(null);let n=na(t);if(n)return new Array(e).fill(n);if(he(t)){let r=t.items.map(o=>na(o));return r.length>=e?r.slice(0,e):[...r,...new Array(e-r.length).fill(null)]}return new Array(e).fill(null)}function an(t,e){return t?q(t.entries.get(e)):null}function Od(t){let e=new TextDecoder("latin1").decode(t),n=e.indexOf(">"),r=(n>=0?e.slice(0,n):e).replace(/\s+/g,"");if(r.length===0)return new Uint8Array(0);let o=r.length%2===0?r:`${r}0`,i=new Uint8Array(o.length/2);for(let s=0;s<i.length;s++){let a=Number.parseInt(o.slice(s*2,s*2+2),16);if(Number.isNaN(a))throw new Error("Invalid ASCIIHex stream data");i[s]=a}return i}function Id(t){let e=new TextDecoder("latin1").decode(t),n=[],r=[];for(let o=0;o<e.length;o++){let i=e[o];if(i==="~"&&e[o+1]===">")break;if(/\s/.test(i))continue;if(i==="z"){if(r.length!==0)throw new Error("Invalid ASCII85 stream data");n.push(0,0,0,0);continue}let s=i.charCodeAt(0);if(!(s<33||s>117)&&(r.push(s-33),r.length===5)){let a=0;for(let c of r)a=a*85+c;n.push(a>>>24&255,a>>>16&255,a>>>8&255,a&255),r=[]}}if(r.length>0){let o=r.length;for(;r.length<5;)r.push(84);let i=0;for(let a of r)i=i*85+a;let s=[i>>>24&255,i>>>16&255,i>>>8&255,i&255];n.push(...s.slice(0,o-1))}return new Uint8Array(n)}function jd(t){let e=[];for(let n=0;n<t.length;){let r=t[n++];if(r===128)break;if(r<128){let s=r+1;for(let a=0;a<s&&n<t.length;a++)e.push(t[n++]);continue}let o=257-r;if(n>=t.length)break;let i=t[n++];for(let s=0;s<o;s++)e.push(i)}return new Uint8Array(e)}function $d(t,e,n){let r=t+e-n,o=Math.abs(r-t),i=Math.abs(r-e),s=Math.abs(r-n);return o<=i&&o<=s?t:i<=s?e:n}function ra(t,e,n,r){let o=Math.max(1,Math.ceil(e*n/8)),i=Math.ceil(r*e*n/8);if(i<=0)return t;let s=i+1,a=Math.floor(t.length/s);if(a<=0)return t;let c=new Uint8Array(a*i),l=new Uint8Array(i);for(let d=0;d<a;d++){let m=t[d*s],h=t.subarray(d*s+1,d*s+1+i),f=c.subarray(d*i,(d+1)*i);switch(m){case 0:{f.set(h);break}case 1:{for(let p=0;p<i;p++){let w=p>=o?f[p-o]:0;f[p]=h[p]+w&255}break}case 2:{for(let p=0;p<i;p++)f[p]=h[p]+l[p]&255;break}case 3:{for(let p=0;p<i;p++){let w=p>=o?f[p-o]:0,y=l[p];f[p]=h[p]+Math.floor((w+y)/2)&255}break}case 4:{for(let p=0;p<i;p++){let w=p>=o?f[p-o]:0,y=l[p],v=p>=o?l[p-o]:0;f[p]=h[p]+$d(w,y,v)&255}break}default:{f.set(h);break}}l=f.slice()}return c}function Bd(t){let e=[{bytes:t,trimmed:0,skippedHeader:!1}];t.length>2&&e.push({bytes:t.subarray(2),trimmed:0,skippedHeader:!0});let n=Math.min(64,Math.max(0,t.length-1));for(let r=1;r<=n;r++){let o=t.subarray(0,t.length-r);e.push({bytes:o,trimmed:r,skippedHeader:!1}),o.length>2&&e.push({bytes:o.subarray(2),trimmed:r,skippedHeader:!0})}for(let r of e){try{return{inflated:new Uint8Array(ea.inflateSync(Buffer.from(r.bytes))),mode:"zlib",trimmed:r.trimmed,skippedHeader:r.skippedHeader}}catch{}try{return{inflated:new Uint8Array(ea.inflateRawSync(Buffer.from(r.bytes))),mode:"raw",trimmed:r.trimmed,skippedHeader:r.skippedHeader}}catch{}}return null}function Ld(t,e){var i,s,a,c;let n=Bd(t);if(!n){let l=Array.from(t.subarray(0,Math.min(8,t.length))).map(h=>`0x${h.toString(16).padStart(2,"0")}`).join(" "),d=Math.max(0,t.length-8),m=Array.from(t.subarray(d)).map(h=>`0x${h.toString(16).padStart(2,"0")}`).join(" ");throw new Error(`FlateDecode failed after zlib/raw retries (including tail-trim recovery). len=${t.length} first=[${l}] last=[${m}]`)}let r=n.inflated;if(n.trimmed>0||n.skippedHeader){let l=[];n.trimmed>0&&l.push(`trimmed ${n.trimmed} byte(s)`),n.skippedHeader&&l.push("skipped first 2 header byte(s)"),console.warn(`[StreamDecoder] FlateDecode recovered (${l.join(", ")}) using ${n.mode} mode`)}if(((i=an(e,"Predictor"))!=null?i:1)>=10){let l=(s=an(e,"Colors"))!=null?s:1,d=(a=an(e,"BitsPerComponent"))!=null?a:8,m=(c=an(e,"Columns"))!=null?c:1;return ra(r,l,d,m)}return r}function Ud(t,e){var w,y,v,b;let i=0,s=9,a=258,c=[];for(let C=0;C<256;C++)c[C]=[C];let l=()=>{if(Math.floor(i/8)>=t.length)return null;let S=0;for(let F=0;F<s;F++){let T=i+F,O=t[Math.floor(T/8)]>>7-T%8&1;S=S<<1|O}return i+=s,S},d=()=>{c.length=0;for(let C=0;C<256;C++)c[C]=[C];s=9,a=258},m=[],h=null;for(;;){let C=l();if(C===null||C===257)break;if(C===256){d(),h=null;continue}let S;if(c[C])S=c[C];else if(h)S=[...h,h[0]];else break;m.push(...S),h&&(c[a++]=[...h,S[0]],a===1<<s&&s<12&&s++),h=S}let f=new Uint8Array(m);if(((w=an(e,"Predictor"))!=null?w:1)>=10){let C=(y=an(e,"Colors"))!=null?y:1,S=(v=an(e,"BitsPerComponent"))!=null?v:8,F=(b=an(e,"Columns"))!=null?b:1;return ra(f,C,S,F)}return f}var we=class{static async decodeStream(e){return this.decodeStreamSync(e)}static decodeStreamSync(e){var c,l;let n=e.dict.entries.get("Filter"),r=e.dict.entries.get("DecodeParms"),o=Ed(n),i=Td(r,o.length),s=(c=e.rawBytes)!=null?c:e.data;if(!s)throw new Error("Stream has no byte payload");if(o.length===0)return s;let a=s;for(let d=0;d<o.length;d++)a=this.applyFilterSync(o[d],a,(l=i[d])!=null?l:null);return a}static createLazyDecoder(e,n){return async()=>{let r={type:"stream",dict:e,rawBytes:n,decode:async()=>n};return this.decodeStreamSync(r)}}static applyFilterSync(e,n,r){switch(e){case"FlateDecode":case"Fl":return Ld(n,r);case"ASCII85Decode":case"A85":return Id(n);case"ASCIIHexDecode":case"AHx":return Od(n);case"LZWDecode":case"LZW":return Ud(n,r);case"DCTDecode":case"DCT":return n;case"JPXDecode":return console.warn("[StreamDecoder] JPXDecode not yet supported; returning raw bytes"),n;case"RunLengthDecode":case"RL":return jd(n);case"CCITTFaxDecode":case"CCF":return console.warn("[StreamDecoder] CCITTFaxDecode not yet supported; returning raw bytes"),n;case"Crypt":return n;default:return console.warn(`[StreamDecoder] Unknown filter: ${e}; returning raw bytes`),n}}};var Gt=class{constructor(e){this.pos=0;this.bytes=e}skipWhitespace(){for(;this.pos<this.bytes.length;){let e=this.bytes[this.pos];if(e===0||e===9||e===10||e===12||e===13||e===32)this.pos++;else if(e===37)for(;this.pos<this.bytes.length&&this.bytes[this.pos]!==10&&this.bytes[this.pos]!==13;)this.pos++;else break}}peek(){return this.skipWhitespace(),this.pos<this.bytes.length?this.bytes[this.pos]:void 0}peekRaw(e=0){let n=this.pos+e;return n<this.bytes.length?this.bytes[n]:void 0}read(){return this.skipWhitespace(),this.pos<this.bytes.length?this.bytes[this.pos++]:void 0}readRaw(){return this.pos<this.bytes.length?this.bytes[this.pos++]:void 0}readWord(){this.skipWhitespace();let e=this.pos;for(;this.pos<this.bytes.length;){let n=this.bytes[this.pos];if(n===0||n===9||n===10||n===12||n===13||n===32||n===60||n===62||n===40||n===41||n===123||n===125||n===91||n===93||n===47||n===37)break;this.pos++}return new TextDecoder().decode(this.bytes.subarray(e,this.pos))}readUntil(e){let n=this.pos,r=new TextEncoder().encode(e),o=r.length;for(;this.pos<=this.bytes.length-o;){let i=!0;for(let s=0;s<o;s++)if(this.bytes[this.pos+s]!==r[s]){i=!1;break}if(i){let s=this.bytes.subarray(n,this.pos);return this.pos+=o,s}this.pos++}throw new Error(`Could not find sequence: ${e}`)}getRemainingBytes(){return this.bytes.subarray(this.pos)}getBytes(){return this.bytes}getPosition(){return this.pos}setPosition(e){this.pos=e}};function _d(t){let e=t.peekRaw(),n=t.peekRaw(1);if(e===13&&n===10){t.readRaw(),t.readRaw();return}if(e===10||e===13){t.readRaw();return}console.warn(`[WARN] No newline after 'stream' keyword at tokenizer position ${t.getPosition()}`)}function Xd(t){let e=t.getBytes(),n=t.getPosition(),r=[101,110,100,115,116,114,101,97,109];for(let o=n;o<=e.length-r.length;o++){let i=!0;for(let m=0;m<r.length;m++)if(e[o+m]!==r[m]){i=!1;break}if(!i)continue;let s=o>0?e[o-1]:10,a=o+r.length<e.length?e[o+r.length]:10;if(!(s===10||s===13||s===32||s===9)||!(a===10||a===13||a===32||a===9||a===62))continue;let d=o;return d>n&&e[d-1]===10&&(d-=1),d>n&&e[d-1]===13&&(d-=1),t.setPosition(o+r.length),e.subarray(n,d)}throw new Error("Could not find 'endstream' marker for stream object")}function oa(t){let e=t.readWord();return parseFloat(e)}function zd(t){if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(t))throw new Error(`Invalid numeric token: ${t}`);let e=parseFloat(t);if(!Number.isFinite(e))throw new Error(`Invalid numeric value: ${t}`);return/^[+-]?\d+$/.test(t)?ri(e):oi(e)}function Yd(t){t.skipWhitespace();let e=t.readWord(),n=zd(e);if(!Yr(n))return n;let r=t.getPosition();try{t.skipWhitespace();let o=t.readWord();if(!/^[+-]?\d+$/.test(o))return t.setPosition(r),n;if(t.skipWhitespace(),t.readWord()==="R")return ii(n.value,parseInt(o,10))}catch{return t.setPosition(r),n}return t.setPosition(r),n}function ia(t){let e=t.peek();if(e===40){t.read();let n=[],r=1;for(;r>0&&t.peekRaw()!==void 0;){let o=t.readRaw();if(o===40)r++;else if(o===41){if(r--,r===0)break;n.push(o)}else if(o===92){let i=t.peekRaw();if(i===void 0)break;if(i>=48&&i<=55){let s="";for(let a=0;a<3;a++){let c=t.peekRaw();if(c!==void 0&&c>=48&&c<=55)s+=String.fromCharCode(t.readRaw());else break}n.push(parseInt(s,8)&255);continue}t.readRaw(),i===110?n.push(10):i===114?n.push(13):i===116?n.push(9):i===98?n.push(8):i===102?n.push(12):i===40?n.push(40):i===41?n.push(41):i===92?n.push(92):i===10||(i===13?t.peekRaw()===10&&t.readRaw():n.push(i))}else n.push(o)}return zr(new Uint8Array(n),"literal")}else if(e===60){t.read();let n=[];for(;t.peekRaw()!==62;){let o=t.readRaw();if(o===void 0)throw new Error("Unexpected EOF in hex string");if(o===0||o===9||o===10||o===12||o===13||o===32)continue;let i=Wd(o);i!==-1&&n.push(i)}t.readRaw(),n.length%2===1&&n.push(0);let r=new Uint8Array(n.length/2);for(let o=0,i=0;o<n.length;o+=2,i++)r[i]=n[o]<<4|n[o+1];return zr(r,"hex")}throw new Error("Invalid string format")}function Wd(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1}function Hd(t){if(t.peek()!==47)throw new Error("Expected / for name");t.read();let n=t.readWord();return ti(n)}function Gd(t){if(t.peek()!==91)throw new Error("Expected [ for array");t.read();let n=[];for(;t.peek()!==93;)n.push(gt(t));return t.read(),{type:"array",items:n}}function Kd(t){if(t.peek()!==60)throw new Error("Expected < for dict");if(t.read(),t.peek()!==60)throw new Error("Expected << for dict");t.read();let n=new Map;for(;;){if(t.skipWhitespace(),t.peekRaw()===62&&t.peekRaw(1)===62){t.readRaw(),t.readRaw();break}let r=gt(t);if(!r||typeof r!="object"||r.type!=="name")throw new Error("Dictionary key must be a name");let o=r.value,i=gt(t);n.set(o,i)}return{type:"dict",entries:n}}function gt(t){let e=t.peek();if(e===void 0)throw new Error("Unexpected EOF while reading object");if(e===110){let n=t.readWord();if(n==="null")return ni();if(n==="true")return zn(!0);if(n==="false")return zn(!1);throw new Error("Unknown keyword: "+n)}if(e===116||e===102){let n=t.readWord();if(n==="true")return zn(!0);if(n==="false")return zn(!1)}if(e===45||e===43||e===46||e>=48&&e<=57)return Yd(t);if(e===40)return ia(t);if(e===47)return Hd(t);if(e===91)return Gd(t);if(e===60){if(t.peekRaw(1)!==60)return ia(t);let r=Kd(t),o=t.getPosition();try{if(t.skipWhitespace(),t.readWord()==="stream"){_d(t);let s,a=r.entries.get("Length"),c=q(a);if(typeof c=="number"){let l=t.getPosition();s=t.getRemainingBytes().subarray(0,c),t.setPosition(l+c),t.skipWhitespace();let d=t.readWord();d!=="endstream"&&console.warn(`[WARN] Expected 'endstream' but got '${d}' - stream may be malformed`)}else s=Xd(t);return{type:"stream",dict:r,rawBytes:s,data:s,decode:we.createLazyDecoder(r,s)}}else return t.setPosition(o),r}catch{return t.setPosition(o),r}}throw new Error(`Unknown object type at byte ${e}`)}function sa(t){let e=oa(t),n=oa(t);if(t.readWord()!=="obj")throw new Error("Expected obj keyword");let o=gt(t),i=t.readWord();if(i!=="endobj"){let s=t.getRemainingBytes(),a=s.subarray(0,Math.min(8192,s.length)),c=new TextDecoder("latin1").decode(a),l=c.search(/\bendobj\b/);if(l===-1){let d=c.replace(/[\r\n\t]+/g," ").slice(0,220);throw new Error(`Expected endobj keyword (got '${i||"<EOF>"}'). Nearby: "${d}"`)}t.setPosition(t.getPosition()+l+6),console.warn(`[ObjectReader] Recovered non-immediate endobj for ${Math.floor(e)} ${Math.floor(n)} obj (first token: '${i||"<EOF>"}')`)}return{objNum:Math.floor(e),genNum:Math.floor(n),object:o}}function Hr(t,e,n){let r=new TextDecoder("latin1");if(!Number.isFinite(e)||e<0||e>=t.length)throw new Error(`Invalid object offset ${e} (file size: ${t.length})`);let o=4096,i=8192,s=Math.max(0,e-o),a=Math.min(t.length,e+i),c=t.subarray(s,a),l=r.decode(c),d=/(\d+)\s+(\d+)\s+obj\b/g,m,h=[];for(;(m=d.exec(l))!==null;){let b=s+m.index,C=Math.abs(b-e),S=parseInt(m[1],10);h.push({absolutePos:b,matched:m[0],distance:C,objNum:S})}if(h.length===0){let b=Math.max(0,e-64),C=Math.min(t.length,e+128),S=r.decode(t.subarray(b,C)).replace(/[\r\n\t]+/g," ").slice(0,220);throw new Error(`Could not find object header near offset ${e} (searched ${s}-${a}). Snippet: "${S}"`)}if(n!==void 0&&!h.some(b=>b.objNum===n)){let b=r.decode(t),C=String(n),S=new RegExp(`(?<![0-9])${C}\\s+\\d+\\s+obj\\b`,"g"),F;for(;(F=S.exec(b))!==null;){let T=F.index;if(h.some(O=>O.absolutePos===T))continue;let N=Math.abs(T-e);h.push({absolutePos:T,matched:F[0].trim(),distance:N,objNum:n})}}h.sort((b,C)=>{let S=n!==void 0&&b.objNum===n?0:1,F=n!==void 0&&C.objNum===n?0:1;return S!==F?S-F:b.distance-C.distance});let f=Math.min(12,h.length),p=[];for(let b=0;b<f;b++){let C=h[b];try{let S=new Gt(t.subarray(C.absolutePos)),F=sa(S);if(n!==void 0&&F.objNum!==n)throw new Error(`Parsed object ${F.objNum} but expected ${n}`);return b>0&&console.warn(`[ObjectReader] Offset ${e} resolved via fallback candidate #${b+1}: ${C.matched} at ${C.absolutePos}`),{...F,objectOffset:C.absolutePos}}catch(S){let F=S instanceof Error?S.message:String(S);p.push(`#${b+1} ${C.matched} @${C.absolutePos}: ${F}`)}}let w=Math.max(0,e-64),y=Math.min(t.length,e+256),v=r.decode(t.subarray(w,y)).replace(/[\r\n\t]+/g," ").slice(0,280);throw new Error(`Failed to read indirect object near offset ${e}. Tried ${f}/${h.length} candidates. Errors: ${p.join(" || ")}. Snippet: "${v}"`)}function ai(t){let e=q(t.entries.get("XRefStm"));return e===null?null:Math.floor(e)}function Vd(t){return t===0||t===9||t===10||t===12||t===13||t===32}function Gr(t,e){let n=e;for(;n<t.length&&Vd(t[n]);)n++;return n}function aa(t,e){let n=e;for(;n<t.length&&t[n]!==10&&t[n]!==13;)n++;let r=new TextDecoder("latin1").decode(t.subarray(e,n));return n<t.length&&t[n]===13&&n++,n<t.length&&t[n]===10&&n++,{line:r,next:n}}function li(t,e,n){e:for(let r=n;r<=t.length-e.length;r++){for(let o=0;o<e.length;o++)if(t[r+o]!==e[o])continue e;return r}return-1}function ca(t){return t===void 0?!0:t===0||t===9||t===10||t===12||t===13||t===32||t===60||t===62||t===40||t===41||t===91||t===93||t===123||t===125||t===47||t===37}function di(t,e,n){if(e<0||e+n.length>t.length)return!1;for(let i=0;i<n.length;i++)if(t[e+i]!==n[i])return!1;let r=e>0?t[e-1]:void 0,o=e+n.length<t.length?t[e+n.length]:void 0;return ca(r)&&ca(o)}function ha(t,e,n){let r=Math.max(0,n);for(;r<=t.length-e.length;){let o=li(t,e,r);if(o===-1)return-1;if(di(t,o,e))return o;r=o+1}return-1}function qd(t,e,n,r){let o=[],i=Math.max(0,n),s=Math.min(t.length-e.length,Math.max(i,r));for(;i<=s;){let a=li(t,e,i);if(a===-1||a>s)break;di(t,a,e)&&o.push(a),i=a+1}return o}function la(t,e,n,r){let o=Math.max(0,n-r),i=Math.min(t.length,n+r),s=qd(t,e,o,i);return s.length===0?-1:(s.sort((a,c)=>Math.abs(a-n)-Math.abs(c-n)),s[0])}function Jd(t,e,n,r){let o=Math.min(r,t.length);for(let i=Math.max(n,0);i<=o-e.length;i++){let s=!0;for(let a=0;a<e.length;a++)if(t[i+a]!==e[a]){s=!1;break}if(s){let a=i;for(let c=i+1;c<=o-e.length;c++){let l=!0;for(let d=0;d<e.length;d++)if(t[c+d]!==e[d]){l=!1;break}l&&(a=c)}return a}}return-1}function ci(t,e){let n=new Gt(t.subarray(e)),r=gt(n);if(!Q(r))throw new Error("Trailer object is not a dictionary");return r}function Dn(t){if(t===null)return"null";if(t===void 0)return"undefined";if(Array.isArray(t))return`Array(len=${t.length})`;if(typeof t=="number")return"number";if(typeof t!="object")return typeof t;let e=t;return typeof e.type=="string"?Array.isArray(e.items)?`PDFObject(type=${e.type}, items=${e.items.length})`:typeof e.value!="undefined"?`PDFObject(type=${e.type}, value=${String(e.value)})`:`PDFObject(type=${e.type})`:"object"}function Zd(t){return!t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null}function fa(t,e){console.debug("[XRefTable]",t,e!=null?e:{})}function da(t,e){console.warn("[XRefTable]",t,e!=null?e:{})}function ua(t,e){if(!t)throw new Error(`/${e} missing`);if(he(t)){let o=[];for(let i of t.items){let s=q(i);if(s===null)throw new Error(`/${e} must contain only numbers`);o.push(Math.floor(s))}return o}if(Array.isArray(t))return t.map(o=>Math.floor(Number(o)||0));if(typeof t=="number")return[Math.floor(t)];let n=q(t);if(n!==null)return[Math.floor(n)];let r=t;if(Array.isArray(r.items))return r.items.map(o=>Math.floor(Number(o)||0));throw new Error(`/${e} must be an array, got ${Dn(t)}`)}function ma(t){let e=t.length,n=Math.min(1024*1024,e),r=new TextDecoder("latin1").decode(t.subarray(e-n,e)),o=r.lastIndexOf("startxref");if(o!==-1){let i=r.slice(o+9).match(/\d+/);if(i)return parseInt(i[0],10)}throw new Error("PDF missing startxref offset")}function sr(t,e){let n=new TextDecoder("latin1"),r=new Uint8Array([120,114,101,102]),o=e,i=ha(t,r,o);if(i===-1||i-e>32){let a=n.decode(t.subarray(e,Math.min(e+20,t.length)));throw new Error(`Expected 'xref' keyword near offset ${e}, found: ${a}`)}for(o=i+r.length;o<t.length&&(t[o]===13||t[o]===10);)o++;let s=new Map;for(;o<t.length;){for(;o<t.length&&(t[o]===13||t[o]===10);)o++;let a=o;for(;o<t.length&&t[o]!==13&&t[o]!==10;)o++;let c=n.decode(t.subarray(a,o)).trim();for(;o<t.length&&(t[o]===13||t[o]===10);)o++;if(!c)continue;if(c==="trailer"||c.startsWith("trailer")||c==="railer"||c.startsWith("railer")){let h=c.startsWith("railer")?Math.max(0,a-1):a,f=Gr(t,h+7),p=ci(t,f),w=p.entries.get("Prev"),y=q(w),v=y===null?null:Math.floor(y),b=ai(p);if(s.size===0&&v===null&&b===null)throw new Error("No valid xref entries found");return{entries:s,trailer:p,prevXRefOffset:v,offset:e,xrefStmOffset:b}}if(c==="%%EOF"||c.startsWith("startxref")){let h=new Uint8Array([116,114,97,105,108,101,114]),f=Jd(t,h,e,a);if(f!==-1){let p=Gr(t,f+7),w=ci(t,p),y=w.entries.get("Prev"),v=q(y),b=v===null?null:Math.floor(v),C=ai(w);if(s.size===0&&b===null&&C===null)throw new Error("No valid xref entries found");return{entries:s,trailer:w,prevXRefOffset:b,offset:e,xrefStmOffset:C}}throw new Error("Reached EOF before trailer in traditional xref section")}let l=c.match(/^(\d+)\s+(\d+)$/);if(!l){if(/^\d+$/.test(c)){let h=new Uint8Array([116,114,97,105,108,101,114]),f=li(t,h,Math.max(0,a-1));if(f!==-1&&f-a<=256){let p=Gr(t,f+7),w=ci(t,p),y=w.entries.get("Prev"),v=q(y),b=v===null?null:Math.floor(v),C=ai(w);if(s.size===0&&b===null&&C===null)throw new Error("No valid xref entries found");return{entries:s,trailer:w,prevXRefOffset:b,offset:e,xrefStmOffset:C}}continue}throw new Error(`Invalid xref subsection header: ${c}`)}let d=parseInt(l[1],10),m=parseInt(l[2],10);for(let h=0;h<m;h++){if(o+20>t.length)throw new Error(`Truncated xref at entry ${d+h}`);let f=o,p=n.decode(t.subarray(o,o+20));o+=20;let w=p.substring(0,10),y=p.substring(11,16),v=p[17],b=0,C=0,S="f";if(/^\d{10}$/.test(w)&&/^\d{5}$/.test(y)&&(v==="n"||v==="f"))b=parseInt(w,10),C=parseInt(y,10),S=v;else{o=f;let F=aa(t,o);o=F.next;let T=0;for(;T<3&&F.line.trim()==="";)F=aa(t,o),o=F.next,T++;let N=F.line.match(/^\s*(\d{10})\s+(\d{5})\s+([nf])\b/);if(!N)throw new Error(`Malformed fixed-width xref entry: ${p}`);b=parseInt(N[1],10),C=parseInt(N[2],10),S=N[3]}s.set(d+h,{type:"uncompressed",offset:b,genNum:C,inUse:S==="n"})}}throw new Error("trailer keyword not found after xref entries")}function Qd(t,e){let{stream:n,resolvedObj:r}=eu(t,e),o=n.dict,i=Zd(o.entries.get("Type"));i!=="XRef"&&da("Resolved stream is not /Type /XRef",{offset:e,resolvedObj:r,type:i}),fa("Parsing xref stream",{offset:e,resolvedObj:r,type:i,wShape:Dn(o.entries.get("W")),indexShape:Dn(o.entries.get("Index")),sizeShape:Dn(o.entries.get("Size"))});let s,a;{let F=o.entries.get("W"),T=o.entries.get("Size"),N=q(T),O=o.entries.get("Index");try{if(s=ua(F,"W"),s.length!==3)throw new Error("/W must contain three integers");if(N===null)throw new Error("XRef stream missing /Size");if(a=O?ua(O,"Index"):[0,Math.floor(N)],a.length%2!==0)throw new Error("/Index must have even number of elements")}catch(A){let H=A instanceof Error?A.message:String(A);throw da("Failed parsing /W or /Index in xref stream",{offset:e,resolvedObj:r,error:H,wShape:Dn(F),indexShape:Dn(O),sizeShape:Dn(T)}),A}}let c=new Map,[l,d,m]=s,h=l+d+m,f=we.decodeStreamSync(n),p=0;for(let F=0;F<a.length;F+=2){let T=a[F],N=a[F+1];for(let O=0;O<N;O++){if(p+h>f.length)throw new Error("XRef stream data is shorter than expected from /W and /Index");let A=ce=>{let le=0;for(let pe=0;pe<ce;pe++)le=le<<8|f[p++];return le},H=l===0?1:A(l),ne=A(d),ie=A(m),I=T+O;H===0?c.set(I,{type:"uncompressed",offset:0,genNum:ie,inUse:!1}):H===1?c.set(I,{type:"uncompressed",offset:ne,genNum:ie,inUse:!0}):H===2&&c.set(I,{type:"compressed",streamNum:ne,indexNum:ie,genNum:0,inUse:!0})}}let w=o.entries.get("Prev"),y=q(w),v=y===null?null:Math.floor(y),b=new Map(o.entries),C=new Set(["W","Index","Filter","DecodeParms","Length","Columns","Predictor","Type","DL"]);for(let F of C)b.delete(F);return{entries:c,trailer:{type:"dict",entries:b},prevXRefOffset:v,offset:e}}function eu(t,e){let n=[0,-64,64,-256,256,-1024,1024,-4096,4096,-8192,8192],r=new Set,o=[],i=[];for(let s of n){let a=e+s;if(!(a<0||a>=t.length))try{let c=Hr(t,a),l=`${c.objNum}.${c.genNum}`;if(r.has(l))continue;if(r.add(l),!fe(c.object)){o.push(`offset ${a}: ${l} is not a stream`);continue}let d=c.object,m=d.dict.entries.has("W"),h=d.dict.entries.has("Size"),f=d.dict.entries.get("Type"),p=f&&typeof f=="object"&&"type"in f&&f.type==="name"?f.value:null,w=p==="XRef";if(m&&h)return fa("Resolved xref stream candidate",{requestedOffset:e,probeOffset:a,object:`${c.objNum} ${c.genNum} obj`,type:p}),{stream:d,resolvedObj:`${c.objNum} ${c.genNum} obj`};i.push(`offset ${a}: ${l} stream type=${p!=null?p:"unknown"} hasW=${m} hasSize=${h} isTypeXRef=${w}`)}catch(c){let l=c instanceof Error?c.message:String(c);o.push(`offset ${a}: ${l}`)}}throw new Error(`Could not resolve xref stream with /W and /Size near startxref ${e}. Non-xref streams: ${i.join(" || ")||"none"}. Failures: ${o.join(" || ")||"none"}`)}function pa(t,e){let n=new Uint8Array([120,114,101,102]),r=Gr(t,e);if(di(t,r,n))return sr(t,r);let o=ha(t,n,Math.max(0,e));if(o!==-1&&o-e<=2048)return sr(t,o);let i=la(t,n,e,32768);if(i!==-1)return sr(t,i);if(new TextDecoder("latin1").decode(t.subarray(e,Math.min(e+64,t.length))).trimStart().startsWith("xref"))return sr(t,e);try{return Qd(t,e)}catch(a){let c=la(t,n,e,131072);if(c!==-1)return sr(t,c);throw a}}function ui(t){let e=[],n=new Set,r=[ma(t)];for(;r.length>0;){let o=r.shift();if(o===null||n.has(o))continue;n.add(o);let i=pa(t,o);e.push(i),i.xrefStmOffset!=null&&r.push(i.xrefStmOffset),i.prevXRefOffset!=null&&r.push(i.prevXRefOffset)}return e}var tu=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);function hi(t){let e=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],n=[3614090360,3905402710,606105819,3250441966,4118548399,1200080426,2821735955,4249261313,1770035416,2336552879,4294925233,2304563134,1804603682,4254626195,2792965006,1236535329,4129170786,3225465664,643717713,3921069994,3593408605,38016083,3634488961,3889429448,568446438,3275163606,4107603335,1163531501,2850285829,4243563512,1735328473,2368359562,4294588738,2272392833,1839030562,4259657740,2763975236,1272893353,4139469664,3200236656,681279174,3936430074,3572445317,76029189,3654602809,3873151461,530742520,3299628645,4096336452,1126891415,2878612391,4237533241,1700485571,2399980690,4293915773,2240044497,1873313359,4264355552,2734768916,1309151649,4149444226,3174756917,718787259,3951481745],r=1732584193,o=4023233417,i=2562383102,s=271733878,a=t.length,c=(56-(a+1)%64+64)%64,l=new Uint8Array(a+1+c+8);l.set(t),l[a]=128;let d=a*8;l[l.length-8]=d&255,l[l.length-7]=d>>>8&255,l[l.length-6]=d>>>16&255,l[l.length-5]=d>>>24&255;let m=new DataView(l.buffer);for(let p=0;p<l.length;p+=64){let w=r,y=o,v=i,b=s,C=new Uint32Array(16);for(let S=0;S<16;S++)C[S]=m.getUint32(p+S*4,!0);for(let S=0;S<64;S++){let F,T;S<16?(F=y&v|~y&b,T=S):S<32?(F=b&y|~b&v,T=(5*S+1)%16):S<48?(F=y^v^b,T=(3*S+5)%16):(F=v^(y|~b),T=7*S%16);let N=b;b=v,v=y;let O=w+F+n[S]+C[T]|0;y=y+(O<<e[S]|O>>>32-e[S])|0,w=N}r=r+w|0,o=o+y|0,i=i+v|0,s=s+b|0}let h=new Uint8Array(16),f=new DataView(h.buffer);return f.setUint32(0,r,!0),f.setUint32(4,o,!0),f.setUint32(8,i,!0),f.setUint32(12,s,!0),h}function nu(t,e){let n=new Uint8Array(256);for(let s=0;s<256;s++)n[s]=s;let r=0;for(let s=0;s<256;s++){r=(r+n[s]+t[s%t.length])%256;let a=n[s];n[s]=n[r],n[r]=a}let o=new Uint8Array(e.length),i=0;r=0;for(let s=0;s<e.length;s++){i=(i+1)%256,r=(r+n[i])%256;let a=n[i];n[i]=n[r],n[r]=a,o[s]=e[s]^n[(n[i]+n[r])%256]}return o}var cn=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),ru=new Uint8Array([82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125]);function ou(t){let e=t.length/4,n=e+6,r=new Uint32Array(4*(n+1));for(let i=0;i<e;i++)r[i]=t[4*i]<<24|t[4*i+1]<<16|t[4*i+2]<<8|t[4*i+3];let o=[0,1,2,4,8,16,32,64,128,27,54];for(let i=e;i<4*(n+1);i++){let s=r[i-1];if(i%e===0){let a=s>>>24&255,c=s>>>16&255,l=s>>>8&255,d=s&255;s=cn[c]<<24|cn[l]<<16|cn[d]<<8|cn[a],s^=o[i/e]<<24}else if(e>6&&i%e===4){let a=s>>>24&255,c=s>>>16&255,l=s>>>8&255,d=s&255;s=cn[a]<<24|cn[c]<<16|cn[l]<<8|cn[d]}r[i]=r[i-e]^s}return r}function ga(t){for(let e=0;e<16;e++)t[e]=ru[t[e]]}function xa(t){let e;e=t[13],t[13]=t[9],t[9]=t[5],t[5]=t[1],t[1]=e,e=t[2],t[2]=t[10],t[10]=e,e=t[6],t[6]=t[14],t[14]=e,e=t[3],t[3]=t[7],t[7]=t[11],t[11]=t[15],t[15]=e}var iu=t=>(t<<1^(t>>>7&1)*27)&255;function tt(t,e){let n=0,r=t;for(let o=0;o<8;o++)e>>>o&1&&(n^=r),r=iu(r);return n}function su(t){for(let e=0;e<4;e++){let n=e*4,r=t[n],o=t[n+1],i=t[n+2],s=t[n+3];t[n]=tt(r,14)^tt(o,11)^tt(i,13)^tt(s,9),t[n+1]=tt(r,9)^tt(o,14)^tt(i,11)^tt(s,13),t[n+2]=tt(r,13)^tt(o,9)^tt(i,14)^tt(s,11),t[n+3]=tt(r,11)^tt(o,13)^tt(i,9)^tt(s,14)}}function fi(t,e,n){for(let r=0;r<4;r++){let o=e[n*4+r];t[r*4]^=o>>>24&255,t[r*4+1]^=o>>>16&255,t[r*4+2]^=o>>>8&255,t[r*4+3]^=o&255}}function au(t,e,n){let r=new Uint8Array(16);r.set(t),fi(r,e,n);for(let o=n-1;o>=1;o--)xa(r),ga(r),fi(r,e,o),su(r);return xa(r),ga(r),fi(r,e,0),r}function cu(t,e){if(e.length<16)return e;let n=ou(t),r=t.length/4+6,o=e.subarray(0,16),i=e.subarray(16),s=i.length/16,a=new Uint8Array(i.length),c=o;for(let d=0;d<s;d++){let m=d*16,h=i.subarray(m,m+16),f=au(h,n,r);for(let p=0;p<16;p++)a[m+p]=f[p]^c[p];c=h}let l=a[a.length-1];if(l>0&&l<=16){let d=!0;for(let m=a.length-l;m<a.length;m++)if(a[m]!==l){d=!1;break}if(d)return a.subarray(0,a.length-l)}return a}var Kr=class{constructor(e,n){this.fileKey=new Uint8Array(0);this.v=0;this.r=0;this.isAes=!1;this.parseEncryptDict(e,n)}parseEncryptDict(e,n){var b,C,S,F;let r=e.entries.get("V"),o=e.entries.get("R"),i=e.entries.get("Length"),s=e.entries.get("O"),a=e.entries.get("U"),c=e.entries.get("P"),l=e.entries.get("EncryptMetadata");this.v=(b=q(r))!=null?b:0,this.r=(C=q(o))!=null?C:0;let m=((S=q(i))!=null?S:40)/8,h=s&&"value"in s&&s.value instanceof Uint8Array?s.value:new Uint8Array(0),f=a&&"value"in a&&a.value instanceof Uint8Array?a.value:new Uint8Array(0),p=(F=q(c))!=null?F:0,w=l&&"value"in l?l.value:!0,y=e.entries.get("CF"),v=e.entries.get("StmF");if(v&&"value"in v&&v.value==="AESV2")this.isAes=!0;else if(y&&Q(y)){let T=y.entries.get("StdCF");if(T&&Q(T)){let N=T.entries.get("CFM");N&&"value"in N&&N.value==="AESV2"&&(this.isAes=!0)}}(this.v===5||this.r===5||this.r===6)&&(this.isAes=!0),this.fileKey=this.deriveFileKey(new Uint8Array(0),m,h,f,p,n,w)}deriveFileKey(e,n,r,o,i,s,a=!0){let c=new Uint8Array(32);c.set(e.subarray(0,Math.min(32,e.length))),e.length<32&&c.set(tu.subarray(0,32-e.length),e.length);let l=[];l.push(...c),l.push(...r),l.push(i&255),l.push(i>>>8&255),l.push(i>>>16&255),l.push(i>>>24&255),s&&s.length>0&&l.push(...s),this.r>=3&&!a&&l.push(255,255,255,255);let d=hi(new Uint8Array(l));if(this.r>=3){let h=d.subarray(0,n);for(let f=0;f<50;f++)h=hi(h).subarray(0,n);return h}return d.subarray(0,n)}deriveObjectKey(e,n){let r=new Uint8Array(5);r[0]=e&255,r[1]=e>>>8&255,r[2]=e>>>16&255,r[3]=n&255,r[4]=n>>>8&255;let o=new Uint8Array(this.fileKey.length+r.length+(this.isAes?4:0));o.set(this.fileKey),o.set(r,this.fileKey.length),this.isAes&&o.set([115,65,108,84],this.fileKey.length+r.length);let i=hi(o),s=Math.min(16,this.fileKey.length+5);return i.subarray(0,s)}decrypt(e,n,r){return this.isAes?cu(this.deriveObjectKey(n,r),e):nu(this.deriveObjectKey(n,r),e)}};var Kt=class{constructor(e){this.document=null;this.objectStreamCache=new Map;this.encryptRef=null;this.decryptionHandler=null;this.bytes=e}parse(){if(this.document)return this.document;try{let e=this.extractVersion(),n=this.parseXRefTables();if(n.length===0)throw new Error("No valid xref tables found in PDF");let r=new Map;for(let a=n.length-1;a>=0;a--)for(let[c,l]of n[a].entries)r.set(c,l);let o=n[0].trailer,i=this.extractRootRef(o);this.document={rawBytes:this.bytes,xrefTables:new Map([[0,r]]),objectCache:new Map,rootRef:i,trailer:o,version:e};let s=o.entries.get("Encrypt");if(s){let a=null;if(Be(s)){this.encryptRef=s;let c=this.loadObject(s);Q(c)&&(a=c)}else Q(s)&&(a=s);if(a){let c,l=o.entries.get("ID");if(l&&he(l)&&l.items.length>0){let d=l.items[0];si(d)&&(c=d.value)}this.decryptionHandler=new Kr(a,c)}}return this.document}catch(e){throw console.error("[ERROR] Parse failed:",e),e}}extractVersion(){let r=new TextDecoder().decode(this.bytes.subarray(0,20)).match(/%PDF-(\d+\.\d+)/);if(!r)throw new Error("Invalid PDF header - no %PDF-X.Y found");return r[1]}parseXRefTables(){return ui(this.bytes)}extractRootRef(e){let n=e.entries.get("Root");if(!n)throw console.error("[ERROR] Trailer has no Root entry. Trailer entries:",Array.from(e.entries.keys())),new Error("Trailer missing /Root reference");if(typeof n!="object"||n.type!=="ref")throw console.error("[ERROR] Root is not a reference object:",n),new Error("Trailer /Root is not a valid reference");return n}loadObject(e){if(!this.document)throw new Error("Parse PDF first");let n=`${e.objNum}.${e.genNum}`;if(this.document.objectCache.has(n))return this.document.objectCache.get(n);let r=this.document.xrefTables.get(0);if(!r)throw new Error("No xref table found");let o=r.get(e.objNum);if(!o)throw new Error(`Object ${e.objNum} not found in xref`);if(o.type==="uncompressed"){if(!o.inUse)throw new Error(`Object ${e.objNum} is marked free in xref`);if(o.offset===0){let i={type:"dict",entries:new Map};throw this.document.objectCache.set(n,i),new Error(`Object ${e.objNum} has ghost xref entry (offset 0)`)}try{let{object:i,objectOffset:s}=Hr(this.bytes,o.offset,e.objNum),a=fe(i)?this.repairStreamBytesFromLengthRef(i,s):i,c=this.decryptObject(a,e.objNum,e.genNum);return this.document.objectCache.set(n,c),c}catch(i){console.warn(`[PDFParser] Failed to load object ${e.objNum}: ${i}`);let s={type:"dict",entries:new Map};throw this.document.objectCache.set(n,s),i}}else{if(!o.inUse)throw new Error(`Object ${e.objNum} is marked free in compressed xref entry`);let i=o.streamNum;if(!this.objectStreamCache.has(i)){let a=this.loadObjectStream(i,r);this.objectStreamCache.set(i,a)}let s=this.document.objectCache.get(n);if(!s)throw new Error(`Object ${e.objNum} not found in object stream ${i}`);return s}}loadObjectStream(e,n){var y,v;let r=n.get(e);if(!r||r.type!=="uncompressed"||!r.inUse)throw new Error(`Object stream ${e} not found or not in-use/uncompressed`);let o={type:"ref",objNum:e,genNum:0},i=this.loadObject(o);if(!fe(i))throw new Error(`Object ${e} is not a stream`);let s=i.dict.entries.get("Type");if(!s||s.type!=="name"||s.value!=="ObjStm")throw new Error(`Object ${e} is not an /ObjStm`);let a=i.dict.entries.get("N"),c=i.dict.entries.get("First");if(!a||!Wr(a)||!c||!Wr(c))throw new Error(`Object stream ${e} missing numeric /N or /First`);let l=Math.floor(a.value),d=Math.floor(c.value);if(l<0||d<0)throw new Error(`Object stream ${e} has invalid /N or /First values`);let m=i,h;try{h=we.decodeStreamSync(m)}catch(b){let C=m.dict.entries.get("Filter"),S=m.dict.entries.get("Length"),F=(v=(y=m.rawBytes)!=null?y:m.data)!=null?v:new Uint8Array(0),T=Array.from(F.subarray(0,8)).map(H=>H.toString(16).padStart(2,"0")).join(" "),N=Math.max(0,F.length-8),O=Array.from(F.subarray(N)).map(H=>H.toString(16).padStart(2,"0")).join(" "),A=b instanceof Error?b.message:String(b);throw new Error(`Object stream ${e} decode failed: ${A}; Filter=${JSON.stringify(C)} Length=${JSON.stringify(S)} rawLen=${F.length} first8=[${T}] last8=[${O}]`)}if(d>h.length)throw new Error(`Object stream ${e} /First (${d}) exceeds decoded length (${h.length})`);let p=new TextDecoder("latin1").decode(h.subarray(0,d)).match(/\d+/g)||[];if(p.length<l*2)throw new Error(`Object stream ${e} header has ${p.length} numbers, expected at least ${l*2}`);let w=new Map;for(let b=0;b<l;b++){let C=parseInt(p[b*2],10),S=parseInt(p[b*2+1],10),F=d+S;if(!(!Number.isFinite(C)||!Number.isFinite(S)||S<0||F>h.length))try{let T=new Gt(h.subarray(F)),N=gt(T);w.set(C,N),this.document.objectCache.set(`${C}.0`,N)}catch(T){console.warn(`[WARN] Failed to parse object ${C} from object stream ${e}:`,T)}}return w}repairStreamBytesFromLengthRef(e,n){var l,d;let r=e.dict.entries.get("Length");if(!r||!Be(r))return e;let o=null;try{let m=this.loadObject(r);o=q(m)}catch{return e}if(o===null)return e;let i=Math.max(0,Math.floor(o)),s=this.findStreamDataStart(n);if(s<0||s+i>this.bytes.length)return e;let a=(l=e.rawBytes)!=null?l:e.data;if(a&&a.length===i)return e;let c=this.bytes.subarray(s,s+i);return console.warn(`[PDFParser] Repaired stream bytes via indirect /Length at offset ${n}: resolved length=${i}, previous length=${(d=a==null?void 0:a.length)!=null?d:0}`),{type:"stream",dict:e.dict,rawBytes:c,data:c,decode:we.createLazyDecoder(e.dict,c)}}findStreamDataStart(e){let n=[115,116,114,101,97,109],r=Math.min(this.bytes.length-n.length,e+1024*1024);for(let o=Math.max(0,e);o<=r;o++){let i=!0;for(let m=0;m<n.length;m++)if(this.bytes[o+m]!==n[m]){i=!1;break}if(!i)continue;let s=o>0?this.bytes[o-1]:32,a=this.bytes[o+n.length];if(!(s===10||s===13||s===32||s===9||s===62)||!(a===10||a===13||a===32||a===9))continue;let d=o+n.length;return this.bytes[d]===13&&this.bytes[d+1]===10?d+=2:(this.bytes[d]===10||this.bytes[d]===13)&&(d+=1),d}return-1}decryptObject(e,n,r){return!this.decryptionHandler||this.encryptRef&&n===this.encryptRef.objNum?e:this.decryptObjectRecursive(e,n,r)}decryptObjectRecursive(e,n,r){var o,i;if(!this.decryptionHandler)return e;if(e.type==="string"){let s=this.decryptionHandler.decrypt(e.value,n,r);return{...e,value:s}}if(e.type==="array")return{...e,items:e.items.map(s=>this.decryptObjectRecursive(s,n,r))};if(e.type==="dict"){let s=new Map;for(let[a,c]of e.entries)s.set(a,this.decryptObjectRecursive(c,n,r));return{...e,entries:s}}if(e.type==="stream"){let s=(i=(o=e.rawBytes)!=null?o:e.data)!=null?i:new Uint8Array(0),a=s.length>0?this.decryptionHandler.decrypt(s,n,r):s,c=this.decryptObjectRecursive(e.dict,n,r);return{type:"stream",dict:c,rawBytes:a,data:a,decode:we.createLazyDecoder(c,a)}}return e}};function ar(t){if(!t)return[];if(Be(t))return[t];if(he(t)){let e=[];for(let n of t.items)e.push(...ar(n));return e}return[]}function lu(t){if(t.length===0)return new Uint8Array(0);let e=Math.max(0,t.length-1),n=t.reduce((i,s)=>i+s.length,0)+e,r=new Uint8Array(n),o=0;for(let i=0;i<t.length;i++)r.set(t[i],o),o+=t[i].length,i<t.length-1&&(r[o]=32,o+=1);return r}async function mi(t,e){let n=ar(t);if(n.length===0)return{combinedBytes:new Uint8Array(0),streamCount:0,streamByteLengths:[]};let r=[];for(let o of n){let i=await Promise.resolve(e(o));if(!fe(i)){console.warn(`[WARN] Contents ref ${o.objNum} ${o.genNum} R is not a stream, skipping`);continue}try{let s=i.decode?await i.decode():await we.decodeStream(i);r.push(s)}catch(s){throw console.error(`[ContentStreamLoader] Failed to decode stream ${o.objNum} ${o.genNum} R:`,s),s}}return{combinedBytes:lu(r),streamCount:r.length,streamByteLengths:r.map(o=>o.length)}}function qt(t){return Yn(t).commands}function Yn(t){let e=new Gt(t),n=[],r=[],o=[],i=-1;for(;e.skipWhitespace(),!(e.getPosition()>=t.length);){let s=e.getPosition(),a=t[s];if(wa(a)){let c=e.readWord();if(!c)break;if(c==="BI"){let d=uu(e,t);d?(n.push(d.command),r.push({start:s,end:d.end})):(n.push({op:"unknown",keyword:"BI",operands:[]}),r.push({start:s,end:e.getPosition()})),o.length=0,i=-1;continue}let l=hu(c,o);l&&(n.push(l),r.push({start:i>=0?i:s,end:e.getPosition()})),o.length=0,i=-1}else{i<0&&(i=s);try{let c=gt(e);o.push(c)}catch{e.setPosition(s+1)}}}return{commands:n,ranges:r}}function wa(t){return t>=65&&t<=90||t>=97&&t<=122||t===39||t===34}var Vr=t=>t===32||t===10||t===13||t===9||t===12||t===0,ba=t=>t===47||t===60||t===62||t===91||t===93||t===40||t===41||t===37||t===123||t===125,du=t=>{var r,o;let e=(r=t.entries.get("IM"))!=null?r:t.entries.get("ImageMask");if(e&&"type"in e&&e.type==="boolean"&&e.value)return 1;let n=(o=t.entries.get("CS"))!=null?o:t.entries.get("ColorSpace");if(!n||!("type"in n)||n.type!=="name")return 1;switch(n.value){case"RGB":case"DeviceRGB":case"CalRGB":return 3;case"CMYK":case"DeviceCMYK":return 4;default:return 1}};function uu(t,e){var n,r,o,i,s;try{let a=new Map;for(;;){t.skipWhitespace();let v=t.getPosition();if(v>=e.length)return null;let b=e[v];if(b===47){let C=gt(t);if(!C||!("type"in C)||C.type!=="name")return null;t.skipWhitespace(),a.set(C.value,gt(t))}else if(wa(b)){if(t.readWord()==="ID")break;return null}else return null}let c={type:"dict",entries:a},l=t.getPosition();Vr(e[l])&&(l+=e[l]===13&&e[l+1]===10?2:1);let d=(n=a.get("L"))!=null?n:a.get("Length"),m=q(d),h=a.has("F")||a.has("Filter"),f=-1;if(m!==null&&m>=0&&l+m<=e.length)f=l+m;else if(!h){let v=q((r=a.get("W"))!=null?r:a.get("Width")),b=q((o=a.get("H"))!=null?o:a.get("Height")),C=(s=q((i=a.get("BPC"))!=null?i:a.get("BitsPerComponent")))!=null?s:8;if(v!==null&&b!==null&&v>0&&b>0){let S=Math.ceil(v*C*du(c)/8)*b;l+S<=e.length&&(f=l+S)}}if(f<0){for(let v=l;v+1<e.length;v++){if(e[v]!==69||e[v+1]!==73||v>l&&!Vr(e[v-1]))continue;let b=e[v+2];if(!(b!==void 0&&!Vr(b)&&!ba(b))){f=Math.max(l,v-1);break}}if(f<0)return null}let p=new Uint8Array(e.subarray(l,f));t.setPosition(f),t.skipWhitespace();let w=t.getPosition();if(e[w]!==69||e[w+1]!==73)return null;let y=e[w+2];return y!==void 0&&!Vr(y)&&!ba(y)?null:(t.setPosition(w+2),{command:{op:"inline_image",params:c,data:p},end:w+2})}catch{return null}}function hu(t,e){switch(t){case"q":return{op:"save_state"};case"Q":return{op:"restore_state"};case"cm":return{op:"set_ctm",matrix:ya(e)};case"w":return{op:"set_line_width",width:re(e,0)};case"J":return{op:"set_line_cap",cap:Math.floor(re(e,0))};case"j":return{op:"set_line_join",join:Math.floor(re(e,0))};case"M":return{op:"set_miter_limit",limit:re(e,0)};case"d":return{op:"set_dash",array:fu(e,0),phase:re(e,1)};case"ri":return{op:"set_rendering_intent",intent:Vt(e,0)};case"gs":return{op:"set_graphics_state",name:Vt(e,0)};case"rg":return{op:"set_fill_color_rgb",r:re(e,0),g:re(e,1),b:re(e,2)};case"RG":return{op:"set_stroke_color_rgb",r:re(e,0),g:re(e,1),b:re(e,2)};case"g":return{op:"set_fill_gray",gray:re(e,0)};case"G":return{op:"set_stroke_gray",gray:re(e,0)};case"k":return{op:"set_fill_cmyk",c:re(e,0),m:re(e,1),y:re(e,2),k:re(e,3)};case"K":return{op:"set_stroke_cmyk",c:re(e,0),m:re(e,1),y:re(e,2),k:re(e,3)};case"cs":return{op:"set_fill_color_space",name:Vt(e,0)};case"CS":return{op:"set_stroke_color_space",name:Vt(e,0)};case"sc":case"scn":{let n=e[e.length-1],r=n&&typeof n=="object"&&"type"in n&&n.type==="name"?n.value:void 0;return{op:"set_fill_color",values:(r?e.slice(0,-1):e).map(qr),patternName:r}}case"SC":case"SCN":{let n=e[e.length-1],r=n&&typeof n=="object"&&"type"in n&&n.type==="name"?n.value:void 0;return{op:"set_stroke_color",values:(r?e.slice(0,-1):e).map(qr),patternName:r}}case"m":return{op:"move_to",x:re(e,0),y:re(e,1)};case"l":return{op:"line_to",x:re(e,0),y:re(e,1)};case"c":return{op:"curve_to",x1:re(e,0),y1:re(e,1),x2:re(e,2),y2:re(e,3),x3:re(e,4),y3:re(e,5)};case"v":return{op:"curve_to_v",x2:re(e,0),y2:re(e,1),x3:re(e,2),y3:re(e,3)};case"y":return{op:"curve_to",x1:re(e,0),y1:re(e,1),x2:re(e,2),y2:re(e,3),x3:re(e,2),y3:re(e,3)};case"re":return{op:"rect",x:re(e,0),y:re(e,1),w:re(e,2),h:re(e,3)};case"h":return{op:"close_path"};case"S":return{op:"stroke"};case"s":return{op:"close_stroke"};case"f":case"F":return{op:"fill"};case"f*":return{op:"fill_even_odd"};case"B":return{op:"fill_stroke"};case"B*":return{op:"fill_stroke_even_odd"};case"b":return{op:"close_fill_stroke"};case"b*":return{op:"close_fill_stroke_even_odd"};case"n":return{op:"end_path"};case"W":return{op:"clip"};case"W*":return{op:"clip_even_odd"};case"BT":return{op:"begin_text"};case"ET":return{op:"end_text"};case"Tf":return{op:"set_font",name:Vt(e,0),size:re(e,1)};case"Td":return{op:"move_text",tx:re(e,0),ty:re(e,1)};case"TD":return{op:"move_text_set_leading",tx:re(e,0),ty:re(e,1)};case"Tm":return{op:"set_text_matrix",matrix:ya(e)};case"T*":return{op:"next_line"};case"Tc":return{op:"set_char_spacing",spacing:re(e,0)};case"Tw":return{op:"set_word_spacing",spacing:re(e,0)};case"Tz":return{op:"set_horiz_scale",scale:re(e,0)};case"TL":return{op:"set_leading",leading:re(e,0)};case"Tr":return{op:"set_text_render",mode:re(e,0)};case"Ts":return{op:"set_text_rise",rise:re(e,0)};case"Tj":return{op:"show_string",data:pi(e,0)};case"TJ":return{op:"show_strings",items:mu(e,0)};case"'":return{op:"next_line_show_string",data:pi(e,0)};case'"':return{op:"set_spacing_next_line_show_string",wordSpacing:re(e,0),charSpacing:re(e,1),data:pi(e,2)};case"d0":return{op:"type3_glyph_width",wx:re(e,0),wy:re(e,1)};case"d1":return{op:"type3_glyph_width",wx:re(e,0),wy:re(e,1)};case"sh":return{op:"shade",name:Vt(e,0)};case"Do":return{op:"xobject",name:Vt(e,0)};case"BMC":return{op:"begin_marked_content",tag:Vt(e,0)};case"BDC":{let n=e[1];return{op:"begin_marked_content",tag:Vt(e,0),properties:Q(n)?n:void 0}}case"EMC":return{op:"end_marked_content"};case"MP":case"DP":case"BX":case"EX":return null;default:return{op:"unknown",keyword:t,operands:[...e]}}}function re(t,e){return qr(t[e])}function qr(t){let e=q(t);return e===null?0:e}function Vt(t,e){let n=t[e];return n&&typeof n=="object"&&"type"in n&&n.type==="name"?n.value:""}function pi(t,e){let n=t[e];return n&&typeof n=="object"&&"type"in n&&n.type==="string"?n.value:new Uint8Array(0)}function fu(t,e){let n=t[e];return he(n)?n.items.map(qr):[]}function mu(t,e){let n=t[e];return he(n)?n.items.map(r=>{let o=q(r);return o!==null?o:r&&typeof r=="object"&&"type"in r&&r.type==="string"?r.value:0}):[]}function ya(t){return[re(t,0),re(t,1),re(t,2),re(t,3),re(t,4),re(t,5)]}var Jr=t=>t.map(e=>e.text).join(""),va=(t,e={})=>{let n=Cn(t);return n.length>1?!0:n.length===0?!1:ln(n[0].style)!==ln(e)},pu=t=>t?`${t.r.toFixed(4)},${t.g.toFixed(4)},${t.b.toFixed(4)}`:"-",ln=t=>{var e;return[t.bold?1:0,t.italic?1:0,t.underline?1:0,t.strikethrough?1:0,(e=t.sizePt)!=null?e:"-",pu(t.color)].join("|")},Cn=t=>{let e=[];for(let n of t){if(n.text.length===0)continue;let r=e[e.length-1];r&&ln(r.style)===ln(n.style)?r.text+=n.text:e.push({text:n.text,style:{...n.style}})}return e},gu=[[/times|serif|georgia|cambria|garamond|minion/,"Times"],[/courier|mono|consol/,"Courier"]],ka=(t,e={})=>{let n=(t!=null?t:"").replace(/^[A-Z]{6}\+/,"").replace(/[#,\s]/g,"").toLowerCase(),r="Helvetica";for(let[i,s]of gu)if(i.test(n)){r=s;break}let o=`${e.bold?"Bold":""}${e.italic?"Italic":""}`;return o?`${r}-${o}`:r};var Zr=(t,e,n,r=.5)=>{let o=t.y+t.height,i=t.y,s=t.x+t.width,a=f=>{let p=f.pdfX+f.width/2,w=f.pdfY+f.height/2;if(p>=t.x&&p<=s&&w>=i&&w<=o)return!0;let y=Math.max(0,Math.min(s,f.pdfX+f.width)-Math.max(t.x,f.pdfX)),v=Math.max(0,Math.min(o,f.pdfY+f.height)-Math.max(i,f.pdfY)),b=f.width*f.height;return b>0&&y*v/b>=.6},c=e.filter(f=>!a(f)),l={},d,m;for(let f of c)if(!(f.pdfX+f.width<=t.x||f.pdfX>=n)){if(f.pdfY>=o)d=d===void 0?f.pdfY:Math.min(d,f.pdfY);else if(f.pdfY+f.height<=i){let p=f.pdfY+f.height;m=m===void 0?p:Math.max(m,p)}}d!==void 0&&(l.maxY=Math.max(o,d-r)),m!==void 0&&(l.minY=Math.min(i,m+r));let h;for(let f of c)Math.min(o,f.pdfY+f.height)-Math.max(i,f.pdfY)<=0||f.pdfX<s||(h=h===void 0?f.pdfX:Math.min(h,f.pdfX));return h!==void 0&&(l.maxRight=Math.max(s,h-r)),l},Qr=(t,e)=>{let n=t.y+t.height,r=t.y,o=t.x+t.width;return e.maxY!==void 0&&e.maxY<n&&e.maxY>r&&(n=e.maxY),e.minY!==void 0&&e.minY>r&&e.minY<n&&(r=e.minY),e.maxRight!==void 0&&e.maxRight<o&&e.maxRight>t.x&&(o=e.maxRight),{x:t.x,y:r,width:Math.max(0,o-t.x),height:Math.max(0,n-r)}};var Wn=class{static getAllPages(e,n={}){let r=[],o=[];try{r.push("[TRAVERSE] Starting page tree traversal...");let i=e.rootRef;r.push(`[CATALOG] Root reference: ${i.objNum} ${i.genNum} R`);let s=`${i.objNum}.${i.genNum}`,a=e.objectCache.get(s);if((!a||!Q(a))&&n.objectLoader)try{a=n.objectLoader(i),r.push("[CATALOG] Loaded root catalog from file")}catch(p){let w=p instanceof Error?p.message:String(p);r.push(`[WARN] Failed to load root catalog: ${w}`)}if(!a||!Q(a))return r.push(`[ERROR] Root catalog not found in object cache at ${s}`),{pages:o,logs:r};let c=a;r.push("[CATALOG] \u2713 Found catalog in cache");let l=c.entries.get("Pages");if(!l)return r.push("[ERROR] /Pages reference not found in catalog"),{pages:o,logs:r};if(!Be(l))return r.push("[ERROR] /Pages is not an indirect reference"),{pages:o,logs:r};let d=l;r.push(`[PAGES] Pages tree root: ${d.objNum} ${d.genNum} R`);let m=`${d.objNum}.${d.genNum}`,h=e.objectCache.get(m);if((!h||!Q(h))&&n.objectLoader)try{h=n.objectLoader(d),r.push("[PAGES] Loaded pages tree root from file")}catch(p){let w=p instanceof Error?p.message:String(p);r.push(`[WARN] Failed to load pages tree root: ${w}`)}if(!h||!Q(h))return r.push(`[ERROR] Pages tree object not in cache at ${m}`),r.push("[NOTE] Page tree object must be loaded before traversal can begin"),r.push("[NEXT STEP] Implement ObjectReader.resolveRef() to load from file"),{pages:o,logs:r};let f=h;return r.push("[PAGES] \u2713 Found pages tree root"),this.walkPageTree(f,d,e,o,r,n,1),r.push(`[TRAVERSE] \u2713 Complete. Found ${o.length} page(s)`),{pages:o,logs:r}}catch(i){let s=i instanceof Error?i.message:String(i);return r.push(`[ERROR] Traversal failed: ${s}`),{pages:o,logs:r}}}static walkPageTree(e,n,r,o,i,s,a){let c=e.entries.get("Type"),l=this.extractName(c);if(l==="Pages"){let d=e.entries.get("Kids");if(!d)return i.push(`[WARN] Pages node has no /Kids at ${n.objNum} ${n.genNum} R`),a;let m=this.extractArray(d);if(!m)return i.push("[WARN] /Kids is not an array"),a;i.push(`[NODE] Pages node with ${m.length} child(ren) at ${n.objNum}`);for(let h of m){if(!Be(h)){i.push("[WARN] /Kids contains non-reference");continue}let f=h,p=`${f.objNum}.${f.genNum}`,w=r.objectCache.get(p);if((!w||!Q(w))&&s.objectLoader)try{w=s.objectLoader(f),i.push(`[NODE] Loaded child page node ${f.objNum} ${f.genNum} R from file`)}catch(y){let v=y instanceof Error?y.message:String(y);i.push(`[WARN] Failed to load child node: ${v}`)}if(!w||!Q(w)){i.push(`[SKIP] Child page node not in cache: ${f.objNum} ${f.genNum} R`),i.push("[NOTE] Would need ObjectReader to load from file");continue}if(a=this.walkPageTree(w,f,r,o,i,s,a),s.maxPages&&o.length>=s.maxPages)return a}return a}else if(l==="Page"){i.push(`[PAGE ${a}] Found at ${n.objNum} ${n.genNum} R`);let d=this.extractContentStreams(e,r,i,s);i.push(`[PAGE ${a}] \u2713 Found ${d.length} stream(s)`);let m=this.extractMediaBox(e),h=this.extractResources(e,r,i,s),f=this.extractNumber(e.entries.get("Rotate"));return o.push({pageNum:a,ref:n,dict:e,contentStreams:d,mediaBox:m||[0,0,612,792],resources:h,rotate:f||0}),a+1}else return i.push(`[WARN] Unknown node type: ${l}`),a}static extractContentStreams(e,n,r,o){let i=[];try{let s=e.entries.get("Contents");if(!s)return r.push("[WARN] Page has no /Contents"),i;if(fe(s))i.push(s);else if(Be(s)){let a=s,c=`${a.objNum}.${a.genNum}`,l=n.objectCache.get(c);if((!l||!fe(l))&&o.objectLoader)try{l=o.objectLoader(a),r.push(`[STREAM] Loaded content stream ${a.objNum} ${a.genNum} R from file`)}catch(d){let m=d instanceof Error?d.message:String(d);r.push(`[WARN] Failed to load content stream ${a.objNum} ${a.genNum} R: ${m}`)}l&&fe(l)?i.push(l):r.push(`[STREAM] Content stream reference not cached: ${a.objNum} ${a.genNum} R`)}else if(he(s)){let a=this.extractArray(s);if(a){for(let c of a)if(fe(c))i.push(c);else if(Be(c)){let l=c,d=`${l.objNum}.${l.genNum}`,m=n.objectCache.get(d);if((!m||!fe(m))&&o.objectLoader)try{m=o.objectLoader(l),r.push(`[STREAM] Loaded content stream ${l.objNum} ${l.genNum} R from file`)}catch(h){let f=h instanceof Error?h.message:String(h);r.push(`[WARN] Failed to load content stream ${l.objNum} ${l.genNum} R: ${f}`)}m&&fe(m)?i.push(m):r.push(`[STREAM] Content stream reference not cached: ${l.objNum} ${l.genNum} R`)}}}}catch(s){r.push(`[ERROR] Failed to extract content streams: ${s instanceof Error?s.message:String(s)}`)}return i}static extractMediaBox(e){let n=e.entries.get("MediaBox");if(n&&he(n)){let r=this.extractArray(n);if(r&&r.length>=4){let o=r.slice(0,4).map(i=>this.extractNumber(i));if(o.every(i=>i!==null))return o}}return null}static extractResources(e,n,r,o){let i=e.entries.get("Resources");if(i&&Q(i))return i;if(i&&Be(i)){let s=i,a=`${s.objNum}.${s.genNum}`,c=n.objectCache.get(a);if((!c||!Q(c))&&o.objectLoader)try{c=o.objectLoader(s),r.push(`[RESOURCES] Loaded resources ${s.objNum} ${s.genNum} R from file`)}catch(l){let d=l instanceof Error?l.message:String(l);r.push(`[WARN] Failed to load resources ${s.objNum} ${s.genNum} R: ${d}`)}if(c&&Q(c))return c;r.push(`[RESOURCES] Reference to resources not in cache: ${s.objNum} ${s.genNum} R`)}}static extractName(e){return!e||typeof e!="object"||!("type"in e)?null:e.type==="name"?e.value:null}static extractArray(e){return!e||typeof e!="object"||!("type"in e)?null:e.type==="array"?e.items||[]:null}static extractNumber(e){return q(e)}};var Pa=new Set(["show_string","show_strings","next_line_show_string"]),Sa=t=>t==="show_string"?"() Tj":t==="show_strings"?"[] TJ":"() '",Da=(t,e)=>{if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0};async function gi(t,e){let n=new Kt(t),r=n.parse(),i=Wn.getAllPages(r,{objectLoader:h=>n.loadObject(h)}).pages[e];if(!i)throw new Error(`Page ${e+1} not found`);let s=ar(i.dict.entries.get("Contents"));if(s.length===0)throw new Error("Page has no content streams");let a=[];for(let h of s){let f=n.loadObject(h);if(!fe(f))continue;let p=f.decode?await f.decode():await we.decodeStream(f);a.push({objNum:h.objNum,genNum:h.genNum,bytes:p})}if(a.length===0)throw new Error("Page content streams could not be decoded");let c=a.reduce((h,f)=>h+f.bytes.length,0)+Math.max(0,a.length-1),l=new Uint8Array(c),d=[],m=0;for(let h=0;h<a.length;h++)l.set(a[h].bytes,m),d.push({start:m,end:m+a[h].bytes.length}),m+=a[h].bytes.length,h<a.length-1&&(l[m]=32,m+=1);return{chunks:a,pristine:l,chunkSpans:d}}var Ca=(t,e)=>t.chunks.map((n,r)=>{let o=new Uint8Array(e.subarray(t.chunkSpans[r].start,t.chunkSpans[r].end));return{objNum:n.objNum,genNum:n.genNum,bytes:o,changed:!Da(o,n.bytes)}});async function Fa(t,e,n,r){let o=await gi(t,e);if(r&&r.length!==o.pristine.length)throw new Error("Stale rewrite state for page");let{commands:i,ranges:s}=Yn(o.pristine),a=new Uint8Array(r!=null?r:o.pristine);for(let c of n){let l=i[c],d=s[c];if(!l||!d)throw new Error(`No operator at index ${c}`);if(!Pa.has(l.op))throw new Error(`Operator ${l.op} at index ${c} is not rewritable`);if(!o.chunkSpans.some(f=>d.start>=f.start&&d.end<=f.end))throw new Error(`Operator at index ${c} spans multiple content streams`);let h=Sa(l.op);if(d.end-d.start<h.length)throw new Error(`Operator span too small at index ${c}`);a.fill(32,d.start,d.end);for(let f=0;f<h.length;f++)a[d.start+f]=h.charCodeAt(f)}return{streams:Ca(o,a),combined:a}}var xu=t=>{let e=t.toFixed(6).replace(/\.?0+$/,"");return e===""||e==="-"?"0":e};async function Ma(t,e,n,r,o){var b;let i=await gi(t,e);if(o&&o.length!==i.pristine.length)throw new Error("Stale rewrite state for page");if(!r.every(Number.isFinite))throw new Error("Non-finite transform matrix");let{commands:s,ranges:a}=Yn(i.pristine);if(n.start<0||n.end<n.start||n.end>=s.length)throw new Error(`Invalid operator span ${n.start}..${n.end}`);let c=0;for(let C=n.start;C<=n.end;C++){let S=(b=s[C])==null?void 0:b.op;if(S==="save_state")c+=1;else if(S==="restore_state"&&(c-=1,c<0))throw new Error("Span restores state it did not save")}if(c!==0)throw new Error("Span has unbalanced q/Q");let l=a[n.start].start,d=a[n.end].end,m=i.chunkSpans.findIndex(C=>l>=C.start&&d<=C.end);if(m<0)throw new Error("Span crosses content-stream chunk boundaries");let h=o!=null?o:i.pristine,f=new TextEncoder().encode(`
|
|
3
|
+
q ${r.map(xu).join(" ")} cm
|
|
4
4
|
`),p=new TextEncoder().encode(`
|
|
5
5
|
Q
|
|
6
|
-
`),w=new Uint8Array(h.length+f.length+p.length);w.set(h.subarray(0,l),0),w.set(f,l),w.set(h.subarray(l,d),l+f.length),w.set(p,l+f.length+(d-l)),w.set(h.subarray(d),l+f.length+(d-l)+p.length);let b=f.length+p.length;return{streams:i.chunks.map((C,S)=>{let F=i.chunkSpans[S].start,O=i.chunkSpans[S].end;S===m?O+=b:S>m&&(F+=b,O+=b);let N=new Uint8Array(w.subarray(F,O));return{objNum:C.objNum,genNum:C.genNum,bytes:N,changed:!Sa(N,C.bytes)}}),combined:w,lengthChanged:!0}}var xu=new Set(["save_state","restore_state","set_ctm","set_graphics_state","set_line_width","set_line_cap","set_line_join","set_miter_limit","set_dash","set_rendering_intent","set_fill_color_rgb","set_stroke_color_rgb","set_fill_gray","set_stroke_gray","set_fill_cmyk","set_stroke_cmyk","set_fill_color","set_stroke_color","set_fill_color_space","set_stroke_color_space","begin_text","end_text","set_font","move_text","move_text_set_leading","set_text_matrix","next_line","set_char_spacing","set_word_spacing","set_horiz_scale","set_leading","set_text_render","set_text_rise","begin_marked_content","end_marked_content","type3_glyph_width"]);async function Ma(t,e,n,r){let o=await pi(t,e);if(r&&r.length!==o.pristine.length)throw new Error("Stale rewrite state for page");let{commands:i,ranges:s}=zn(o.pristine),a=new Uint8Array(r!=null?r:o.pristine),c=l=>{let d=s[l];if(!o.chunkSpans.some(h=>d.start>=h.start&&d.end<=h.end))throw new Error(`Operator at index ${l} spans multiple content streams`);a.fill(32,d.start,d.end)};for(let l of n){if(l.start<0||l.end<l.start||l.end>=i.length)throw new Error(`Invalid operator span ${l.start}..${l.end}`);let d=0;for(let m=l.start;m<=l.end;m++){let h=i[m],f=s[m];if(!h||!f)throw new Error(`No operator at index ${m}`);if(h.op==="save_state"){d+=1;continue}if(h.op==="restore_state"){d-=1;continue}if(!xu.has(h.op)){if(h.op==="clip"||h.op==="clip_even_odd"){if(d<=0)throw new Error("Span contains a clip that outlives it");c(m);continue}if(h.op==="set_spacing_next_line_show_string")throw new Error('Span contains a " operator (spacing side effects)');if(ka.has(h.op)){let p=Pa(h.op);if(f.end-f.start<p.length)throw new Error(`Operator span too small at index ${m}`);c(m);for(let w=0;w<p.length;w++)a[f.start+w]=p.charCodeAt(w);continue}c(m)}}}return{streams:Da(o,a),combined:a}}var Ra=["view","annotate"],Aa=["view","annotate","edit-text","sign","redact","forms","export-clean"];import{ed25519 as bu}from"@noble/curves/ed25519";var Na="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",ar={};for(let t=0;t<Na.length;t++)ar[Na[t]]=t;function Ta(t){return new TextDecoder().decode(t)}function Oa(t){let e=t.trim(),n=new Uint8Array(e.length>>1);for(let r=0;r<n.length;r++)n[r]=parseInt(e.substr(r*2,2),16);return n}function Ea(t){let e=[];for(let n=0;n<t.length;n+=4){let r=ar[t[n]],o=ar[t[n+1]];if(r===void 0||o===void 0)break;e.push(r<<2|o>>4);let i=ar[t[n+2]];if(i===void 0)break;e.push((o&15)<<4|i>>2);let s=ar[t[n+3]];if(s===void 0)break;e.push((i&3)<<6|s)}return new Uint8Array(e)}function Ia(t,e){let n=t.indexOf(".");if(n<0)return null;try{let r=Ea(t.slice(0,n)),o=Ea(t.slice(n+1));return bu.verify(o,r,e)?r:null}catch{return null}}var cr="bde297640169e8f75d2d9bd260e8eab78aa93c39e10c84a8f6abe565a19057e3";function ja(t,e){if(!t||/^0+$/.test(e))return null;let n=Ia(t,Oa(e));if(!n)return null;try{return JSON.parse(Ta(n))}catch{return null}}function Qr(t,e=cr){let n=ja(t,e);return!n||typeof n.lid!="string"||!Array.isArray(n.features)?null:n}function eo(t,e=cr){let n=ja(t,e);return!n||typeof n.lid!="string"||!Array.isArray(n.features)?null:n}function gi(t,e){return t===0||t*1e3>e}function $a(t,e){if(!e||e==="localhost"||e==="127.0.0.1"||e==="::1")return!0;let n=e.toLowerCase();return t.some(r=>{let o=r.trim().toLowerCase();return o==="*"||o===n?!0:n.endsWith("."+o)})}var xi="NamahaPDF \xB7 Unlicensed SDK";function bi(t,e,n,r=xi){t.save(),t.globalAlpha=.16,t.fillStyle="#C20E3A";let o=Math.max(14,Math.round(Math.min(e,n)/22));t.font=`600 ${o}px Inter, system-ui, sans-serif`,t.textAlign="center",t.textBaseline="middle";let i=o*9;t.translate(e/2,n/2),t.rotate(-28*Math.PI/180);for(let s=-n;s<n;s+=i*.5)for(let a=-e;a<e;a+=i)t.fillText(r,a,s);t.restore()}async function yi(t,e=xi){try{let{PDFDocument:n,StandardFonts:r,rgb:o,degrees:i}=await import("pdf-lib"),s=await n.load(t,{ignoreEncryption:!0}),a=await s.embedFont(r.HelveticaBold),c=o(.76,.055,.227);for(let l of s.getPages()){let{width:d,height:m}=l.getSize(),h=Math.max(16,Math.min(d,m)/26),f=h*6,p=a.widthOfTextAtSize(e,h)+h*4;for(let w=-m;w<m*2;w+=f)for(let b=-d;b<d*2;b+=p)l.drawText(e,{x:b,y:w,size:h,font:a,color:c,opacity:.14,rotate:i(28)})}return await s.save()}catch{return t}}var La=5,yu=4320*60*1e3,wu=4320*60*1e3,vu="/api/license/activate",Ee={publicKeyHex:cr,now:()=>Date.now()},xt=null,to=[];function ku(){let t=new Map;return{getItem:e=>{var n;return(n=t.get(e))!=null?n:null},setItem:(e,n)=>{t.set(e,n)}}}function Pu(t){if(t.storage)return t.storage;try{if(typeof localStorage!="undefined")return localStorage}catch{}return ku()}function Ua(t){if(t.host)return t.host;try{if(typeof location!="undefined")return location.hostname}catch{}return""}function _a(t){return`namaha.lic.${t}`}function Xa(t){try{let e=xt==null?void 0:xt.getItem(_a(t));if(e)return JSON.parse(e)}catch{}return{failCount:0,firstSeen:Ee.now(),lastAttempt:0}}function vi(t,e){try{xt==null||xt.setItem(_a(t),JSON.stringify(e))}catch{}}function Su(){if(Ee.deviceId)return Ee.deviceId;let t="namaha.lic.device";try{let n=xt==null?void 0:xt.getItem(t);if(n)return n}catch{}let e="dev_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{xt==null||xt.setItem(t,e)}catch{}return e}function Fn(){let t=Ee.now();if(Ee.owner)return{status:"LICENSED",edition:"enterprise",features:Aa,watermark:!1,reason:"owner"};if(!Ee.licenseKey)return c("UNLICENSED","no key");let e=Qr(Ee.licenseKey,Ee.publicKeyHex);if(!e)return c("INVALID","bad signature");if(!gi(e.exp,t))return c("INVALID","key expired");if(!$a(e.domains,Ua(Ee)))return c("INVALID","domain not allowed");let n=Xa(e.lid);if(n.revoked)return c("DEGRADED","revoked");let r=n.token?eo(n.token,Ee.publicKeyHex):null;if(r&&r.lid===e.lid&&gi(r.exp,t))return l("LICENSED",r.edition,r.features,"active token");let o=r?r.exp*1e3:n.firstSeen,i=r?wu:yu,s=t-o<i,a=n.failCount<La;if(s||a)return l("GRACE",e.edition,e.features,"grace");return c("DEGRADED","grace exhausted");function c(d,m){return{status:d,edition:null,features:Ra.slice(),watermark:!0,reason:m}}function l(d,m,h,f){return{status:d,edition:m,features:h.slice(),watermark:!1,reason:f}}}function ki(){let t=Fn();for(let e of to)try{e(t)}catch{}}async function Du(){var s,a;if(Ee.owner||!Ee.licenseKey)return;let t=Qr(Ee.licenseKey,Ee.publicKeyHex);if(!t)return;let e=(s=Ee.activationUrl)!=null?s:vu,n=(a=Ee.fetchImpl)!=null?a:typeof fetch!="undefined"?fetch:null;if(!n)return;let r=Ua(Ee),o=Su(),i=Xa(t.lid);try{let c=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({licenseKey:Ee.licenseKey,origin:r,deviceId:o})}),l=await c.json().catch(()=>({}));if(l.status==="revoked"||l.status==="invalid"){vi(t.lid,{...i,revoked:!0,lastAttempt:Ee.now()}),ki();return}if(c.ok&&l.status==="active"&&l.token&&eo(l.token,Ee.publicKeyHex)){vi(t.lid,{...i,token:l.token,failCount:0,lastAttempt:Ee.now(),revoked:!1}),ki();return}Ba(t.lid,i)}catch{Ba(t.lid,i)}}function Ba(t,e){vi(t,{...e,failCount:Math.min(La,e.failCount+1),lastAttempt:Ee.now()}),ki()}function Pi(t={}){Ee={publicKeyHex:cr,now:()=>Date.now(),...t},xt=Pu(t);let e=Fn();return Cu(),e}var wi=!1;async function Cu(){var e;if(wi||Ee.owner||!Ee.licenseKey)return;wi=!0;let t=(e=Ee.retryDelays)!=null?e:[0,2e3,6e3,2e4];try{for(let n=0;n<t.length;n++){t[n]>0&&await Fu(t[n]);let r=Fn();if(r.status==="LICENSED"&&r.reason==="active token"||r.status==="DEGRADED"||r.status==="INVALID"||r.status==="UNLICENSED")break;await Du();let o=Fn();if(o.status==="LICENSED"||o.status==="DEGRADED")break}}finally{wi=!1}}function Fu(t){return new Promise(e=>setTimeout(e,t))}function Mu(){return Fn()}function za(t){return Fn().features.includes(t)}function Ya(t){if(!za(t))throw new Error(`NamahaPDF: feature "${t}" requires a license. See namahapdf.com/sdk.`)}function no(){return Fn().watermark}function Ru(t){return to.push(t),()=>{to=to.filter(e=>e!==t)}}import{PDFName as qa,PDFString as ln}from"pdf-lib";var Di=t=>t.kind==="highlight"||t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly",Au=t=>t.kind==="rect"||t.kind==="ellipse"||t.kind==="line"||t.kind==="arrow"||t.kind==="polygon"||t.kind==="polyline",Si=t=>{let e=t.map(i=>i.x),n=t.map(i=>i.y),r=Math.min(...e),o=Math.min(...n);return{x:r,y:o,width:Math.max(...e)-r,height:Math.max(...n)-o}},at=t=>{if(Di(t)){let e=[];for(let n of t.quads)e.push({x:n.x,y:n.y},{x:n.x+n.width,y:n.y+n.height});return e.length?Si(e):{x:0,y:0,width:0,height:0}}if(t.kind==="ink"){let e=t.strokes.flat();return e.length?Si(e):{x:0,y:0,width:0,height:0}}return t.kind==="note"||t.kind==="freetext"?{...t.rect}:Si(t.points)},Nu=(t,e,n,r)=>t>=n.x-r&&t<=n.x+n.width+r&&e>=n.y-r&&e<=n.y+n.height+r,Wa=(t,e,n)=>{let r=n.x-e.x,o=n.y-e.y,i=r*r+o*o;if(i===0)return Math.hypot(t.x-e.x,t.y-e.y);let s=((t.x-e.x)*r+(t.y-e.y)*o)/i;return s=Math.max(0,Math.min(1,s)),Math.hypot(t.x-(e.x+s*r),t.y-(e.y+s*o))},Ga=(t,e,n=4)=>{var o;let r=Math.max(n,((o=e.style.strokeWidth)!=null?o:0)/2+2);if((e.kind==="line"||e.kind==="arrow"||e.kind==="polyline")&&Au(e)){for(let i=0;i<e.points.length-1;i++)if(Wa(t,e.points[i],e.points[i+1])<=r)return!0;return!1}if(e.kind==="ink"){for(let i of e.strokes){for(let s=0;s<i.length-1;s++)if(Wa(t,i[s],i[s+1])<=r)return!0;if(i.length===1&&Math.hypot(t.x-i[0].x,t.y-i[0].y)<=r)return!0}return!1}return Nu(t.x,t.y,at(e),n)},Ka=(t,e,n)=>{if(Di(t))return{...t,quads:t.quads.map(o=>({...o,x:o.x+e,y:o.y+n,baselineY:o.baselineY+n}))};if(t.kind==="ink")return{...t,strokes:t.strokes.map(o=>o.map(i=>({x:i.x+e,y:i.y+n})))};if(t.kind==="note"||t.kind==="freetext")return{...t,rect:{...t.rect,x:t.rect.x+e,y:t.rect.y+n}};let r=t;return{...r,points:r.points.map(o=>({x:o.x+e,y:o.y+n}))}},Ha=(t,e,n,r,o)=>n<=0?r:r+(t-e)/n*o,Va=(t,e)=>{let n=at(t),r=s=>Ha(s,n.x,n.width,e.x,e.width),o=s=>Ha(s,n.y,n.height,e.y,e.height);if(Di(t))return{...t,quads:t.quads.map(s=>{let a=r(s.x),c=o(s.y);return{x:a,y:c,width:r(s.x+s.width)-a,height:o(s.y+s.height)-c,baselineY:o(s.baselineY)}})};if(t.kind==="ink")return{...t,strokes:t.strokes.map(s=>s.map(a=>({x:r(a.x),y:o(a.y)})))};if(t.kind==="note"||t.kind==="freetext")return{...t,rect:{x:e.x,y:e.y,width:e.width,height:e.height}};let i=t;return{...i,points:i.points.map(s=>({x:r(s.x),y:o(s.y)}))}};var lr=1.5,oe=t=>{let e=Math.round(t*1e3)/1e3;return Object.is(e,-0)?"0":String(e)},Mn=t=>[Math.min(1,Math.max(0,t.r)),Math.min(1,Math.max(0,t.g)),Math.min(1,Math.max(0,t.b))],Ja=t=>{let e=new Date(t),n=r=>String(r).padStart(2,"0");return`D:${e.getFullYear()}${n(e.getMonth()+1)}${n(e.getDate())}${n(e.getHours())}${n(e.getMinutes())}${n(e.getSeconds())}`},Qa=(t,e)=>({x:t.x-e,y:t.y-e,width:t.width+e*2,height:t.height+e*2}),Za=t=>[t.x,t.y,t.x+t.width,t.y+t.height],Wn=t=>{var i;let[e,n,r]=Mn(t.color),o=(i=t.strokeWidth)!=null?i:lr;return`${oe(o)} w 1 J 1 j ${oe(e)} ${oe(n)} ${oe(r)} RG`},ro=t=>{let[e,n,r]=Mn(t);return`${oe(e)} ${oe(n)} ${oe(r)} rg`},Ci=t=>{var r;let e=!!t.fill,n=((r=t.strokeWidth)!=null?r:lr)>0;return e&&n?"B":e?"f":"S"},Eu=t=>{let n=t.x+t.width/2,r=t.y+t.height/2,o=t.width/2,i=t.height/2;return[`${oe(n+o)} ${oe(r)} m`,`${oe(n+o)} ${oe(r+i*.5523)} ${oe(n+o*.5523)} ${oe(r+i)} ${oe(n)} ${oe(r+i)} c`,`${oe(n-o*.5523)} ${oe(r+i)} ${oe(n-o)} ${oe(r+i*.5523)} ${oe(n-o)} ${oe(r)} c`,`${oe(n-o)} ${oe(r-i*.5523)} ${oe(n-o*.5523)} ${oe(r-i)} ${oe(n)} ${oe(r-i)} c`,`${oe(n+o*.5523)} ${oe(r-i)} ${oe(n+o)} ${oe(r-i*.5523)} ${oe(n+o)} ${oe(r)} c`].join(`
|
|
7
|
-
`)},
|
|
8
|
-
`)},
|
|
6
|
+
`),w=new Uint8Array(h.length+f.length+p.length);w.set(h.subarray(0,l),0),w.set(f,l),w.set(h.subarray(l,d),l+f.length),w.set(p,l+f.length+(d-l)),w.set(h.subarray(d),l+f.length+(d-l)+p.length);let y=f.length+p.length;return{streams:i.chunks.map((C,S)=>{let F=i.chunkSpans[S].start,T=i.chunkSpans[S].end;S===m?T+=y:S>m&&(F+=y,T+=y);let N=new Uint8Array(w.subarray(F,T));return{objNum:C.objNum,genNum:C.genNum,bytes:N,changed:!Da(N,C.bytes)}}),combined:w,lengthChanged:!0}}var bu=new Set(["save_state","restore_state","set_ctm","set_graphics_state","set_line_width","set_line_cap","set_line_join","set_miter_limit","set_dash","set_rendering_intent","set_fill_color_rgb","set_stroke_color_rgb","set_fill_gray","set_stroke_gray","set_fill_cmyk","set_stroke_cmyk","set_fill_color","set_stroke_color","set_fill_color_space","set_stroke_color_space","begin_text","end_text","set_font","move_text","move_text_set_leading","set_text_matrix","next_line","set_char_spacing","set_word_spacing","set_horiz_scale","set_leading","set_text_render","set_text_rise","begin_marked_content","end_marked_content","type3_glyph_width"]);async function Ra(t,e,n,r){let o=await gi(t,e);if(r&&r.length!==o.pristine.length)throw new Error("Stale rewrite state for page");let{commands:i,ranges:s}=Yn(o.pristine),a=new Uint8Array(r!=null?r:o.pristine),c=l=>{let d=s[l];if(!o.chunkSpans.some(h=>d.start>=h.start&&d.end<=h.end))throw new Error(`Operator at index ${l} spans multiple content streams`);a.fill(32,d.start,d.end)};for(let l of n){if(l.start<0||l.end<l.start||l.end>=i.length)throw new Error(`Invalid operator span ${l.start}..${l.end}`);let d=0;for(let m=l.start;m<=l.end;m++){let h=i[m],f=s[m];if(!h||!f)throw new Error(`No operator at index ${m}`);if(h.op==="save_state"){d+=1;continue}if(h.op==="restore_state"){d-=1;continue}if(!bu.has(h.op)){if(h.op==="clip"||h.op==="clip_even_odd"){if(d<=0)throw new Error("Span contains a clip that outlives it");c(m);continue}if(h.op==="set_spacing_next_line_show_string")throw new Error('Span contains a " operator (spacing side effects)');if(Pa.has(h.op)){let p=Sa(h.op);if(f.end-f.start<p.length)throw new Error(`Operator span too small at index ${m}`);c(m);for(let w=0;w<p.length;w++)a[f.start+w]=p.charCodeAt(w);continue}c(m)}}}return{streams:Ca(o,a),combined:a}}var Aa=["view","annotate"],Na=["view","annotate","edit-text","sign","redact","forms","export-clean"];import{ed25519 as yu}from"@noble/curves/ed25519";var Ea="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",cr={};for(let t=0;t<Ea.length;t++)cr[Ea[t]]=t;function Oa(t){return new TextDecoder().decode(t)}function Ia(t){let e=t.trim(),n=new Uint8Array(e.length>>1);for(let r=0;r<n.length;r++)n[r]=parseInt(e.substr(r*2,2),16);return n}function Ta(t){let e=[];for(let n=0;n<t.length;n+=4){let r=cr[t[n]],o=cr[t[n+1]];if(r===void 0||o===void 0)break;e.push(r<<2|o>>4);let i=cr[t[n+2]];if(i===void 0)break;e.push((o&15)<<4|i>>2);let s=cr[t[n+3]];if(s===void 0)break;e.push((i&3)<<6|s)}return new Uint8Array(e)}function ja(t,e){let n=t.indexOf(".");if(n<0)return null;try{let r=Ta(t.slice(0,n)),o=Ta(t.slice(n+1));return yu.verify(o,r,e)?r:null}catch{return null}}var lr="bde297640169e8f75d2d9bd260e8eab78aa93c39e10c84a8f6abe565a19057e3";function $a(t,e){if(!t||/^0+$/.test(e))return null;let n=ja(t,Ia(e));if(!n)return null;try{return JSON.parse(Oa(n))}catch{return null}}function eo(t,e=lr){let n=$a(t,e);return!n||typeof n.lid!="string"||!Array.isArray(n.features)?null:n}function to(t,e=lr){let n=$a(t,e);return!n||typeof n.lid!="string"||!Array.isArray(n.features)?null:n}function xi(t,e){return t===0||t*1e3>e}function Ba(t,e){if(!e||e==="localhost"||e==="127.0.0.1"||e==="::1")return!0;let n=e.toLowerCase();return t.some(r=>{let o=r.trim().toLowerCase();return o==="*"||o===n?!0:n.endsWith("."+o)})}var bi="NamahaPDF \xB7 Unlicensed SDK";function yi(t,e,n,r=bi){t.save(),t.globalAlpha=.16,t.fillStyle="#C20E3A";let o=Math.max(14,Math.round(Math.min(e,n)/22));t.font=`600 ${o}px Inter, system-ui, sans-serif`,t.textAlign="center",t.textBaseline="middle";let i=o*9;t.translate(e/2,n/2),t.rotate(-28*Math.PI/180);for(let s=-n;s<n;s+=i*.5)for(let a=-e;a<e;a+=i)t.fillText(r,a,s);t.restore()}async function wi(t,e=bi){try{let{PDFDocument:n,StandardFonts:r,rgb:o,degrees:i}=await import("pdf-lib"),s=await n.load(t,{ignoreEncryption:!0}),a=await s.embedFont(r.HelveticaBold),c=o(.76,.055,.227);for(let l of s.getPages()){let{width:d,height:m}=l.getSize(),h=Math.max(16,Math.min(d,m)/26),f=h*6,p=a.widthOfTextAtSize(e,h)+h*4;for(let w=-m;w<m*2;w+=f)for(let y=-d;y<d*2;y+=p)l.drawText(e,{x:y,y:w,size:h,font:a,color:c,opacity:.14,rotate:i(28)})}return await s.save()}catch{return t}}var Ua=5,wu=4320*60*1e3,vu=4320*60*1e3,ku="/api/license/activate",Ee={publicKeyHex:lr,now:()=>Date.now()},xt=null,no=[];function Pu(){let t=new Map;return{getItem:e=>{var n;return(n=t.get(e))!=null?n:null},setItem:(e,n)=>{t.set(e,n)}}}function Su(t){if(t.storage)return t.storage;try{if(typeof localStorage!="undefined")return localStorage}catch{}return Pu()}function _a(t){if(t.host)return t.host;try{if(typeof location!="undefined")return location.hostname}catch{}return""}function Xa(t){return`namaha.lic.${t}`}function za(t){try{let e=xt==null?void 0:xt.getItem(Xa(t));if(e)return JSON.parse(e)}catch{}return{failCount:0,firstSeen:Ee.now(),lastAttempt:0}}function ki(t,e){try{xt==null||xt.setItem(Xa(t),JSON.stringify(e))}catch{}}function Du(){if(Ee.deviceId)return Ee.deviceId;let t="namaha.lic.device";try{let n=xt==null?void 0:xt.getItem(t);if(n)return n}catch{}let e="dev_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{xt==null||xt.setItem(t,e)}catch{}return e}function Fn(){let t=Ee.now();if(Ee.owner)return{status:"LICENSED",edition:"enterprise",features:Na,watermark:!1,reason:"owner"};if(!Ee.licenseKey)return c("UNLICENSED","no key");let e=eo(Ee.licenseKey,Ee.publicKeyHex);if(!e)return c("INVALID","bad signature");if(!xi(e.exp,t))return c("INVALID","key expired");if(!Ba(e.domains,_a(Ee)))return c("INVALID","domain not allowed");let n=za(e.lid);if(n.revoked)return c("DEGRADED","revoked");let r=n.token?to(n.token,Ee.publicKeyHex):null;if(r&&r.lid===e.lid&&xi(r.exp,t))return l("LICENSED",r.edition,r.features,"active token");let o=r?r.exp*1e3:n.firstSeen,i=r?vu:wu,s=t-o<i,a=n.failCount<Ua;if(s||a)return l("GRACE",e.edition,e.features,"grace");return c("DEGRADED","grace exhausted");function c(d,m){return{status:d,edition:null,features:Aa.slice(),watermark:!0,reason:m}}function l(d,m,h,f){return{status:d,edition:m,features:h.slice(),watermark:!1,reason:f}}}function Pi(){let t=Fn();for(let e of no)try{e(t)}catch{}}async function Cu(){var s,a;if(Ee.owner||!Ee.licenseKey)return;let t=eo(Ee.licenseKey,Ee.publicKeyHex);if(!t)return;let e=(s=Ee.activationUrl)!=null?s:ku,n=(a=Ee.fetchImpl)!=null?a:typeof fetch!="undefined"?fetch:null;if(!n)return;let r=_a(Ee),o=Du(),i=za(t.lid);try{let c=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({licenseKey:Ee.licenseKey,origin:r,deviceId:o})}),l=await c.json().catch(()=>({}));if(l.status==="revoked"||l.status==="invalid"){ki(t.lid,{...i,revoked:!0,lastAttempt:Ee.now()}),Pi();return}if(c.ok&&l.status==="active"&&l.token&&to(l.token,Ee.publicKeyHex)){ki(t.lid,{...i,token:l.token,failCount:0,lastAttempt:Ee.now(),revoked:!1}),Pi();return}La(t.lid,i)}catch{La(t.lid,i)}}function La(t,e){ki(t,{...e,failCount:Math.min(Ua,e.failCount+1),lastAttempt:Ee.now()}),Pi()}function Si(t={}){Ee={publicKeyHex:lr,now:()=>Date.now(),...t},xt=Su(t);let e=Fn();return Fu(),e}var vi=!1;async function Fu(){var e;if(vi||Ee.owner||!Ee.licenseKey)return;vi=!0;let t=(e=Ee.retryDelays)!=null?e:[0,2e3,6e3,2e4];try{for(let n=0;n<t.length;n++){t[n]>0&&await Mu(t[n]);let r=Fn();if(r.status==="LICENSED"&&r.reason==="active token"||r.status==="DEGRADED"||r.status==="INVALID"||r.status==="UNLICENSED")break;await Cu();let o=Fn();if(o.status==="LICENSED"||o.status==="DEGRADED")break}}finally{vi=!1}}function Mu(t){return new Promise(e=>setTimeout(e,t))}function Ru(){return Fn()}function Ya(t){return Fn().features.includes(t)}function Wa(t){if(!Ya(t))throw new Error(`NamahaPDF: feature "${t}" requires a license. See namahapdf.com/sdk.`)}function ro(){return Fn().watermark}function Au(t){return no.push(t),()=>{no=no.filter(e=>e!==t)}}import{PDFName as Ja,PDFString as dn}from"pdf-lib";var Ci=t=>t.kind==="highlight"||t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly",Nu=t=>t.kind==="rect"||t.kind==="ellipse"||t.kind==="line"||t.kind==="arrow"||t.kind==="polygon"||t.kind==="polyline",Di=t=>{let e=t.map(i=>i.x),n=t.map(i=>i.y),r=Math.min(...e),o=Math.min(...n);return{x:r,y:o,width:Math.max(...e)-r,height:Math.max(...n)-o}},ct=t=>{if(Ci(t)){let e=[];for(let n of t.quads)e.push({x:n.x,y:n.y},{x:n.x+n.width,y:n.y+n.height});return e.length?Di(e):{x:0,y:0,width:0,height:0}}if(t.kind==="ink"){let e=t.strokes.flat();return e.length?Di(e):{x:0,y:0,width:0,height:0}}return t.kind==="note"||t.kind==="freetext"?{...t.rect}:Di(t.points)},Eu=(t,e,n,r)=>t>=n.x-r&&t<=n.x+n.width+r&&e>=n.y-r&&e<=n.y+n.height+r,Ha=(t,e,n)=>{let r=n.x-e.x,o=n.y-e.y,i=r*r+o*o;if(i===0)return Math.hypot(t.x-e.x,t.y-e.y);let s=((t.x-e.x)*r+(t.y-e.y)*o)/i;return s=Math.max(0,Math.min(1,s)),Math.hypot(t.x-(e.x+s*r),t.y-(e.y+s*o))},Ka=(t,e,n=4)=>{var o;let r=Math.max(n,((o=e.style.strokeWidth)!=null?o:0)/2+2);if((e.kind==="line"||e.kind==="arrow"||e.kind==="polyline")&&Nu(e)){for(let i=0;i<e.points.length-1;i++)if(Ha(t,e.points[i],e.points[i+1])<=r)return!0;return!1}if(e.kind==="ink"){for(let i of e.strokes){for(let s=0;s<i.length-1;s++)if(Ha(t,i[s],i[s+1])<=r)return!0;if(i.length===1&&Math.hypot(t.x-i[0].x,t.y-i[0].y)<=r)return!0}return!1}return Eu(t.x,t.y,ct(e),n)},Va=(t,e,n)=>{if(Ci(t))return{...t,quads:t.quads.map(o=>({...o,x:o.x+e,y:o.y+n,baselineY:o.baselineY+n}))};if(t.kind==="ink")return{...t,strokes:t.strokes.map(o=>o.map(i=>({x:i.x+e,y:i.y+n})))};if(t.kind==="note"||t.kind==="freetext")return{...t,rect:{...t.rect,x:t.rect.x+e,y:t.rect.y+n}};let r=t;return{...r,points:r.points.map(o=>({x:o.x+e,y:o.y+n}))}},Ga=(t,e,n,r,o)=>n<=0?r:r+(t-e)/n*o,qa=(t,e)=>{let n=ct(t),r=s=>Ga(s,n.x,n.width,e.x,e.width),o=s=>Ga(s,n.y,n.height,e.y,e.height);if(Ci(t))return{...t,quads:t.quads.map(s=>{let a=r(s.x),c=o(s.y);return{x:a,y:c,width:r(s.x+s.width)-a,height:o(s.y+s.height)-c,baselineY:o(s.baselineY)}})};if(t.kind==="ink")return{...t,strokes:t.strokes.map(s=>s.map(a=>({x:r(a.x),y:o(a.y)})))};if(t.kind==="note"||t.kind==="freetext")return{...t,rect:{x:e.x,y:e.y,width:e.width,height:e.height}};let i=t;return{...i,points:i.points.map(s=>({x:r(s.x),y:o(s.y)}))}};var dr=1.5,oe=t=>{let e=Math.round(t*1e3)/1e3;return Object.is(e,-0)?"0":String(e)},Mn=t=>[Math.min(1,Math.max(0,t.r)),Math.min(1,Math.max(0,t.g)),Math.min(1,Math.max(0,t.b))],Za=t=>{let e=new Date(t),n=r=>String(r).padStart(2,"0");return`D:${e.getFullYear()}${n(e.getMonth()+1)}${n(e.getDate())}${n(e.getHours())}${n(e.getMinutes())}${n(e.getSeconds())}`},ec=(t,e)=>({x:t.x-e,y:t.y-e,width:t.width+e*2,height:t.height+e*2}),Qa=t=>[t.x,t.y,t.x+t.width,t.y+t.height],Hn=t=>{var i;let[e,n,r]=Mn(t.color),o=(i=t.strokeWidth)!=null?i:dr;return`${oe(o)} w 1 J 1 j ${oe(e)} ${oe(n)} ${oe(r)} RG`},oo=t=>{let[e,n,r]=Mn(t);return`${oe(e)} ${oe(n)} ${oe(r)} rg`},Fi=t=>{var r;let e=!!t.fill,n=((r=t.strokeWidth)!=null?r:dr)>0;return e&&n?"B":e?"f":"S"},Tu=t=>{let n=t.x+t.width/2,r=t.y+t.height/2,o=t.width/2,i=t.height/2;return[`${oe(n+o)} ${oe(r)} m`,`${oe(n+o)} ${oe(r+i*.5523)} ${oe(n+o*.5523)} ${oe(r+i)} ${oe(n)} ${oe(r+i)} c`,`${oe(n-o*.5523)} ${oe(r+i)} ${oe(n-o)} ${oe(r+i*.5523)} ${oe(n-o)} ${oe(r)} c`,`${oe(n-o)} ${oe(r-i*.5523)} ${oe(n-o*.5523)} ${oe(r-i)} ${oe(n)} ${oe(r-i)} c`,`${oe(n+o*.5523)} ${oe(r-i)} ${oe(n+o)} ${oe(r-i*.5523)} ${oe(n+o)} ${oe(r)} c`].join(`
|
|
7
|
+
`)},Mi=(t,e)=>{let n=t.map((r,o)=>`${oe(r.x)} ${oe(r.y)} ${o===0?"m":"l"}`);return e&&n.push("h"),n.join(`
|
|
8
|
+
`)},Ou=(t,e,n)=>{let r=Math.atan2(e.y-t.y,e.x-t.x),o=Math.PI/7,i={x:e.x-n*Math.cos(r-o),y:e.y-n*Math.sin(r-o)},s={x:e.x-n*Math.cos(r+o),y:e.y-n*Math.sin(r+o)};return`${oe(i.x)} ${oe(i.y)} m ${oe(e.x)} ${oe(e.y)} l ${oe(s.x)} ${oe(s.y)} l S`},Iu=(t,e)=>{let o=[`${oe(t.x)} ${oe(e)} m`],i=!0;for(let s=t.x+4;s<=t.x+t.width;s+=4)o.push(`${oe(s)} ${oe(i?e+1.5:e-1.5)} l`),i=!i;return`${o.join(`
|
|
9
9
|
`)}
|
|
10
|
-
S`},
|
|
10
|
+
S`},ju=t=>{var s,a,c;let e=Math.max((s=t.style.strokeWidth)!=null?s:dr,2)+1,n=ec(ct(t),e);if(t.kind==="highlight"){let l=t.quads.map(d=>`${oe(d.x)} ${oe(d.y)} ${oe(d.width)} ${oe(d.height)} re`).join(`
|
|
11
11
|
`);return{content:`/GS0 gs
|
|
12
|
-
${
|
|
12
|
+
${oo(t.style.color)}
|
|
13
13
|
${l}
|
|
14
|
-
f`,bbox:n,multiply:!0}}if(t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly"){let l=Math.max(.75,(a=t.style.strokeWidth)!=null?a:1),d=t.quads.map(p=>{let w=t.kind==="strikeout"?p.y+p.height*.5:p.baselineY-Math.max(1,p.height*.12);return t.kind==="squiggly"?
|
|
14
|
+
f`,bbox:n,multiply:!0}}if(t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly"){let l=Math.max(.75,(a=t.style.strokeWidth)!=null?a:1),d=t.quads.map(p=>{let w=t.kind==="strikeout"?p.y+p.height*.5:p.baselineY-Math.max(1,p.height*.12);return t.kind==="squiggly"?Iu(p,p.y+1):`${oe(p.x)} ${oe(w)} m ${oe(p.x+p.width)} ${oe(w)} l S`}).join(`
|
|
15
15
|
`),[m,h,f]=Mn(t.style.color);return{content:`${oe(l)} w ${oe(m)} ${oe(h)} ${oe(f)} RG
|
|
16
|
-
${d}`,bbox:n,multiply:!1}}if(t.kind==="ink"){let l=t.strokes.map(d=>
|
|
16
|
+
${d}`,bbox:n,multiply:!1}}if(t.kind==="ink"){let l=t.strokes.map(d=>Mi(d,!1)+`
|
|
17
17
|
S`).join(`
|
|
18
|
-
`);return{content:`${
|
|
19
|
-
${l}`,bbox:n,multiply:!1}}if(t.kind==="rect"){let l=
|
|
20
|
-
`:"")+
|
|
18
|
+
`);return{content:`${Hn(t.style)}
|
|
19
|
+
${l}`,bbox:n,multiply:!1}}if(t.kind==="rect"){let l=ct(t),d=`${oe(l.x)} ${oe(l.y)} ${oe(l.width)} ${oe(l.height)} re`;return{content:`${(t.style.fill?oo(t.style.fill)+`
|
|
20
|
+
`:"")+Hn(t.style)}
|
|
21
21
|
${d}
|
|
22
|
-
${
|
|
23
|
-
`:"")+
|
|
24
|
-
${
|
|
25
|
-
${
|
|
26
|
-
`:"")+
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
S`,bbox:n,multiply:!1};let[r,o]=t.points,i=`${
|
|
31
|
-
${oe(r.x)} ${oe(r.y)} m ${oe(o.x)} ${oe(o.y)} l S`;if(t.kind==="arrow"){let l=Math.max(8,((c=t.style.strokeWidth)!=null?c:
|
|
32
|
-
${
|
|
22
|
+
${Fi(t.style)}`,bbox:n,multiply:!1}}if(t.kind==="ellipse")return{content:`${(t.style.fill?oo(t.style.fill)+`
|
|
23
|
+
`:"")+Hn(t.style)}
|
|
24
|
+
${Tu(ct(t))}
|
|
25
|
+
${Fi(t.style)}`,bbox:n,multiply:!1};if(t.kind==="polygon")return{content:`${(t.style.fill?oo(t.style.fill)+`
|
|
26
|
+
`:"")+Hn(t.style)}
|
|
27
|
+
${Mi(t.points,!0)}
|
|
28
|
+
${Fi(t.style)}`,bbox:n,multiply:!1};if(t.kind==="polyline")return{content:`${Hn(t.style)}
|
|
29
|
+
${Mi(t.points,!1)}
|
|
30
|
+
S`,bbox:n,multiply:!1};let[r,o]=t.points,i=`${Hn(t.style)}
|
|
31
|
+
${oe(r.x)} ${oe(r.y)} m ${oe(o.x)} ${oe(o.y)} l S`;if(t.kind==="arrow"){let l=Math.max(8,((c=t.style.strokeWidth)!=null?c:dr)*4);i+=`
|
|
32
|
+
${Ou(r,o,l)}`}return{content:i,bbox:n,multiply:!1}},$u=t=>({highlight:"Highlight",underline:"Underline",strikeout:"StrikeOut",squiggly:"Squiggly",rect:"Square",ellipse:"Circle",line:"Line",arrow:"Line",polygon:"Polygon",polyline:"PolyLine",ink:"Ink",note:"Text",freetext:"FreeText"})[t.kind],Bu=t=>{let e=[];for(let n of t){let r=n.y+n.height;e.push(n.x,r,n.x+n.width,r,n.x,n.y,n.x+n.width,n.y)}return e},tc=(t,e)=>{var c,l,d;let n=t.getPageCount();if(e.pageIndex<0||e.pageIndex>=n)return;let r=t.getPage(e.pageIndex),o=t.context,i=ct(e),s={Type:"Annot",Subtype:$u(e),Rect:Qa(ec(i,Math.max((c=e.style.strokeWidth)!=null?c:dr,2)+1)),C:Mn(e.style.color),CA:e.style.opacity,F:4,NM:dn.of(e.id),M:dn.of(Za(e.createdAt)),CreationDate:dn.of(Za(e.createdAt))};if(e.author&&(s.T=dn.of(e.author)),e.kind==="highlight"||e.kind==="underline"||e.kind==="strikeout"||e.kind==="squiggly")s.QuadPoints=Bu(e.quads),e.text&&(s.Contents=dn.of(e.text));else if(e.kind==="line"||e.kind==="arrow"){let[m,h]=e.points;s.L=[m.x,m.y,h.x,h.y],e.kind==="arrow"&&(s.LE=["None","ClosedArrow"]),e.style.strokeWidth&&(s.BS={W:e.style.strokeWidth,S:"S"})}else if(e.kind==="polygon"||e.kind==="polyline")s.Vertices=e.points.flatMap(m=>[m.x,m.y]),e.style.fill&&(s.IC=Mn(e.style.fill)),e.style.strokeWidth&&(s.BS={W:e.style.strokeWidth,S:"S"});else if(e.kind==="rect"||e.kind==="ellipse")e.style.fill&&(s.IC=Mn(e.style.fill)),e.style.strokeWidth&&(s.BS={W:e.style.strokeWidth,S:"S"});else if(e.kind==="ink")s.InkList=e.strokes.map(m=>m.flatMap(h=>[h.x,h.y])),e.style.strokeWidth&&(s.BS={W:e.style.strokeWidth,S:"S"});else if(e.kind==="note")s.Contents=dn.of((l=e.text)!=null?l:""),s.Name="Comment",s.Open=!1;else if(e.kind==="freetext"){s.Contents=dn.of((d=e.text)!=null?d:"");let[m,h,f]=Mn(e.style.color);s.DA=dn.of(`${oe(m)} ${oe(h)} ${oe(f)} rg /Helv 12 Tf`),s.Q=0}if(e.kind!=="note"){let{content:m,bbox:h,multiply:f}=ju(e),p={Type:"XObject",Subtype:"Form",FormType:1,BBox:Qa(h),Resources:f?{ExtGState:{GS0:{Type:"ExtGState",BM:"Multiply",ca:1,CA:1}}}:{}},w=o.stream(m,p),y=o.register(w);s.AP={N:y}}let a=o.register(o.obj(s));r.node.addAnnot(a),r.node.get(Ja.of("Annots"))||r.node.set(Ja.of("Annots"),o.obj([a]))};var Pe=(t,e)=>{let[n,r,o,i,s,a]=t,[c,l,d,m,h,f]=e;return[n*c+o*l,r*c+i*l,n*d+o*m,r*d+i*m,n*h+o*f+s,r*h+i*f+a]};var Gn=t=>{let e=t[0]*t[3]-t[1]*t[2];if(!Number.isFinite(e)||Math.abs(e)<1e-12)return null;let n=t[3]/e,r=-t[1]/e,o=-t[2]/e,i=t[0]/e;return[n,r,o,i,-(n*t[4]+o*t[5]),-(r*t[4]+i*t[5])]};var Uu={left:Ai.Left,center:Ai.Center,right:Ai.Right},_u={"insert-text":"edit-text","replace-text":"edit-text","delete-object":"edit-text","transform-object":"edit-text","insert-image":"edit-text","rotate-page":"edit-text","delete-page":"edit-text","redact-area":"redact","create-form-field":"forms","update-form-field":"forms","set-form-values":"forms","delete-form-field":"forms","flatten-form":"forms","add-annotation":"annotate"},hr=t=>({r:Math.min(1,Math.max(0,t.r)),g:Math.min(1,Math.max(0,t.g)),b:Math.min(1,Math.max(0,t.b))}),Xu=t=>{let e=(t!=null?t:"").replace(/^[A-Z]{6}\+/,"").replace(/[#,\s]/g,"").toLowerCase(),n=e.includes("bold")||e.includes("black")||e.includes("heavy"),r=e.includes("italic")||e.includes("oblique");return e.includes("times")?n&&r?dt.TimesRomanBoldItalic:n?dt.TimesRomanBold:r?dt.TimesRomanItalic:dt.TimesRoman:e.includes("courier")?n&&r?dt.CourierBoldOblique:n?dt.CourierBold:r?dt.CourierOblique:dt.Courier:n&&r?dt.HelveticaBoldOblique:n?dt.HelveticaBold:r?dt.HelveticaOblique:dt.Helvetica},io=t=>{let e=[];for(let n=0;n<t.length;){let r=t.codePointAt(n);if(r===void 0)break;e.push(r),n+=r>65535?2:1}return e},zu=new Map([["\xAD",""],["\u200B",""],["\u200C",""],["\u200D",""],["\uFEFF",""],["\u2000"," "],["\u2001"," "],["\u2002"," "],["\u2003"," "],["\u2004"," "],["\u2005"," "],["\u2006"," "],["\u2007"," "],["\u2008"," "],["\u2009"," "],["\u200A"," "],["\u3000"," "],["\u2010","-"],["\u2011","-"],["\u2012","-"],["\u2015","-"],["\u2212","-"],["\u2024","."],["\u2032","'"],["\u2033",'"'],["\u02BC","'"],["\u2044","/"],["\u2215","/"],["\u2028",`
|
|
33
33
|
`],["\u2029",`
|
|
34
|
-
`],["\uFB01","fi"],["\uFB02","fl"],["\uFB00","ff"],["\uFB03","ffi"],["\uFB04","ffl"]]),rc=t=>(t!=null?t:"").replace(/^[A-Z]{6}\+/,"").replace(/[#,\s]/g,"").toLowerCase(),Ai=t=>!t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null,Rn=(t,e)=>{if(t){if(!Be(t))return t;try{return e(t)}catch{return}}},zu=t=>{if(!(!t||!he(t)))return t.items[0]},Yu=(t,e)=>{let n=Rn(t.entries.get("FontDescriptor"),e);if(n&&Z(n))return n;let r=Rn(t.entries.get("DescendantFonts"),e),o=Rn(zu(r),e);if(o&&Z(o)){let i=Rn(o.entries.get("FontDescriptor"),e);if(i&&Z(i))return i}},Wu=t=>{var a,c,l,d,m,h,f,p;let e=new Gt(t),r=e.parse().xrefTables.get(0);if(!r)return[];let o=[],i=new Set,s=w=>e.loadObject(w);for(let[w,b]of r.entries()){if(!b.inUse)continue;let y;try{y=s({type:"ref",objNum:w,genNum:b.genNum})}catch{continue}if(!Z(y))continue;let k=Ai(y.entries.get("Subtype"));if(!k||!["Type1","TrueType","Type0","CIDFontType0","CIDFontType2"].includes(k))continue;let C=Yu(y,s);if(!C)continue;let S=(c=(a=Rn(C.entries.get("FontFile2"),s))!=null?a:Rn(C.entries.get("FontFile3"),s))!=null?c:Rn(C.entries.get("FontFile"),s);if(!S||!me(S))continue;let F=(d=(l=Ai(y.entries.get("BaseFont")))!=null?l:Ai(C.entries.get("FontName")))!=null?d:`Font${w}`,O=rc(F),N=`${O}:${(p=(f=(m=S.rawBytes)==null?void 0:m.length)!=null?f:(h=S.data)==null?void 0:h.length)!=null?p:0}`;if(!i.has(N))try{let I=ve.decodeStreamSync(S);if(I.length===0)continue;o.push({baseName:F,normalizedName:O,bytes:I}),i.add(N)}catch{continue}}return o},nc=(t,e,n,r)=>{let o=Math.max(0,t.x-e),i=Math.max(0,t.y-e),s=Math.min(n,t.x+t.width+e),a=Math.min(r,t.y+t.height+e);return{x:o,y:i,width:Math.max(0,s-o),height:Math.max(0,a-i)}},io=class t{constructor(e,n){this.pdfDoc=e;this.pdfBytes=n;this.standardFontCache=new Map;this.embeddedFontCache=new Map;this.embeddedFonts=null;this.fontkitRegistered=!1;this.rewrittenPages=new Map;this.indexInvalidPages=new Set;this.embeddedImageCache=new Map;this.currentBytes=n}static async fromAvniDocument(e){let n=await e.blob.arrayBuffer(),r=new Uint8Array(n),o=await tc.load(r);return new t(o,r)}static async fromBytes(e){let n=e instanceof Uint8Array?e:new Uint8Array(e),r=await tc.load(n);return new t(r,n)}getPageCount(){return this.pdfDoc.getPageCount()}async applyOperations(e){var r,o,i,s,a,c,l,d,m,h,f,p,w,b,y,k,C,S,F,O,N,I;if(e.length===0)return;for(let R of e)Ya(Uu[R.type]);let n=await this.getStandardFont(lt.Helvetica);for(let R of e){if(R.type==="create-form-field"||R.type==="set-form-values"||R.type==="delete-form-field"||R.type==="flatten-form")continue;if(R.type==="delete-page"){this.deletePage(R.pageIndex);continue}if(R.type==="delete-object"){if(!await this.tryNeutralizeSpans(R.pageIndex,R.spans))throw new Error("This object cannot be deleted safely.");continue}if(R.type==="transform-object"){if(!await this.tryWrapSpanWithTransform(R))throw new Error("This object cannot be moved safely.");continue}if(R.type==="add-annotation"){ec(this.pdfDoc,R.annotation);continue}let H=this.pdfDoc.getPage(R.pageIndex);if(R.type==="insert-image"){let te=await this.getEmbeddedImage(R.bytes,R.format);H.drawImage(te,{x:R.x,y:R.y,width:R.width,height:R.height});continue}if(R.type==="insert-text"){if((r=R.spans)!=null&&r.length){await this.drawStyledSpans(H,R.spans,R.x,R.y,(o=R.size)!=null?o:14,R.fontName);continue}let te=ur((i=R.color)!=null?i:{r:0,g:0,b:0}),T=this.fitTextToFont(n,R.text);if(T.length===0)continue;H.drawText(T,{x:R.x,y:R.y,size:(s=R.size)!=null?s:14,font:n,color:dr(te.r,te.g,te.b)});continue}if(R.type==="redact-area"){let te=ur((a=R.color)!=null?a:{r:1,g:1,b:1}),{width:T,height:ce}=H.getSize();(l=(c=R.removeOperators)==null?void 0:c.streamOperatorIndices)!=null&&l.length&&await this.tryRemoveTextOperators(R.pageIndex,R.removeOperators.streamOperatorIndices);let se=nc({x:R.x,y:R.y,width:R.width,height:R.height},(d=R.padding)!=null?d:1.75,T,ce);H.drawRectangle({x:se.x,y:se.y,width:se.width,height:se.height,color:dr(te.r,te.g,te.b)});continue}if(R.type==="replace-text"){let te=ur((m=R.backgroundColor)!=null?m:{r:1,g:1,b:1}),T=ur((p=(f=R.color)!=null?f:(h=R.font)==null?void 0:h.color)!=null?p:{r:0,g:0,b:0}),ce=(y=(b=R.size)!=null?b:(w=R.font)==null?void 0:w.sizePt)!=null?y:Math.max(8,R.height*.8),se=(k=R.font)!=null&&k.pdfName?await this.getRenderableFont(R.font.pdfName,R.newText):n,fe=this.fitTextToFont(se,R.newText),{width:pe,height:ie}=H.getSize(),J=fe.trim().length>0?se.widthOfTextAtSize(fe,ce):0;if(!((S=(C=R.removeOperators)==null?void 0:C.streamOperatorIndices)!=null&&S.length?await this.tryRemoveTextOperators(R.pageIndex,R.removeOperators.streamOperatorIndices):!1)){let le=Math.min(pe-R.x,Math.max(R.width,J+ce*.25)),ge=nc({x:R.x,y:R.y,width:le,height:R.height},(F=R.erasePadding)!=null?F:1.75,pe,ie);R.eraseClamp&&(ge=Zr(ge,R.eraseClamp)),H.drawRectangle({x:ge.x,y:ge.y,width:ge.width,height:ge.height,color:dr(te.r,te.g,te.b)})}let Q=(O=R.baselineY)!=null?O:R.y+Math.max(0,(R.height-ce)/2);if((N=R.spans)!=null&&N.length){await this.drawStyledSpans(H,R.spans,R.x,Q,ce,(I=R.font)==null?void 0:I.pdfName);continue}if(fe.length===0)continue;H.drawText(fe,{x:R.x,y:Q,size:ce,font:se,color:dr(T.r,T.g,T.b)});continue}if(R.type==="rotate-page"){let te=H.getRotation().angle;H.setRotation(Bu(te+R.degrees))}}await this.applyFormOperations(e,n)}async applyFormOperations(e,n){let r=e.filter(a=>a.type==="create-form-field"||a.type==="update-form-field"||a.type==="set-form-values"||a.type==="delete-form-field"||a.type==="flatten-form");if(r.length===0)return;let o=this.pdfDoc.getForm(),i=!1,s=!1;for(let a of r)if(a.type==="create-form-field")this.createFormField(a,n),i=!0;else if(a.type==="update-form-field"){try{let c=o.getField(a.oldName);c&&o.removeField(c)}catch{}this.createFormField(a,n),i=!0}else if(a.type==="set-form-values"){for(let c of a.values)this.setFieldValue(o,c.name,c.fieldType,c.value);i=!0}else if(a.type==="delete-form-field"){try{let c=o.getField(a.name);c&&o.removeField(c)}catch{}i=!0}else a.type==="flatten-form"&&(s=!0);if(i)try{o.updateFieldAppearances(n)}catch{}if(s)try{o.flatten()}catch{}}createFormField(e,n){var d,m;let r=this.pdfDoc.getForm(),o=this.pdfDoc.getPage(e.pageIndex),{x:i,y:s,width:a,height:c}=e.rect,l=e.fontSize&&e.fontSize>0?e.fontSize:void 0;switch(e.fieldType){case"text":case"signature":{let h=r.createTextField(e.name);if(e.value&&h.setText(e.value),l)try{h.setFontSize(l)}catch{}if(e.multiline)try{h.enableMultiline()}catch{}if(e.maxLength&&e.maxLength>0)try{h.setMaxLength(e.maxLength)}catch{}if(e.align)try{h.setAlignment(Lu[e.align])}catch{}h.addToPage(o,{x:i,y:s,width:a,height:c,font:n}),(e.fieldType==="signature"||e.readOnly)&&h.enableReadOnly(),e.required&&h.enableRequired();break}case"checkbox":{let h=r.createCheckBox(e.name);h.addToPage(o,{x:i,y:s,width:a,height:c}),e.value&&e.value!=="Off"?h.check():h.uncheck(),e.readOnly&&h.enableReadOnly(),e.required&&h.enableRequired();break}case"dropdown":{let h=r.createDropdown(e.name);if((d=e.options)!=null&&d.length&&h.addOptions(e.options),e.editable)try{h.enableEditing()}catch{}if(e.value)try{h.select(e.value)}catch{}if(l)try{h.setFontSize(l)}catch{}h.addToPage(o,{x:i,y:s,width:a,height:c,font:n}),e.readOnly&&h.enableReadOnly(),e.required&&h.enableRequired();break}case"radio":{let h=r.createRadioGroup(e.name);if(((m=e.options)!=null?m:[]).forEach((p,w)=>{var y,k;let b=(k=(y=e.optionRects)==null?void 0:y[w])!=null?k:{x:i,y:s-w*(c+4),width:a,height:c};h.addOptionToPage(p,o,{x:b.x,y:b.y,width:b.width,height:b.height})}),e.value)try{h.select(e.value)}catch{}e.readOnly&&h.enableReadOnly(),e.required&&h.enableRequired();break}}}setFieldValue(e,n,r,o){try{switch(r){case"text":case"signature":e.getTextField(n).setText(o!=null?o:"");break;case"checkbox":{let i=e.getCheckBox(n);o&&o!=="Off"&&o!=="false"?i.check():i.uncheck();break}case"dropdown":o?e.getDropdown(n).select(o):e.getDropdown(n).clear();break;case"radio":o&&o!=="Off"?e.getRadioGroup(n).select(o):e.getRadioGroup(n).clear();break}}catch{}}async toBlob(){let e=await this.pdfDoc.save({useObjectStreams:!1}),n=e instanceof Uint8Array?e:Uint8Array.from(e),r=n.slice().buffer;this.currentBytes=n,this.rewrittenPages.clear(),this.indexInvalidPages.clear();for(let o of this.pdfDoc.getPages()){let i=o;i.contentStream=void 0,i.contentStreamRef=void 0}return new Blob([r],{type:"application/pdf"})}async tryRemoveTextOperators(e,n){if(this.indexInvalidPages.has(e))return!1;try{let{streams:r,combined:o}=await Ca(this.currentBytes,e,n,this.rewrittenPages.get(e)),i=r.filter(l=>l.changed);if(i.length===0)return!1;let s=i.map(l=>Mi.of(l.objNum,l.genNum));for(let l of s)if(!this.pdfDoc.context.lookup(l))return!1;i.forEach((l,d)=>{this.pdfDoc.context.assign(s[d],this.pdfDoc.context.flateStream(l.bytes))});let a=this.pdfDoc.getPage(e),c=a.contentStreamRef;return c&&s.some(l=>l.tag===c.tag)&&(a.contentStream=void 0),this.rewrittenPages.set(e,o),!0}catch{return!1}}async tryNeutralizeSpans(e,n){if(!n.length||this.indexInvalidPages.has(e))return!1;try{let{streams:r,combined:o}=await Ma(this.currentBytes,e,n,this.rewrittenPages.get(e)),i=r.filter(l=>l.changed);if(i.length===0)return!1;let s=i.map(l=>Mi.of(l.objNum,l.genNum));for(let l of s)if(!this.pdfDoc.context.lookup(l))return!1;i.forEach((l,d)=>{this.pdfDoc.context.assign(s[d],this.pdfDoc.context.flateStream(l.bytes))});let a=this.pdfDoc.getPage(e),c=a.contentStreamRef;return c&&s.some(l=>l.tag===c.tag)&&(a.contentStream=void 0),this.rewrittenPages.set(e,o),!0}catch{return!1}}async tryWrapSpanWithTransform(e){if(this.indexInvalidPages.has(e.pageIndex))return!1;try{let n=Hn(e.baseCtm);if(!n)return!1;let r=Se(Se(n,e.matrix),e.baseCtm),{streams:o,combined:i}=await Fa(this.currentBytes,e.pageIndex,e.span,r,this.rewrittenPages.get(e.pageIndex)),s=o.filter(d=>d.changed);if(s.length===0)return!1;let a=s.map(d=>Mi.of(d.objNum,d.genNum));for(let d of a)if(!this.pdfDoc.context.lookup(d))return!1;s.forEach((d,m)=>{this.pdfDoc.context.assign(a[m],this.pdfDoc.context.flateStream(d.bytes))});let c=this.pdfDoc.getPage(e.pageIndex),l=c.contentStreamRef;return l&&a.some(d=>d.tag===l.tag)&&(c.contentStream=void 0),this.rewrittenPages.set(e.pageIndex,i),this.indexInvalidPages.add(e.pageIndex),!0}catch{return!1}}deletePage(e){if(this.pdfDoc.getPageCount()<=1)throw new Error("Cannot delete the last remaining page");this.pdfDoc.removePage(e)}getEmbeddedImage(e,n){let r=0;for(let a=0;a<e.length;a+=Math.max(1,e.length>>5))r=r*31+e[a]>>>0;let o=`${n}:${e.length}:${r}`,i=this.embeddedImageCache.get(o);if(i)return i;let s=n==="png"?this.pdfDoc.embedPng(e):this.pdfDoc.embedJpg(e);return this.embeddedImageCache.set(o,s),s}getStandardFont(e){let n=this.standardFontCache.get(e);if(n)return n;let r=this.pdfDoc.embedFont(e);return this.standardFontCache.set(e,r),r}async drawStyledSpans(e,n,r,o,i,s){var c,l;let a=r;for(let d of n){if(d.text.length===0)continue;let m=(c=d.style.sizePt)!=null?c:i,h=va(s,{bold:d.style.bold,italic:d.style.italic}),f=await this.getRenderableFont(h,d.text),p=this.fitTextToFont(f,d.text);if(p.length===0)continue;let w=ur((l=d.style.color)!=null?l:{r:0,g:0,b:0}),b=dr(w.r,w.g,w.b),y=f.widthOfTextAtSize(p,m);if(e.drawText(p,{x:a,y:o,size:m,font:f,color:b}),d.style.underline||d.style.strikethrough){let k=Math.max(.5,m*.06);d.style.underline&&e.drawRectangle({x:a,y:o-m*.12,width:y,height:k,color:b}),d.style.strikethrough&&e.drawRectangle({x:a,y:o+m*.28,width:y,height:k,color:b})}a+=y}}async getRenderableFont(e,n){let r=rc(e),o=await this.getStandardFont(_u(e));if(this.fontSupportsText(o,n))return o;let i=await this.getStandardFont(lt.Helvetica);if(this.fontSupportsText(i,n))return i;let s=await this.getEmbeddedFont(r);if(s&&this.fontSupportsText(s,n))return s;let a=s?[o,i,s]:[o,i],c=a[0],l=1/0;for(let d of a){let m=this.unsupportedCount(d,n);m<l&&(l=m,c=d)}return c}supportedCodePoints(e){try{return new Set(e.getCharacterSet())}catch{return new Set}}unsupportedCount(e,n){let r=this.supportedCodePoints(e);return oo(n).filter(o=>{let i=String.fromCodePoint(o);return i!=="\r"&&i!==`
|
|
35
|
-
`&&i!==" "&&!r.has(o)}).length}fitTextToFont(e,n){if(this.fontSupportsText(e,n))return n;let r=this.supportedCodePoints(e),o=[],i="";for(let s of
|
|
36
|
-
`||a===" "||r.has(s)){i+=a;continue}let c=
|
|
37
|
-
`||r.has(d))){i+=c;continue}o.push(a)}o.length>0&&console.warn(`[PDFEditSession] Dropped ${o.length} character(s) the font cannot encode: ${[...new Set(o)].join(" ")}`);try{return e.encodeText(i),i}catch{return i.replace(/[^\x20-\x7E\r\n\t]/g,"")}}fontSupportsText(e,n){if(n.length===0)return!0;try{let r=new Set(e.getCharacterSet());return
|
|
38
|
-
`&&s!==" "}).some(i=>!r.has(i))?!1:(e.encodeText(n),!0)}catch{return!1}}async getEmbeddedFont(e){let n=this.embeddedFontCache.get(e);if(n)return n;let r=(async()=>{var s;await this.ensureFontkitRegistered();let o=this.getEmbeddedFontPrograms(),i=(s=o.find(a=>a.normalizedName===e))!=null?s:o.find(a=>a.normalizedName.includes(e)||e.includes(a.normalizedName));if(!i)return null;try{return await this.pdfDoc.embedFont(i.bytes,{subset:!0})}catch{return null}})();return this.embeddedFontCache.set(e,r),r}getEmbeddedFontPrograms(){return this.embeddedFonts||(this.embeddedFonts=Wu(this.pdfBytes)),this.embeddedFonts}async ensureFontkitRegistered(){if(this.fontkitRegistered)return;let e=(await import("./fontkit.es-6MF4HMXW.js")).default;this.pdfDoc.registerFontkit(e),this.fontkitRegistered=!0}};var oc=new WeakMap,so=class{constructor(){this.name="pdf-editor-core";this.supportedTypes=["pdf"]}async process(e,n){var r,o;try{let i=(r=n.operations)!=null?r:[];if(i.length===0)return{success:!1,document:e,error:"No edit operations were provided."};let s=(o=oc.get(e.blob))!=null?o:await io.fromAvniDocument(e);await s.applyOperations(i);let a=await s.toBlob();oc.set(a,s);let c={taskId:crypto.randomUUID(),processorName:this.name,timestamp:Date.now(),params:n};return{success:!0,document:{...e,blob:a,size:a.size,history:[...e.history,c]},metrics:{duration:0,originalSize:e.size,newSize:a.size}}}catch(i){return{success:!1,document:e,error:i instanceof Error?i.message:"Unknown PDF edit failure"}}}};import{forwardRef as sh,useCallback as Oi,useEffect as hc,useImperativeHandle as ah,useLayoutEffect as ch,useRef as mr,useState as fc}from"react";var Hu=t=>t?`rgb(${Math.round(t.r*255)},${Math.round(t.g*255)},${Math.round(t.b*255)})`:"#000",Gu=(t,e,n,r)=>{var s,a;let o=((s=t.sizePt)!=null?s:n)*e,i=[t.underline?"underline":"",t.strikethrough?"line-through":""].filter(Boolean).join(" ");return[`font-weight:${t.bold?"700":"400"}`,`font-style:${t.italic?"italic":"normal"}`,`text-decoration:${i||"none"}`,`font-size:${o}px`,`color:${Hu((a=t.color)!=null?a:r)}`,"white-space:pre-wrap"].join(";")},Ku=(t,e,n,r)=>{let o=document.createElement("span"),{style:i}=t;return i.bold&&(o.dataset.b="1"),i.italic&&(o.dataset.i="1"),i.underline&&(o.dataset.u="1"),i.strikethrough&&(o.dataset.s="1"),i.sizePt!==void 0&&(o.dataset.size=String(i.sizePt)),i.color&&(o.dataset.color=`${i.color.r},${i.color.g},${i.color.b}`),o.setAttribute("style",Gu(i,e,n,r)),o.textContent=t.text,o},Vu=(t,e)=>{let n={},r=t;for(;r;){let o=r.dataset;if(o.b==="1"&&(n.bold=!0),o.i==="1"&&(n.italic=!0),o.u==="1"&&(n.underline=!0),o.s==="1"&&(n.strikethrough=!0),o.size&&n.sizePt===void 0&&(n.sizePt=parseFloat(o.size)),o.color&&!n.color){let[i,s,a]=o.color.split(",").map(Number);[i,s,a].every(Number.isFinite)&&(n.color={r:i,g:s,b:a})}if(r===e)break;r=r.parentElement}return n},ao=t=>{let e=[],n=r=>{var o;if(r.nodeType===Node.TEXT_NODE){let i=(o=r.textContent)!=null?o:"";if(i.length===0)return;e.push({text:i,style:Vu(r.parentElement,t)})}else r.nodeName!=="BR"&&r.childNodes.forEach(n)};return t.childNodes.forEach(n),Cn(e)},Ni=(t,e,n,r,o)=>{t.textContent="";for(let i of e)i.text.length!==0&&t.appendChild(Ku(i,n,r,o))},qu=t=>t.reduce((e,n)=>e+n.text.length,0),Ei=t=>{let e=window.getSelection();if(!e||e.rangeCount===0)return null;let n=e.getRangeAt(0);if(!t.contains(n.commonAncestorContainer))return null;let r=n.cloneRange();r.selectNodeContents(t),r.setEnd(n.startContainer,n.startOffset);let o=r.toString().length;return{start:o,end:o+n.toString().length}},ic=(t,e)=>{let n=e,r=null,o=i=>{var s,a;if(!r)if(i.nodeType===Node.TEXT_NODE){let c=(a=(s=i.textContent)==null?void 0:s.length)!=null?a:0;if(n<=c){r={node:i,offset:n};return}n-=c}else i.childNodes.forEach(o)};return t.childNodes.forEach(o),r!=null?r:{node:t,offset:t.childNodes.length}},co=(t,e,n)=>{let r=ic(t,e),o=ic(t,n),i=document.createRange();i.setStart(r.node,r.offset),i.setEnd(o.node,o.offset);let s=window.getSelection();s&&(s.removeAllRanges(),s.addRange(i))},sc=t=>{let e=[];for(let n of t)for(let r of n.text.split(""))e.push({ch:r,style:{...n.style}});return e},ac=(t,e,n,r)=>{let o=e,i=n;o===i&&(o=0,i=qu(t));let s=sc(t);for(let a=o;a<i&&a<s.length;a++)s[a].style={...s[a].style,...r};return Cn(s.map(a=>({text:a.ch,style:a.style})))},Ti=(t,e,n,r)=>{let o=sc(t);if(e===n){let m=o[Math.max(0,e-1)];return m?{...m.style}:{...r}}let i=o.slice(e,n);if(i.length===0)return{...r};let s=m=>i.every(h=>h.style[m]),a=i.every(m=>m.style.sizePt===i[0].style.sizePt)?i[0].style.sizePt:void 0,c=m=>m?`${m.r},${m.g},${m.b}`:"",l=i[0].style.color,d=i.every(m=>c(m.style.color)===c(l))?l:void 0;return{bold:s("bold"),italic:s("italic"),underline:s("underline"),strikethrough:s("strikethrough"),sizePt:a!=null?a:r.sizePt,color:d!=null?d:r.color}};import{Bold as eh,Italic as th,Underline as nh,Strikethrough as rh,Minus as lc,Plus as dc}from"lucide-react";import{jsx as dn,jsxs as Gn}from"react/jsx-runtime";var un=t=>{let e=n=>Math.round(Math.min(1,Math.max(0,n))*255).toString(16).padStart(2,"0");return`#${e(t.r)}${e(t.g)}${e(t.b)}`},Ju=t=>({r:parseInt(t.slice(1,3),16)/255,g:parseInt(t.slice(3,5),16)/255,b:parseInt(t.slice(5,7),16)/255}),Zu=(t,e)=>!!t&&Math.abs(t.r-e.r)<.02&&Math.abs(t.g-e.g)<.02&&Math.abs(t.b-e.b)<.02,Qu=[{r:1,g:.85,b:0},{r:.18,g:.8,b:.44},{r:.2,g:.6,b:.95},{r:.91,g:.3,b:.4},{r:.96,g:.62,b:.04},{r:.55,g:.36,b:.96}],cc=({children:t})=>dn("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:t});function Lt({color:t,onColor:e,opacity:n,onOpacity:r,presets:o=Qu,shape:i="round",label:s="Color",allowNone:a=!1,isNone:c=!1,onNone:l,keepFocus:d=!1}){let m=d?f=>f.preventDefault():void 0,h=i==="round"?"rounded-full":"rounded-md";return Gn("div",{children:[dn(cc,{children:s}),Gn("div",{className:"flex flex-wrap items-center gap-1.5",children:[a&&dn("button",{type:"button",title:"No fill",onMouseDown:m,onClick:l,className:`relative h-7 w-7 overflow-hidden border bg-white ${h} ${c?"ring-2 ring-crimson-600 ring-offset-1 dark:ring-offset-zinc-900":"border-ink-line-strong dark:border-white/20"}`,children:dn("span",{className:"absolute left-1/2 top-0 h-[140%] w-px -translate-x-1/2 rotate-45 bg-red-500"})}),o.map(f=>dn("button",{type:"button",title:un(f),onMouseDown:m,onClick:()=>e(f),style:{background:un(f)},className:`h-7 w-7 border ${h} ${!c&&Zu(t,f)?"ring-2 ring-crimson-600 ring-offset-1 dark:ring-offset-zinc-900":"border-ink-line-strong dark:border-white/20"}`},un(f))),Gn("label",{className:`flex h-7 w-7 cursor-pointer items-center justify-center border border-dashed border-ink-line-strong text-[11px] font-bold text-ink-muted dark:border-white/20 ${h}`,title:"Custom color",children:[dn("input",{type:"color",value:un(t),onMouseDown:f=>f.stopPropagation(),onChange:f=>e(Ju(f.target.value)),className:"h-0 w-0 opacity-0"}),"+"]})]}),r&&typeof n=="number"&&Gn("div",{className:"mt-3",children:[Gn("div",{className:"mb-1 flex items-center justify-between",children:[dn(cc,{children:"Opacity"}),Gn("span",{className:"text-[10px] font-semibold tabular-nums text-ink-soft dark:text-zinc-400",children:[Math.round(n*100),"%"]})]}),dn("input",{type:"range",min:10,max:100,value:Math.round(n*100),onMouseDown:m,onChange:f=>r(parseInt(f.target.value,10)/100),className:"h-1.5 w-full cursor-pointer appearance-none rounded-full bg-ink-line accent-crimson-600 dark:bg-white/15"})]})]})}import{jsx as Le,jsxs as hr}from"react/jsx-runtime";var oh=[{r:0,g:0,b:0},{r:.86,g:.15,b:.15},{r:.15,g:.39,b:.92},{r:.09,g:.64,b:.29},{r:.96,g:.62,b:.04},{r:1,g:1,b:1}],ih=(t,e)=>!!t&&Math.abs(t.r-e.r)<.02&&Math.abs(t.g-e.g)<.02&&Math.abs(t.b-e.b)<.02,uc=[{attr:"bold",icon:Le(eh,{className:"h-3.5 w-3.5"}),title:"Bold (Ctrl+B)"},{attr:"italic",icon:Le(th,{className:"h-3.5 w-3.5"}),title:"Italic (Ctrl+I)"},{attr:"underline",icon:Le(nh,{className:"h-3.5 w-3.5"}),title:"Underline (Ctrl+U)"},{attr:"strikethrough",icon:Le(rh,{className:"h-3.5 w-3.5"}),title:"Strikethrough"}];function fr({value:t,onToggle:e,onSize:n,onColor:r,variant:o="bar",fallbackSizePt:i}){var c,l;let s=Math.round((c=t.sizePt)!=null?c:i),a=d=>d.preventDefault();return o==="panel"?hr("div",{className:"flex flex-col gap-4 p-4",onMouseDown:a,children:[hr("div",{children:[Le("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:"Style"}),Le("div",{className:"flex gap-1",children:uc.map(({attr:d,icon:m,title:h})=>Le("button",{type:"button",title:h,onMouseDown:a,onClick:()=>e(d),className:`flex h-8 w-8 items-center justify-center rounded-lg border transition-colors ${t[d]?"border-crimson-600 bg-crimson-600 text-white":"border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800"}`,children:m},d))})]}),hr("div",{children:[Le("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:"Size"}),hr("div",{className:"flex items-center gap-1.5",children:[Le("button",{type:"button",onMouseDown:a,onClick:()=>n(Math.max(4,s-1)),className:"flex h-8 w-8 items-center justify-center rounded-lg border border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:Le(lc,{className:"h-3.5 w-3.5"})}),Le("input",{type:"number",value:s,min:4,max:96,onMouseDown:d=>d.stopPropagation(),onChange:d=>{let m=parseInt(d.target.value,10);Number.isFinite(m)&&n(Math.min(96,Math.max(4,m)))},className:"h-8 w-14 rounded-lg border border-ink-line-strong bg-paper-raised text-center text-sm text-ink dark:border-white/10 dark:bg-zinc-800 dark:text-white"}),Le("button",{type:"button",onMouseDown:a,onClick:()=>n(Math.min(96,s+1)),className:"flex h-8 w-8 items-center justify-center rounded-lg border border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:Le(dc,{className:"h-3.5 w-3.5"})})]})]}),Le(Lt,{color:(l=t.color)!=null?l:{r:0,g:0,b:0},onColor:r,shape:"square",keepFocus:!0})]}):hr("div",{onMouseDown:a,className:"flex items-center gap-0.5 rounded-lg bg-inverse-surface px-1 py-1 text-inverse-on-surface shadow-2xl",children:[uc.map(({attr:d,icon:m,title:h})=>Le("button",{type:"button",title:h,onMouseDown:a,onClick:()=>e(d),className:`flex h-7 w-7 items-center justify-center rounded-md transition-colors ${t[d]?"bg-primary text-white":"hover:bg-white/15"}`,children:m},d)),Le("span",{className:"mx-0.5 h-4 w-px bg-white/20"}),Le("button",{type:"button",title:"Smaller",onMouseDown:a,onClick:()=>n(Math.max(4,s-1)),className:"flex h-7 w-6 items-center justify-center rounded-md hover:bg-white/15",children:Le(lc,{className:"h-3 w-3"})}),Le("span",{className:"w-6 text-center text-xs font-semibold tabular-nums",children:s}),Le("button",{type:"button",title:"Larger",onMouseDown:a,onClick:()=>n(Math.min(96,s+1)),className:"flex h-7 w-6 items-center justify-center rounded-md hover:bg-white/15",children:Le(dc,{className:"h-3 w-3"})}),Le("span",{className:"mx-0.5 h-4 w-px bg-white/20"}),oh.slice(0,5).map(d=>Le("button",{type:"button",title:un(d),onMouseDown:a,onClick:()=>r(d),style:{background:un(d)},className:`h-4 w-4 rounded ${ih(t.color,d)?"ring-2 ring-white":"ring-1 ring-white/30"}`},un(d)))]})}import{jsx as pr,jsxs as dh}from"react/jsx-runtime";var lh=sh(function(e,n){let{containerX:r,containerY:o,screenWidth:i,screenHeight:s,scale:a,fontSizePt:c,fontFamily:l,baselineOffsetPx:d,maxWidth:m,initialSpans:h,baseColor:f,maskRect:p,bgColor:w,ocr:b,placeholder:y,onCommit:k,onCancel:C,onActiveStyleChange:S}=e,F=mr(null),O=mr(null),N=mr({sizePt:c,color:f}),I=mr(!0),R=mr(""),[H,te]=fc(N.current),[T,ce]=fc(0);hc(()=>()=>{I.current=!1},[]);let se=Oi(()=>{var Xe;let J=O.current;if(!J)return;let _=(Xe=Ei(J))!=null?Xe:{start:0,end:0},Q=ao(J),le=Ti(Q,_.start,_.end,N.current),ge=cn(le);ge!==R.current&&(R.current=ge,te(le),S==null||S(le))},[S]);ch(()=>{let J=O.current;if(!J)return;Ni(J,h,a,c,f),J.focus();let _=qr(h).length;if(co(J,_,_),se(),d!=null){let Q=document.createElement("span");Q.style.cssText="display:inline-block;width:0;height:0;overflow:hidden;vertical-align:baseline",Q.setAttribute("aria-hidden","true"),J.insertBefore(Q,J.firstChild);let le=Q.getBoundingClientRect().top-J.getBoundingClientRect().top;J.removeChild(Q),Number.isFinite(le)&&ce(d-le)}},[]),hc(()=>{let J=()=>{let _=O.current;_&&document.activeElement===_&&se()};return document.addEventListener("selectionchange",J),()=>document.removeEventListener("selectionchange",J)},[se]);let fe=Oi((J,_)=>{var ht;let Q=O.current;if(!Q)return;Q.focus();let le=(ht=Ei(Q))!=null?ht:{start:0,end:0},ge=ao(Q),Xe=J;if(_){let et=Ti(ge,le.start,le.end,N.current);Xe={[_]:!et[_]}}let Ce=ac(ge,le.start,le.end,Xe);Ni(Q,Ce,a,c,f);let Te=qr(Ce).length;le.start===le.end?co(Q,0,Te):co(Q,Math.min(le.start,Te),Math.min(le.end,Te)),se()},[a,c,f,se]),pe=Oi(()=>{let J=O.current;if(!J){C();return}let _=ao(J);k(_,qr(_))},[k,C]);ah(n,()=>({toggle:J=>fe({},J),setSize:J=>fe({sizePt:J}),setColor:J=>fe({color:J}),commit:pe,focus:()=>{var J;return(J=O.current)==null?void 0:J.focus()}}),[fe,pe]);let ie=Math.max(s,Math.ceil(c*a*1.2));return dh("div",{ref:F,style:{position:"absolute",left:`${r}px`,top:`${o}px`,zIndex:50,pointerEvents:"none"},children:[p&&pr("div",{style:{position:"absolute",left:`${p.x}px`,top:`${p.y}px`,width:`${p.w}px`,height:`${p.h}px`,background:w?`rgb(${Math.round(w.r*255)},${Math.round(w.g*255)},${Math.round(w.b*255)})`:"#fff",pointerEvents:"none"}}),pr("div",{style:{position:"absolute",left:0,top:-40,pointerEvents:"auto"},onMouseDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),children:pr(fr,{value:H,onToggle:J=>fe({},J),onSize:J=>fe({sizePt:J}),onColor:J=>fe({color:J}),variant:"bar",fallbackSizePt:c})}),pr("div",{ref:O,contentEditable:!0,suppressContentEditableWarning:!0,"data-placeholder":y,onMouseDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),onKeyUp:se,onMouseUp:se,onBlur:()=>{setTimeout(()=>{var _;if(!I.current)return;let J=document.activeElement;(_=F.current)!=null&&_.contains(J)||pe()},150)},onKeyDown:J=>{if((J.ctrlKey||J.metaKey)&&!J.shiftKey){let _=J.key.toLowerCase();if(_==="b"){J.preventDefault(),fe({},"bold");return}if(_==="i"){J.preventDefault(),fe({},"italic");return}if(_==="u"){J.preventDefault(),fe({},"underline");return}}J.key==="Enter"&&(J.preventDefault(),pe()),J.key==="Escape"&&(J.preventDefault(),C())},style:{position:"relative",display:"inline-block",transform:`translateY(${T}px)`,minWidth:`${Math.max(40,i)}px`,width:"auto",maxWidth:m?`${m}px`:void 0,minHeight:`${ie}px`,height:"auto",padding:0,margin:0,border:"none",outline:"none",background:w?`rgb(${Math.round(w.r*255)},${Math.round(w.g*255)},${Math.round(w.b*255)})`:p?"#fff":"transparent",fontSize:`${c*a}px`,lineHeight:`${ie}px`,fontFamily:l!=null?l:"inherit",color:f?`rgb(${Math.round(f.r*255)},${Math.round(f.g*255)},${Math.round(f.b*255)})`:"#000",caretColor:"rgba(59, 130, 246, 0.9)",pointerEvents:"auto",whiteSpace:"pre-wrap",overflowWrap:"break-word",overflow:"visible"}}),b&&pr("div",{style:{position:"absolute",left:-1,top:s+6,whiteSpace:"nowrap",pointerEvents:"none",background:"rgba(180, 83, 9, 0.95)",color:"#fff",fontSize:10,lineHeight:1.4,padding:"2px 6px",borderRadius:4},children:"Recognized from image, font may change to closest match"})]})}),mc=lh;import{MousePointer as ph,Type as ji,MessageSquareText as gh,Eraser as xh,Highlighter as bc,PenLine as yc,StickyNote as bh,PenTool as wc,FileText as yh,Trash2 as wh,Eye as vh,Underline as kh,Strikethrough as Ph,Minus as Sh,ArrowUpRight as Dh,Square as Ch,Circle as Fh,Hexagon as Mh,CheckSquare as Rh,Circle as Ah,ChevronDownSquare as Nh,Layers as Eh}from"lucide-react";import{Plus as uh,Trash2 as hh,X as fh}from"lucide-react";import{jsx as De,jsxs as Ct}from"react/jsx-runtime";var mh=({children:t})=>De("p",{className:"mb-1 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:t}),qt="w-full rounded-lg border border-ink-line-strong bg-paper px-2.5 py-1.5 text-sm text-ink outline-none focus:border-crimson-600 dark:border-white/10 dark:bg-zinc-800/60 dark:text-white",hn=({label:t,children:e})=>Ct("div",{children:[De(mh,{children:t}),e]}),gr=({label:t,checked:e,onChange:n})=>Ct("label",{className:"flex cursor-pointer items-center justify-between gap-2 text-sm text-ink-soft dark:text-zinc-300",children:[De("span",{children:t}),De("input",{type:"checkbox",checked:e,onChange:r=>n(r.target.checked),className:"h-4 w-4 accent-crimson-600"})]});function Ii({field:t,onChange:e,onDelete:n}){var h,f,p,w;let{type:r,rect:o}=t,i=r==="text"||r==="signature",s=r==="dropdown"||r==="radio",a=(h=t.options)!=null?h:[],c=b=>e({rect:{...o,...b}}),l=(b,y)=>{let k=a.slice();k[b]=y,e({options:k})},d=()=>e({options:[...a,`Option ${a.length+1}`]}),m=b=>e({options:a.filter((y,k)=>k!==b)});return Ct("div",{className:"flex flex-col gap-3 border-t border-ink-line pt-3 dark:border-white/10",children:[Ct("p",{className:"text-[10px] font-bold uppercase tracking-widest text-crimson-600",children:[r," field"]}),De(hn,{label:"Field name",children:De("input",{className:qt,value:t.name,onChange:b=>e({name:b.target.value})})}),De(hn,{label:"Default value",children:r==="checkbox"?De(gr,{label:"Checked by default",checked:!!t.value&&t.value!=="Off",onChange:b=>{var y;return e({value:b?(y=t.onState)!=null?y:"Yes":"Off"})}}):s?Ct("select",{className:qt,value:(f=t.value)!=null?f:"",onChange:b=>e({value:b.target.value}),children:[De("option",{value:"",children:"- none -"}),a.map(b=>De("option",{value:b,children:b},b))]}):De("input",{className:qt,value:(p=t.value)!=null?p:"",onChange:b=>e({value:b.target.value})})}),Ct("div",{className:"grid grid-cols-2 gap-2",children:[De(hn,{label:"Width (pt)",children:De("input",{type:"number",min:1,className:qt,value:Math.round(o.width),onChange:b=>c({width:Math.max(1,Number(b.target.value)||0)})})}),De(hn,{label:"Height (pt)",children:De("input",{type:"number",min:1,className:qt,value:Math.round(o.height),onChange:b=>c({height:Math.max(1,Number(b.target.value)||0)})})}),De(hn,{label:"X (pt)",children:De("input",{type:"number",className:qt,value:Math.round(o.x),onChange:b=>c({x:Number(b.target.value)||0})})}),De(hn,{label:"Y (pt)",children:De("input",{type:"number",className:qt,value:Math.round(o.y),onChange:b=>c({y:Number(b.target.value)||0})})})]}),(i||r==="dropdown")&&De(hn,{label:"Font size (0 = auto)",children:De("input",{type:"number",min:0,className:qt,value:(w=t.fontSize)!=null?w:0,onChange:b=>e({fontSize:Math.max(0,Number(b.target.value)||0)})})}),s&&De(hn,{label:"Options",children:Ct("div",{className:"flex flex-col gap-1.5",children:[a.map((b,y)=>Ct("div",{className:"flex items-center gap-1.5",children:[De("input",{className:qt,value:b,onChange:k=>l(y,k.target.value)}),De("button",{type:"button",onClick:()=>m(y),className:"shrink-0 rounded-md p-1.5 text-ink-muted hover:bg-paper hover:text-red-500 dark:hover:bg-zinc-800",title:"Remove option",children:De(fh,{className:"h-3.5 w-3.5"})})]},y)),Ct("button",{type:"button",onClick:d,className:"flex items-center justify-center gap-1.5 rounded-lg border border-dashed border-ink-line-strong px-2 py-1.5 text-xs font-semibold text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:[De(uh,{className:"h-3.5 w-3.5"})," Add option"]})]})}),Ct("div",{className:"flex flex-col gap-2 rounded-lg bg-paper px-3 py-2 dark:bg-zinc-800/40",children:[De(gr,{label:"Required",checked:!!t.required,onChange:b=>e({required:b})}),r!=="signature"&&De(gr,{label:"Read-only",checked:!!t.readOnly,onChange:b=>e({readOnly:b})}),i&&De(gr,{label:"Multi-line",checked:!!t.multiline,onChange:b=>e({multiline:b})}),r==="dropdown"&&De(gr,{label:"Allow custom text",checked:!!t.editable,onChange:b=>e({editable:b})})]}),Ct("button",{type:"button",onClick:n,className:"flex items-center justify-center gap-1.5 rounded-lg border border-red-200 px-3 py-2 text-xs font-semibold text-red-500 transition-colors hover:bg-red-50 dark:border-red-500/30 dark:hover:bg-red-500/10",children:[De(hh,{className:"h-3.5 w-3.5"})," Delete field"]})]})}import{Fragment as lo,jsx as de,jsxs as _e}from"react/jsx-runtime";var Th=[1,2,4,8],pc={view:{icon:de(vh,{className:"h-4 w-4"}),title:"View",help:"Read the document like a normal PDF. Drag to select text and press Ctrl/Cmd+C to copy. Use the toolbar to zoom, jump between pages and search. Form fields stay fillable and links are clickable."},select:{icon:de(ph,{className:"h-4 w-4"}),title:"Select",help:"Click any text, image, shape or annotation to select it. Drag to move, drag a corner handle to resize, recolor it in the popover, and press Delete to remove. Click empty space to deselect."},"edit-text":{icon:de(ji,{className:"h-4 w-4"}),title:"Edit Text",help:"Click any text to edit it inline. Select a word or phrase, then use B / I / U / S, size or color to format just that selection. Press Enter to save, Esc to cancel."},"add-text":{icon:de(ji,{className:"h-4 w-4"}),title:"Add Text",help:"Click anywhere on the page to drop a new text box, then start typing. Select text to make it bold, italic, underlined, a different size or color."},annotate:{icon:de(bc,{className:"h-4 w-4"}),title:"Annotate",help:"Pick a markup tool, choose a color and opacity, then mark up the page. Highlight, underline and strikethrough follow the text you select; brush draws freehand."},draw:{icon:de(yc,{className:"h-4 w-4"}),title:"Draw Shapes",help:"Pick a shape, set stroke color/width (and fill for closed shapes), then drag on the page. For polygons, click each point and double-click to finish."},stamp:{icon:de(gh,{className:"h-4 w-4"}),title:"Stamp",help:"Type or pick a preset stamp, choose a size and color on the toolbar, then click the page to place it."},redact:{icon:de(xh,{className:"h-4 w-4"}),title:"Redact",help:"Drag a box over anything you want to permanently remove, then press Apply. Redacted text is stripped from the file and cannot be recovered."},comment:{icon:de(bh,{className:"h-4 w-4"}),title:"Comment",help:"Click anywhere to drop a sticky-note pin. Click an existing pin to edit or delete its note. Notes export as real PDF text annotations."},sign:{icon:de(wc,{className:"h-4 w-4"}),title:"Sign",help:"Choose or draw your signature, then click the page where it should go."},form:{icon:de(yh,{className:"h-4 w-4"}),title:"Form Fields",help:"Pick a field type, then drag on the page to place a fillable field. Click any field to edit its name, default value, size, options and flags below. Use Flatten to bake the values permanently into the page."}},Oh=[{key:"text",icon:de(ji,{className:"h-4 w-4"}),label:"Text"},{key:"checkbox",icon:de(Rh,{className:"h-4 w-4"}),label:"Checkbox"},{key:"radio",icon:de(Ah,{className:"h-4 w-4"}),label:"Radio"},{key:"dropdown",icon:de(Nh,{className:"h-4 w-4"}),label:"Dropdown"},{key:"signature",icon:de(wc,{className:"h-4 w-4"}),label:"Signature"}],Ih=[{key:"highlight",icon:de(bc,{className:"h-4 w-4"}),label:"Highlight"},{key:"underline",icon:de(kh,{className:"h-4 w-4"}),label:"Underline"},{key:"strikeout",icon:de(Ph,{className:"h-4 w-4"}),label:"Strike"},{key:"brush",icon:de(yc,{className:"h-4 w-4"}),label:"Brush"}],jh=[{key:"line",icon:de(Sh,{className:"h-4 w-4"}),label:"Line"},{key:"arrow",icon:de(Dh,{className:"h-4 w-4"}),label:"Arrow"},{key:"rect",icon:de(Ch,{className:"h-4 w-4"}),label:"Rectangle"},{key:"ellipse",icon:de(Fh,{className:"h-4 w-4"}),label:"Ellipse"},{key:"polygon",icon:de(Mh,{className:"h-4 w-4"}),label:"Polygon"}],Kn=({children:t})=>de("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:t}),gc=({value:t,options:e,onChange:n})=>de("div",{className:"grid grid-cols-2 gap-1.5",children:e.map(r=>_e("button",{type:"button",onClick:()=>n(r.key),className:`flex items-center justify-center gap-1.5 rounded-lg border px-2 py-2 text-xs font-semibold transition-colors ${t===r.key?"border-crimson-600 bg-crimson-600 text-white":"border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800"}`,children:[r.icon,r.label]},r.key))}),xc=({value:t,onChange:e})=>_e("div",{children:[de(Kn,{children:"Thickness"}),de("div",{className:"flex gap-1.5",children:Th.map(n=>_e("button",{type:"button",onClick:()=>e(n),className:`flex h-8 flex-1 items-center justify-center rounded-lg border text-xs font-bold transition-colors ${t===n?"border-crimson-600 bg-crimson-600 text-white":"border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800"}`,children:[n,"px"]},n))})]});function $i(t){var a,c,l;let{tool:e,annotStyle:n,setAnnotStyle:r}=t,o=(a=pc[e])!=null?a:pc.select,i=e==="edit-text"||e==="add-text",s=t.drawShape==="rect"||t.drawShape==="ellipse"||t.drawShape==="polygon";return _e("aside",{className:"flex w-64 shrink-0 flex-col border-l border-ink-line bg-paper-card dark:border-white/10 dark:bg-[#1a1712]",children:[_e("div",{className:"flex items-center gap-2 border-b border-ink-line px-4 py-3 text-crimson-600 dark:border-white/10",children:[o.icon,de("span",{className:"font-display text-sm font-bold text-ink dark:text-white",children:o.title})]}),_e("div",{className:"flex-1 overflow-y-auto",children:[_e("div",{className:"flex flex-col gap-4 p-4",children:[i&&_e(lo,{children:[!t.textActive&&de("p",{className:"rounded-lg bg-paper px-3 py-2 text-xs text-ink-soft dark:bg-zinc-800/60 dark:text-zinc-400",children:e==="add-text"?"Click the page to add a text box.":"Click any text on the page to start editing."}),_e("div",{children:[de(Kn,{children:"Font"}),_e("div",{className:"flex items-center justify-between rounded-lg border border-ink-line-strong bg-paper px-3 py-2 text-sm text-ink-soft dark:border-white/10 dark:bg-zinc-800/60 dark:text-zinc-400",title:"Changing the font family is coming soon",children:[de("span",{className:"truncate",children:((c=t.fontName)!=null?c:"Helvetica").replace(/^[A-Z]{6}\+/,"")}),de("span",{className:"ml-2 shrink-0 text-[9px] font-semibold uppercase tracking-wide text-ink-muted dark:text-zinc-500",children:"soon"})]})]})]}),e==="annotate"&&_e(lo,{children:[_e("div",{children:[de(Kn,{children:"Tool"}),de(gc,{value:t.annotSubtool,options:Ih,onChange:t.setAnnotSubtool})]}),t.annotSubtool==="highlight"&&_e("div",{children:[de(Kn,{children:"Mode"}),de(gc,{value:t.highlightMode,options:[{key:"select",label:"Select text"},{key:"box",label:"Box / region"}],onChange:t.setHighlightMode})]}),de(Lt,{color:n.color,onColor:d=>r({color:d}),opacity:n.opacity,onOpacity:d=>r({opacity:d})}),t.annotSubtool==="brush"&&de(xc,{value:n.strokeWidth,onChange:d=>r({strokeWidth:d})})]}),e==="draw"&&_e(lo,{children:[_e("div",{children:[de(Kn,{children:"Shape"}),de("div",{className:"grid grid-cols-3 gap-1.5",children:jh.map(d=>de("button",{type:"button",title:d.label,onClick:()=>t.setDrawShape(d.key),className:`flex h-10 items-center justify-center rounded-lg border transition-colors ${t.drawShape===d.key?"border-crimson-600 bg-crimson-600 text-white":"border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800"}`,children:d.icon},d.key))})]}),de(Lt,{label:"Stroke",color:n.color,onColor:d=>r({color:d}),opacity:n.opacity,onOpacity:d=>r({opacity:d})}),de(xc,{value:n.strokeWidth,onChange:d=>r({strokeWidth:d})}),s&&de(Lt,{label:"Fill",color:(l=n.fill)!=null?l:{r:1,g:1,b:1},onColor:d=>r({fill:d}),allowNone:!0,isNone:n.fill===null,onNone:()=>r({fill:null})})]}),e==="form"&&_e(lo,{children:[_e("div",{children:[de(Kn,{children:"Add field"}),de("div",{className:"grid grid-cols-2 gap-1.5",children:Oh.map(d=>_e("button",{type:"button",onClick:()=>t.setAddFieldType(t.addFieldType===d.key?null:d.key),className:`flex items-center justify-center gap-1.5 rounded-lg border px-2 py-2 text-xs font-semibold transition-colors ${t.addFieldType===d.key?"border-crimson-600 bg-crimson-600 text-white":"border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800"}`,children:[d.icon,d.label]},d.key))}),t.addFieldType&&_e("p",{className:"mt-1.5 text-xs font-semibold text-crimson-600",children:["Drag on the page to place the ",t.addFieldType," field."]})]}),t.selectedField?de(Ii,{field:t.selectedField,onChange:t.onUpdateField,onDelete:t.onDeleteField}):de("p",{className:"rounded-lg bg-paper px-3 py-2 text-xs text-ink-soft dark:bg-zinc-800/60 dark:text-zinc-400",children:t.hasFormFields?"Click a field on the page to edit its properties.":"No fields yet, add one above."}),_e("button",{type:"button",onClick:t.onFlattenForm,disabled:!t.hasFormFields,title:"Bake all field values into the page (no longer editable)",className:"flex items-center justify-center gap-1.5 rounded-lg border border-ink-line-strong px-3 py-2 text-xs font-semibold text-ink-soft transition-colors hover:bg-paper disabled:opacity-40 dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:[de(Eh,{className:"h-3.5 w-3.5"})," Flatten form"]})]}),(e==="annotate"||e==="draw")&&t.annotationCount>0&&_e("button",{type:"button",onClick:t.onClearAnnotations,className:"flex items-center justify-center gap-1.5 rounded-lg border border-red-200 px-3 py-2 text-xs font-semibold text-red-500 transition-colors hover:bg-red-50 dark:border-red-500/30 dark:hover:bg-red-500/10",children:[de(wh,{className:"h-3.5 w-3.5"})," Clear all annotations"]})]}),i&&de(fr,{value:t.textStyle,onToggle:t.onToggle,onSize:t.onSize,onColor:t.onColor,variant:"panel",fallbackSizePt:t.fallbackSizePt})]}),_e("div",{className:"border-t border-ink-line bg-[#F3ECDD] px-4 py-3 dark:border-white/10 dark:bg-zinc-800/30",children:[de("p",{className:"mb-1 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:"How to use"}),de("p",{className:"text-xs leading-relaxed text-ink-soft dark:text-zinc-400",children:o.help})]})]})}var dt=(t,e,n,r,o)=>{let i=t-n.left,s=e-n.top;return{x:i/r,y:o-s/r}},Ke=(t,e,n,r)=>({x:t*n,y:(r-e)*n});import{Fragment as _h,jsx as We,jsxs as xr}from"react/jsx-runtime";var uo=t=>`rgb(${Math.round(t.r*255)},${Math.round(t.g*255)},${Math.round(t.b*255)})`,vc=(t,e,n)=>{let r=Math.atan2(e.y-t.y,e.x-t.x),o=Math.PI/7,i={x:e.x-n*Math.cos(r-o),y:e.y-n*Math.sin(r-o)},s={x:e.x-n*Math.cos(r+o),y:e.y-n*Math.sin(r+o)};return`${i.x},${i.y} ${e.x},${e.y} ${s.x},${s.y}`},$h=(t,e,n)=>{let r=1.5*n,o=4*n,i=t(e.x,e.y+1),s=[`M ${i.x} ${i.y}`],a=t(e.x+e.width,e.y).x,c=!0;for(let l=i.x+o;l<=a;l+=o)s.push(`L ${l} ${i.y+(c?-r:r)}`),c=!c;return s.join(" ")},kc=(t,e,n,r,o,i)=>e.map((s,a)=>{if(t==="highlight"){let m=n(s.x,s.y+s.height);return We("rect",{x:m.x,y:m.y,width:s.width*r,height:s.height*r,fill:o,opacity:Math.min(.4,i),style:{mixBlendMode:"multiply"}},a)}if(t==="squiggly")return We("path",{d:$h(n,s,r),stroke:o,strokeWidth:Math.max(.75,r),fill:"none",opacity:i},a);let c=t==="strikeout"?s.y+s.height*.5:s.baselineY-Math.max(1,s.height*.12),l=n(s.x,c),d=n(s.x+s.width,c);return We("line",{x1:l.x,y1:l.y,x2:d.x,y2:d.y,stroke:o,strokeWidth:Math.max(1.5,r),opacity:i},a)}),Bh=(t,e,n)=>{var l;let r=uo(t.style.color),o=Math.max(.5,((l=t.style.strokeWidth)!=null?l:1.5)*n),i=t.style.fill?uo(t.style.fill):"none";if(t.kind==="highlight"||t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly")return kc(t.kind,t.quads,e,n,r,t.style.opacity);if(t.kind==="ink")return t.strokes.map((d,m)=>{let h=d.map((f,p)=>{let w=e(f.x,f.y);return`${p===0?"M":"L"} ${w.x} ${w.y}`}).join(" ");return We("path",{d:h,stroke:r,strokeWidth:o,fill:"none",strokeLinecap:"round",strokeLinejoin:"round",opacity:t.style.opacity},m)});if(t.kind==="rect"){let d=at(t),m=e(d.x,d.y+d.height);return We("rect",{x:m.x,y:m.y,width:d.width*n,height:d.height*n,stroke:r,strokeWidth:o,fill:i,opacity:t.style.opacity})}if(t.kind==="ellipse"){let d=at(t),m=e(d.x+d.width/2,d.y+d.height/2);return We("ellipse",{cx:m.x,cy:m.y,rx:d.width/2*n,ry:d.height/2*n,stroke:r,strokeWidth:o,fill:i,opacity:t.style.opacity})}if(t.kind==="polygon"||t.kind==="polyline"){let d=t.points.map(m=>{let h=e(m.x,m.y);return`${h.x},${h.y}`}).join(" ");return t.kind==="polygon"?We("polygon",{points:d,stroke:r,strokeWidth:o,fill:i,opacity:t.style.opacity}):We("polyline",{points:d,stroke:r,strokeWidth:o,fill:"none",opacity:t.style.opacity})}let s=t,a=e(s.points[0].x,s.points[0].y),c=e(s.points[1].x,s.points[1].y);return xr("g",{opacity:t.style.opacity,children:[We("line",{x1:a.x,y1:a.y,x2:c.x,y2:c.y,stroke:r,strokeWidth:o,strokeLinecap:"round"}),t.kind==="arrow"&&We("polyline",{points:vc(a,c,Math.max(8,o*3)),stroke:r,strokeWidth:o,fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})]})},Lh=(t,e,n,r,o)=>{let i=uo(r.color),s=Math.max(.5,r.strokeWidth*n),a=r.fill?uo(r.fill):"none";if(t.kind==="quads")return kc(o,t.quads,e,n,i,r.opacity);if(t.kind==="box"){let d=e(t.rect.x,t.rect.y+t.rect.height);return We("rect",{x:d.x,y:d.y,width:t.rect.width*n,height:t.rect.height*n,stroke:i,strokeWidth:s,fill:a,opacity:r.opacity,strokeDasharray:"4 3"})}if(t.kind==="line"){let d=e(t.a.x,t.a.y),m=e(t.b.x,t.b.y);return xr("g",{opacity:r.opacity,children:[We("line",{x1:d.x,y1:d.y,x2:m.x,y2:m.y,stroke:i,strokeWidth:s,strokeLinecap:"round"}),t.arrow&&We("polyline",{points:vc(d,m,Math.max(8,s*3)),stroke:i,strokeWidth:s,fill:"none"})]})}if(t.kind==="ink"){let d=t.points.map((m,h)=>{let f=e(m.x,m.y);return`${h===0?"M":"L"} ${f.x} ${f.y}`}).join(" ");return We("path",{d,stroke:i,strokeWidth:s,fill:"none",strokeLinecap:"round",strokeLinejoin:"round",opacity:r.opacity})}let c=t.points.map(d=>{let m=e(d.x,d.y);return`${m.x},${m.y}`}).join(" "),l=t.cursor?e(t.cursor.x,t.cursor.y):null;return xr("g",{opacity:r.opacity,children:[We("polyline",{points:c,stroke:i,strokeWidth:s,fill:"none"}),l&&t.points.length>0&&(()=>{let d=e(t.points[t.points.length-1].x,t.points[t.points.length-1].y);return We("line",{x1:d.x,y1:d.y,x2:l.x,y2:l.y,stroke:i,strokeWidth:s,strokeDasharray:"4 3"})})(),t.points.map((d,m)=>{let h=e(d.x,d.y);return We("circle",{cx:h.x,cy:h.y,r:3,fill:i},m)})]})},Uh=[{key:"nw",cursor:"nwse-resize"},{key:"ne",cursor:"nesw-resize"},{key:"sw",cursor:"nesw-resize"},{key:"se",cursor:"nwse-resize"}];function Bi({pageIndex:t,pageHeight:e,scale:n,annots:r,live:o,liveStyle:i,selectedId:s,interactive:a,liveMarkupKind:c,onBeginResize:l}){var f;let d=(p,w)=>Ke(p,w,n,e),m=r.filter(p=>p.pageIndex===t),h=(f=m.find(p=>p.id===s))!=null?f:null;return xr(_h,{children:[xr("svg",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"visible",zIndex:11,pointerEvents:"none"},xmlns:"http://www.w3.org/2000/svg",children:[m.map(p=>We("g",{children:Bh(p,d,n)},p.id)),(o==null?void 0:o.pageIndex)===t&&Lh(o,d,n,i,c),h&&(()=>{let p=at(h),w=d(p.x,p.y+p.height);return We("rect",{x:w.x-3,y:w.y-3,width:p.width*n+6,height:p.height*n+6,fill:"none",stroke:"#D6002F",strokeWidth:1,strokeDasharray:"4 3"})})()]}),a&&h&&(()=>{let p=at(h),w={nw:d(p.x,p.y+p.height),ne:d(p.x+p.width,p.y+p.height),sw:d(p.x,p.y),se:d(p.x+p.width,p.y)};return We("div",{style:{position:"absolute",inset:0,zIndex:12,pointerEvents:"none"},children:Uh.map(({key:b,cursor:y})=>We("div",{onMouseDown:k=>{k.stopPropagation(),k.preventDefault(),l(h.id,b,k)},style:{position:"absolute",left:w[b].x-5,top:w[b].y-5,width:10,height:10,background:"#fff",border:"1.5px solid #D6002F",borderRadius:2,cursor:y,pointerEvents:"auto"}},b))})})()]})}var Xh=t=>{var r;let e=Array.from(t.text);if((r=t.glyphs)!=null&&r.length){let o=[];for(let i of t.glyphs){let s=Math.max(1,Array.from(i.char).length);for(let a=0;a<s;a++)o.push({x:i.pdfX,y:i.pdfY,width:i.width,height:i.height,baselineY:i.pdfBaselineY})}if(o.length===e.length)return e.map((i,s)=>({char:i,...o[s]}))}let n=t.width/Math.max(1,e.length);return e.map((o,i)=>({char:o,x:t.pdfX+i*n,y:t.pdfY,width:n,height:t.height,baselineY:t.pdfBaselineY}))},zh=t=>{let e=[],n=0;for(let r of t)for(let o of Xh(r))e.push({...o,order:n++});return e},Pc=(t,e)=>{if(!t.length)return-1;let n=t.filter(s=>e.y>=s.y-2&&e.y<=s.y+s.height+2),r=n.length?n:t,o=-1,i=Number.POSITIVE_INFINITY;for(let s of r){let a=e.x<s.x?s.x:e.x>s.x+s.width?s.x+s.width:e.x,c=e.y<s.y?s.y:e.y>s.y+s.height?s.y+s.height:e.y,l=Math.hypot(e.x-a,e.y-c);l<i&&(i=l,o=s.order)}return o},Yh=t=>{if(!t.length)return[];let e=[],n=[];for(let r of t){if(n.length){let o=Math.max(2,r.height*.5);Math.abs(r.baselineY-n[0].baselineY)>o&&(e.push(n),n=[])}n.push(r)}return n.length&&e.push(n),e.map(r=>{let o=Math.min(...r.map(d=>d.x)),i=Math.min(...r.map(d=>d.y)),s=Math.max(...r.map(d=>d.x+d.width)),a=Math.max(...r.map(d=>d.y+d.height)),c=r.map(d=>d.baselineY).sort((d,m)=>d-m),l=c[Math.floor(c.length/2)];return{x:o,y:i,width:s-o,height:a-i,baselineY:l}})},Sc=(t,e,n)=>{let r=zh(t);if(!r.length)return{quads:[],text:""};let o=Pc(r,e),i=Pc(r,n);if(o<0||i<0)return{quads:[],text:""};let s=Math.min(o,i),a=Math.max(o,i),c=r.slice(s,a+1);return{quads:Yh(c),text:c.map(l=>l.char).join("")}};function qe(t,e){if(t){if(!Be(t))return t;try{return e(t)}catch{return}}}function Wh(t,e){if(!t)return;let n=qe(t.entries.get("AcroForm"),e);if(!(!n||!Z(n)))return n}function Hh(t,e){if(!t)return[];let n=qe(t.entries.get("Annots"),e);if(!n)return[];let r=[];if(he(n))for(let o of n.items){let i=qe(o,e);i&&Z(i)&&r.push(i)}return r}var Li=t=>t&&typeof t=="object"&&"type"in t&&t.type==="name"?t.value:null,An=t=>{if(!t||typeof t!="object"||!("type"in t)||t.type!=="string")return null;let e=t.value;if(e.length>=2&&e[0]===254&&e[1]===255){let r="";for(let o=2;o+1<e.length;o+=2)r+=String.fromCharCode(e[o]<<8|e[o+1]);return r}let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return n},Cc=t=>t&&typeof t=="object"&&"type"in t&&(t.type==="integer"||t.type==="real")?t.value:null,Gh=1,Kh=2,Vh=4096,qh=32768,Jh=65536,Xx=1<<17,Zh=t=>{if(!t||!he(t)||t.items.length<4)return null;let e=t.items.slice(0,4).map(s=>Cc(s));if(e.some(s=>s===null))return null;let[n,r,o,i]=e;return{x:Math.min(n,o),y:Math.min(r,i),width:Math.abs(o-n),height:Math.abs(i-r)}},Dc=(t,e)=>{let n=qe(t.entries.get("AP"),e);if(!n||!Z(n))return[];let r=qe(n.entries.get("N"),e);return!r||!Z(r)?[]:Array.from(r.entries.keys()).filter(o=>o!=="Off")},Qh=(t,e)=>{var o,i,s;let n=qe(t,e);if(!n||!he(n))return[];let r=[];for(let a of n.items){let c=qe(a,e);c&&he(c)&&c.items.length>0?r.push((i=(o=An(c.items[0]))!=null?o:An(c.items[1]))!=null?i:""):r.push((s=An(c))!=null?s:"")}return r.filter(a=>a.length>0)},ef=t=>{if(!t)return;let e=t.match(/([\d.]+)\s+Tf/);if(!e)return;let n=parseFloat(e[1]);return Number.isFinite(n)?n:void 0},tf=(t,e)=>{switch(t){case"Tx":return"text";case"Ch":return"dropdown";case"Sig":return"signature";case"Btn":return e&Jh?null:e&qh?"radio":"checkbox";default:return null}},nf=(t,e)=>{let n=new Map;for(let[r,o]of t)for(let i of Hh(o,e))n.has(i)||n.set(i,r);return n};function Fc(t,e,n){let r=Wh(t,n);if(!r)return[];let o=qe(r.entries.get("Fields"),n);if(!o||!he(o))return[];let i=An(r.entries.get("DA")),s=nf(e,n),a=[],c=(l,d)=>{var fe,pe,ie,J,_;let m=An(l.entries.get("T")),h=m?d.namePrefix?`${d.namePrefix}.${m}`:m:d.namePrefix,f=Cc(l.entries.get("Ff")),p=f!==null?f:d.flags,w=(fe=Li(l.entries.get("FT")))!=null?fe:d.ft,b=(pe=An(l.entries.get("DA")))!=null?pe:d.da,y=(J=(ie=An(l.entries.get("V")))!=null?ie:Li(l.entries.get("V")))!=null?J:d.value,k={flags:p,namePrefix:h,ft:w,da:b,value:y!=null?y:void 0},C=qe(l.entries.get("Kids"),n),S=C&&he(C)?C.items.map(Q=>qe(Q,n)).filter(Q=>!!Q&&Z(Q)):[],O=Li(l.entries.get("Subtype"))==="Widget"||S.length===0&&l.entries.has("Rect"),N=S.some(Q=>Q.entries.has("T"));if(S.length>0&&N){for(let Q of S)c(Q,k);return}let I=tf(w,p);if(!I){for(let Q of S)c(Q,k);return}let R=ef(b!=null?b:i),H=(p&Gh)!==0,te=(p&Kh)!==0,T=(p&Vh)!==0,ce=I==="dropdown"?Qh(l.entries.get("Opt"),n):void 0,se=S.length>0?S:O?[l]:[];for(let Q of se){let le=Zh(qe(Q.entries.get("Rect"),n));if(!le)continue;let ge=(_=s.get(Q))!=null?_:0,Ce=(I==="checkbox"||I==="radio"?Dc(Q,n):[])[0];a.push({id:`${h}__${a.length}`,name:h,type:I,pageIndex:ge,rect:le,value:y!=null?y:void 0,options:I==="radio"?se.map(Te=>Dc(Te,n)[0]).filter(Te=>!!Te):ce,onState:Ce,fontSize:R,multiline:T,readOnly:H,required:te})}};for(let l of o.items){let d=qe(l,n);d&&Z(d)&&c(d,{flags:0,namePrefix:""})}return a}var Mc=t=>t&&typeof t=="object"&&"type"in t&&t.type==="name"?t.value:null,rf=t=>t&&typeof t=="object"&&"type"in t&&(t.type==="integer"||t.type==="real")?t.value:null,of=t=>{if(!t||typeof t!="object"||!("type"in t)||t.type!=="string")return null;let e=t.value;if(e.length>=2&&e[0]===254&&e[1]===255){let r="";for(let o=2;o+1<e.length;o+=2)r+=String.fromCharCode(e[o]<<8|e[o+1]);return r}let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return n},sf=t=>{if(!t||!he(t)||t.items.length<4)return null;let e=t.items.slice(0,4).map(s=>rf(s));if(e.some(s=>s===null))return null;let[n,r,o,i]=e;return{x:Math.min(n,o),y:Math.min(r,i),width:Math.abs(o-n),height:Math.abs(i-r)}},Rc=(t,e,n)=>{let r=Be(t)?t:qe(t,n);if(!r||!he(r)||r.items.length===0)return;let o=r.items[0];if(Be(o))return e.get(`${o.objNum}:${o.genNum}`)};function Ui(t,e,n){var i;if(!t)return[];let r=qe(t.entries.get("Annots"),n);if(!r||!he(r))return[];let o=[];for(let s of r.items){let a=qe(s,n);if(!a||!Z(a)||Mc(a.entries.get("Subtype"))!=="Link")continue;let c=sf(qe(a.entries.get("Rect"),n));if(!c||c.width<1||c.height<1)continue;let l,d,m=qe(a.entries.get("A"),n);if(m&&Z(m)){let h=Mc(m.entries.get("S"));h==="URI"?l=(i=of(m.entries.get("URI")))!=null?i:void 0:h==="GoTo"&&(d=Rc(m.entries.get("D"),e,n))}l===void 0&&d===void 0&&(d=Rc(a.entries.get("Dest"),e,n)),(l||d!==void 0)&&o.push({rect:c,uri:l,destPageIndex:d})}return o}import{useLayoutEffect as af,useRef as cf}from"react";import{jsx as Ac,jsxs as lf}from"react/jsx-runtime";function _i({runs:t,scale:e,pageHeight:n}){let r=cf(null);return af(()=>{let o=r.current;if(!o)return;o.querySelectorAll("span[data-w]").forEach(s=>{var l;let a=parseFloat((l=s.dataset.w)!=null?l:"0"),c=s.offsetWidth;a>0&&c>0&&(s.style.transform=`scaleX(${a/c})`)})},[t,e,n]),lf("div",{ref:r,className:"pdf-text-layer",style:{position:"absolute",inset:0,zIndex:4,cursor:"text",userSelect:"text",WebkitUserSelect:"text",lineHeight:1},children:[Ac("style",{children:".pdf-text-layer ::selection{background:rgba(37,99,235,0.30)}"}),t.map((o,i)=>{var a;if(!o.text)return null;let s=Ke(o.pdfX,o.pdfY+o.height,e,n);return Ac("span",{"data-w":o.width*e,style:{position:"absolute",left:`${s.x}px`,top:`${s.y}px`,fontSize:`${Math.max(1,o.fontSize*e)}px`,fontFamily:(a=o.fontFamily)!=null?a:"sans-serif",color:"transparent",whiteSpace:"pre",transformOrigin:"0 0",pointerEvents:"auto"},children:o.text},i)})]})}var Xi=(t,e,n,r=0)=>t>=n.pdfX-r&&t<=n.pdfX+n.width+r&&e>=n.pdfY-r&&e<=n.pdfY+n.height+r,Nc=(t,e,n)=>{let r=Math.max(n.pdfX-t,0,t-(n.pdfX+n.width)),o=Math.max(n.pdfY-e,0,e-(n.pdfY+n.height));return Math.hypot(r,o)},Ec=(t,e,n=5)=>{var a,c;if(!e||e.length===0)return null;let r=[...e].sort((l,d)=>{var h,f;let m=((h=d.contentStreamIndex)!=null?h:0)-((f=l.contentStreamIndex)!=null?f:0);return m!==0?m:l.width*l.height-d.width*d.height});for(let l of r){let d=Math.max(n,l.fontSize*.35);if((a=l.glyphs)==null?void 0:a.some(h=>Xi(t.x,t.y,h,d)))return l}let o=r.find(l=>Xi(t.x,t.y,l,Math.max(n,l.fontSize*.25)));if(o)return o;let i=null,s=Number.POSITIVE_INFINITY;for(let l of e){let d=(c=l.glyphs)==null?void 0:c.reduce((p,w)=>Math.min(p,Nc(t.x,t.y,w)),Number.POSITIVE_INFINITY),m=Nc(t.x,t.y,l),h=Math.abs(t.y-l.pdfBaselineY)*.2,f=Math.min(d!=null?d:Number.POSITIVE_INFINITY,m+h);f<s&&(s=f,i=l)}return i&&s<=Math.max(n,i.fontSize*.5)?i:null},ho=(t,e,n=3)=>{if(!e||e.length===0)return null;let r=e.filter(o=>Xi(t.x,t.y,o,n));return r.length===0?null:(r.sort((o,i)=>i.spanEnd!==o.spanEnd?i.spanEnd-o.spanEnd:o.width*o.height-i.width*i.height),r[0])};var df=(t,e,n)=>{let r=t.canvasX/n,o=Math.max(1,t.canvasWidth/n),i=Math.max(1,t.canvasHeight/n),s=e-(t.canvasY+t.canvasHeight)/n,a=e-t.canvasBaselineY/n;return{x:r,y:s,width:o,height:i,baselineY:a}},Tc=(t,e,n,r,o,i)=>({pdfX:t/i,pdfY:o-(e+r)/i,width:Math.max(.5,n/i),height:Math.max(.5,r/i)}),Oc=(t,e,n,r)=>({kind:"image",pageIndex:e,...Tc(t.canvasX,t.canvasY,t.canvasWidth,t.canvasHeight,n,r),spanStart:t.streamOperatorIndex,spanEnd:t.streamOperatorIndex,ctm:[...t.ctm],fromXObject:t.fromXObject,xobjectName:t.xobjectName}),Ic=(t,e,n,r)=>({kind:"graphic",pageIndex:e,...Tc(t.canvasX,t.canvasY,t.canvasWidth,t.canvasHeight,n,r),spanStart:t.operatorStart,spanEnd:t.operatorEnd,ctm:[...t.ctmAtStart],fromXObject:t.fromXObject}),jc=(t,e,n,r)=>{let o=df(t,n,r);return{pageIndex:e,text:t.text,pdfX:o.x,pdfY:o.y,pdfBaselineY:o.baselineY,width:o.width,height:o.height,fontSize:Math.max(6,t.fontSize),fontName:t.fontName,fontFamily:t.fontFamily,color:t.fillColor,streamOperatorIndices:[t.streamOperatorIndex],fromXObject:t.fromXObject,glyphs:t.glyphs.map(i=>({char:i.char,pdfX:i.canvasX/r,pdfY:n-(i.canvasY+i.canvasHeight)/r,pdfBaselineY:n-i.canvasBaselineY/r,width:Math.max(1,i.canvasWidth/r),height:Math.max(1,i.canvasHeight/r)}))}};var $c=t=>{var r;let e=t.color,n=e?`${Math.round(e.r*255)},${Math.round(e.g*255)},${Math.round(e.b*255)}`:"-";return`${(r=t.fontName)!=null?r:"-"}|${Math.round(t.fontSize)}|${n}`},Bc=(t,e,n)=>{var o,i;if(!((o=t.glyphs)!=null&&o.length)||!((i=e.glyphs)!=null&&i.length))return;let r=[...t.glyphs];if(n){let s=t.pdfX+t.width;r.push({char:" ",pdfX:s,pdfY:t.pdfY,width:Math.max(0,e.pdfX-s),height:t.height,pdfBaselineY:t.pdfBaselineY})}return r.push(...e.glyphs),r},fo=t=>{if(!t.length)return[];let e=[...t].sort((o,i)=>Math.abs(i.pdfBaselineY-o.pdfBaselineY)>2?i.pdfBaselineY-o.pdfBaselineY:o.pdfX-i.pdfX),n=[];e.forEach(o=>{let i=Math.max(2,o.height*.45),s=n[n.length-1];if(!s||Math.abs(s.baselineY-o.pdfBaselineY)>i){n.push({baselineY:o.pdfBaselineY,runs:[o]});return}s.runs.push(o),s.baselineY=(s.baselineY*(s.runs.length-1)+o.pdfBaselineY)/s.runs.length});let r=[];return n.forEach(o=>{var a,c,l,d,m,h,f,p,w,b;let i=[...o.runs].sort((y,k)=>y.pdfX-k.pdfX);if(!i.length)return;let s={...i[0]};for(let y=1;y<i.length;y+=1){let k=i[y],C=k.pdfX-(s.pdfX+s.width),S=Math.max(1,s.fontSize*.15),F=Math.max(2,s.fontSize*.6);if(!(((a=s.contentStreamIndex)!=null?a:0)===((c=k.contentStreamIndex)!=null?c:0))){r.push(s),s={...k};continue}if($c(s)!==$c(k)){r.push(s),s={...k};continue}C<=S?s={...s,text:`${s.text}${k.text}`,width:k.pdfX+k.width-s.pdfX,height:Math.max(s.height,k.height),glyphs:Bc(s,k,!1),streamOperatorIndices:[...(l=s.streamOperatorIndices)!=null?l:[],...(d=k.streamOperatorIndices)!=null?d:[]],fromXObject:((m=s.fromXObject)!=null?m:!1)||((h=k.fromXObject)!=null?h:!1)}:C<=F?s={...s,text:`${s.text} ${k.text}`,width:k.pdfX+k.width-s.pdfX,height:Math.max(s.height,k.height),glyphs:Bc(s,k,!0),streamOperatorIndices:[...(f=s.streamOperatorIndices)!=null?f:[],...(p=k.streamOperatorIndices)!=null?p:[]],fromXObject:((w=s.fromXObject)!=null?w:!1)||((b=k.fromXObject)!=null?b:!1)}:(r.push(s),s={...k})}r.push(s)}),r};function Lc(t,e,n,r){var s;let o=r>0?r:1,i=[];for(let a of t){let c=((s=a.text)!=null?s:"").trim();if(!c)continue;let l=Math.max(1,a.width/o),d=Math.max(1,a.height/o),m=a.x/o,h=n-(a.y+a.height)/o,f=h+d*.2;i.push({text:c,pdfX:m,pdfY:h,width:l,height:d,pdfBaselineY:f,fontSize:Math.max(4,d*.78),fontName:"Helvetica",color:{r:0,g:0,b:0},pageIndex:e,ocr:!0})}return i}var mo=()=>({ctm:[1,0,0,1,0,0],font:"",fontSize:12,charSpacing:0,wordSpacing:0,horizScale:100,leading:0,textRise:0,textRenderMode:0,textMatrix:[1,0,0,1,0,0],textLineMatrix:[1,0,0,1,0,0],fillColorSpace:"DeviceGray",strokeColorSpace:"DeviceGray",fillColor:{space:"gray",gray:0},strokeColor:{space:"gray",gray:0},fillPatternName:null,strokePatternName:null,fillPattern:null,strokePattern:null,lineWidth:1,lineCap:0,lineJoin:0,miterLimit:10,dashArray:[],dashPhase:0,fillAlpha:1,strokeAlpha:1,blendMode:"Normal"});var Uc=t=>t===" "||t===" "||t==="\r"||t===`
|
|
39
|
-
`||t==="\f"||t==="\0";function
|
|
40
|
-
`&&t[r]!=="\r";)r++;continue}if(o==="{"){let c=[];n[n.length-1].push(c),n.push(c),r++;continue}if(o==="}"){if(n.length===1)throw new Error("Unbalanced } in PostScript function");n.pop(),r++;continue}let i=r;for(;i<t.length&&!Uc(t[i])&&t[i]!=="{"&&t[i]!=="}"&&t[i]!=="%";)i++;let s=t.slice(r,i);r=i;let a=Number(s);Number.isFinite(a)&&/^[-+.0-9eE]+$/.test(s)?n[n.length-1].push(a):n[n.length-1].push(s.toLowerCase())}if(n.length!==1)throw new Error("Unbalanced { in PostScript function");return e.length===1&&Array.isArray(e[0])?e[0]:e}var zi=Math.PI/180;function ke(t,e){if(typeof t!="number")throw new Error(`${e}: expected number`);return t}function Qe(t,e){if(typeof t!="number")throw new Error(`${e}: expected integer`);return Math.trunc(t)}function _c(t,e){if(typeof t!="boolean")throw new Error(`${e}: expected boolean`);return t}function zc(t,e,n){let r=[...e],o=0,i=m=>{if(r.length>=100)throw new Error("PostScript stack overflow");r.push(m)},s=m=>{let h=r.pop();if(h===void 0)throw new Error(`${m}: stack underflow`);return h},a=m=>{let h=s(m);if(!Array.isArray(h))throw new Error(`${m}: expected procedure`);return h},c=m=>{for(let h of m){if(++o>1e4)throw new Error("PostScript op budget exceeded");if(typeof h=="number"){i(h);continue}if(Array.isArray(h)){i(h);continue}switch(h){case"add":{let f=ke(s(h),h),p=ke(s(h),h);i(p+f);break}case"sub":{let f=ke(s(h),h),p=ke(s(h),h);i(p-f);break}case"mul":{let f=ke(s(h),h),p=ke(s(h),h);i(p*f);break}case"div":{let f=ke(s(h),h),p=ke(s(h),h);i(f===0?0:p/f);break}case"idiv":{let f=Qe(s(h),h),p=Qe(s(h),h);i(f===0?0:Math.trunc(p/f));break}case"mod":{let f=Qe(s(h),h),p=Qe(s(h),h);i(f===0?0:p%f);break}case"neg":i(-ke(s(h),h));break;case"abs":i(Math.abs(ke(s(h),h)));break;case"ceiling":i(Math.ceil(ke(s(h),h)));break;case"floor":i(Math.floor(ke(s(h),h)));break;case"round":i(Math.round(ke(s(h),h)));break;case"truncate":i(Math.trunc(ke(s(h),h)));break;case"sqrt":i(Math.sqrt(Math.max(0,ke(s(h),h))));break;case"sin":i(Math.sin(ke(s(h),h)*zi));break;case"cos":i(Math.cos(ke(s(h),h)*zi));break;case"atan":{let f=ke(s(h),h),p=ke(s(h),h),w=Math.atan2(p,f)/zi;w<0&&(w+=360),i(w);break}case"exp":{let f=ke(s(h),h),p=ke(s(h),h);i(Math.pow(p,f));break}case"ln":i(Math.log(Math.max(Number.MIN_VALUE,ke(s(h),h))));break;case"log":i(Math.log10(Math.max(Number.MIN_VALUE,ke(s(h),h))));break;case"cvi":i(Math.trunc(ke(s(h),h)));break;case"cvr":i(ke(s(h),h));break;case"eq":{let f=s(h),p=s(h);i(p===f);break}case"ne":{let f=s(h),p=s(h);i(p!==f);break}case"gt":{let f=ke(s(h),h),p=ke(s(h),h);i(p>f);break}case"ge":{let f=ke(s(h),h),p=ke(s(h),h);i(p>=f);break}case"lt":{let f=ke(s(h),h),p=ke(s(h),h);i(p<f);break}case"le":{let f=ke(s(h),h),p=ke(s(h),h);i(p<=f);break}case"and":{let f=s(h),p=s(h);i(typeof p=="boolean"&&typeof f=="boolean"?p&&f:Qe(p,h)&Qe(f,h));break}case"or":{let f=s(h),p=s(h);i(typeof p=="boolean"&&typeof f=="boolean"?p||f:Qe(p,h)|Qe(f,h));break}case"xor":{let f=s(h),p=s(h);i(typeof p=="boolean"&&typeof f=="boolean"?p!==f:Qe(p,h)^Qe(f,h));break}case"not":{let f=s(h);i(typeof f=="boolean"?!f:~Qe(f,h));break}case"bitshift":{let f=Qe(s(h),h),p=Qe(s(h),h);i(f>=0?p<<f:p>>-f);break}case"true":i(!0);break;case"false":i(!1);break;case"pop":s(h);break;case"exch":{let f=s(h),p=s(h);i(f),i(p);break}case"dup":{let f=s(h);i(f),i(f);break}case"copy":{let f=Qe(s(h),h);if(f<0||f>r.length)throw new Error("copy: bad count");let p=r.length-f;for(let w=0;w<f;w++)i(r[p+w]);break}case"index":{let f=Qe(s(h),h);if(f<0||f>=r.length)throw new Error("index: out of range");i(r[r.length-1-f]);break}case"roll":{let f=Qe(s(h),h),p=Qe(s(h),h);if(p<0||p>r.length)throw new Error("roll: bad count");if(p>0&&f!==0){let w=r.splice(r.length-p,p),b=(f%p+p)%p;r.push(...w.slice(p-b),...w.slice(0,p-b))}break}case"if":{let f=a(h);_c(s(h),h)&&c(f);break}case"ifelse":{let f=a(h),p=a(h),w=_c(s(h),h);c(w?p:f);break}default:throw new Error(`Unknown PostScript operator: ${h}`)}}};c(t);let l=Math.floor(n.length/2);if(r.length<l)throw new Error("PostScript function returned too few values");return r.slice(r.length-l).map((m,h)=>{if(typeof m!="number"&&typeof m!="boolean")throw new Error("PostScript function returned a non-numeric value");let f=typeof m=="number"?m:m?1:0,p=n[h*2],w=n[h*2+1];return Math.max(p,Math.min(w,f))})}var po=K,Ut=t=>!t||!he(t)?null:t.items.map(e=>{var n;return(n=po(e))!=null?n:0}),rt=(t,e)=>{if(t){if(!Be(t))return t;try{return e(t)}catch{return}}},Yc=new WeakMap,uf=(t,e,n)=>{var c;let r=e*n,o=r>>3,i=r&7,s=n,a=0;for(;s>0;){let l=8-i,d=Math.min(l,s),h=((c=t[o])!=null?c:0)>>l-d&(1<<d)-1;a=a*(1<<d)+h,s-=d,i+=d,i===8&&(i=0,o++)}return a},hf=(t,e)=>t.map((n,r)=>{let o=e[r*2],i=e[r*2+1];return o===void 0||i===void 0?n:Math.max(o,Math.min(i,n))}),go=(t,e,n)=>{var l,d,m,h,f,p,w,b,y,k,C,S,F,O,N,I,R,H,te,T,ce,se,fe,pe,ie,J;let r=rt(t,n);if(!r)return null;let o=me(r)?r.dict:Z(r)?r:null;if(!o)return null;let i=Math.floor((l=po(rt(o.entries.get("FunctionType"),n)))!=null?l:-1),s=(d=Ut(rt(o.entries.get("Domain"),n)))!=null?d:[0,1],a=Math.max(1,Math.floor(s.length/2)),c=[];for(let _=0;_<a;_++){let Q=(m=e[_])!=null?m:0,le=(h=s[_*2])!=null?h:0,ge=(f=s[_*2+1])!=null?f:1;c.push(Math.max(Math.min(le,ge),Math.min(Math.max(le,ge),Q)))}if(i===2){let _=(p=po(rt(o.entries.get("N"),n)))!=null?p:1,Q=(w=Ut(rt(o.entries.get("C0"),n)))!=null?w:[0],le=(b=Ut(rt(o.entries.get("C1"),n)))!=null?b:[1],ge=Math.pow(c[0],_);return Q.map((Xe,Ce)=>{var Te;return Xe+ge*(((Te=le[Ce])!=null?Te:1)-Xe)})}if(i===0){if(!me(r))return null;let _=((y=Ut(rt(o.entries.get("Size"),n)))!=null?y:[2]).map(Pe=>Math.max(1,Math.floor(Pe)));if(_.length<a||a>8)return null;let Q=Math.floor((k=po(rt(o.entries.get("BitsPerSample"),n)))!=null?k:8);if(![1,2,4,8,12,16,24,32].includes(Q))return null;let le=Ut(rt(o.entries.get("Range"),n));if(!le||le.length<2)return null;let ge=Math.floor(le.length/2),Xe=[];for(let Pe=0;Pe<a;Pe++)Xe.push(0,_[Pe]-1);let Ce=(C=Ut(rt(o.entries.get("Encode"),n)))!=null?C:Xe,Te=(S=Ut(rt(o.entries.get("Decode"),n)))!=null?S:le,ht=Q===32?4294967295:(1<<Q)-1,et;try{et=ve.decodeStreamSync(r)}catch{return null}let ct=[],Rt=[];for(let Pe=0;Pe<a;Pe++){let Ge=(F=s[Pe*2])!=null?F:0,Ze=(O=s[Pe*2+1])!=null?O:1,Ne=(N=Ce[Pe*2])!=null?N:0,yn=(I=Ce[Pe*2+1])!=null?I:_[Pe]-1,vt=Ze!==Ge?(c[Pe]-Ge)/(Ze-Ge):0,kr=Math.max(0,Math.min(_[Pe]-1,Ne+vt*(yn-Ne))),At=Math.min(_[Pe]-1,Math.floor(kr));ct.push(At),Rt.push(Math.max(0,Math.min(1,kr-At)))}let ft=[],xn=1;for(let Pe=0;Pe<a;Pe++)ft.push(xn),xn*=_[Pe];let be=new Array(ge).fill(0),Ve=1<<a;for(let Pe=0;Pe<Ve;Pe++){let Ge=1,Ze=0;for(let Ne=0;Ne<a;Ne++)if(Pe>>Ne&1){if(Rt[Ne]===0){Ge=0;break}Ge*=Rt[Ne],Ze+=Math.min(_[Ne]-1,ct[Ne]+1)*ft[Ne]}else Ge*=1-Rt[Ne],Ze+=ct[Ne]*ft[Ne];if(Ge!==0)for(let Ne=0;Ne<ge;Ne++)be[Ne]+=Ge*uf(et,Ze*ge+Ne,Q)}let bn=be.map((Pe,Ge)=>{var yn,vt;let Ze=(yn=Te[Ge*2])!=null?yn:0,Ne=(vt=Te[Ge*2+1])!=null?vt:1;return Ze+Pe/ht*(Ne-Ze)});return hf(bn,le)}if(i===3){let _=(R=Ut(rt(o.entries.get("Bounds"),n)))!=null?R:[],Q=(H=Ut(rt(o.entries.get("Encode"),n)))!=null?H:[],le=rt(o.entries.get("Functions"),n);if(!le||!he(le))return null;let ge=le.items,Xe=c[0],Ce=0;for(let ft=0;ft<_.length&&Xe>=_[ft];ft++)Ce=ft+1;let Te=Ce===0?(te=s[0])!=null?te:0:(ce=(T=_[Ce-1])!=null?T:s[0])!=null?ce:0,ht=Ce<_.length?(fe=(se=_[Ce])!=null?se:s[1])!=null?fe:1:(pe=s[1])!=null?pe:1,et=(ie=Q[Ce*2])!=null?ie:0,ct=(J=Q[Ce*2+1])!=null?J:1,Rt=Te===ht?et:et+(Xe-Te)/(ht-Te)*(ct-et);return go(ge[Ce],[Rt],n)}if(i===4){if(!me(r))return null;let _=Ut(rt(o.entries.get("Range"),n));if(!_||_.length<2)return null;try{let Q=Yc.get(r);if(!Q){let le=new TextDecoder("latin1").decode(ve.decodeStreamSync(r));Q=Xc(le),Yc.set(r,Q)}return zc(Q,c,_)}catch{return null}}return null},xo=(t,e,n)=>go(t,[e],n),Yi=(t,e,n)=>{let r=rt(t,n);if(!r)return null;if(he(r)){let o=[];for(let i of r.items){let s=go(i,e,n);if(!s)return null;o.push(...s)}return o}return go(r,e,n)};var Wc=t=>Math.max(1,Math.min(2048,Math.ceil(t)));function Hc(t,e,n,r){if(![...t,e,n,...r].every(Number.isFinite)||Math.abs(e)<1e-9||Math.abs(n)<1e-9)return null;let o=Math.hypot(r[0],r[1]),i=Math.hypot(r[2],r[3]);if(o<1e-12||i<1e-12)return null;let s=Wc(Math.abs(e)*o),a=Wc(Math.abs(n)*i),[c,l]=t,d=[s/e,0,0,-a/n,-c*s/e,(l+n)*a/n],m=Hn(d);return m?{cellPxW:s,cellPxH:a,contentTransform:d,paintTransform:m}:null}var Vn=5e4,Hi=class{constructor(e){this.bytes=e;this.bitPos=0}get hasData(){return this.bitPos<this.bytes.length*8}get remainingBits(){return Math.max(0,this.bytes.length*8-this.bitPos)}read(e){var o;let n=0,r=e;for(;r>0;){let i=this.bitPos>>3,a=8-(this.bitPos&7),c=Math.min(a,r),d=((o=this.bytes[i])!=null?o:0)>>a-c&(1<<c)-1;n=n*(1<<c)+d,this.bitPos+=c,r-=c}return n}alignToByte(){this.bitPos=this.bitPos+7&-8}},ff=t=>t>=32?4294967295:(1<<t)-1,Wi=(t,e,n,r)=>n+t/ff(e)*(r-n);function Gc(t,e,n,r){var S;let o=new Hi(n),i=[],{bitsPerCoordinate:s,bitsPerComponent:a,bitsPerFlag:c,decode:l,numColorComponents:d}=e;if(l.length<4+d*2)return[];let m=()=>[Wi(o.read(s),s,l[0],l[1]),Wi(o.read(s),s,l[2],l[3])],h=()=>{let F=[];for(let O=0;O<d;O++)F.push(Wi(o.read(a),a,l[4+O*2],l[5+O*2]));return r(F)},f=2*s+d*a;if(t===4){let F=c+f,O=null,N=null,I=null,R=()=>{let H=o.read(c),[te,T]=m(),ce=h();return o.alignToByte(),{flag:H,v:{x:te,y:T,color:ce}}};for(;o.remainingBits>=F&&i.length<Vn;){let H=R();if(H.flag===0||O===null||N===null||I===null){if(O=H.v,o.remainingBits<F||(N=R().v,o.remainingBits<F))break;I=R().v}else H.flag===1?(O=N,N=I,I=H.v):(N=I,I=H.v);br(i,O,N,I)}return i}if(t===5){let F=Math.max(2,Math.floor((S=e.verticesPerRow)!=null?S:2)),O=[];for(;o.remainingBits>=F*f;){let N=[];for(let I=0;I<F;I++){let[R,H]=m();N.push({x:R,y:H,color:h()})}if(O.push(N),O.length*F>Vn)break}for(let N=0;N+1<O.length&&i.length<Vn;N++)for(let I=0;I+1<F&&i.length<Vn;I++)br(i,O[N][I],O[N][I+1],O[N+1][I]),br(i,O[N][I+1],O[N+1][I+1],O[N+1][I]);return i}let p=t===6?12:16,w=t===6?8:12,b=null,y=null,k=p*2*s+4*d*a,C=w*2*s+2*d*a;for(;o.remainingBits>=c+C&&i.length<Vn;){let F=o.read(c),O,N;if(F===0||!b||!y){if(o.remainingBits<k)break;O=[];for(let I=0;I<p;I++)O.push(m());N=[h(),h(),h(),h()]}else{let I=[];for(let ce=0;ce<w;ce++)I.push(m());let R=h(),H=h(),te,T;F===1?(te=[b[3],b[4],b[5],b[6]],T=[y[1],y[2]]):F===2?(te=[b[6],b[7],b[8],b[9]],T=[y[2],y[3]]):(te=[b[9],b[10],b[11],b[0]],T=[y[3],y[0]]),O=[...te,...I],N=[T[0],T[1],R,H]}if(!Number.isFinite(O[0][0]))break;pf(i,O,N),b=O,y=N}return i}var br=(t,e,n,r)=>{t.push({p:[[e.x,e.y],[n.x,n.y],[r.x,r.y]],c:[e.color,n.color,r.color]})},bo=(t,e,n,r,o)=>{let i=1-o,s=i*i*i,a=3*i*i*o,c=3*i*o*o,l=o*o*o;return[s*t[0]+a*e[0]+c*n[0]+l*r[0],s*t[1]+a*e[1]+c*n[1]+l*r[1]]},mf=6,pf=(t,e,n)=>{let[r,o,i,s,a,c,l,d,m,h,f,p]=e,[w,b,y,k]=n,C=(N,I)=>{let R=bo(r,o,i,s,I),H=bo(h,m,d,l,I),te=bo(r,p,f,h,N),T=bo(s,a,c,l,N),ce=(1-N)*R[0]+N*H[0]+(1-I)*te[0]+I*T[0]-((1-N)*(1-I)*r[0]+N*(1-I)*h[0]+(1-N)*I*s[0]+N*I*l[0]),se=(1-N)*R[1]+N*H[1]+(1-I)*te[1]+I*T[1]-((1-N)*(1-I)*r[1]+N*(1-I)*h[1]+(1-N)*I*s[1]+N*I*l[1]);return[ce,se]},S=(N,I)=>[(1-N)*(1-I)*w[0]+(1-N)*I*b[0]+N*I*y[0]+N*(1-I)*k[0],(1-N)*(1-I)*w[1]+(1-N)*I*b[1]+N*I*y[1]+N*(1-I)*k[1],(1-N)*(1-I)*w[2]+(1-N)*I*b[2]+N*I*y[2]+N*(1-I)*k[2]],F=mf,O=[];for(let N=0;N<=F;N++){let I=[];for(let R=0;R<=F;R++){let H=R/F,te=N/F,[T,ce]=C(H,te);I.push({x:T,y:ce,color:S(H,te)})}O.push(I)}for(let N=0;N<F;N++)for(let I=0;I<F;I++){if(t.length+2>Vn)return;br(t,O[N][I],O[N][I+1],O[N+1][I]),br(t,O[N][I+1],O[N+1][I+1],O[N+1][I])}};function Kc(t,e,n,r){let o=new Uint8ClampedArray(n*r*4),i=(s,a)=>[e[0]*s+e[2]*a+e[4],e[1]*s+e[3]*a+e[5]];for(let s of t){let[a,c,l]=s.p.map(([w,b])=>i(w,b)),d=(c[0]-a[0])*(l[1]-a[1])-(c[1]-a[1])*(l[0]-a[0]);if(Math.abs(d)<1e-9)continue;let m=Math.max(0,Math.floor(Math.min(a[0],c[0],l[0]))),h=Math.min(n-1,Math.ceil(Math.max(a[0],c[0],l[0]))),f=Math.max(0,Math.floor(Math.min(a[1],c[1],l[1]))),p=Math.min(r-1,Math.ceil(Math.max(a[1],c[1],l[1])));for(let w=f;w<=p;w++)for(let b=m;b<=h;b++){let y=b+.5,k=w+.5,C=((c[0]-y)*(l[1]-k)-(c[1]-k)*(l[0]-y))/d,S=((l[0]-y)*(a[1]-k)-(l[1]-k)*(a[0]-y))/d,F=1-C-S;if(C<-1e-6||S<-1e-6||F<-1e-6)continue;let O=(w*n+b)*4;o[O]=255*(C*s.c[0][0]+S*s.c[1][0]+F*s.c[2][0]),o[O+1]=255*(C*s.c[0][1]+S*s.c[1][1]+F*s.c[2][1]),o[O+2]=255*(C*s.c[0][2]+S*s.c[1][2]+F*s.c[2][2]),o[O+3]=255}}return o}var gf=12,xf=(t,e,n)=>t.minX-n<=e.maxX&&e.minX-n<=t.maxX&&t.minY-n<=e.maxY&&e.minY-n<=t.maxY,bf=(t,e)=>({minX:Math.min(t.minX,e.minX),minY:Math.min(t.minY,e.minY),maxX:Math.max(t.maxX,e.maxX),maxY:Math.max(t.maxY,e.maxY)});function Vc(t,e,n,r){if(!t.length)return[];let o=Math.max(2,.01*Math.hypot(n,r)),i=[...e].sort((d,m)=>d-m),s=(d,m)=>{let h=0,f=i.length-1;for(;h<=f;){let p=h+f>>1,w=i[p];if(w<=d)h=p+1;else if(w>=m)f=p-1;else return!0}return!1},a=[],c=null;for(let d of t)c!==null&&d.fromXObject===c.fromXObject&&d.pathStartIndex-c.operatorEnd<=gf&&!s(c.operatorEnd,d.pathStartIndex)&&xf(c.bbox,d.bbox,o)&&c?(c.bbox=bf(c.bbox,d.bbox),c.operatorEnd=Math.max(c.operatorEnd,d.paintIndex),c.operatorStart=Math.min(c.operatorStart,d.pathStartIndex),c.paintOperatorIndices.push(d.paintIndex)):(c&&a.push(c),c={bbox:{...d.bbox},operatorStart:d.pathStartIndex,operatorEnd:d.paintIndex,paintOperatorIndices:[d.paintIndex],ctmAtStart:[...d.ctmAtStart],fromXObject:d.fromXObject});c&&a.push(c);let l=n*r;return a.filter(d=>{let m=d.bbox.maxX-d.bbox.minX,h=d.bbox.maxY-d.bbox.minY;return m>0&&h>0&&m*h<=.9*l})}function yf(t){return t&&typeof t=="object"&&"type"in t&&t.type==="name"&&"value"in t?String(t.value):""}function qc(t,e){if(!t)return null;let n=s=>{let a=e(s);if(!a||!me(a))return null;try{return ve.decodeStreamSync(a)}catch{return null}},r=n(t.entries.get("FontFile2"));if(r&&r.length>0)return{bytes:r,kind:"truetype"};let o=e(t.entries.get("FontFile3"));if(o&&me(o)){let s=n(o);if(s&&s.length>0){let c=yf(o.dict.entries.get("Subtype"))==="OpenType"?"opentype":"cff";return{bytes:s,kind:c}}}let i=n(t.entries.get("FontFile"));return i&&i.length>0?{bytes:i,kind:"type1"}:null}function wf(t){return t==="truetype"||t==="opentype"}var yo=(t,e)=>t[e]<<8|t[e+1],vf=(t,e)=>t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];function kf(t){if(t.length<12)return!1;let e=yo(t,4),n=-1;for(let o=0;o<e;o+=1){let i=12+o*16;if(i+16>t.length)return!1;if(t[i]===99&&t[i+1]===109&&t[i+2]===97&&t[i+3]===112){n=vf(t,i+8);break}}if(n<0||n+4>t.length)return!1;let r=yo(t,n+2);for(let o=0;o<r;o+=1){let i=n+4+o*8;if(i+8>t.length)break;let s=yo(t,i),a=yo(t,i+2);if(s===3&&(a===1||a===10)||s===0)return!0}return!1}function Pf(t){let e=2166136261,n=t.length,r=Math.max(1,Math.floor(n/4096));for(let o=0;o<n;o+=r)e^=t[o],e=Math.imul(e,16777619);return e^=n,e=Math.imul(e,16777619),`npf-${(e>>>0).toString(16)}`}var Gi=new Map,Ki=new Map,Sf=()=>typeof document!="undefined"&&typeof globalThis.FontFace!="undefined"&&!!document.fonts;async function Jc(t){if(!Sf()||!wf(t.kind)||!kf(t.bytes))return null;let e=Pf(t.bytes),n=Gi.get(e);if(n==="loaded")return e;if(n==="failed")return null;let r=Ki.get(e);if(r)return r;let o=(async()=>{try{let i=t.bytes.slice().buffer,s=new FontFace(e,i);return await s.load(),document.fonts.add(s),Gi.set(e,"loaded"),e}catch{return Gi.set(e,"failed"),null}finally{Ki.delete(e)}})();return Ki.set(e,o),o}var Vi=null,wo=()=>Vi!=null?Vi:Vi=import("./pdf.image_decoders.min-ABCYWBEM.js"),Zc=new Set,Qc=new Set,el=new Set(["F1","F3","F4"]),tl=new WeakMap,Df=()=>new Promise(t=>setTimeout(t,0)),qn=class qn{constructor(e,n,r,o,i){this.canvas=e;this.pageWidth=n;this.pageHeight=r;this.scale=o;this.stateStack=[];this.state=mo();this.atomicLogCount=0;this.commandIndex=0;this.xobjectDepth=0;this.pageResources=null;this.objectLoader=null;this.fontCache=new Map;this.embeddedFamilies=new Map;this.glyphWidthCache=new Map;this.separationColorCache=new Map;this.fillColorResolver=null;this.strokeColorResolver=null;this.resolverStack=[];this.capturedTextRuns=[];this.fontDiagnosticsLogged=new Set;this.rawByteDiagnosticsLogged=new Set;this.currentPathX=0;this.currentPathY=0;this.pathStartX=0;this.pathStartY=0;this.initialTransform=null;this.forcedColor=null;this.patternDepth=0;this.patternCache=new Map;this.meshCache=new Map;this.layerStack=[];this.layerPool=[];this.capturedImages=[];this.paintRecords=[];this.breakerIndices=[];this.pendingPath=null;this.captureSuppressed=0;var c,l,d,m,h,f,p;let s=(c=i==null?void 0:i.debugAtomic)!=null?c:!1,a=e.getContext("2d",{willReadFrequently:s});if(!a)throw new Error("2D context unavailable");this.ctx=a,this.baseCtx=a,this.disableClip=(l=i==null?void 0:i.disableClip)!=null?l:!1,this.debug=(d=i==null?void 0:i.debug)!=null?d:!1,this.debugAtomic=s,this.maxAtomicLogs=(m=i==null?void 0:i.maxAtomicLogs)!=null?m:500,this.initialTransform=(h=i==null?void 0:i.initialTransform)!=null?h:null,this.forcedColor=(f=i==null?void 0:i.forcedColor)!=null?f:null,this.patternDepth=(p=i==null?void 0:i.patternDepth)!=null?p:0,e.width=Math.ceil(n*o),e.height=Math.ceil(r*o),i!=null&&i.transparentBackground||(this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.fillStyle="white",this.ctx.fillRect(0,0,e.width,e.height),this.ctx.restore()),this.forcedColor&&(this.state.fillColor=this.forcedColor,this.state.strokeColor=this.forcedColor,this.ctx.fillStyle=Jt(this.forcedColor),this.ctx.strokeStyle=Jt(this.forcedColor)),this.applyCurrentTransform(),this.logDebug("init",{pageWidth:n,pageHeight:r,scale:o,canvasWidth:e.width,canvasHeight:e.height,disableClip:this.disableClip})}render(e){this.commandIndex=0,this.capturedTextRuns=[],this.applyCurrentTransform(),this.logDebug("render:start",{commandCount:e.length}),this.logDebug("orientation",{flipYApplied:!0});for(let n of e){let r=this.commandIndex++;this.debug&&this.logDebug("command",{index:r,op:n.op,payload:this.commandPayload(n)});let i=this.debugAtomic&&this.atomicLogCount<this.maxAtomicLogs?this.captureAtomicState():null;this.execute(n),i&&this.logAtomic(r,n,i,this.captureAtomicState())}this.logDebug("render:end",{renderedCommands:e.length,capturedTextRuns:this.capturedTextRuns.length,finalTextMatrix:this.state.textMatrix,finalLineMatrix:this.state.textLineMatrix,finalCTM:this.state.ctm,stackDepth:this.stateStack.length})}async renderAsync(e){for(this.commandIndex=0,this.xobjectDepth=0,this.capturedTextRuns=[],this.capturedImages=[],this.paintRecords=[],this.breakerIndices=[],this.pendingPath=null,this.patternCache.clear(),this.meshCache.clear(),this.glyphWidthCache.clear(),this.ctx=this.baseCtx,this.layerStack=[],this.applyCurrentTransform(),this.logDebug("render:start",{commandCount:e.length,async:!0}),await this.preloadEmbeddedFonts(),await this.runCommandsAsync(e);this.layerStack.length>0;)this.popLayer();this.logDebug("render:end",{renderedCommands:e.length,capturedTextRuns:this.capturedTextRuns.length,finalTextMatrix:this.state.textMatrix,finalLineMatrix:this.state.textLineMatrix,finalCTM:this.state.ctm,stackDepth:this.stateStack.length,async:!0})}async renderAnnotations(e){if(!e)return;let n=this.resolveObject(e.entries.get("Annots"));if(!n||!he(n))return;let r=this.state;this.state=mo(),this.applyCurrentTransform();try{for(let o of n.items){let i=this.resolveObject(o);if(!(!i||!Z(i)))try{await this.renderOneAnnotation(i)}catch(s){this.logDebug("annot:render-failed",{error:s instanceof Error?s.message:String(s)})}}}finally{this.state=r,this.applyCurrentTransform()}}async renderOneAnnotation(e){var l,d;let n=Me(e.entries.get("Subtype"));if(n==="Popup"||n==="Link"||n==="Widget")return;let r=Math.floor((l=K(e.entries.get("F")))!=null?l:0);if((r&2)!==0||(r&32)!==0)return;let o=this.resolveAppearanceStream(e);if(!o)return;let i=ut(this.resolveObject(e.entries.get("Rect")));if(!i||i.length<4)return;let s=ut(o.dict.entries.get("BBox"));if(!s||s.length<4)return;let a=(d=yr(o.dict.entries.get("Matrix")))!=null?d:[1,0,0,1,0,0],c=Rf(i,s,a);if(c){this.execute({op:"save_state"}),this.execute({op:"set_ctm",matrix:c});try{await this.renderFormStreamInline(o)}finally{this.execute({op:"restore_state"})}}}resolveAppearanceStream(e){let n=this.resolveObject(e.entries.get("AP"));if(!n||!Z(n))return null;let r=this.resolveObject(n.entries.get("N"));if(r&&Z(r)){let o=Me(e.entries.get("AS"));r=o?this.resolveObject(r.entries.get(o)):void 0}return r&&me(r)?r:null}async runCommandsAsync(e){let n=()=>typeof performance!="undefined"?performance.now():Date.now(),r=n();for(let o of e){let i=this.commandIndex++;this.debug&&this.logDebug("command",{index:i,op:o.op,payload:this.commandPayload(o)}),n()-r>12&&(await Df(),r=n());let a=this.debugAtomic&&this.atomicLogCount<this.maxAtomicLogs?this.captureAtomicState():null;o.op==="xobject"?await this.renderXObject(o.name):o.op==="inline_image"?await this.renderInlineImage(o.params,o.data):(o.op==="set_fill_color"||o.op==="set_stroke_color")&&o.patternName&&!this.forcedColor&&(o.op==="set_fill_color"?this.state.fillColorSpace:this.state.strokeColorSpace)==="Pattern"?await this.applyPatternColor(o.op==="set_fill_color"?"fill":"stroke",o.patternName,o.values):o.op==="set_graphics_state"?(this.execute(o),await this.applySoftMaskFromExtGState(o.name)):this.execute(o),a&&this.logAtomic(i,o,a,this.captureAtomicState())}}getCapturedTextRuns(){return this.capturedTextRuns.map(e=>({...e,glyphs:e.glyphs.map(n=>({...n}))}))}getCapturedImages(){return this.capturedImages.map(e=>({...e,ctm:[...e.ctm]}))}getCapturedGraphics(){return Vc(this.paintRecords,this.breakerIndices,this.canvas.width,this.canvas.height).map(e=>({canvasX:e.bbox.minX,canvasY:e.bbox.minY,canvasWidth:e.bbox.maxX-e.bbox.minX,canvasHeight:e.bbox.maxY-e.bbox.minY,operatorStart:e.operatorStart,operatorEnd:e.operatorEnd,paintOperatorIndices:e.paintOperatorIndices,ctmAtStart:e.ctmAtStart,fromXObject:e.fromXObject}))}extendPendingPath(e){if(this.captureSuppressed>0)return;this.pendingPath||(this.pendingPath={bbox:{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},startIndex:Math.max(0,this.commandIndex-1),ctmAtStart:[...this.state.ctm]});let n=Se(this.deviceBase(),this.state.ctm),r=this.pendingPath.bbox;for(let[o,i]of e){let s=Ue(n,o,i);s.x<r.minX&&(r.minX=s.x),s.x>r.maxX&&(r.maxX=s.x),s.y<r.minY&&(r.minY=s.y),s.y>r.maxY&&(r.maxY=s.y)}}recordPaintForCapture(){let e=this.pendingPath;this.pendingPath=null,!(this.captureSuppressed>0||!e)&&(e.bbox.minX>e.bbox.maxX||this.paintRecords.push({bbox:{...e.bbox},pathStartIndex:e.startIndex,paintIndex:Math.max(0,this.commandIndex-1),ctmAtStart:e.ctmAtStart,fromXObject:this.xobjectDepth>0}))}recordBreaker(){this.captureSuppressed>0||this.breakerIndices.push(Math.max(0,this.commandIndex-1))}captureImageBox(e,n){if(this.recordBreaker(),this.captureSuppressed>0)return;let r=Se(this.deviceBase(),this.state.ctm),o=[Ue(r,0,0),Ue(r,1,0),Ue(r,0,1),Ue(r,1,1)],i=o.map(l=>l.x),s=o.map(l=>l.y),a=Math.min(...i),c=Math.min(...s);this.capturedImages.push({canvasX:a,canvasY:c,canvasWidth:Math.max(...i)-a,canvasHeight:Math.max(...s)-c,ctm:[...this.state.ctm],kind:e,xobjectName:n,streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0})}setFontContext(e,n){this.pageResources=e!=null?e:null,this.objectLoader=n!=null?n:null,this.fontCache.clear(),this.fontDiagnosticsLogged.clear(),this.rawByteDiagnosticsLogged.clear(),this.patternCache.clear()}execute(e){var n,r;switch(e.op){case"save_state":this.stateStack.push(Gf(this.state)),this.resolverStack.push({fill:this.fillColorResolver,stroke:this.strokeColorResolver}),this.ctx.save();break;case"restore_state":for(;this.layerStack.length>0&&this.stateStack.length>0;){let o=this.layerStack[this.layerStack.length-1];if(o.kind==="smask"&&o.stateDepthAtPush>=this.stateStack.length)this.popLayer();else break}if(this.stateStack.length>0&&(this.state=this.stateStack.pop()),this.resolverStack.length>0){let o=this.resolverStack.pop();this.fillColorResolver=o.fill,this.strokeColorResolver=o.stroke}this.ctx.restore();break;case"set_ctm":this.state.ctm=Se(this.state.ctm,e.matrix),this.applyCurrentTransform(),this.logDebug("ctm:update",{ctm:this.state.ctm,cmd:e.matrix});break;case"set_line_width":this.state.lineWidth=e.width,this.ctx.lineWidth=e.width;break;case"set_line_cap":{let o=["butt","round","square"];this.state.lineCap=e.cap,this.ctx.lineCap=(n=o[e.cap])!=null?n:"butt";break}case"set_line_join":{let o=["miter","round","bevel"];this.state.lineJoin=e.join,this.ctx.lineJoin=(r=o[e.join])!=null?r:"miter";break}case"set_miter_limit":this.state.miterLimit=e.limit,this.ctx.miterLimit=e.limit;break;case"set_dash":this.state.dashArray=e.array,this.state.dashPhase=e.phase,this.ctx.setLineDash(e.array),this.ctx.lineDashOffset=e.phase;break;case"set_rendering_intent":break;case"set_graphics_state":this.applyExtGState(e.name);break;case"set_fill_color_rgb":if(this.forcedColor)break;this.state.fillColorSpace="DeviceRGB",this.state.fillColor={space:"rgb",r:e.r,g:e.g,b:e.b},this.state.fillPatternName=null,this.state.fillPattern=null,this.ctx.fillStyle=Ft(e.r,e.g,e.b);break;case"set_stroke_color_rgb":if(this.forcedColor)break;this.state.strokeColorSpace="DeviceRGB",this.state.strokeColor={space:"rgb",r:e.r,g:e.g,b:e.b},this.state.strokePatternName=null,this.state.strokePattern=null,this.ctx.strokeStyle=Ft(e.r,e.g,e.b);break;case"set_fill_gray":if(this.forcedColor)break;this.state.fillColorSpace="DeviceGray",this.state.fillColor={space:"gray",gray:e.gray},this.state.fillPatternName=null,this.state.fillPattern=null,this.ctx.fillStyle=Ft(e.gray,e.gray,e.gray);break;case"set_stroke_gray":if(this.forcedColor)break;this.state.strokeColorSpace="DeviceGray",this.state.strokeColor={space:"gray",gray:e.gray},this.state.strokePatternName=null,this.state.strokePattern=null,this.ctx.strokeStyle=Ft(e.gray,e.gray,e.gray);break;case"set_fill_cmyk":{if(this.forcedColor)break;this.state.fillColorSpace="DeviceCMYK",this.state.fillColor={space:"cmyk",c:e.c,m:e.m,y:e.y,k:e.k},this.state.fillPatternName=null,this.state.fillPattern=null;let o=Zn(e.c,e.m,e.y,e.k);this.ctx.fillStyle=Ft(o.r,o.g,o.b);break}case"set_stroke_cmyk":{if(this.forcedColor)break;this.state.strokeColorSpace="DeviceCMYK",this.state.strokeColor={space:"cmyk",c:e.c,m:e.m,y:e.y,k:e.k},this.state.strokePatternName=null,this.state.strokePattern=null;let o=Zn(e.c,e.m,e.y,e.k);this.ctx.strokeStyle=Ft(o.r,o.g,o.b);break}case"move_to":this.ctx.beginPath(),this.ctx.moveTo(e.x,e.y),this.currentPathX=e.x,this.currentPathY=e.y,this.pathStartX=e.x,this.pathStartY=e.y,this.extendPendingPath([[e.x,e.y]]);break;case"line_to":this.ctx.lineTo(e.x,e.y),this.currentPathX=e.x,this.currentPathY=e.y,this.extendPendingPath([[e.x,e.y]]);break;case"curve_to":this.ctx.bezierCurveTo(e.x1,e.y1,e.x2,e.y2,e.x3,e.y3),this.extendPendingPath([[e.x1,e.y1],[e.x2,e.y2],[e.x3,e.y3]]),this.currentPathX=e.x3,this.currentPathY=e.y3;break;case"curve_to_v":this.ctx.bezierCurveTo(this.currentPathX,this.currentPathY,e.x2,e.y2,e.x3,e.y3),this.extendPendingPath([[e.x2,e.y2],[e.x3,e.y3]]),this.currentPathX=e.x3,this.currentPathY=e.y3;break;case"rect":this.ctx.beginPath(),this.ctx.rect(e.x,e.y,e.w,e.h),this.currentPathX=e.x,this.currentPathY=e.y,this.pathStartX=e.x,this.pathStartY=e.y,this.extendPendingPath([[e.x,e.y],[e.x+e.w,e.y+e.h]]);break;case"close_path":this.ctx.closePath(),this.currentPathX=this.pathStartX,this.currentPathY=this.pathStartY;break;case"end_path":this.ctx.beginPath(),this.pendingPath=null;break;case"stroke":this.paintStroke(),this.recordPaintForCapture();break;case"close_stroke":this.ctx.closePath(),this.currentPathX=this.pathStartX,this.currentPathY=this.pathStartY,this.paintStroke(),this.recordPaintForCapture();break;case"fill":this.paintFill(),this.recordPaintForCapture();break;case"fill_stroke":this.paintFill(),this.paintStroke(),this.recordPaintForCapture();break;case"fill_even_odd":this.paintFill("evenodd"),this.recordPaintForCapture();break;case"fill_stroke_even_odd":this.paintFill("evenodd"),this.paintStroke(),this.recordPaintForCapture();break;case"close_fill_stroke":this.ctx.closePath(),this.paintFill(),this.paintStroke(),this.recordPaintForCapture();break;case"close_fill_stroke_even_odd":this.ctx.closePath(),this.paintFill("evenodd"),this.paintStroke(),this.recordPaintForCapture();break;case"clip":this.disableClip?this.logDebug("clip:skipped",{rule:"nonzero"}):this.ctx.clip();break;case"clip_even_odd":this.disableClip?this.logDebug("clip:skipped",{rule:"evenodd"}):this.ctx.clip("evenodd");break;case"begin_text":this.state.textMatrix=[1,0,0,1,0,0],this.state.textLineMatrix=[1,0,0,1,0,0];break;case"end_text":break;case"set_font":this.state.font=e.name,this.state.fontSize=e.size;break;case"set_text_matrix":this.state.textMatrix=[...e.matrix],this.state.textLineMatrix=[...e.matrix];break;case"move_text":this.state.textLineMatrix=Se(this.state.textLineMatrix,[1,0,0,1,e.tx,e.ty]),this.state.textMatrix=[...this.state.textLineMatrix];break;case"move_text_set_leading":this.state.leading=-e.ty,this.state.textLineMatrix=Se(this.state.textLineMatrix,[1,0,0,1,e.tx,e.ty]),this.state.textMatrix=[...this.state.textLineMatrix];break;case"next_line":this.state.textLineMatrix=Se(this.state.textLineMatrix,[1,0,0,1,0,-this.state.leading]),this.state.textMatrix=[...this.state.textLineMatrix];break;case"set_char_spacing":this.state.charSpacing=e.spacing;break;case"set_word_spacing":this.state.wordSpacing=e.spacing;break;case"set_horiz_scale":this.state.horizScale=e.scale;break;case"set_leading":this.state.leading=e.leading;break;case"set_text_render":this.state.textRenderMode=e.mode;break;case"set_text_rise":this.state.textRise=e.rise;break;case"show_string":this.recordBreaker(),this.renderText(e.data);break;case"show_strings":this.recordBreaker();for(let o of e.items)if(o instanceof Uint8Array)this.renderText(o);else{let i=-(o/1e3)*this.state.fontSize*(this.state.horizScale/100);this.state.textMatrix=Se(this.state.textMatrix,[1,0,0,1,i,0])}break;case"next_line_show_string":this.recordBreaker(),this.moveToNextTextLine(),this.renderText(e.data);break;case"set_spacing_next_line_show_string":this.recordBreaker(),this.state.wordSpacing=e.wordSpacing,this.state.charSpacing=e.charSpacing,this.moveToNextTextLine(),this.renderText(e.data);break;case"xobject":case"inline_image":break;case"set_fill_color_space":this.state.fillColorSpace=this.resolveColorSpaceName(e.name),this.fillColorResolver=this.buildComplexColorResolver(e.name);break;case"set_stroke_color_space":this.state.strokeColorSpace=this.resolveColorSpaceName(e.name),this.strokeColorResolver=this.buildComplexColorResolver(e.name);break;case"set_fill_color":if(this.forcedColor)break;if(this.state.fillColorSpace==="Pattern"&&e.patternName){this.state.fillPatternName=e.patternName;let o=this.resolvePatternFillStyle(e.patternName,"fill");this.ctx.fillStyle=o}else this.state.fillPatternName=null,this.state.fillPattern=null,this.state.fillColor=this.fillColorResolver?this.fillColorResolver(e.values):mn(this.state.fillColorSpace,e.values),this.ctx.fillStyle=Jt(this.state.fillColor);break;case"set_stroke_color":if(this.forcedColor)break;if(this.state.strokeColorSpace==="Pattern"&&e.patternName){this.state.strokePatternName=e.patternName;let o=this.resolvePatternFillStyle(e.patternName,"stroke");this.ctx.strokeStyle=o}else this.state.strokePatternName=null,this.state.strokePattern=null,this.state.strokeColor=this.strokeColorResolver?this.strokeColorResolver(e.values):mn(this.state.strokeColorSpace,e.values),this.ctx.strokeStyle=Jt(this.state.strokeColor);break;case"shade":this.renderShadeOperator(e.name);break;case"type3_glyph_width":case"begin_marked_content":case"end_marked_content":case"unknown":break}}moveToNextTextLine(){this.state.textLineMatrix=Se(this.state.textLineMatrix,[1,0,0,1,0,-this.state.leading]),this.state.textMatrix=[...this.state.textLineMatrix]}renderText(e){var xn;if(e.length===0)return;let n=this.getCurrentFontInfo();if(n.isType3){this.renderType3Text(e,n);return}let r=this.decodeTextWithFont(e,n),o=Math.max(1,this.state.fontSize);this.ctx.font=al(n,o);let i=be=>this.measureGlyphWidthCached(be),s=jf(e,r,n,o,this.state.charSpacing,this.state.wordSpacing,i),a=s.glyphs,c=a.map(be=>be.text).join("")||r;this.logDebug("text:before",{text:c,textLength:c.length,font:this.state.font,fontSize:o,textMatrix:this.state.textMatrix,fillColor:Jt(this.state.fillColor),textRise:this.state.textRise,horizScale:this.state.horizScale}),this.ctx.save();let l=this.state.textMatrix;this.ctx.transform(l[0],l[1],l[2],l[3],l[4],l[5]);let d=this.state.horizScale/100;d!==1&&this.ctx.scale(d,1);let m=this.state.textRise;this.ctx.font=al(n,o),this.ctx.fillStyle=Jt(this.state.fillColor),this.ctx.globalAlpha=this.state.fillAlpha;let h=this.ctx.measureText(c),f=Math.max(1e-4,h.width),p=s.hasPdfMetrics?a.reduce((be,Ve)=>be+Ve.advance,0)*d:null,w=p!=null?p:f*d,b=Math.max(1,h.actualBoundingBoxAscent||o*.8),y=Math.max(1,h.actualBoundingBoxDescent||o*.2);this.ctx.scale(1,-1);let k=s.hasPdfMetrics&&a.length>0,C=f*Math.max(1e-4,d),S=p?Hf(w/C,.5,1.8):1;!k&&S!==1&&this.ctx.scale(S,1);let F=this.state.textRenderMode,O=F===0||F===2||F===4||F===6,N=F===1||F===2||F===5||F===6;O&&(this.ctx.fillStyle=Jt(this.state.fillColor)),N&&(this.ctx.strokeStyle=Jt(this.state.strokeColor),this.ctx.lineWidth=Math.max(.01,this.state.lineWidth/o));let I=(be,Ve)=>{O&&(this.ctx.globalAlpha=this.state.fillAlpha,this.ctx.fillText(be,Ve,-m)),N&&(this.ctx.globalAlpha=this.state.strokeAlpha,this.ctx.strokeText(be,Ve,-m))};if(k){let be=0;for(let Ve of a)Ve.text&&I(Ve.text,be),be+=Ve.advance}else I(c,0);this.ctx.restore();let R=[1,0,0,-1,0,this.pageHeight],H=Se(Se(R,this.state.ctm),l),te=w,T=Ue(H,0,m),ce=[Ue(H,0,m+b),Ue(H,te,m+b),Ue(H,te,m-y),Ue(H,0,m-y)],se=Math.min(...ce.map(be=>be.x)),fe=Math.max(...ce.map(be=>be.x)),pe=Math.min(...ce.map(be=>be.y)),ie=Math.max(...ce.map(be=>be.y)),J=se*this.scale,_=pe*this.scale,Q=Math.max(1,(fe-se)*this.scale),le=Math.max(1,(ie-pe)*this.scale),ge=fn(this.state.fillColor),Xe=(xn=n.baseFontName)!=null?xn:this.state.font,Ce=Se(this.state.ctm,l),Te=Math.hypot(Ce[1],Ce[3]),ht=Math.max(1,o*(Te>.01?Te:1)),et=this.capturedTextRuns.length,ct=0,Rt=a.map(be=>{let Ve=s.hasPdfMetrics?be.advance:f>0?this.measureGlyphWidthCached(be.text)/f*(w/Math.max(1e-4,d)):0,bn=Ue(H,ct*d,m),Pe=Ue(H,(ct+Ve)*d,m),Ge=Math.min(bn.x,Pe.x)*this.scale,Ze=Math.max(1,Math.abs(Pe.x-bn.x)*this.scale);return ct+=Ve,{canvasX:Ge,canvasY:_,canvasWidth:Ze,canvasHeight:le,canvasBaselineY:T.y*this.scale,char:be.text,charCode:be.code,runIndex:et}});this.capturedTextRuns.push({index:et,text:c,fontName:Xe,fontSize:ht,canvasX:J,canvasY:_,canvasWidth:Q,canvasHeight:le,canvasBaselineX:T.x*this.scale,canvasBaselineY:T.y*this.scale,fillColor:ge,streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0,glyphs:Rt,fontFamily:ts(n)});let ft=p!=null?p:w;this.state.textMatrix=Se(this.state.textMatrix,[1,0,0,1,ft,0]),this.logDebug("text:after",{text:c,measuredWidth:f,advance:ft,needsTextFlip:!0,bytesHexPreview:Array.from(e.slice(0,12)).map(be=>be.toString(16).padStart(2,"0")).join(" "),printableChars:Array.from(r).filter(be=>be>=" "&&be<="~").length,totalChars:r.length,nextTextMatrix:this.state.textMatrix})}renderType3Text(e,n){var O,N,I,R,H,te,T,ce;let r=n.type3CharProcs,o=n.type3Encoding;if(!r)return;let i=Math.max(1,this.state.fontSize),s=this.state.horizScale/100,a=this.state.textRise,c=(O=n.fontMatrix)!=null?O:[.001,0,0,.001,0,0],l=this.capturedTextRuns.length,d="";for(let se=0;se<e.length;se++){let fe=e[se],pe=(N=n.encodingMap)==null?void 0:N.get(fe);d+=pe!=null?pe:o&&(I=o.get(fe))!=null?I:String.fromCharCode(fe)}let m=[...this.state.textMatrix],h=[1,0,0,-1,0,this.pageHeight],f=this.pageResources;for(let se=0;se<e.length;se++){let fe=e[se],pe=(R=o==null?void 0:o.get(fe))!=null?R:".notdef",J=((T=(te=(H=n.widths)==null?void 0:H.get(fe))!=null?te:n.defaultWidth)!=null?T:1e3)/1e3*i+this.state.charSpacing+(fe===32?this.state.wordSpacing:0),_=r.entries.get(pe),Q=_?this.resolveObject(_):void 0;if(Q&&me(Q)){let le=this.state.textMatrix,ge=[i*s,0,0,i,0,a],Xe=Se(Se(le,ge),c),Ce=[...this.state.textMatrix],Te=[...this.state.textLineMatrix];this.execute({op:"save_state"}),this.execute({op:"set_ctm",matrix:Xe}),n.type3Resources&&(this.pageResources=n.type3Resources),this.captureSuppressed+=1;try{let ht=ve.decodeStreamSync(Q),et=Vt(ht);for(let ct of et)ct.op!=="type3_glyph_width"&&this.execute(ct)}catch{}finally{this.captureSuppressed-=1}this.pageResources=f,this.execute({op:"restore_state"}),this.state.textMatrix=Ce,this.state.textLineMatrix=Te}this.state.textMatrix=Se(this.state.textMatrix,[1,0,0,1,J,0])}let p=Se(Se(h,this.state.ctm),m),w=Ue(p,0,a),b=Se(Se(h,this.state.ctm),this.state.textMatrix),y=Ue(b,0,a),k=Math.min(w.x,y.x)*this.scale,C=(Math.min(w.y,y.y)-i)*this.scale,S=Math.max(1,Math.abs(y.x-w.x)*this.scale),F=Math.max(1,i*this.scale);this.capturedTextRuns.push({index:l,text:d,fontName:(ce=n.baseFontName)!=null?ce:this.state.font,fontSize:i,canvasX:k,canvasY:C,canvasWidth:S,canvasHeight:F,canvasBaselineX:w.x*this.scale,canvasBaselineY:w.y*this.scale,fillColor:fn(this.state.fillColor),streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0,glyphs:[],fontFamily:ts(n)})}commandPayload(e){return e.op==="show_string"?{text:this.decodeText(e.data),bytes:e.data.length}:e.op==="show_strings"?{items:e.items.map(n=>n instanceof Uint8Array?{type:"text",text:this.decodeText(n),bytes:n.length}:{type:"adjust",value:n})}:e}decodeText(e){return this.decodeTextWithFont(e,this.getCurrentFontInfo())}measureGlyphWidthCached(e){let n=`${this.ctx.font}|${e}`,r=this.glyphWidthCache.get(n);if(r!==void 0)return r;let o=this.ctx.measureText(e).width;return this.glyphWidthCache.set(n,o),o}async preloadEmbeddedFonts(){if(this.embeddedFamilies.clear(),!this.pageResources)return;let e=this.resolveObject(this.pageResources.entries.get("Font"));if(!e||!Z(e))return;let n=r=>this.resolveObject(r);for(let[r,o]of e.entries)try{let i=this.resolveObject(o);if(!i||!Z(i))continue;let a=Me(i.entries.get("Subtype"))==="Type0"?il(i,n):void 0,c=sl(i,a,n),l=qc(c,n);if(!l)continue;let d=await Jc(l);d&&this.embeddedFamilies.set(r,d)}catch{}}getCurrentFontInfo(){let e=this.state.font;if(!e)return ko();let n=this.fontCache.get(e);if(n)return n;let r=this.loadFontInfo(e);return this.fontCache.set(e,r),r}loadFontInfo(e){var H,te,T,ce,se,fe,pe,ie,J;if(!this.pageResources)return ko();let n=this.resolveObject(this.pageResources.entries.get("Font"));if(!n||!Z(n))return ko();let r=n.entries.get(e),o=this.resolveObject(r);if(!o||!Z(o))return ko();let i=tl.get(o);if(i)return i;let s=o.entries.get("Subtype"),a=(H=Me(s))!=null?H:"Unknown",c=(te=Me(o.entries.get("BaseFont")))!=null?te:void 0,l=a==="Type0",d=Math.floor((T=K(o.entries.get("FirstChar")))!=null?T:0),m=l?il(o,_=>this.resolveObject(_)):void 0,h=sl(o,m,_=>this.resolveObject(_)),f=l?Tf(m):Ef(o,d),p=l?Of(m):If(o),w=o.entries.get("ToUnicode"),b=o.entries.get("Encoding"),y=null,k=this.resolveObject(w);if(k&&me(k))try{let _=ve.decodeStreamSync(k),Q=new TextDecoder("latin1").decode(_),le=wm(Q);this.logFontDiagnostic(e,{subtype:a,isComposite:l,hasRawToUnicode:!!w,rawToUnicodeType:Zt(w),resolvedToUnicodeType:Zt(k),encoding:Zt(b),cmapRaw:le}),this.debug&&el.has(e)&&!Qc.has(e)&&(Qc.add(e),console.log(`=== Raw CMap text for ${e} (first 500 chars) ===`),console.log(Q.slice(0,500)),console.log("===")),y=Kf(Q),this.logDebug("font:cmap-parsed",{fontName:e,cmapType:y.cmapType,isUsable:y.isUsable,bfChar:y.bfChar.size,bfRange:y.bfRange.length,codeSpaceRanges:y.codeSpaceRanges.length}),y&&el.has(e)&&Zf(y,e)}catch(_){this.logDebug("font:toUnicode-failed",{fontName:e,subtype:a,error:_ instanceof Error?_.message:String(_)}),this.logFontDiagnostic(e,{subtype:a,isComposite:l,hasRawToUnicode:!!w,rawToUnicodeType:Zt(w),resolvedToUnicodeType:Zt(k),encoding:Zt(b),toUnicodeError:_ instanceof Error?_.message:String(_)})}else this.logFontDiagnostic(e,{subtype:a,isComposite:l,hasRawToUnicode:!!w,rawToUnicodeType:Zt(w),resolvedToUnicodeType:Zt(k),encoding:Zt(b),note:l?"Composite font without resolved ToUnicode stream":"No ToUnicode stream"});if(!y&&l){let _=o.entries.get("Encoding");_&&_.type==="name"&&(_.value==="Identity-H"||_.value==="Identity-V")&&this.logDebug("font:identity-no-tounicode",{fontName:e,subtype:a,encoding:_.value})}let C;l||(C=Yf(b,_=>this.resolveObject(_)));let S=!1,F,O,N,I;if(a==="Type3"){S=!0;let _=this.resolveObject(o.entries.get("CharProcs"));_&&Z(_)&&(F=_);let Q=o.entries.get("FontMatrix");if(Q&&he(Q)){let ge=Q.items;N=[(ce=K(ge[0]))!=null?ce:.001,(se=K(ge[1]))!=null?se:0,(fe=K(ge[2]))!=null?fe:0,(pe=K(ge[3]))!=null?pe:.001,(ie=K(ge[4]))!=null?ie:0,(J=K(ge[5]))!=null?J:0]}let le=this.resolveObject(o.entries.get("Resources"));le&&Z(le)&&(I=le),O=Wf(b,ge=>this.resolveObject(ge))}let R={subtype:a,baseFontName:c,fontWeight:$f(c,h),fontStyle:Bf(c,h),isComposite:l,firstChar:d,widths:f,defaultWidth:p,toUnicode:y,encodingMap:C,isType3:S,type3CharProcs:F,type3Encoding:O,fontMatrix:N,type3Resources:I,registeredFamily:this.embeddedFamilies.get(e)};return this.logDebug("font:loaded",{fontName:e,subtype:a,isComposite:l,hasToUnicode:!!y}),tl.set(o,R),R}logFontDiagnostic(e,n){if(!this.debug)return;let r=`${e}|${String(n.subtype)}|${String(n.rawToUnicodeType)}|${String(n.resolvedToUnicodeType)}`;this.fontDiagnosticsLogged.has(r)||(this.fontDiagnosticsLogged.add(r),console.info("[PageRenderer][FontDiag]",{font:e,...n}))}resolveObject(e){if(e){if(!Be(e))return e;if(this.objectLoader)try{return this.objectLoader(e)}catch{return}}}resolveColorSpaceName(e){var i;let n=Mt(e);if(n)return n;if(!this.pageResources)return e;let r=this.resolveObject(this.pageResources.entries.get("ColorSpace"));if(!r||!Z(r))return e;let o=this.resolveObject(r.entries.get(e));return(i=rl(o))!=null?i:e}buildComplexColorResolver(e){var f;if(Mt(e))return null;let n=this.separationColorCache.get(e);if(n)return n;if(!this.pageResources||!this.objectLoader)return null;let r=this.resolveObject(this.pageResources.entries.get("ColorSpace"));if(!r||!Z(r))return null;let o=this.resolveObject(r.entries.get(e));if(!o||!he(o)||o.items.length<2)return null;let i=Me(o.items[0]);if(i!=="Separation"&&i!=="DeviceN")return null;let s=2,a=3,c=o.items[s]?this.resolveObject(o.items[s]):void 0,l=(f=rl(c))!=null?f:"DeviceGray",d=o.items[a],m=this.objectLoader,h=p=>{var y;let w=(y=p[0])!=null?y:0,b=xo(d,w,m);return b&&b.length>0?mn(l,b):l==="DeviceCMYK"?{space:"cmyk",c:0,m:0,y:0,k:w}:{space:"gray",gray:1-w}};return this.separationColorCache.set(e,h),h}async renderXObject(e){if(!this.pageResources)return;let n=this.resolveObject(this.pageResources.entries.get("XObject"));if(!n||!Z(n))return;let r=this.resolveObject(n.entries.get(e));if(!r||!me(r))return;let o=Me(r.dict.entries.get("Subtype"));if(o==="Image"){this.captureImageBox("xobject",e),await this.renderImageXObject(r);return}if(o==="Form")try{let i=r,s=this.resolveObject(i.dict.entries.get("Resources")),c=await(i.decode?i.decode():Promise.resolve(ve.decodeStreamSync(i))),l=Vt(c instanceof Uint8Array?c:new Uint8Array(await c)),d=this.pageResources,m=this.objectLoader,h=this.patternCache;this.patternCache=new Map,this.pageResources=s&&Z(s)?s:this.pageResources;let f=this.resolveObject(i.dict.entries.get("Group")),b=!!f&&Z(f)&&Me(f.entries.get("S"))==="Transparency"&&(this.state.fillAlpha<1||this.state.strokeAlpha<1||this.state.blendMode!=="Normal")&&this.pushLayer("group",this.state.fillAlpha,this.state.blendMode,null);this.execute({op:"save_state"}),b&&(this.state.fillAlpha=1,this.state.strokeAlpha=1,this.state.blendMode="Normal",this.ctx.globalAlpha=1,this.ctx.globalCompositeOperation="source-over");let y=i.dict.entries.get("Matrix");if(y&&Array.isArray(y.items))try{let C=y.items.map(S=>{var F;return Number((F=K(S))!=null?F:0)});this.execute({op:"set_ctm",matrix:C})}catch{}let k=this.commandIndex;this.xobjectDepth+=1;try{await this.runCommandsAsync(l)}finally{this.xobjectDepth-=1,this.commandIndex=k}this.execute({op:"restore_state"}),b&&this.popLayer(),this.pageResources=d,this.objectLoader=m,this.patternCache=h;return}catch(i){this.logDebug("xobject:form-failed",{name:e,error:i instanceof Error?i.message:String(i)});return}}resolveImageColorSpace(e){var r,o,i;if(!e)return"DeviceRGB";let n=Me(e);if(n)return(r=Mt(n))!=null?r:n;if(he(e)&&e.items.length>0){let s=Me(e.items[0]);if(s==="ICCBased"){let a=this.resolveObject(e.items[1]);if(a&&me(a)){let c=Math.floor((o=K(a.dict.entries.get("N")))!=null?o:3);return c===1?"DeviceGray":c===4?"DeviceCMYK":"DeviceRGB"}return"DeviceRGB"}if(s==="Indexed")return"Indexed";if(s==="CalRGB")return"DeviceRGB";if(s==="CalGray")return"DeviceGray";if(s)return(i=Mt(s))!=null?i:s}return"DeviceRGB"}resolveDecodeParms(e){var r;let n=this.resolveObject((r=e.entries.get("DecodeParms"))!=null?r:e.entries.get("DP"));if(!n)return null;if(Z(n))return n;if(he(n))for(let o of n.items){let i=this.resolveObject(o);if(i&&Z(i))return i}return null}async decodeJbig2(e){var r;let n=(r=e.rawBytes)!=null?r:e.data;if(!n||n.length===0)return null;try{let{Jbig2Image:o}=await wo(),i,s=this.resolveDecodeParms(e.dict);if(s){let l=this.resolveObject(s.entries.get("JBIG2Globals"));if(l&&me(l))try{i=ve.decodeStreamSync(l)}catch{}}let a=[];i&&i.length>0&&a.push({data:i,start:0,end:i.length}),a.push({data:n,start:0,end:n.length});let c=new o().parseChunks(a);for(let l=0;l<c.length;l++)c[l]^=255;return c}catch(o){return this.logDebug("xobject:jbig2-failed",{error:o instanceof Error?o.message:String(o)}),null}}async decodeCcitt(e,n,r){var i;let o=(i=e.rawBytes)!=null?i:e.data;if(!o||o.length===0)return null;try{let{CCITTFaxDecoder:s}=await wo(),a=this.resolveDecodeParms(e.dict),c=(S,F)=>{var O;return a?Math.floor((O=K(a.entries.get(S)))!=null?O:F):F},l=(S,F)=>{let O=a==null?void 0:a.entries.get(S);return O&&typeof O=="object"&&"type"in O&&O.type==="boolean"?O.value:F},d=c("Columns",1728),m=c("Rows",r),h=0,f={next:()=>h<o.length?o[h++]:-1},p=new s(f,{K:c("K",0),EndOfLine:l("EndOfLine",!1),EncodedByteAlign:l("EncodedByteAlign",!1),Columns:d,Rows:m,EndOfBlock:l("EndOfBlock",!0),BlackIs1:l("BlackIs1",!1)}),b=(d+7>>3)*(m>0?m:r),y=new Uint8Array(b),k=0,C;for(;k<b&&(C=p.readNextChar())!==-1;)y[k++]=C;return k>0?y.subarray(0,k):null}catch(s){return this.logDebug("xobject:ccitt-failed",{error:s instanceof Error?s.message:String(s)}),null}}drawRgbaImageData(e,n,r){let o=document.createElement("canvas");o.width=n,o.height=r;let i=o.getContext("2d");i&&(i.putImageData(e,0,0),this.drawImageBitmapLike(o))}async renderImageXObject(e){var h,f,p,w;let n=e.dict,r=Math.floor((h=K(n.entries.get("Width")))!=null?h:0),o=Math.floor((f=K(n.entries.get("Height")))!=null?f:0);if(r<=0||o<=0)return;let i=ol(n.entries.get("Filter")),s=Math.floor((p=K(n.entries.get("BitsPerComponent")))!=null?p:8),a=n.entries.get("ImageMask"),c=a!=null&&typeof a=="object"&&"type"in a&&a.type==="boolean"&&a.value===!0||Me(a)==="true",l=this.resolveImageColorSpace(n.entries.get("ColorSpace")),d=i.includes("JBIG2Decode"),m=i.includes("CCITTFaxDecode")||i.includes("CCF");try{let b=null;if(d?b=await this.decodeJbig2(e):m&&(b=await this.decodeCcitt(e,r,o)),(d||m)&&!b)return;if(c){await this.renderStencilMask(e,r,o,b);return}if(!d&&!m&&(i.includes("DCTDecode")||i.includes("DCT"))){let y=(w=e.rawBytes)!=null?w:e.data;if(!y)return;if(l==="DeviceCMYK"){await this.renderJpegViaPdfjs(e,y,r,o);return}let k=this.resolveObject(n.entries.get("SMask"));if(k&&me(k))await this.renderImageWithSMask(y,"image/jpeg",k,r,o);else{let C=await qi(y,"image/jpeg");this.drawImageBitmapLike(C),Ji(C)}return}if(!d&&!m&&i.includes("JPXDecode")){await this.renderJpxViaPdfjs(e,r,o);return}if(!b&&i.some(y=>!Ff.has(y)))return;if(s===1||s===2||s===4||s===8||s===16){let y=b!=null?b:ve.decodeStreamSync(e),k=null;if(l==="Indexed"){let S=n.entries.get("ColorSpace"),F=N=>this.resolveObject(N),O=Zi(y,r,o,1,s,!1);k=Xf(O,r,o,S&&he(S)?S.items:[],F)}else{let S=Uf(l),F=Zi(y,r,o,S,s,!0);k=_f(F,r,o,l)}if(!k)return;Mf(k,ut(n.entries.get("Decode")),l);let C=this.resolveObject(n.entries.get("SMask"));if(C&&me(C))try{let S=await this.decodeSMaskAlpha(C,r,o);vo(k,S,r,o)}catch{}this.drawRgbaImageData(k,r,o)}}catch(b){this.logDebug("xobject:image-failed",{width:r,height:o,colorSpace:l,bitsPerComponent:s,filters:i,error:b instanceof Error?b.message:String(b)})}}async renderJpegViaPdfjs(e,n,r,o){let{JpegImage:i}=await wo(),s=new i;s.parse(n);let a=s.getData({width:r,height:o,forceRGBA:!0,isSourcePDF:!0});if(a.length<r*o*4)return;let c=new ImageData(new Uint8ClampedArray(a.subarray(0,r*o*4)),r,o),l=this.resolveObject(e.dict.entries.get("SMask"));if(l&&me(l))try{let d=await this.decodeSMaskAlpha(l,r,o);vo(c,d,r,o)}catch{}this.drawRgbaImageData(c,r,o)}async renderJpxViaPdfjs(e,n,r){var w,b,y;let o=(w=e.rawBytes)!=null?w:e.data;if(!o)return;let{JpxImage:i}=await wo(),s=new i;s.parse(o);let a=s.width||n,c=s.height||r,l=s.componentsCount||1,d=(y=(b=s.tiles)==null?void 0:b[0])==null?void 0:y.items;if(!d)return;let m=a*c,h=new Uint8ClampedArray(m*4);for(let k=0,C=0;k<m;k++,C+=4){let S=k*l;if(l>=4){let F=d[S],O=d[S+1],N=d[S+2],I=d[S+3];h[C]=255-Math.min(255,F+I),h[C+1]=255-Math.min(255,O+I),h[C+2]=255-Math.min(255,N+I)}else l===3?(h[C]=d[S],h[C+1]=d[S+1],h[C+2]=d[S+2]):h[C]=h[C+1]=h[C+2]=d[S];h[C+3]=255}let f=new ImageData(h,a,c),p=this.resolveObject(e.dict.entries.get("SMask"));if(p&&me(p))try{let k=await this.decodeSMaskAlpha(p,a,c);vo(f,k,a,c)}catch{}this.drawRgbaImageData(f,a,c)}async renderInlineImage(e,n){var l;this.captureImageBox("inline",null);let r={W:"Width",H:"Height",BPC:"BitsPerComponent",CS:"ColorSpace",F:"Filter",IM:"ImageMask",D:"Decode",DP:"DecodeParms",I:"Interpolate"},o={AHx:"ASCIIHexDecode",A85:"ASCII85Decode",LZW:"LZWDecode",Fl:"FlateDecode",RL:"RunLengthDecode",CCF:"CCITTFaxDecode",DCT:"DCTDecode"},i={G:"DeviceGray",RGB:"DeviceRGB",CMYK:"DeviceCMYK",I:"Indexed"},s=(d,m)=>d&&"type"in d&&d.type==="name"&&m[d.value]?{type:"name",value:m[d.value]}:d,a=new Map;for(let[d,m]of e.entries){let h=(l=r[d])!=null?l:d,f=m;if(h==="Filter")f=he(m)?{type:"array",items:m.items.map(p=>s(p,o))}:s(m,o);else if(h==="ColorSpace")if(m&&"type"in m&&m.type==="name"&&!i[m.value]&&!["DeviceGray","DeviceRGB","DeviceCMYK","Indexed"].includes(m.value)){let p=this.lookupResource("ColorSpace",m.value);f=p!=null?p:m}else f=s(m,i);a.set(h,f)}let c={type:"stream",dict:{type:"dict",entries:a},data:n,rawBytes:n};await this.renderImageXObject(c)}lookupResource(e,n){if(!this.pageResources)return;let r=this.resolveObject(this.pageResources.entries.get(e));if(!(!r||!Z(r)))return this.resolveObject(r.entries.get(n))}async decodeSMaskAlpha(e,n,r){var m,h,f,p;let o=ol(e.dict.entries.get("Filter")),i=o.includes("JPXDecode");if(o.includes("DCTDecode")||o.includes("DCT")||i){let w=(m=e.rawBytes)!=null?m:e.data;if(w&&w.length>0){let b=await qi(w,i?"image/jp2":"image/jpeg");try{let y=document.createElement("canvas");y.width=n,y.height=r;let k=y.getContext("2d");if(k){k.drawImage(b,0,0,n,r);let{data:C}=k.getImageData(0,0,n,r),S=new Uint8Array(n*r);for(let F=0;F<S.length;F++)S[F]=C[F*4];return S}}finally{Ji(b)}}}let a=ve.decodeStreamSync(e),c=Math.floor((h=K(e.dict.entries.get("BitsPerComponent")))!=null?h:8);if(c===8)return a;let l=Math.floor((f=K(e.dict.entries.get("Width")))!=null?f:n),d=Math.floor((p=K(e.dict.entries.get("Height")))!=null?p:r);return Zi(a,l,d,1,c,!0)}async renderImageWithSMask(e,n,r,o,i){let s=await qi(e,n);try{let a=document.createElement("canvas");a.width=o,a.height=i;let c=a.getContext("2d");if(!c){this.drawImageBitmapLike(s);return}c.drawImage(s,0,0,o,i);let l=c.getImageData(0,0,o,i);try{let d=await this.decodeSMaskAlpha(r,o,i);vo(l,d,o,i)}catch{}c.putImageData(l,0,0),this.drawImageBitmapLike(a)}finally{Ji(s)}}async renderStencilMask(e,n,r,o){try{let i=o!=null?o:ve.decodeStreamSync(e),s=fn(this.state.fillColor),a=Math.round(s.r*255),c=Math.round(s.g*255),l=Math.round(s.b*255),d=n*r,m=new Uint8ClampedArray(d*4),h=ut(e.dict.entries.get("Decode")),f=!!h&&h.length>=2&&h[0]===1&&h[1]===0,p=0;for(let y=0;y<i.length&&p<d;y++){let k=i[y];for(let C=7;C>=0&&p<d;C--){let S=k>>C&1,F=p*4;S===1!==f&&(m[F]=a,m[F+1]=c,m[F+2]=l,m[F+3]=255),p++}}let w=document.createElement("canvas");w.width=n,w.height=r;let b=w.getContext("2d");if(!b)return;b.putImageData(new ImageData(m,n,r),0,0),this.drawImageBitmapLike(w)}catch(i){this.logDebug("xobject:stencil-mask-failed",{error:i instanceof Error?i.message:String(i)})}}drawImageBitmapLike(e){this.ctx.save(),this.ctx.transform(1,0,0,-1,0,1),this.ctx.drawImage(e,0,0,1,1),this.ctx.restore()}decodeTextWithFont(e,n){var r;if(e.length===0)return"";if(this.debug){let o=String(this.state.font||"").toLowerCase();if(o==="f1"||o==="f2"){let i=Array.from(e.subarray(0,24)).map(a=>a.toString(16).padStart(2,"0")).join(" "),s=`${o}|${i}`;this.rawByteDiagnosticsLogged.has(s)||(this.rawByteDiagnosticsLogged.add(s),console.log(`[${o} RAW BYTES] ${i}`))}}if(n.toUnicode)return!n.toUnicode.isUsable&&n.isComposite?em(e,n.toUnicode):Qf(e,n.toUnicode,n.isComposite,this.state.font,this.debug);if(n.isComposite)return pl(e);if(n.encodingMap&&n.encodingMap.size>0){let o="";for(let i of e)o+=(r=n.encodingMap.get(i))!=null?r:String.fromCharCode(i);return o}return new TextDecoder("latin1").decode(e)}logDebug(e,n){this.debug&&console.debug(`[PageRenderer] ${e}`,n)}captureAtomicState(){return{transform:this.ctx.getTransform(),lineWidth:this.ctx.lineWidth,fillStyle:String(this.ctx.fillStyle),strokeStyle:String(this.ctx.strokeStyle),stackDepth:this.stateStack.length,samples:this.samplePixels()}}samplePixels(){let e=this.canvas.width,n=this.canvas.height;if(e<=0||n<=0)return[];let r=[[1,1],[Math.max(1,Math.floor(e/2)),Math.max(1,Math.floor(n/2))],[Math.max(1,e-2),Math.max(1,n-2)],[Math.max(1,Math.floor(e*.25)),Math.max(1,Math.floor(n*.25))],[Math.max(1,Math.floor(e*.75)),Math.max(1,Math.floor(n*.75))]],o=[],i=this.ctx.getTransform();this.ctx.setTransform(1,0,0,1,0,0);try{for(let[s,a]of r){let c=this.ctx.getImageData(Math.min(e-1,s),Math.min(n-1,a),1,1).data;o.push([c[0],c[1],c[2],c[3]])}}finally{this.ctx.setTransform(i.a,i.b,i.c,i.d,i.e,i.f)}return o}logAtomic(e,n,r,o){if(!this.debugAtomic||this.atomicLogCount>=this.maxAtomicLogs)return;let i=JSON.stringify(r.samples),s=JSON.stringify(o.samples),a=i!==s;!(n.op==="stroke"||n.op==="fill"||n.op==="fill_even_odd"||n.op==="fill_stroke"||n.op==="show_string"||n.op==="show_strings")&&!a||(this.atomicLogCount+=1,console.debug("[PageRenderer][atomic]",{index:e,op:n.op,stackDepthBefore:r.stackDepth,stackDepthAfter:o.stackDepth,transformBefore:[r.transform.a,r.transform.b,r.transform.c,r.transform.d,r.transform.e,r.transform.f],transformAfter:[o.transform.a,o.transform.b,o.transform.c,o.transform.d,o.transform.e,o.transform.f],lineWidthBefore:r.lineWidth,lineWidthAfter:o.lineWidth,fillStyleBefore:r.fillStyle,fillStyleAfter:o.fillStyle,strokeStyleBefore:r.strokeStyle,strokeStyleAfter:o.strokeStyle,pixelChanged:a,samplesBefore:r.samples,samplesAfter:o.samples}))}applyExtGState(e){var p,w,b;if(!this.pageResources)return;let n=this.resolveObject(this.pageResources.entries.get("ExtGState"));if(!n||!Z(n))return;let r=this.resolveObject(n.entries.get(e));if(!r||!Z(r))return;let o=r,i=K(o.entries.get("LW"));i!==null&&(this.state.lineWidth=i,this.ctx.lineWidth=i);let s=K(o.entries.get("LC"));if(s!==null){let y=Math.floor(s),k=["butt","round","square"];this.state.lineCap=y,this.ctx.lineCap=(p=k[y])!=null?p:"butt"}let a=K(o.entries.get("LJ"));if(a!==null){let y=Math.floor(a),k=["miter","round","bevel"];this.state.lineJoin=y,this.ctx.lineJoin=(w=k[y])!=null?w:"miter"}let c=K(o.entries.get("ML"));c!==null&&(this.state.miterLimit=c,this.ctx.miterLimit=c);let l=o.entries.get("D");if(l&&he(l)&&l.items.length>=1){let y=l.items[0],k=(b=K(l.items[1]))!=null?b:0;if(he(y)){let C=y.items.map(S=>{var F;return(F=K(S))!=null?F:0});this.state.dashArray=C,this.state.dashPhase=k,this.ctx.setLineDash(C),this.ctx.lineDashOffset=k}}let d=K(o.entries.get("CA"));d!==null&&(this.state.strokeAlpha=Je(d));let m=K(o.entries.get("ca"));m!==null&&(this.state.fillAlpha=Je(m));let h=o.entries.get("BM"),f=Me(h);f&&(this.state.blendMode=f,this.ctx.globalCompositeOperation=nl(f))}deviceBase(){if(this.initialTransform)return this.initialTransform;let e=this.scale;return[e,0,0,-e,0,e*this.pageHeight]}applyCurrentTransform(){let e=Se(this.deviceBase(),this.state.ctm);this.ctx.setTransform(e[0],e[1],e[2],e[3],e[4],e[5])}resolvePatternFillStyle(e,n){var r,o,i;try{if(!this.pageResources||!this.objectLoader)return"transparent";let s=this.resolveObject(this.pageResources.entries.get("Pattern"));if(!s||!Z(s))return"transparent";let a=this.resolveObject(s.entries.get(e));if(!a||!Z(a)||Math.floor((r=K(a.entries.get("PatternType")))!=null?r:0)!==2)return"transparent";let l=this.resolveObject(a.entries.get("Shading"));if(!l||!Z(l))return"transparent";let d=(o=yr(a.entries.get("Matrix")))!=null?o:[1,0,0,1,0,0];return(i=this.createCanvasGradient(l,d))!=null?i:"transparent"}catch{return"transparent"}}async resolvePattern(e,n){var s,a;let r=`${e}|${Jt(n)}`,o=this.patternCache.get(r);if(o!==void 0)return o;let i=null;try{if(this.pageResources&&this.objectLoader){let c=this.resolveObject(this.pageResources.entries.get("Pattern")),l=c&&Z(c)?this.resolveObject(c.entries.get(e)):void 0,d=l?me(l)?l.dict:Z(l)?l:null:null;if(d){let m=Math.floor((s=K(d.entries.get("PatternType")))!=null?s:0),h=(a=yr(d.entries.get("Matrix")))!=null?a:[1,0,0,1,0,0];if(m===2){let f=this.resolveObject(d.entries.get("Shading")),p=f?me(f)?f.dict:Z(f)?f:null:null;p&&(i={kind:"shading",shading:p,stream:f&&me(f)?f:null,matrix:h})}else m===1&&l&&me(l)&&(i=await this.renderTilingCell(l,d,h,n))}}}catch{i=null}return this.patternCache.set(r,i),i}async applyPatternColor(e,n,r){let o=e==="fill"?this.state.fillColor:this.state.strokeColor,i=r.length>=4?{space:"cmyk",c:r[0],m:r[1],y:r[2],k:r[3]}:r.length===3?{space:"rgb",r:r[0],g:r[1],b:r[2]}:r.length===1?{space:"gray",gray:r[0]}:o,s=await this.resolvePattern(n,i);e==="fill"?(this.state.fillPatternName=n,this.state.fillPattern=s,s||(this.ctx.fillStyle="transparent")):(this.state.strokePatternName=n,this.state.strokePattern=s,s||(this.ctx.strokeStyle="transparent"))}async renderTilingCell(e,n,r,o){var O,N,I,R;if(this.patternDepth>=4)return null;let i=ut(n.entries.get("BBox"));if(!i||i.length<4)return null;let s=[i[0],i[1],i[2],i[3]],a=s[2]-s[0],c=s[3]-s[1],l=(O=K(n.entries.get("XStep")))!=null?O:a,d=(N=K(n.entries.get("YStep")))!=null?N:c,m=Math.abs(l)<1e-9?a:l,h=Math.abs(d)<1e-9?c:d,f=Math.floor((I=K(n.entries.get("PaintType")))!=null?I:1),p=Se(this.deviceBase(),r),w=Hc(s,m,h,p);if(!w)return null;let b=document.createElement("canvas"),y=new qn(b,w.cellPxW,w.cellPxH,1,{disableClip:this.disableClip,transparentBackground:!0,initialTransform:w.contentTransform,forcedColor:f===2?o:void 0,patternDepth:this.patternDepth+1}),k=this.resolveObject(n.entries.get("Resources"));y.setFontContext(k&&Z(k)?k:void 0,(R=this.objectLoader)!=null?R:void 0);let C=e.decode?await e.decode():ve.decodeStreamSync(e),S=Vt(C),F=a>0&&c>0?[{op:"rect",x:s[0],y:s[1],w:a,h:c},{op:"clip"},{op:"end_path"}]:[];return await y.renderAsync([...F,...S]),{kind:"tiling",cell:b,layout:w,matrix:r}}paintFill(e){let n=this.state.fillPattern;if(!n){this.ctx.globalAlpha=this.state.fillAlpha,e?this.ctx.fill(e):this.ctx.fill();return}this.paintPatternThroughPath(n,this.state.fillAlpha,e!=null?e:"nonzero")}paintStroke(){let e=this.state.strokePattern;if(this.ctx.globalAlpha=this.state.strokeAlpha,e)if(e.kind==="tiling"){let c=this.ctx.createPattern(e.cell,"repeat");c&&(this.ctx.strokeStyle=c)}else{let c=this.createCanvasGradient(e.shading,e.matrix);c&&(this.ctx.strokeStyle=c)}let n=this.deviceBase(),r=Math.sqrt(Math.abs(n[0]*n[3]-n[1]*n[2]))||1,o=this.state.ctm,i=Math.sqrt(Math.abs(o[0]*o[3]-o[1]*o[2]))||1,s=r*i,a=this.state.lineWidth*s;this.ctx.lineWidth=this.state.lineWidth===0||a<1?1/s:this.state.lineWidth,this.ctx.stroke()}paintPatternThroughPath(e,n,r){this.ctx.save();try{this.ctx.globalAlpha=n,this.ctx.clip(r);let o=Se(this.deviceBase(),e.matrix);if(e.kind==="tiling"){let i=this.ctx.createPattern(e.cell,"repeat");if(!i)return;let s=Se(o,e.layout.paintTransform);this.ctx.setTransform(s[0],s[1],s[2],s[3],s[4],s[5]),this.ctx.fillStyle=i,this.floodCanvasExtent(s,Math.max(e.layout.cellPxW,e.layout.cellPxH))}else this.paintShadingBackground(e.shading,o),this.paintShadingWithBase(e.shading,e.stream,o)}finally{this.ctx.restore()}}paintShadingBackground(e,n){var a,c;let r=ut(e.entries.get("Background"));if(!r||!r.length)return;let o=(a=Me(e.entries.get("ColorSpace")))!=null?a:"DeviceRGB",i=(c=Mt(o))!=null?c:"DeviceRGB",s=fn(mn(i,r));this.ctx.save(),this.ctx.setTransform(n[0],n[1],n[2],n[3],n[4],n[5]),this.ctx.fillStyle=Ft(s.r,s.g,s.b),this.floodCanvasExtent(n,0),this.ctx.restore()}paintShadingWithBase(e,n,r){var i;let o=Math.floor((i=K(e.entries.get("ShadingType")))!=null?i:0);if(o===2||o===3){let s=this.createCanvasGradient(e);if(!s)return;this.ctx.save(),this.ctx.setTransform(r[0],r[1],r[2],r[3],r[4],r[5]),this.ctx.fillStyle=s,this.floodCanvasExtent(r,0),this.ctx.restore();return}if(o===1){this.paintFunctionShading(e,r);return}o>=4&&o<=7&&n&&this.paintMeshShading(o,e,n,r)}paintFunctionShading(e,n){var C,S,F,O,N,I,R,H;if(!this.objectLoader)return;let r=e.entries.get("Function");if(!r)return;let o=(C=ut(e.entries.get("Domain")))!=null?C:[0,1,0,1],[i,s,a,c]=[(S=o[0])!=null?S:0,(F=o[1])!=null?F:1,(O=o[2])!=null?O:0,(N=o[3])!=null?N:1];if(!(s>i)||!(c>a))return;let l=(I=yr(e.entries.get("Matrix")))!=null?I:[1,0,0,1,0,0],d=(R=Me(e.entries.get("ColorSpace")))!=null?R:"DeviceRGB",m=(H=Mt(d))!=null?H:"DeviceRGB",h=128,f=128,p=new ImageData(h,f);for(let te=0;te<f;te++){let T=a+(te+.5)/f*(c-a);for(let ce=0;ce<h;ce++){let se=i+(ce+.5)/h*(s-i),fe=Yi(r,[se,T],this.objectLoader);if(!fe)continue;let pe=fn(mn(m,fe)),ie=(te*h+ce)*4;p.data[ie]=Math.round(pe.r*255),p.data[ie+1]=Math.round(pe.g*255),p.data[ie+2]=Math.round(pe.b*255),p.data[ie+3]=255}}let w=document.createElement("canvas");w.width=h,w.height=f;let b=w.getContext("2d");if(!b)return;b.putImageData(p,0,0);let y=[(s-i)/h,0,0,(c-a)/f,i,a],k=Se(Se(n,l),y);this.ctx.save(),this.ctx.setTransform(k[0],k[1],k[2],k[3],k[4],k[5]),this.ctx.drawImage(w,0,0),this.ctx.restore()}paintMeshShading(e,n,r,o){var y,k,C,S,F,O;if(!this.objectLoader)return;let i=this.objectLoader,s=this.meshCache.get(n);if(!s){try{let N=ve.decodeStreamSync(r),I=(y=Me(n.entries.get("ColorSpace")))!=null?y:"DeviceRGB",R=(k=Mt(I))!=null?k:"DeviceRGB",H=n.entries.get("Function"),te=H?1:Cf(R),T=ut(n.entries.get("Decode"));if(!T)return;let ce=se=>{var ie;let fe=H&&(ie=Yi(H,se,i))!=null?ie:se,pe=fn(mn(R,fe));return[pe.r,pe.g,pe.b]};s=Gc(e,{bitsPerCoordinate:Math.floor((C=K(n.entries.get("BitsPerCoordinate")))!=null?C:16),bitsPerComponent:Math.floor((S=K(n.entries.get("BitsPerComponent")))!=null?S:8),bitsPerFlag:Math.floor((F=K(n.entries.get("BitsPerFlag")))!=null?F:8),decode:T,numColorComponents:te,verticesPerRow:(O=K(n.entries.get("VerticesPerRow")))!=null?O:void 0},N,ce)}catch{s=[]}this.meshCache.set(n,s)}if(!s.length)return;let a=1/0,c=1/0,l=-1/0,d=-1/0;for(let N of s)for(let[I,R]of N.p){let H=Ue(o,I,R);H.x<a&&(a=H.x),H.x>l&&(l=H.x),H.y<c&&(c=H.y),H.y>d&&(d=H.y)}a=Math.max(0,Math.floor(a)),c=Math.max(0,Math.floor(c)),l=Math.min(this.canvas.width,Math.ceil(l)),d=Math.min(this.canvas.height,Math.ceil(d));let m=Math.min(4096,l-a),h=Math.min(4096,d-c);if(m<=0||h<=0)return;let f=Se([1,0,0,1,-a,-c],o),p=Kc(s,f,m,h),w=document.createElement("canvas");w.width=m,w.height=h;let b=w.getContext("2d");b&&(b.putImageData(new ImageData(p,m,h),0,0),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(w,a,c),this.ctx.restore())}floodCanvasExtent(e,n){let r=Hn(e);if(!r)return;let o=this.canvas.width,i=this.canvas.height,s=[Ue(r,0,0),Ue(r,o,0),Ue(r,0,i),Ue(r,o,i)],a=s.map(f=>f.x),c=s.map(f=>f.y),l=Math.min(...a)-n,d=Math.min(...c)-n,m=Math.max(...a)+n,h=Math.max(...c)+n;this.ctx.fillRect(l,d,m-l,h-d)}createCanvasGradient(e,n){var b,y,k,C;let r=Math.floor((b=K(e.entries.get("ShadingType")))!=null?b:0),o=(y=Me(e.entries.get("ColorSpace")))!=null?y:"DeviceRGB",i=(k=Mt(o))!=null?k:"DeviceRGB",s=e.entries.get("Function"),a=(C=ut(e.entries.get("Domain")))!=null?C:[0,1],[c,l]=Af(e.entries.get("Extend")),d=S=>{var N,I;let F=a[0]+S*(((N=a[1])!=null?N:1)-a[0]),O=this.objectLoader?(I=xo(s,F,this.objectLoader))!=null?I:[0]:[0];return fn(mn(i,O))},m=S=>`rgb(${Math.round(S.r*255)},${Math.round(S.g*255)},${Math.round(S.b*255)})`,h=S=>`rgba(${Math.round(S.r*255)},${Math.round(S.g*255)},${Math.round(S.b*255)},0)`,f=ut(e.entries.get("Coords"));if(!f)return null;let p=(S,F)=>n?[n[0]*S+n[2]*F+n[4],n[1]*S+n[3]*F+n[5]]:[S,F],w=S=>{let O=.000244140625,N=c?0:O,I=l?1:1-O;c||S.addColorStop(0,h(d(0)));for(let R=0;R<=64;R++){let H=R/64;S.addColorStop(N+H*(I-N),m(d(H)))}l||S.addColorStop(1,h(d(1)))};try{if(r===2){let[S,F,O,N]=f,[I,R]=p(S,F),[H,te]=p(O,N),T=this.ctx.createLinearGradient(I,R,H,te);return w(T),T}if(r===3){let[S,F,O,N,I,R]=f,[H,te]=p(S,F),[T,ce]=p(N,I),se=n?(Math.hypot(n[0],n[1])+Math.hypot(n[2],n[3]))/2:1,fe=this.ctx.createRadialGradient(H,te,Math.max(0,O*se),T,ce,Math.max(0,R*se));return w(fe),fe}}catch{return null}return null}acquireLayerCanvas(){var n;let e=(n=this.layerPool.pop())!=null?n:document.createElement("canvas");if(e.width!==this.canvas.width||e.height!==this.canvas.height)e.width=this.canvas.width,e.height=this.canvas.height;else{let r=e.getContext("2d");if(!r)return null;r.save(),r.setTransform(1,0,0,1,0,0),r.clearRect(0,0,e.width,e.height),r.restore()}return e}releaseLayerCanvas(e){this.layerPool.length<qn.MAX_LAYER_DEPTH&&this.layerPool.push(e)}pushLayer(e,n,r,o){if(this.layerStack.length>=qn.MAX_LAYER_DEPTH)return!1;let i=this.acquireLayerCanvas(),s=i==null?void 0:i.getContext("2d");return!i||!s?!1:(s.setTransform(this.ctx.getTransform()),s.lineWidth=this.ctx.lineWidth,s.lineCap=this.ctx.lineCap,s.lineJoin=this.ctx.lineJoin,s.miterLimit=this.ctx.miterLimit,s.setLineDash(this.ctx.getLineDash()),s.lineDashOffset=this.ctx.lineDashOffset,s.fillStyle=this.ctx.fillStyle,s.strokeStyle=this.ctx.strokeStyle,s.globalAlpha=1,s.globalCompositeOperation="source-over",this.layerStack.push({savedCtx:this.ctx,canvas:i,alpha:n,blend:r,mask:o,kind:e,stateDepthAtPush:this.stateStack.length}),this.ctx=s,!0)}popLayer(){let e=this.layerStack.pop();if(!e)return;let n=e.canvas.getContext("2d");n&&e.mask&&(n.save(),n.setTransform(1,0,0,1,0,0),n.globalAlpha=1,n.globalCompositeOperation="destination-in",n.drawImage(e.mask,0,0),n.restore(),this.releaseLayerCanvas(e.mask)),this.ctx=e.savedCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.globalAlpha=e.alpha,this.ctx.globalCompositeOperation=nl(e.blend),this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.releaseLayerCanvas(e.canvas)}async applySoftMaskFromExtGState(e){try{if(!this.pageResources)return;let n=this.resolveObject(this.pageResources.entries.get("ExtGState"));if(!n||!Z(n))return;let r=this.resolveObject(n.entries.get(e));if(!r||!Z(r))return;let o=r.entries.get("SMask");if(!o)return;if(Me(o)==="None"){for(;this.layerStack.length>0;){let a=this.layerStack[this.layerStack.length-1];if(a.kind==="smask"&&a.stateDepthAtPush===this.stateStack.length)this.popLayer();else break}return}let i=this.resolveObject(o);if(!i||!Z(i))return;let s=await this.renderSMaskCanvas(i);if(!s)return;this.pushLayer("smask",1,"Normal",s)}catch{}}async renderSMaskCanvas(e){var m;let n=this.resolveObject(e.entries.get("G"));if(!n||!me(n))return null;let r=((m=Me(e.entries.get("S")))!=null?m:"Alpha")==="Luminosity",o=this.acquireLayerCanvas(),i=o==null?void 0:o.getContext("2d",{willReadFrequently:!0});if(!o||!i)return null;if(r){let h=ut(e.entries.get("BC"));if(i.save(),i.setTransform(1,0,0,1,0,0),h&&h.length){let f=fn(mn(h.length===1?"DeviceGray":h.length===4?"DeviceCMYK":"DeviceRGB",h));i.fillStyle=Ft(f.r,f.g,f.b)}else i.fillStyle="black";i.fillRect(0,0,o.width,o.height),i.restore()}i.setTransform(this.ctx.getTransform());let s=this.ctx,a=this.capturedTextRuns.length;this.ctx=i,this.captureSuppressed+=1;try{await this.renderFormStreamInline(n)}finally{this.captureSuppressed-=1,this.ctx=s,this.capturedTextRuns.length=a}let c=e.entries.get("TR"),l=this.objectLoader,d=c&&l&&Me(c)!=="Identity"?h=>{let f=xo(c,h,l);return f&&f.length?Math.max(0,Math.min(1,f[0])):h}:null;try{let h=i.getImageData(0,0,o.width,o.height),f=h.data;for(let p=0;p<f.length;p+=4){let w=r?(.3*f[p]+.59*f[p+1]+.11*f[p+2])/255:f[p+3]/255,b=d?d(w):w;f[p+3]=Math.round(b*255)}i.putImageData(h,0,0)}catch{return this.releaseLayerCanvas(o),null}return o}async renderFormStreamInline(e){let n=e.decode?await e.decode():ve.decodeStreamSync(e),r=Vt(n),o=this.pageResources,i=this.objectLoader,s=this.patternCache;this.patternCache=new Map;let a=this.resolveObject(e.dict.entries.get("Resources"));this.pageResources=a&&Z(a)?a:this.pageResources,this.execute({op:"save_state"});let c=yr(e.dict.entries.get("Matrix"));c&&this.execute({op:"set_ctm",matrix:c});let l=ut(e.dict.entries.get("BBox"));l&&l.length>=4&&(this.ctx.beginPath(),this.ctx.rect(l[0],l[1],l[2]-l[0],l[3]-l[1]),this.ctx.clip());let d=this.commandIndex;this.xobjectDepth+=1;try{await this.runCommandsAsync(r)}finally{this.xobjectDepth-=1,this.commandIndex=d,this.execute({op:"restore_state"}),this.pageResources=o,this.objectLoader=i,this.patternCache=s}}renderShadeOperator(e){try{if(!this.pageResources||!this.objectLoader)return;let n=this.resolveObject(this.pageResources.entries.get("Shading"));if(!n||!Z(n))return;let r=this.resolveObject(n.entries.get(e)),o=r?me(r)?r.dict:Z(r)?r:null:null;if(!o)return;let i=r&&me(r)?r:null;this.ctx.save();try{this.ctx.globalAlpha=this.state.fillAlpha;let s=ut(o.entries.get("BBox"));s&&s.length>=4&&(this.ctx.beginPath(),this.ctx.rect(s[0],s[1],s[2]-s[0],s[3]-s[1]),this.ctx.clip());let a=Se(this.deviceBase(),this.state.ctm);this.paintShadingWithBase(o,i,a)}finally{this.ctx.restore()}}catch{}}};qn.MAX_LAYER_DEPTH=6;var vr=qn,Cf=t=>t==="DeviceGray"||t==="CalGray"?1:t==="DeviceCMYK"?4:3,nl=t=>{switch(t){case"Normal":case"Compatible":return"source-over";case"Multiply":return"multiply";case"Screen":return"screen";case"Overlay":return"overlay";case"Darken":return"darken";case"Lighten":return"lighten";case"ColorDodge":return"color-dodge";case"ColorBurn":return"color-burn";case"HardLight":return"hard-light";case"SoftLight":return"soft-light";case"Difference":return"difference";case"Exclusion":return"exclusion";case"Hue":return"hue";case"Saturation":return"saturation";case"Color":return"color";case"Luminosity":return"luminosity";default:return"source-over"}},ut=t=>!t||!he(t)?null:t.items.map(e=>{var n;return(n=K(e))!=null?n:0}),Ff=new Set(["FlateDecode","Fl","LZWDecode","LZW","ASCII85Decode","A85","ASCIIHexDecode","AHx","RunLengthDecode","RL","Crypt"]),Mf=(t,e,n)=>{if(!e||e.length<2||n!=="DeviceGray"&&n!=="DeviceRGB"||!(e[0]===1&&e[1]===0))return;let r=t.data;for(let o=0;o<r.length;o+=4)r[o]=255-r[o],r[o+1]=255-r[o+1],r[o+2]=255-r[o+2]},yr=t=>{let e=ut(t);return!e||e.length<6?null:[e[0],e[1],e[2],e[3],e[4],e[5]]},Rf=(t,e,n)=>{let r=[Ue(n,e[0],e[1]),Ue(n,e[2],e[1]),Ue(n,e[2],e[3]),Ue(n,e[0],e[3])],o=r.map(k=>k.x),i=r.map(k=>k.y),s=Math.min(...o),a=Math.max(...o),c=Math.min(...i),l=Math.max(...i),d=Math.min(t[0],t[2]),m=Math.max(t[0],t[2]),h=Math.min(t[1],t[3]),f=Math.max(t[1],t[3]),p=a-s,w=l-c;if(!(p>1e-6)||!(w>1e-6))return null;let b=(m-d)/p,y=(f-h)/w;return[b,0,0,y,d-b*s,h-y*c]},Af=t=>{if(!t||!he(t))return[!1,!1];let e=n=>!!n&&typeof n=="object"&&"type"in n&&n.type==="boolean"&&n.value;return[e(t.items[0]),e(t.items[1])]},Ft=(t,e,n)=>`rgb(${Math.round(Je(t)*255)},${Math.round(Je(e)*255)},${Math.round(Je(n)*255)})`,Jt=t=>{if(t.space==="rgb")return Ft(t.r,t.g,t.b);if(t.space==="gray")return Ft(t.gray,t.gray,t.gray);let e=Zn(t.c,t.m,t.y,t.k);return Ft(e.r,e.g,e.b)},fn=t=>{if(t.space==="rgb")return{r:Je(t.r),g:Je(t.g),b:Je(t.b)};if(t.space==="gray"){let e=Je(t.gray);return{r:e,g:e,b:e}}return Zn(t.c,t.m,t.y,t.k)},Mt=t=>{switch(t){case"DeviceRGB":case"RGB":return"DeviceRGB";case"DeviceGray":case"G":case"Gray":return"DeviceGray";case"DeviceCMYK":case"CMYK":return"DeviceCMYK";default:return null}},rl=t=>{var r;let e=Me(t),n=e?Mt(e):null;if(n)return n;if(t&&he(t)&&t.items.length>0){let o=Me(t.items[0]),i=o?Mt(o):null;if(i)return i;if(o==="ICCBased"){let s=t.items[1];if(s&&me(s)){let a=Math.floor((r=K(s.dict.entries.get("N")))!=null?r:0);if(a===1)return"DeviceGray";if(a===3)return"DeviceRGB";if(a===4)return"DeviceCMYK"}}if(o==="CalGray")return"DeviceGray";if(o==="CalRGB")return"DeviceRGB";if(o==="Lab")return"Lab";if(o==="Separation")return"Separation";if(o==="DeviceN")return"DeviceN";if(o==="Indexed")return"Indexed";if(o==="Pattern")return"Pattern"}return null},Nf=(t,e,n)=>{let r=(t+16)/116,o=e/500+r,i=r-n/200,s=p=>p>.206897?p*p*p:(p-16/116)/7.787,a=.9642*s(o),c=1*s(r),l=.8249*s(i),d=3.1338561*a-1.6168667*c-.4906146*l,m=-.9787684*a+1.9161415*c+.033454*l,h=.0719453*a-.2289914*c+1.4052427*l,f=p=>p<=.0031308?12.92*p:1.055*Math.pow(Math.max(0,p),1/2.4)-.055;return{r:Je(f(d)),g:Je(f(m)),b:Je(f(h))}},mn=(t,e)=>{var r,o,i,s,a,c,l,d,m,h,f,p,w,b,y,k,C;let n=Mt(t);if(n==="DeviceGray")return{space:"gray",gray:(r=e[0])!=null?r:0};if(n==="DeviceCMYK")return{space:"cmyk",c:(o=e[0])!=null?o:0,m:(i=e[1])!=null?i:0,y:(s=e[2])!=null?s:0,k:(a=e[3])!=null?a:0};if(n==="DeviceRGB"||!n&&e.length===3)return{space:"rgb",r:(c=e[0])!=null?c:0,g:(l=e[1])!=null?l:0,b:(d=e[2])!=null?d:0};if(t==="Lab"){let S=Nf((m=e[0])!=null?m:0,(h=e[1])!=null?h:0,(f=e[2])!=null?f:0);return{space:"rgb",r:S.r,g:S.g,b:S.b}}return t==="Separation"||t==="DeviceN"?{space:"gray",gray:1-((p=e[0])!=null?p:0)}:e.length>=4?{space:"cmyk",c:(w=e[0])!=null?w:0,m:(b=e[1])!=null?b:0,y:(y=e[2])!=null?y:0,k:(k=e[3])!=null?k:0}:{space:"gray",gray:(C=e[0])!=null?C:0}},ol=t=>{if(!t)return[];let e=Me(t);return e?[e]:he(t)?t.items.map(n=>Me(n)).filter(n=>n!==null):[]},qi=async(t,e)=>typeof createImageBitmap=="function"?createImageBitmap(new Blob([t.slice().buffer],{type:e})):new Promise((n,r)=>{let o=new Image,i=URL.createObjectURL(new Blob([t.slice().buffer],{type:e}));o.onload=()=>{URL.revokeObjectURL(i),n(o)},o.onerror=()=>{URL.revokeObjectURL(i),r(new Error(`Could not decode image ${e}`))},o.src=i}),Ji=t=>{"close"in t&&typeof t.close=="function"&&t.close()},Ef=(t,e)=>{let n=t.entries.get("Widths");if(!n||!he(n))return;let r=new Map;return n.items.forEach((o,i)=>{let s=K(o);s!==null&&r.set(e+i,s)}),r.size>0?r:void 0},il=(t,e)=>{let n=t.entries.get("DescendantFonts");if(!n||!he(n)||n.items.length===0)return;let r=e(n.items[0]);return r&&Z(r)?r:void 0},sl=(t,e,n)=>{let r=n(t.entries.get("FontDescriptor"));if(r&&Z(r))return r;let o=n(e==null?void 0:e.entries.get("FontDescriptor"));return o&&Z(o)?o:void 0},Tf=t=>{let e=t==null?void 0:t.entries.get("W");if(!e||!he(e))return;let n=new Map,r=e.items;for(let o=0;o<r.length;o+=1){let i=K(r[o]);if(i===null)continue;let s=r[o+1];if(s&&he(s)){s.items.forEach((l,d)=>{let m=K(l);m!==null&&n.set(i+d,m)}),o+=1;continue}let a=K(s),c=K(r[o+2]);if(!(a===null||c===null)){for(let l=i;l<=a;l+=1)n.set(l,c);o+=2}}return n.size>0?n:void 0},Of=t=>{let e=K(t==null?void 0:t.entries.get("DW"));return e!=null?e:void 0},If=t=>{let e=t.entries.get("FontDescriptor");if(!e||!Z(e))return;let n=K(e.entries.get("MissingWidth"));return n!=null?n:void 0},jf=(t,e,n,r,o,i,s)=>{let a=n.isComposite?Lf(t,n.toUnicode):Array.from(t).map((h,f)=>({code:h,bytes:t.slice(f,f+1)})),c=Array.from(e),l=!!n.widths||n.defaultWidth!==void 0,d=0;return{glyphs:a.map(h=>{var k,C,S;let f=n.toUnicode?Qt(h.code,n.toUnicode):null,p=(k=f!=null?f:c[d])!=null?k:"";d+=Math.max(1,Array.from(p).length);let w=(S=(C=n.widths)==null?void 0:C.get(h.code))!=null?S:n.defaultWidth,b;w!==void 0?b=w/1e3*r:s?b=s(p):b=(n.isComposite?1e3:500)/1e3*r,b>0||(b=s?Math.max(.01,s(p||" ")):r*.5);let y=o+(p===" "||h.code===32?i:0);return{text:p,code:h.code,bytes:h.bytes,glyphWidth:b,advance:b+y}}),hasPdfMetrics:l}},ts=t=>{var r;let e=Do((r=t.baseFontName)!=null?r:"").toLowerCase(),n=fl(e);return t.registeredFamily?`"${t.registeredFamily}", ${n}`:n},al=(t,e)=>{var s,a,c;let r=Do((s=t.baseFontName)!=null?s:"").toLowerCase(),o=(a=t.fontStyle)!=null?a:r.includes("italic")||r.includes("oblique")?"italic":"normal",i=String((c=t.fontWeight)!=null?c:r.includes("bold")||r.includes("black")?700:400);return t.registeredFamily?`${e}px ${ts(t)}`:`${o} ${i} ${e}px ${fl(r)}`},$f=(t,e)=>{var s;let n=Do(t!=null?t:"").toLowerCase(),r=K(e==null?void 0:e.entries.get("FontWeight"));if(r!==null)return Math.max(100,Math.min(900,Math.round(r/100)*100));let o=Math.floor((s=K(e==null?void 0:e.entries.get("Flags")))!=null?s:0),i=K(e==null?void 0:e.entries.get("StemV"));if(n.includes("bold")||n.includes("black")||n.includes("heavy")||(o&262144)!==0||i!==null&&i>=120)return 700},Bf=(t,e)=>{var i;let n=Do(t!=null?t:"").toLowerCase(),r=Math.floor((i=K(e==null?void 0:e.entries.get("Flags")))!=null?i:0),o=K(e==null?void 0:e.entries.get("ItalicAngle"));if(n.includes("italic")||n.includes("oblique")||(r&64)!==0||o!==null&&o!==0)return"italic"},Do=t=>/^[A-Z]{6}\+/.test(t)?t.slice(7):t,fl=t=>t.includes("courier")?'"Courier New", Courier, monospace':t.includes("times")||t.includes("serif")?'"Times New Roman", Times, serif':t.includes("symbol")?'Symbol, "Times New Roman", serif':t.includes("zapfdingbats")||t.includes("dingbats")?'ZapfDingbats, "Times New Roman", serif':(t.includes("helvetica")||t.includes("arial"),"Helvetica, Arial, sans-serif"),Lf=(t,e)=>{var r,o;if(t.length===0)return[];if(e!=null&&e.codeSpaceRanges.length){let i=Array.from(new Set(e.codeSpaceRanges.map(a=>a.byteLength))).sort((a,c)=>c-a),s=[];for(let a=0;a<t.length;){let c=0,l=0;for(let d of i){if(a+d>t.length)continue;let m=Jn(t,a,d);if(m!==null&&gl(m,d,e.codeSpaceRanges)){c=d,l=m;break}}c===0&&(c=Math.min(2,t.length-a),l=(r=Jn(t,a,c))!=null?r:t[a]),s.push({code:l,bytes:t.slice(a,a+c)}),a+=c}return s}let n=[];for(let i=0;i<t.length;){let s=Math.min(2,t.length-i);n.push({code:(o=Jn(t,i,s))!=null?o:t[i],bytes:t.slice(i,i+s)}),i+=s}return n},Uf=t=>t==="DeviceCMYK"?4:t==="DeviceGray"||t==="Separation"?1:3,Zi=(t,e,n,r,o,i)=>{var d,m,h,f;if(o===8)return t;let s=e*r,a=new Uint8Array(s*n);if(o===16){for(let p=0,w=0;p<a.length;p++,w+=2)a[p]=(d=t[w])!=null?d:0;return a}let c=(1<<o)-1,l=Math.ceil(s*o/8);for(let p=0;p<n;p++){let w=p*l,b=0;for(let y=0;y<s;y++){let k=w+(b>>3),S=8-(b&7),F;if(o<=S)F=((m=t[k])!=null?m:0)>>S-o&c;else{let O=o-S,N=((h=t[k])!=null?h:0)&(1<<S)-1,I=((f=t[k+1])!=null?f:0)>>8-O;F=N<<O|I}a[p*s+y]=i?Math.round(F*255/c):F,b+=o}}return a},_f=(t,e,n,r)=>{let o=e*n,i=new Uint8ClampedArray(o*4);if(r==="DeviceRGB"){if(t.length<o*3)return null;for(let a=0,c=0;c<i.length;a+=3,c+=4)i[c]=t[a],i[c+1]=t[a+1],i[c+2]=t[a+2],i[c+3]=255;return new ImageData(i,e,n)}if(r==="DeviceGray"){if(t.length<o)return null;for(let a=0,c=0;c<i.length;a+=1,c+=4){let l=t[a];i[c]=l,i[c+1]=l,i[c+2]=l,i[c+3]=255}return new ImageData(i,e,n)}if(r==="DeviceCMYK"){if(t.length<o*4)return null;for(let a=0,c=0;c<i.length;a+=4,c+=4){let l=Zn(t[a]/255,t[a+1]/255,t[a+2]/255,t[a+3]/255);i[c]=Math.round(l.r*255),i[c+1]=Math.round(l.g*255),i[c+2]=Math.round(l.b*255),i[c+3]=255}return new ImageData(i,e,n)}let s=Math.floor(t.length/Math.max(1,o));if(s>=3){let a=s;for(let c=0,l=0;c<o;c++,l+=4){let d=c*a;i[l]=t[d],i[l+1]=t[d+1],i[l+2]=t[d+2],i[l+3]=255}return new ImageData(i,e,n)}if(s>=1){let a=r==="Separation"||r==="DeviceN";for(let c=0,l=0;c<o;c++,l+=4){let d=a?255-t[c]:t[c];i[l]=d,i[l+1]=d,i[l+2]=d,i[l+3]=255}return new ImageData(i,e,n)}return null},vo=(t,e,n,r)=>{let o=t.data,i=n*r;for(let s=0;s<i&&s<e.length;s++)o[s*4+3]=e[s]},Xf=(t,e,n,r,o)=>{var h,f,p,w,b,y,k,C,S,F,O;if(r.length<4)return null;let i=(h=Me(r[1]))!=null?h:"DeviceRGB",s=Math.floor((f=K(r[2]))!=null?f:255),a=o(r[3]),c=null;if(a&&me(a))try{c=ve.decodeStreamSync(a)}catch{}else a&&typeof a=="object"&&"type"in a&&a.type==="string"&&(c=a.value);if(!c)return null;let l=i==="DeviceCMYK"?4:i==="DeviceGray"?1:3,d=e*n,m=new Uint8ClampedArray(d*4);for(let N=0;N<d;N++){let R=Math.min((p=t[N])!=null?p:0,s)*l,H=0,te=0,T=0;if(l===3)H=(w=c[R])!=null?w:0,te=(b=c[R+1])!=null?b:0,T=(y=c[R+2])!=null?y:0;else if(l===1)H=te=T=(k=c[R])!=null?k:0;else if(l===4){let se=Zn(((C=c[R])!=null?C:0)/255,((S=c[R+1])!=null?S:0)/255,((F=c[R+2])!=null?F:0)/255,((O=c[R+3])!=null?O:0)/255);H=Math.round(se.r*255),te=Math.round(se.g*255),T=Math.round(se.b*255)}let ce=N*4;m[ce]=H,m[ce+1]=te,m[ce+2]=T,m[ce+3]=255}return new ImageData(m,e,n)},zf=t=>{var o;if(!t)return null;let e=t.match(/^uni([0-9A-Fa-f]{4,6})$/);if(e){let i=parseInt(e[1],16);try{return String.fromCodePoint(i)}catch{return null}}let n=t.match(/^u([0-9A-Fa-f]{5,6})$/);if(n){let i=parseInt(n[1],16);try{return String.fromCodePoint(i)}catch{return null}}return t.length===1?t:(o={space:" ",exclam:"!",quotedbl:'"',numbersign:"#",dollar:"$",percent:"%",ampersand:"&",quotesingle:"'",parenleft:"(",parenright:")",asterisk:"*",plus:"+",comma:",",hyphen:"-",period:".",slash:"/",zero:"0",one:"1",two:"2",three:"3",four:"4",five:"5",six:"6",seven:"7",eight:"8",nine:"9",colon:":",semicolon:";",less:"<",equal:"=",greater:">",question:"?",at:"@",A:"A",B:"B",C:"C",D:"D",E:"E",F:"F",G:"G",H:"H",I:"I",J:"J",K:"K",L:"L",M:"M",N:"N",O:"O",P:"P",Q:"Q",R:"R",S:"S",T:"T",U:"U",V:"V",W:"W",X:"X",Y:"Y",Z:"Z",bracketleft:"[",backslash:"\\",bracketright:"]",asciicircum:"^",underscore:"_",grave:"`",a:"a",b:"b",c:"c",d:"d",e:"e",f:"f",g:"g",h:"h",i:"i",j:"j",k:"k",l:"l",m:"m",n:"n",o:"o",p:"p",q:"q",r:"r",s:"s",t:"t",u:"u",v:"v",w:"w",x:"x",y:"y",z:"z",braceleft:"{",bar:"|",braceright:"}",asciitilde:"~",exclamdown:"\xA1",cent:"\xA2",sterling:"\xA3",currency:"\xA4",yen:"\xA5",brokenbar:"\xA6",section:"\xA7",dieresis:"\xA8",copyright:"\xA9",ordfeminine:"\xAA",guillemotleft:"\xAB",logicalnot:"\xAC",minus:"\u2212",registered:"\xAE",macron:"\xAF",degree:"\xB0",plusminus:"\xB1",twosuperior:"\xB2",threesuperior:"\xB3",acute:"\xB4",mu:"\xB5",paragraph:"\xB6",periodcentered:"\xB7",cedilla:"\xB8",onesuperior:"\xB9",ordmasculine:"\xBA",guillemotright:"\xBB",onequarter:"\xBC",onehalf:"\xBD",threequarters:"\xBE",questiondown:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acircumflex:"\xC2",Atilde:"\xC3",Adieresis:"\xC4",Aring:"\xC5",AE:"\xC6",Ccedilla:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecircumflex:"\xCA",Edieresis:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icircumflex:"\xCE",Idieresis:"\xCF",Eth:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocircumflex:"\xD4",Otilde:"\xD5",Odieresis:"\xD6",multiply:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucircumflex:"\xDB",Udieresis:"\xDC",Yacute:"\xDD",Thorn:"\xDE",germandbls:"\xDF",agrave:"\xE0",aacute:"\xE1",acircumflex:"\xE2",atilde:"\xE3",adieresis:"\xE4",aring:"\xE5",ae:"\xE6",ccedilla:"\xE7",egrave:"\xE8",eacute:"\xE9",ecircumflex:"\xEA",edieresis:"\xEB",igrave:"\xEC",iacute:"\xED",icircumflex:"\xEE",idieresis:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocircumflex:"\xF4",otilde:"\xF5",odieresis:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucircumflex:"\xFB",udieresis:"\xFC",yacute:"\xFD",thorn:"\xFE",ydieresis:"\xFF",OE:"\u0152",oe:"\u0153",Scaron:"\u0160",scaron:"\u0161",Ydieresis:"\u0178",Zcaron:"\u017D",zcaron:"\u017E",florin:"\u0192",circumflex:"\u02C6",tilde:"\u02DC",endash:"\u2013",emdash:"\u2014",quotedblleft:"\u201C",quotedblright:"\u201D",quoteleft:"\u2018",quoteright:"\u2019",quotesinglbase:"\u201A",quotedblbase:"\u201E",dagger:"\u2020",daggerdbl:"\u2021",bullet:"\u2022",ellipsis:"\u2026",perthousand:"\u2030",guilsinglleft:"\u2039",guilsinglright:"\u203A",fraction:"\u2044",Euro:"\u20AC",trademark:"\u2122",fi:"\uFB01",fl:"\uFB02",ff:"\uFB00",ffi:"\uFB03",ffl:"\uFB04",lslash:"\u0142",Lslash:"\u0141",dotaccent:"\u02D9",ring:"\u02DA",caron:"\u02C7",breve:"\u02D8",dotlessi:"\u0131",hungarumlaut:"\u02DD",ogonek:"\u02DB",Delta:"\u2206",Omega:"\u03A9",pi:"\u03C0",infinity:"\u221E",lessequal:"\u2264",greaterequal:"\u2265",notequal:"\u2260",approxequal:"\u2248",radical:"\u221A",summation:"\u2211",product:"\u220F",integral:"\u222B",partialdiff:"\u2202",lozenge:"\u25CA",apple:"\uF8FF"}[t])!=null?o:null},cl=(()=>{let t=[[128,196],[129,197],[130,199],[131,201],[132,209],[133,214],[134,220],[135,225],[136,224],[137,226],[138,228],[139,227],[140,229],[141,231],[142,233],[143,232],[144,234],[145,235],[146,237],[147,236],[148,238],[149,239],[150,241],[151,243],[152,242],[153,244],[154,246],[155,250],[156,249],[157,251],[158,252],[159,8224],[160,176],[161,162],[162,163],[163,167],[164,8226],[165,182],[166,223],[167,174],[168,169],[169,8482],[170,180],[171,168],[172,8800],[173,198],[174,216],[175,8734],[176,177],[177,8804],[178,8805],[179,165],[180,181],[181,8706],[182,8721],[183,8719],[184,960],[185,8747],[186,170],[187,186],[188,937],[189,230],[190,248],[191,191],[192,161],[193,172],[194,8730],[195,402],[196,8776],[197,8710],[198,171],[199,187],[200,8230],[201,160],[202,192],[203,195],[204,213],[205,338],[206,339],[207,8211],[208,8212],[209,8220],[210,8221],[211,8216],[212,8217],[213,247],[214,9674],[215,255],[216,376],[217,8260],[218,8364],[219,8249],[220,8250],[221,64257],[222,64258],[223,8225],[224,183],[225,8218],[226,8222],[227,8240],[228,194],[229,202],[230,193],[231,203],[232,200],[233,205],[234,206],[235,207],[236,204],[237,211],[238,212],[239,210],[240,218],[241,219],[242,217],[243,305],[244,710],[245,732],[246,175],[247,728],[248,729],[249,730],[250,184],[251,733],[252,731],[253,711],[254,254],[255,255]],e=new Map;for(let[n,r]of t)e.set(n,String.fromCodePoint(r));return e})(),ll=(()=>{let t=[[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]],e=new Map;for(let[n,r]of t)e.set(n,String.fromCodePoint(r));return e})(),Yf=(t,e)=>{if(!t)return;let n=e(t);if(!n)return;let r=Me(n);if(r)return r==="MacRomanEncoding"?new Map(cl):r==="WinAnsiEncoding"?new Map(ll):void 0;if(!Z(n))return;let o=n,i=Me(o.entries.get("BaseEncoding")),s;i==="MacRomanEncoding"?s=new Map(cl):i==="WinAnsiEncoding"?s=new Map(ll):s=new Map;let a=o.entries.get("Differences");if(!a||!he(a))return s.size>0?s:void 0;let c=0;for(let l of a.items){let d=K(l);if(d!==null)c=Math.floor(d);else{let m=Me(l);if(m){let h=zf(m);h&&s.set(c,h),c++}}}return s.size>0?s:void 0},Wf=(t,e)=>{let n=new Map;if(!t)return n;let r=e(t);if(!r||!Z(r))return n;let o=r.entries.get("Differences");if(!o||!he(o))return n;let i=0;for(let s of o.items){let a=K(s);if(a!==null)i=Math.floor(a);else{let c=Me(s);c&&(n.set(i,c),i++)}}return n},Zn=(t,e,n,r)=>({r:(1-Je(t))*(1-Je(r)),g:(1-Je(e))*(1-Je(r)),b:(1-Je(n))*(1-Je(r))}),Je=t=>!Number.isFinite(t)||t<0?0:t>1?1:t,Hf=(t,e,n)=>Number.isFinite(t)?Math.min(n,Math.max(e,t)):e,Gf=t=>({...t,ctm:[...t.ctm],textMatrix:[...t.textMatrix],textLineMatrix:[...t.textLineMatrix],fillColor:{...t.fillColor},strokeColor:{...t.strokeColor},dashArray:[...t.dashArray]}),Ue=(t,e,n)=>({x:t[0]*e+t[2]*n+t[4],y:t[1]*e+t[3]*n+t[5]}),ko=()=>({subtype:"Unknown",baseFontName:void 0,isComposite:!1,firstChar:void 0,widths:void 0,defaultWidth:void 0,toUnicode:null}),Kf=t=>{let e={bfChar:new Map,bfRange:[],codeSpaceRanges:[],cmapType:0,isUsable:!0},n=t.match(/\/CMapType\s+(\d+)\s+def/);n&&(e.cmapType=Number.parseInt(n[1],10),e.isUsable=e.cmapType!==0);let r=t.replace(/\r\n/g,`
|
|
34
|
+
`],["\uFB01","fi"],["\uFB02","fl"],["\uFB00","ff"],["\uFB03","ffi"],["\uFB04","ffl"]]),oc=t=>(t!=null?t:"").replace(/^[A-Z]{6}\+/,"").replace(/[#,\s]/g,"").toLowerCase(),Ni=t=>!t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null,Rn=(t,e)=>{if(t){if(!Be(t))return t;try{return e(t)}catch{return}}},Yu=t=>{if(!(!t||!he(t)))return t.items[0]},Wu=(t,e)=>{let n=Rn(t.entries.get("FontDescriptor"),e);if(n&&Q(n))return n;let r=Rn(t.entries.get("DescendantFonts"),e),o=Rn(Yu(r),e);if(o&&Q(o)){let i=Rn(o.entries.get("FontDescriptor"),e);if(i&&Q(i))return i}},Hu=t=>{var a,c,l,d,m,h,f,p;let e=new Kt(t),r=e.parse().xrefTables.get(0);if(!r)return[];let o=[],i=new Set,s=w=>e.loadObject(w);for(let[w,y]of r.entries()){if(!y.inUse)continue;let v;try{v=s({type:"ref",objNum:w,genNum:y.genNum})}catch{continue}if(!Q(v))continue;let b=Ni(v.entries.get("Subtype"));if(!b||!["Type1","TrueType","Type0","CIDFontType0","CIDFontType2"].includes(b))continue;let C=Wu(v,s);if(!C)continue;let S=(c=(a=Rn(C.entries.get("FontFile2"),s))!=null?a:Rn(C.entries.get("FontFile3"),s))!=null?c:Rn(C.entries.get("FontFile"),s);if(!S||!fe(S))continue;let F=(d=(l=Ni(v.entries.get("BaseFont")))!=null?l:Ni(C.entries.get("FontName")))!=null?d:`Font${w}`,T=oc(F),N=`${T}:${(p=(f=(m=S.rawBytes)==null?void 0:m.length)!=null?f:(h=S.data)==null?void 0:h.length)!=null?p:0}`;if(!i.has(N))try{let O=we.decodeStreamSync(S);if(O.length===0)continue;o.push({baseName:F,normalizedName:T,bytes:O}),i.add(N)}catch{continue}}return o},rc=(t,e,n,r)=>{let o=Math.max(0,t.x-e),i=Math.max(0,t.y-e),s=Math.min(n,t.x+t.width+e),a=Math.min(r,t.y+t.height+e);return{x:o,y:i,width:Math.max(0,s-o),height:Math.max(0,a-i)}},so=class t{constructor(e,n){this.pdfDoc=e;this.pdfBytes=n;this.standardFontCache=new Map;this.embeddedFontCache=new Map;this.embeddedFonts=null;this.fontkitRegistered=!1;this.rewrittenPages=new Map;this.indexInvalidPages=new Set;this.embeddedImageCache=new Map;this.currentBytes=n}static async fromAvniDocument(e){let n=await e.blob.arrayBuffer(),r=new Uint8Array(n),o=await nc.load(r);return new t(o,r)}static async fromBytes(e){let n=e instanceof Uint8Array?e:new Uint8Array(e),r=await nc.load(n);return new t(r,n)}getPageCount(){return this.pdfDoc.getPageCount()}async applyOperations(e){var r,o,i,s,a,c,l,d,m,h,f,p,w,y,v,b,C,S,F,T,N,O;if(e.length===0)return;for(let A of e)Wa(_u[A.type]);let n=await this.getStandardFont(dt.Helvetica);for(let A of e){if(A.type==="create-form-field"||A.type==="set-form-values"||A.type==="delete-form-field"||A.type==="flatten-form")continue;if(A.type==="delete-page"){this.deletePage(A.pageIndex);continue}if(A.type==="delete-object"){if(!await this.tryNeutralizeSpans(A.pageIndex,A.spans))throw new Error("This object cannot be deleted safely.");continue}if(A.type==="transform-object"){if(!await this.tryWrapSpanWithTransform(A))throw new Error("This object cannot be moved safely.");continue}if(A.type==="add-annotation"){tc(this.pdfDoc,A.annotation);continue}let H=this.pdfDoc.getPage(A.pageIndex);if(A.type==="insert-image"){let ne=await this.getEmbeddedImage(A.bytes,A.format);H.drawImage(ne,{x:A.x,y:A.y,width:A.width,height:A.height});continue}if(A.type==="insert-text"){if((r=A.spans)!=null&&r.length){await this.drawStyledSpans(H,A.spans,A.x,A.y,(o=A.size)!=null?o:14,A.fontName);continue}let ne=hr((i=A.color)!=null?i:{r:0,g:0,b:0}),ie=this.fitTextToFont(n,A.text);if(ie.length===0)continue;H.drawText(ie,{x:A.x,y:A.y,size:(s=A.size)!=null?s:14,font:n,color:ur(ne.r,ne.g,ne.b)});continue}if(A.type==="redact-area"){let ne=hr((a=A.color)!=null?a:{r:1,g:1,b:1}),{width:ie,height:I}=H.getSize();(l=(c=A.removeOperators)==null?void 0:c.streamOperatorIndices)!=null&&l.length&&await this.tryRemoveTextOperators(A.pageIndex,A.removeOperators.streamOperatorIndices);let ce=rc({x:A.x,y:A.y,width:A.width,height:A.height},(d=A.padding)!=null?d:1.75,ie,I);H.drawRectangle({x:ce.x,y:ce.y,width:ce.width,height:ce.height,color:ur(ne.r,ne.g,ne.b)});continue}if(A.type==="replace-text"){let ne=hr((m=A.backgroundColor)!=null?m:{r:1,g:1,b:1}),ie=hr((p=(f=A.color)!=null?f:(h=A.font)==null?void 0:h.color)!=null?p:{r:0,g:0,b:0}),I=(v=(y=A.size)!=null?y:(w=A.font)==null?void 0:w.sizePt)!=null?v:Math.max(8,A.height*.8),ce=(b=A.font)!=null&&b.pdfName?await this.getRenderableFont(A.font.pdfName,A.newText):n,le=this.fitTextToFont(ce,A.newText),{width:pe,height:De}=H.getSize(),_=le.trim().length>0?ce.widthOfTextAtSize(le,I):0;if(!((S=(C=A.removeOperators)==null?void 0:C.streamOperatorIndices)!=null&&S.length?await this.tryRemoveTextOperators(A.pageIndex,A.removeOperators.streamOperatorIndices):!1)){let ae=Math.min(pe-A.x,Math.max(A.width,_+I*.25)),me=rc({x:A.x,y:A.y,width:ae,height:A.height},(F=A.erasePadding)!=null?F:1.75,pe,De);A.eraseClamp&&(me=Qr(me,A.eraseClamp)),H.drawRectangle({x:me.x,y:me.y,width:me.width,height:me.height,color:ur(ne.r,ne.g,ne.b)})}let G=(T=A.baselineY)!=null?T:A.y+Math.max(0,(A.height-I)/2);if((N=A.spans)!=null&&N.length){await this.drawStyledSpans(H,A.spans,A.x,G,I,(O=A.font)==null?void 0:O.pdfName);continue}if(le.length===0)continue;H.drawText(le,{x:A.x,y:G,size:I,font:ce,color:ur(ie.r,ie.g,ie.b)});continue}if(A.type==="rotate-page"){let ne=H.getRotation().angle;H.setRotation(Lu(ne+A.degrees))}}await this.applyFormOperations(e,n)}async applyFormOperations(e,n){let r=e.filter(a=>a.type==="create-form-field"||a.type==="update-form-field"||a.type==="set-form-values"||a.type==="delete-form-field"||a.type==="flatten-form");if(r.length===0)return;let o=this.pdfDoc.getForm(),i=!1,s=!1;for(let a of r)if(a.type==="create-form-field")this.createFormField(a,n),i=!0;else if(a.type==="update-form-field"){try{let c=o.getField(a.oldName);c&&o.removeField(c)}catch{}this.createFormField(a,n),i=!0}else if(a.type==="set-form-values"){for(let c of a.values)this.setFieldValue(o,c.name,c.fieldType,c.value);i=!0}else if(a.type==="delete-form-field"){try{let c=o.getField(a.name);c&&o.removeField(c)}catch{}i=!0}else a.type==="flatten-form"&&(s=!0);if(i)try{o.updateFieldAppearances(n)}catch{}if(s)try{o.flatten()}catch{}}createFormField(e,n){var d,m;let r=this.pdfDoc.getForm(),o=this.pdfDoc.getPage(e.pageIndex),{x:i,y:s,width:a,height:c}=e.rect,l=e.fontSize&&e.fontSize>0?e.fontSize:void 0;switch(e.fieldType){case"text":case"signature":{let h=r.createTextField(e.name);if(e.value&&h.setText(e.value),l)try{h.setFontSize(l)}catch{}if(e.multiline)try{h.enableMultiline()}catch{}if(e.maxLength&&e.maxLength>0)try{h.setMaxLength(e.maxLength)}catch{}if(e.align)try{h.setAlignment(Uu[e.align])}catch{}h.addToPage(o,{x:i,y:s,width:a,height:c,font:n}),(e.fieldType==="signature"||e.readOnly)&&h.enableReadOnly(),e.required&&h.enableRequired();break}case"checkbox":{let h=r.createCheckBox(e.name);h.addToPage(o,{x:i,y:s,width:a,height:c}),e.value&&e.value!=="Off"?h.check():h.uncheck(),e.readOnly&&h.enableReadOnly(),e.required&&h.enableRequired();break}case"dropdown":{let h=r.createDropdown(e.name);if((d=e.options)!=null&&d.length&&h.addOptions(e.options),e.editable)try{h.enableEditing()}catch{}if(e.value)try{h.select(e.value)}catch{}if(l)try{h.setFontSize(l)}catch{}h.addToPage(o,{x:i,y:s,width:a,height:c,font:n}),e.readOnly&&h.enableReadOnly(),e.required&&h.enableRequired();break}case"radio":{let h=r.createRadioGroup(e.name);if(((m=e.options)!=null?m:[]).forEach((p,w)=>{var v,b;let y=(b=(v=e.optionRects)==null?void 0:v[w])!=null?b:{x:i,y:s-w*(c+4),width:a,height:c};h.addOptionToPage(p,o,{x:y.x,y:y.y,width:y.width,height:y.height})}),e.value)try{h.select(e.value)}catch{}e.readOnly&&h.enableReadOnly(),e.required&&h.enableRequired();break}}}setFieldValue(e,n,r,o){try{switch(r){case"text":case"signature":e.getTextField(n).setText(o!=null?o:"");break;case"checkbox":{let i=e.getCheckBox(n);o&&o!=="Off"&&o!=="false"?i.check():i.uncheck();break}case"dropdown":o?e.getDropdown(n).select(o):e.getDropdown(n).clear();break;case"radio":o&&o!=="Off"?e.getRadioGroup(n).select(o):e.getRadioGroup(n).clear();break}}catch{}}async toBlob(){let e=await this.pdfDoc.save({useObjectStreams:!1}),n=e instanceof Uint8Array?e:Uint8Array.from(e),r=n.slice().buffer;this.currentBytes=n,this.rewrittenPages.clear(),this.indexInvalidPages.clear();for(let o of this.pdfDoc.getPages()){let i=o;i.contentStream=void 0,i.contentStreamRef=void 0}return new Blob([r],{type:"application/pdf"})}async tryRemoveTextOperators(e,n){if(this.indexInvalidPages.has(e))return!1;try{let{streams:r,combined:o}=await Fa(this.currentBytes,e,n,this.rewrittenPages.get(e)),i=r.filter(l=>l.changed);if(i.length===0)return!1;let s=i.map(l=>Ri.of(l.objNum,l.genNum));for(let l of s)if(!this.pdfDoc.context.lookup(l))return!1;i.forEach((l,d)=>{this.pdfDoc.context.assign(s[d],this.pdfDoc.context.flateStream(l.bytes))});let a=this.pdfDoc.getPage(e),c=a.contentStreamRef;return c&&s.some(l=>l.tag===c.tag)&&(a.contentStream=void 0),this.rewrittenPages.set(e,o),!0}catch{return!1}}async tryNeutralizeSpans(e,n){if(!n.length||this.indexInvalidPages.has(e))return!1;try{let{streams:r,combined:o}=await Ra(this.currentBytes,e,n,this.rewrittenPages.get(e)),i=r.filter(l=>l.changed);if(i.length===0)return!1;let s=i.map(l=>Ri.of(l.objNum,l.genNum));for(let l of s)if(!this.pdfDoc.context.lookup(l))return!1;i.forEach((l,d)=>{this.pdfDoc.context.assign(s[d],this.pdfDoc.context.flateStream(l.bytes))});let a=this.pdfDoc.getPage(e),c=a.contentStreamRef;return c&&s.some(l=>l.tag===c.tag)&&(a.contentStream=void 0),this.rewrittenPages.set(e,o),!0}catch{return!1}}async tryWrapSpanWithTransform(e){if(this.indexInvalidPages.has(e.pageIndex))return!1;try{let n=Gn(e.baseCtm);if(!n)return!1;let r=Pe(Pe(n,e.matrix),e.baseCtm),{streams:o,combined:i}=await Ma(this.currentBytes,e.pageIndex,e.span,r,this.rewrittenPages.get(e.pageIndex)),s=o.filter(d=>d.changed);if(s.length===0)return!1;let a=s.map(d=>Ri.of(d.objNum,d.genNum));for(let d of a)if(!this.pdfDoc.context.lookup(d))return!1;s.forEach((d,m)=>{this.pdfDoc.context.assign(a[m],this.pdfDoc.context.flateStream(d.bytes))});let c=this.pdfDoc.getPage(e.pageIndex),l=c.contentStreamRef;return l&&a.some(d=>d.tag===l.tag)&&(c.contentStream=void 0),this.rewrittenPages.set(e.pageIndex,i),this.indexInvalidPages.add(e.pageIndex),!0}catch{return!1}}deletePage(e){if(this.pdfDoc.getPageCount()<=1)throw new Error("Cannot delete the last remaining page");this.pdfDoc.removePage(e)}getEmbeddedImage(e,n){let r=0;for(let a=0;a<e.length;a+=Math.max(1,e.length>>5))r=r*31+e[a]>>>0;let o=`${n}:${e.length}:${r}`,i=this.embeddedImageCache.get(o);if(i)return i;let s=n==="png"?this.pdfDoc.embedPng(e):this.pdfDoc.embedJpg(e);return this.embeddedImageCache.set(o,s),s}getStandardFont(e){let n=this.standardFontCache.get(e);if(n)return n;let r=this.pdfDoc.embedFont(e);return this.standardFontCache.set(e,r),r}async drawStyledSpans(e,n,r,o,i,s){var c,l;let a=r;for(let d of n){if(d.text.length===0)continue;let m=(c=d.style.sizePt)!=null?c:i,h=ka(s,{bold:d.style.bold,italic:d.style.italic}),f=await this.getRenderableFont(h,d.text),p=this.fitTextToFont(f,d.text);if(p.length===0)continue;let w=hr((l=d.style.color)!=null?l:{r:0,g:0,b:0}),y=ur(w.r,w.g,w.b),v=f.widthOfTextAtSize(p,m);if(e.drawText(p,{x:a,y:o,size:m,font:f,color:y}),d.style.underline||d.style.strikethrough){let b=Math.max(.5,m*.06);d.style.underline&&e.drawRectangle({x:a,y:o-m*.12,width:v,height:b,color:y}),d.style.strikethrough&&e.drawRectangle({x:a,y:o+m*.28,width:v,height:b,color:y})}a+=v}}async getRenderableFont(e,n){let r=oc(e),o=await this.getStandardFont(Xu(e));if(this.fontSupportsText(o,n))return o;let i=await this.getStandardFont(dt.Helvetica);if(this.fontSupportsText(i,n))return i;let s=await this.getEmbeddedFont(r);if(s&&this.fontSupportsText(s,n))return s;let a=s?[o,i,s]:[o,i],c=a[0],l=1/0;for(let d of a){let m=this.unsupportedCount(d,n);m<l&&(l=m,c=d)}return c}supportedCodePoints(e){try{return new Set(e.getCharacterSet())}catch{return new Set}}unsupportedCount(e,n){let r=this.supportedCodePoints(e);return io(n).filter(o=>{let i=String.fromCodePoint(o);return i!=="\r"&&i!==`
|
|
35
|
+
`&&i!==" "&&!r.has(o)}).length}fitTextToFont(e,n){if(this.fontSupportsText(e,n))return n;let r=this.supportedCodePoints(e),o=[],i="";for(let s of io(n)){let a=String.fromCodePoint(s);if(a==="\r"||a===`
|
|
36
|
+
`||a===" "||r.has(s)){i+=a;continue}let c=zu.get(a);if(c!==void 0&&io(c).every(d=>String.fromCodePoint(d)===`
|
|
37
|
+
`||r.has(d))){i+=c;continue}o.push(a)}o.length>0&&console.warn(`[PDFEditSession] Dropped ${o.length} character(s) the font cannot encode: ${[...new Set(o)].join(" ")}`);try{return e.encodeText(i),i}catch{return i.replace(/[^\x20-\x7E\r\n\t]/g,"")}}fontSupportsText(e,n){if(n.length===0)return!0;try{let r=new Set(e.getCharacterSet());return io(n).filter(i=>{let s=String.fromCodePoint(i);return s!=="\r"&&s!==`
|
|
38
|
+
`&&s!==" "}).some(i=>!r.has(i))?!1:(e.encodeText(n),!0)}catch{return!1}}async getEmbeddedFont(e){let n=this.embeddedFontCache.get(e);if(n)return n;let r=(async()=>{var s;await this.ensureFontkitRegistered();let o=this.getEmbeddedFontPrograms(),i=(s=o.find(a=>a.normalizedName===e))!=null?s:o.find(a=>a.normalizedName.includes(e)||e.includes(a.normalizedName));if(!i)return null;try{return await this.pdfDoc.embedFont(i.bytes,{subset:!0})}catch{return null}})();return this.embeddedFontCache.set(e,r),r}getEmbeddedFontPrograms(){return this.embeddedFonts||(this.embeddedFonts=Hu(this.pdfBytes)),this.embeddedFonts}async ensureFontkitRegistered(){if(this.fontkitRegistered)return;let e=(await import("./fontkit.es-6MF4HMXW.js")).default;this.pdfDoc.registerFontkit(e),this.fontkitRegistered=!0}};var ic=new WeakMap,ao=class{constructor(){this.name="pdf-editor-core";this.supportedTypes=["pdf"]}async process(e,n){var r,o;try{let i=(r=n.operations)!=null?r:[];if(i.length===0)return{success:!1,document:e,error:"No edit operations were provided."};let s=(o=ic.get(e.blob))!=null?o:await so.fromAvniDocument(e);await s.applyOperations(i);let a=await s.toBlob();ic.set(a,s);let c={taskId:crypto.randomUUID(),processorName:this.name,timestamp:Date.now(),params:n};return{success:!0,document:{...e,blob:a,size:a.size,history:[...e.history,c]},metrics:{duration:0,originalSize:e.size,newSize:a.size}}}catch(i){return{success:!1,document:e,error:i instanceof Error?i.message:"Unknown PDF edit failure"}}}};import{forwardRef as ah,useCallback as Ii,useEffect as fc,useImperativeHandle as ch,useLayoutEffect as lh,useRef as pr,useState as mc}from"react";var Gu=t=>t?`rgb(${Math.round(t.r*255)},${Math.round(t.g*255)},${Math.round(t.b*255)})`:"#000",Ku=(t,e,n,r)=>{var s,a;let o=((s=t.sizePt)!=null?s:n)*e,i=[t.underline?"underline":"",t.strikethrough?"line-through":""].filter(Boolean).join(" ");return[`font-weight:${t.bold?"700":"400"}`,`font-style:${t.italic?"italic":"normal"}`,`text-decoration:${i||"none"}`,`font-size:${o}px`,`color:${Gu((a=t.color)!=null?a:r)}`,"white-space:pre-wrap"].join(";")},Vu=(t,e,n,r)=>{let o=document.createElement("span"),{style:i}=t;return i.bold&&(o.dataset.b="1"),i.italic&&(o.dataset.i="1"),i.underline&&(o.dataset.u="1"),i.strikethrough&&(o.dataset.s="1"),i.sizePt!==void 0&&(o.dataset.size=String(i.sizePt)),i.color&&(o.dataset.color=`${i.color.r},${i.color.g},${i.color.b}`),o.setAttribute("style",Ku(i,e,n,r)),o.textContent=t.text,o},qu=(t,e)=>{let n={},r=t;for(;r;){let o=r.dataset;if(o.b==="1"&&(n.bold=!0),o.i==="1"&&(n.italic=!0),o.u==="1"&&(n.underline=!0),o.s==="1"&&(n.strikethrough=!0),o.size&&n.sizePt===void 0&&(n.sizePt=parseFloat(o.size)),o.color&&!n.color){let[i,s,a]=o.color.split(",").map(Number);[i,s,a].every(Number.isFinite)&&(n.color={r:i,g:s,b:a})}if(r===e)break;r=r.parentElement}return n},co=t=>{let e=[],n=r=>{var o;if(r.nodeType===Node.TEXT_NODE){let i=(o=r.textContent)!=null?o:"";if(i.length===0)return;e.push({text:i,style:qu(r.parentElement,t)})}else r.nodeName!=="BR"&&r.childNodes.forEach(n)};return t.childNodes.forEach(n),Cn(e)},Ei=(t,e,n,r,o)=>{t.textContent="";for(let i of e)i.text.length!==0&&t.appendChild(Vu(i,n,r,o))},Ju=t=>t.reduce((e,n)=>e+n.text.length,0),Ti=t=>{let e=window.getSelection();if(!e||e.rangeCount===0)return null;let n=e.getRangeAt(0);if(!t.contains(n.commonAncestorContainer))return null;let r=n.cloneRange();r.selectNodeContents(t),r.setEnd(n.startContainer,n.startOffset);let o=r.toString().length;return{start:o,end:o+n.toString().length}},sc=(t,e)=>{let n=e,r=null,o=i=>{var s,a;if(!r)if(i.nodeType===Node.TEXT_NODE){let c=(a=(s=i.textContent)==null?void 0:s.length)!=null?a:0;if(n<=c){r={node:i,offset:n};return}n-=c}else i.childNodes.forEach(o)};return t.childNodes.forEach(o),r!=null?r:{node:t,offset:t.childNodes.length}},lo=(t,e,n)=>{let r=sc(t,e),o=sc(t,n),i=document.createRange();i.setStart(r.node,r.offset),i.setEnd(o.node,o.offset);let s=window.getSelection();s&&(s.removeAllRanges(),s.addRange(i))},ac=t=>{let e=[];for(let n of t)for(let r of n.text.split(""))e.push({ch:r,style:{...n.style}});return e},cc=(t,e,n,r)=>{let o=e,i=n;o===i&&(o=0,i=Ju(t));let s=ac(t);for(let a=o;a<i&&a<s.length;a++)s[a].style={...s[a].style,...r};return Cn(s.map(a=>({text:a.ch,style:a.style})))},Oi=(t,e,n,r)=>{let o=ac(t);if(e===n){let m=o[Math.max(0,e-1)];return m?{...m.style}:{...r}}let i=o.slice(e,n);if(i.length===0)return{...r};let s=m=>i.every(h=>h.style[m]),a=i.every(m=>m.style.sizePt===i[0].style.sizePt)?i[0].style.sizePt:void 0,c=m=>m?`${m.r},${m.g},${m.b}`:"",l=i[0].style.color,d=i.every(m=>c(m.style.color)===c(l))?l:void 0;return{bold:s("bold"),italic:s("italic"),underline:s("underline"),strikethrough:s("strikethrough"),sizePt:a!=null?a:r.sizePt,color:d!=null?d:r.color}};import{Bold as th,Italic as nh,Underline as rh,Strikethrough as oh,Minus as dc,Plus as uc}from"lucide-react";import{jsx as un,jsxs as Kn}from"react/jsx-runtime";var hn=t=>{let e=n=>Math.round(Math.min(1,Math.max(0,n))*255).toString(16).padStart(2,"0");return`#${e(t.r)}${e(t.g)}${e(t.b)}`},Zu=t=>({r:parseInt(t.slice(1,3),16)/255,g:parseInt(t.slice(3,5),16)/255,b:parseInt(t.slice(5,7),16)/255}),Qu=(t,e)=>!!t&&Math.abs(t.r-e.r)<.02&&Math.abs(t.g-e.g)<.02&&Math.abs(t.b-e.b)<.02,eh=[{r:1,g:.85,b:0},{r:.18,g:.8,b:.44},{r:.2,g:.6,b:.95},{r:.91,g:.3,b:.4},{r:.96,g:.62,b:.04},{r:.55,g:.36,b:.96}],lc=({children:t})=>un("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:t});function Bt({color:t,onColor:e,opacity:n,onOpacity:r,presets:o=eh,shape:i="round",label:s="Color",allowNone:a=!1,isNone:c=!1,onNone:l,keepFocus:d=!1}){let m=d?f=>f.preventDefault():void 0,h=i==="round"?"rounded-full":"rounded-md";return Kn("div",{children:[un(lc,{children:s}),Kn("div",{className:"flex flex-wrap items-center gap-1.5",children:[a&&un("button",{type:"button",title:"No fill",onMouseDown:m,onClick:l,className:`relative h-7 w-7 overflow-hidden border bg-white ${h} ${c?"ring-2 ring-crimson-600 ring-offset-1 dark:ring-offset-zinc-900":"border-ink-line-strong dark:border-white/20"}`,children:un("span",{className:"absolute left-1/2 top-0 h-[140%] w-px -translate-x-1/2 rotate-45 bg-red-500"})}),o.map(f=>un("button",{type:"button",title:hn(f),onMouseDown:m,onClick:()=>e(f),style:{background:hn(f)},className:`h-7 w-7 border ${h} ${!c&&Qu(t,f)?"ring-2 ring-crimson-600 ring-offset-1 dark:ring-offset-zinc-900":"border-ink-line-strong dark:border-white/20"}`},hn(f))),Kn("label",{className:`flex h-7 w-7 cursor-pointer items-center justify-center border border-dashed border-ink-line-strong text-[11px] font-bold text-ink-muted dark:border-white/20 ${h}`,title:"Custom color",children:[un("input",{type:"color",value:hn(t),onMouseDown:f=>f.stopPropagation(),onChange:f=>e(Zu(f.target.value)),className:"h-0 w-0 opacity-0"}),"+"]})]}),r&&typeof n=="number"&&Kn("div",{className:"mt-3",children:[Kn("div",{className:"mb-1 flex items-center justify-between",children:[un(lc,{children:"Opacity"}),Kn("span",{className:"text-[10px] font-semibold tabular-nums text-ink-soft dark:text-zinc-400",children:[Math.round(n*100),"%"]})]}),un("input",{type:"range",min:10,max:100,value:Math.round(n*100),onMouseDown:m,onChange:f=>r(parseInt(f.target.value,10)/100),className:"h-1.5 w-full cursor-pointer appearance-none rounded-full bg-ink-line accent-crimson-600 dark:bg-white/15"})]})]})}import{jsx as Le,jsxs as fr}from"react/jsx-runtime";var ih=[{r:0,g:0,b:0},{r:.86,g:.15,b:.15},{r:.15,g:.39,b:.92},{r:.09,g:.64,b:.29},{r:.96,g:.62,b:.04},{r:1,g:1,b:1}],sh=(t,e)=>!!t&&Math.abs(t.r-e.r)<.02&&Math.abs(t.g-e.g)<.02&&Math.abs(t.b-e.b)<.02,hc=[{attr:"bold",icon:Le(th,{className:"h-3.5 w-3.5"}),title:"Bold (Ctrl+B)"},{attr:"italic",icon:Le(nh,{className:"h-3.5 w-3.5"}),title:"Italic (Ctrl+I)"},{attr:"underline",icon:Le(rh,{className:"h-3.5 w-3.5"}),title:"Underline (Ctrl+U)"},{attr:"strikethrough",icon:Le(oh,{className:"h-3.5 w-3.5"}),title:"Strikethrough"}];function mr({value:t,onToggle:e,onSize:n,onColor:r,variant:o="bar",fallbackSizePt:i}){var c,l;let s=Math.round((c=t.sizePt)!=null?c:i),a=d=>d.preventDefault();return o==="panel"?fr("div",{className:"flex flex-col gap-4 p-4",onMouseDown:a,children:[fr("div",{children:[Le("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:"Style"}),Le("div",{className:"flex gap-1",children:hc.map(({attr:d,icon:m,title:h})=>Le("button",{type:"button",title:h,onMouseDown:a,onClick:()=>e(d),className:`flex h-8 w-8 items-center justify-center rounded-lg border transition-colors ${t[d]?"border-crimson-600 bg-crimson-600 text-white":"border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800"}`,children:m},d))})]}),fr("div",{children:[Le("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:"Size"}),fr("div",{className:"flex items-center gap-1.5",children:[Le("button",{type:"button",onMouseDown:a,onClick:()=>n(Math.max(4,s-1)),className:"flex h-8 w-8 items-center justify-center rounded-lg border border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:Le(dc,{className:"h-3.5 w-3.5"})}),Le("input",{type:"number",value:s,min:4,max:96,onMouseDown:d=>d.stopPropagation(),onChange:d=>{let m=parseInt(d.target.value,10);Number.isFinite(m)&&n(Math.min(96,Math.max(4,m)))},className:"h-8 w-14 rounded-lg border border-ink-line-strong bg-paper-raised text-center text-sm text-ink dark:border-white/10 dark:bg-zinc-800 dark:text-white"}),Le("button",{type:"button",onMouseDown:a,onClick:()=>n(Math.min(96,s+1)),className:"flex h-8 w-8 items-center justify-center rounded-lg border border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:Le(uc,{className:"h-3.5 w-3.5"})})]})]}),Le(Bt,{color:(l=t.color)!=null?l:{r:0,g:0,b:0},onColor:r,shape:"square",keepFocus:!0})]}):fr("div",{onMouseDown:a,className:"flex items-center gap-0.5 rounded-lg bg-inverse-surface px-1 py-1 text-inverse-on-surface shadow-2xl",children:[hc.map(({attr:d,icon:m,title:h})=>Le("button",{type:"button",title:h,onMouseDown:a,onClick:()=>e(d),className:`flex h-7 w-7 items-center justify-center rounded-md transition-colors ${t[d]?"bg-primary text-white":"hover:bg-white/15"}`,children:m},d)),Le("span",{className:"mx-0.5 h-4 w-px bg-white/20"}),Le("button",{type:"button",title:"Smaller",onMouseDown:a,onClick:()=>n(Math.max(4,s-1)),className:"flex h-7 w-6 items-center justify-center rounded-md hover:bg-white/15",children:Le(dc,{className:"h-3 w-3"})}),Le("span",{className:"w-6 text-center text-xs font-semibold tabular-nums",children:s}),Le("button",{type:"button",title:"Larger",onMouseDown:a,onClick:()=>n(Math.min(96,s+1)),className:"flex h-7 w-6 items-center justify-center rounded-md hover:bg-white/15",children:Le(uc,{className:"h-3 w-3"})}),Le("span",{className:"mx-0.5 h-4 w-px bg-white/20"}),ih.slice(0,5).map(d=>Le("button",{type:"button",title:hn(d),onMouseDown:a,onClick:()=>r(d),style:{background:hn(d)},className:`h-4 w-4 rounded ${sh(t.color,d)?"ring-2 ring-white":"ring-1 ring-white/30"}`},hn(d)))]})}import{jsx as gr,jsxs as uh}from"react/jsx-runtime";var dh=ah(function(e,n){let{containerX:r,containerY:o,screenWidth:i,screenHeight:s,scale:a,fontSizePt:c,fontFamily:l,baselineOffsetPx:d,maxWidth:m,initialSpans:h,baseColor:f,maskRect:p,bgColor:w,ocr:y,placeholder:v,onCommit:b,onCancel:C,onActiveStyleChange:S}=e,F=pr(null),T=pr(null),N=pr({sizePt:c,color:f}),O=pr(!0),A=pr(""),[H,ne]=mc(N.current),[ie,I]=mc(0);fc(()=>()=>{O.current=!1},[]);let ce=Ii(()=>{var Xe;let _=T.current;if(!_)return;let K=(Xe=Ti(_))!=null?Xe:{start:0,end:0},G=co(_),ae=Oi(G,K.start,K.end,N.current),me=ln(ae);me!==A.current&&(A.current=me,ne(ae),S==null||S(ae))},[S]);lh(()=>{let _=T.current;if(!_)return;Ei(_,h,a,c,f),_.focus();let K=Jr(h).length;if(lo(_,K,K),ce(),d!=null){let G=document.createElement("span");G.style.cssText="display:inline-block;width:0;height:0;overflow:hidden;vertical-align:baseline",G.setAttribute("aria-hidden","true"),_.insertBefore(G,_.firstChild);let ae=G.getBoundingClientRect().top-_.getBoundingClientRect().top;_.removeChild(G),Number.isFinite(ae)&&I(d-ae)}},[]),fc(()=>{let _=()=>{let K=T.current;K&&document.activeElement===K&&ce()};return document.addEventListener("selectionchange",_),()=>document.removeEventListener("selectionchange",_)},[ce]);let le=Ii((_,K)=>{var lt;let G=T.current;if(!G)return;G.focus();let ae=(lt=Ti(G))!=null?lt:{start:0,end:0},me=co(G),Xe=_;if(K){let rt=Oi(me,ae.start,ae.end,N.current);Xe={[K]:!rt[K]}}let Te=cc(me,ae.start,ae.end,Xe);Ei(G,Te,a,c,f);let Me=Jr(Te).length;ae.start===ae.end?lo(G,0,Me):lo(G,Math.min(ae.start,Me),Math.min(ae.end,Me)),ce()},[a,c,f,ce]),pe=Ii(()=>{let _=T.current;if(!_){C();return}let K=co(_);b(K,Jr(K))},[b,C]);ch(n,()=>({toggle:_=>le({},_),setSize:_=>le({sizePt:_}),setColor:_=>le({color:_}),commit:pe,focus:()=>{var _;return(_=T.current)==null?void 0:_.focus()}}),[le,pe]);let De=Math.max(s,Math.ceil(c*a*1.2));return uh("div",{ref:F,style:{position:"absolute",left:`${r}px`,top:`${o}px`,zIndex:50,pointerEvents:"none"},children:[p&&gr("div",{style:{position:"absolute",left:`${p.x}px`,top:`${p.y}px`,width:`${p.w}px`,height:`${p.h}px`,background:w?`rgb(${Math.round(w.r*255)},${Math.round(w.g*255)},${Math.round(w.b*255)})`:"#fff",pointerEvents:"none"}}),gr("div",{style:{position:"absolute",left:0,top:-40,pointerEvents:"auto"},onMouseDown:_=>_.stopPropagation(),onClick:_=>_.stopPropagation(),children:gr(mr,{value:H,onToggle:_=>le({},_),onSize:_=>le({sizePt:_}),onColor:_=>le({color:_}),variant:"bar",fallbackSizePt:c})}),gr("div",{ref:T,contentEditable:!0,suppressContentEditableWarning:!0,"data-placeholder":v,onMouseDown:_=>_.stopPropagation(),onClick:_=>_.stopPropagation(),onKeyUp:ce,onMouseUp:ce,onBlur:()=>{setTimeout(()=>{var K;if(!O.current)return;let _=document.activeElement;(K=F.current)!=null&&K.contains(_)||pe()},150)},onKeyDown:_=>{if((_.ctrlKey||_.metaKey)&&!_.shiftKey){let K=_.key.toLowerCase();if(K==="b"){_.preventDefault(),le({},"bold");return}if(K==="i"){_.preventDefault(),le({},"italic");return}if(K==="u"){_.preventDefault(),le({},"underline");return}}_.key==="Enter"&&(_.preventDefault(),pe()),_.key==="Escape"&&(_.preventDefault(),C())},style:{position:"relative",display:"inline-block",transform:`translateY(${ie}px)`,minWidth:`${Math.max(40,i)}px`,width:"auto",maxWidth:m?`${m}px`:void 0,minHeight:`${De}px`,height:"auto",padding:0,margin:0,border:"none",outline:"none",background:w?`rgb(${Math.round(w.r*255)},${Math.round(w.g*255)},${Math.round(w.b*255)})`:p?"#fff":"transparent",fontSize:`${c*a}px`,lineHeight:`${De}px`,fontFamily:l!=null?l:"inherit",color:f?`rgb(${Math.round(f.r*255)},${Math.round(f.g*255)},${Math.round(f.b*255)})`:"#000",caretColor:"rgba(59, 130, 246, 0.9)",pointerEvents:"auto",whiteSpace:"pre-wrap",overflowWrap:"break-word",overflow:"visible"}}),y&&gr("div",{style:{position:"absolute",left:-1,top:s+6,whiteSpace:"nowrap",pointerEvents:"none",background:"rgba(180, 83, 9, 0.95)",color:"#fff",fontSize:10,lineHeight:1.4,padding:"2px 6px",borderRadius:4},children:"Recognized from image, font may change to closest match"})]})}),pc=dh;import{MousePointer as gh,Type as $i,MessageSquareText as xh,Eraser as bh,Highlighter as yc,PenLine as wc,StickyNote as yh,PenTool as vc,FileText as wh,Trash2 as vh,Eye as kh,Underline as Ph,Strikethrough as Sh,Minus as Dh,ArrowUpRight as Ch,Square as Fh,Circle as Mh,Hexagon as Rh,CheckSquare as Ah,Circle as Nh,ChevronDownSquare as Eh,Layers as Th}from"lucide-react";import{Plus as hh,Trash2 as fh,X as mh}from"lucide-react";import{jsx as Se,jsxs as Dt}from"react/jsx-runtime";var ph=({children:t})=>Se("p",{className:"mb-1 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:t}),Jt="w-full rounded-lg border border-ink-line-strong bg-paper px-2.5 py-1.5 text-sm text-ink outline-none focus:border-crimson-600 dark:border-white/10 dark:bg-zinc-800/60 dark:text-white",fn=({label:t,children:e})=>Dt("div",{children:[Se(ph,{children:t}),e]}),xr=({label:t,checked:e,onChange:n})=>Dt("label",{className:"flex cursor-pointer items-center justify-between gap-2 text-sm text-ink-soft dark:text-zinc-300",children:[Se("span",{children:t}),Se("input",{type:"checkbox",checked:e,onChange:r=>n(r.target.checked),className:"h-4 w-4 accent-crimson-600"})]});function ji({field:t,onChange:e,onDelete:n}){var h,f,p,w;let{type:r,rect:o}=t,i=r==="text"||r==="signature",s=r==="dropdown"||r==="radio",a=(h=t.options)!=null?h:[],c=y=>e({rect:{...o,...y}}),l=(y,v)=>{let b=a.slice();b[y]=v,e({options:b})},d=()=>e({options:[...a,`Option ${a.length+1}`]}),m=y=>e({options:a.filter((v,b)=>b!==y)});return Dt("div",{className:"flex flex-col gap-3 border-t border-ink-line pt-3 dark:border-white/10",children:[Dt("p",{className:"text-[10px] font-bold uppercase tracking-widest text-crimson-600",children:[r," field"]}),Se(fn,{label:"Field name",children:Se("input",{className:Jt,value:t.name,onChange:y=>e({name:y.target.value})})}),Se(fn,{label:"Default value",children:r==="checkbox"?Se(xr,{label:"Checked by default",checked:!!t.value&&t.value!=="Off",onChange:y=>{var v;return e({value:y?(v=t.onState)!=null?v:"Yes":"Off"})}}):s?Dt("select",{className:Jt,value:(f=t.value)!=null?f:"",onChange:y=>e({value:y.target.value}),children:[Se("option",{value:"",children:"- none -"}),a.map(y=>Se("option",{value:y,children:y},y))]}):Se("input",{className:Jt,value:(p=t.value)!=null?p:"",onChange:y=>e({value:y.target.value})})}),Dt("div",{className:"grid grid-cols-2 gap-2",children:[Se(fn,{label:"Width (pt)",children:Se("input",{type:"number",min:1,className:Jt,value:Math.round(o.width),onChange:y=>c({width:Math.max(1,Number(y.target.value)||0)})})}),Se(fn,{label:"Height (pt)",children:Se("input",{type:"number",min:1,className:Jt,value:Math.round(o.height),onChange:y=>c({height:Math.max(1,Number(y.target.value)||0)})})}),Se(fn,{label:"X (pt)",children:Se("input",{type:"number",className:Jt,value:Math.round(o.x),onChange:y=>c({x:Number(y.target.value)||0})})}),Se(fn,{label:"Y (pt)",children:Se("input",{type:"number",className:Jt,value:Math.round(o.y),onChange:y=>c({y:Number(y.target.value)||0})})})]}),(i||r==="dropdown")&&Se(fn,{label:"Font size (0 = auto)",children:Se("input",{type:"number",min:0,className:Jt,value:(w=t.fontSize)!=null?w:0,onChange:y=>e({fontSize:Math.max(0,Number(y.target.value)||0)})})}),s&&Se(fn,{label:"Options",children:Dt("div",{className:"flex flex-col gap-1.5",children:[a.map((y,v)=>Dt("div",{className:"flex items-center gap-1.5",children:[Se("input",{className:Jt,value:y,onChange:b=>l(v,b.target.value)}),Se("button",{type:"button",onClick:()=>m(v),className:"shrink-0 rounded-md p-1.5 text-ink-muted hover:bg-paper hover:text-red-500 dark:hover:bg-zinc-800",title:"Remove option",children:Se(mh,{className:"h-3.5 w-3.5"})})]},v)),Dt("button",{type:"button",onClick:d,className:"flex items-center justify-center gap-1.5 rounded-lg border border-dashed border-ink-line-strong px-2 py-1.5 text-xs font-semibold text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:[Se(hh,{className:"h-3.5 w-3.5"})," Add option"]})]})}),Dt("div",{className:"flex flex-col gap-2 rounded-lg bg-paper px-3 py-2 dark:bg-zinc-800/40",children:[Se(xr,{label:"Required",checked:!!t.required,onChange:y=>e({required:y})}),r!=="signature"&&Se(xr,{label:"Read-only",checked:!!t.readOnly,onChange:y=>e({readOnly:y})}),i&&Se(xr,{label:"Multi-line",checked:!!t.multiline,onChange:y=>e({multiline:y})}),r==="dropdown"&&Se(xr,{label:"Allow custom text",checked:!!t.editable,onChange:y=>e({editable:y})})]}),Dt("button",{type:"button",onClick:n,className:"flex items-center justify-center gap-1.5 rounded-lg border border-red-200 px-3 py-2 text-xs font-semibold text-red-500 transition-colors hover:bg-red-50 dark:border-red-500/30 dark:hover:bg-red-500/10",children:[Se(fh,{className:"h-3.5 w-3.5"})," Delete field"]})]})}import{Fragment as uo,jsx as de,jsxs as _e}from"react/jsx-runtime";var Oh=[1,2,4,8],gc={view:{icon:de(kh,{className:"h-4 w-4"}),title:"View",help:"Read the document like a normal PDF. Drag to select text and press Ctrl/Cmd+C to copy. Use the toolbar to zoom, jump between pages and search. Form fields stay fillable and links are clickable."},select:{icon:de(gh,{className:"h-4 w-4"}),title:"Select",help:"Click any text, image, shape or annotation to select it. Drag to move, drag a corner handle to resize, recolor it in the popover, and press Delete to remove. Click empty space to deselect."},"edit-text":{icon:de($i,{className:"h-4 w-4"}),title:"Edit Text",help:"Click any text to edit it inline. Select a word or phrase, then use B / I / U / S, size or color to format just that selection. Press Enter to save, Esc to cancel."},"add-text":{icon:de($i,{className:"h-4 w-4"}),title:"Add Text",help:"Click anywhere on the page to drop a new text box, then start typing. Select text to make it bold, italic, underlined, a different size or color."},annotate:{icon:de(yc,{className:"h-4 w-4"}),title:"Annotate",help:"Pick a markup tool, choose a color and opacity, then mark up the page. Highlight, underline and strikethrough follow the text you select; brush draws freehand."},draw:{icon:de(wc,{className:"h-4 w-4"}),title:"Draw Shapes",help:"Pick a shape, set stroke color/width (and fill for closed shapes), then drag on the page. For polygons, click each point and double-click to finish."},stamp:{icon:de(xh,{className:"h-4 w-4"}),title:"Stamp",help:"Type or pick a preset stamp, choose a size and color on the toolbar, then click the page to place it."},redact:{icon:de(bh,{className:"h-4 w-4"}),title:"Redact",help:"Drag a box over anything you want to permanently remove, then press Apply. Redacted text is stripped from the file and cannot be recovered."},comment:{icon:de(yh,{className:"h-4 w-4"}),title:"Comment",help:"Click anywhere to drop a sticky-note pin. Click an existing pin to edit or delete its note. Notes export as real PDF text annotations."},sign:{icon:de(vc,{className:"h-4 w-4"}),title:"Sign",help:"Choose or draw your signature, then click the page where it should go."},form:{icon:de(wh,{className:"h-4 w-4"}),title:"Form Fields",help:"Pick a field type, then drag on the page to place a fillable field. Click any field to edit its name, default value, size, options and flags below. Use Flatten to bake the values permanently into the page."}},Ih=[{key:"text",icon:de($i,{className:"h-4 w-4"}),label:"Text"},{key:"checkbox",icon:de(Ah,{className:"h-4 w-4"}),label:"Checkbox"},{key:"radio",icon:de(Nh,{className:"h-4 w-4"}),label:"Radio"},{key:"dropdown",icon:de(Eh,{className:"h-4 w-4"}),label:"Dropdown"},{key:"signature",icon:de(vc,{className:"h-4 w-4"}),label:"Signature"}],jh=[{key:"highlight",icon:de(yc,{className:"h-4 w-4"}),label:"Highlight"},{key:"underline",icon:de(Ph,{className:"h-4 w-4"}),label:"Underline"},{key:"strikeout",icon:de(Sh,{className:"h-4 w-4"}),label:"Strike"},{key:"brush",icon:de(wc,{className:"h-4 w-4"}),label:"Brush"}],$h=[{key:"line",icon:de(Dh,{className:"h-4 w-4"}),label:"Line"},{key:"arrow",icon:de(Ch,{className:"h-4 w-4"}),label:"Arrow"},{key:"rect",icon:de(Fh,{className:"h-4 w-4"}),label:"Rectangle"},{key:"ellipse",icon:de(Mh,{className:"h-4 w-4"}),label:"Ellipse"},{key:"polygon",icon:de(Rh,{className:"h-4 w-4"}),label:"Polygon"}],Vn=({children:t})=>de("p",{className:"mb-1.5 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:t}),xc=({value:t,options:e,onChange:n})=>de("div",{className:"grid grid-cols-2 gap-1.5",children:e.map(r=>_e("button",{type:"button",onClick:()=>n(r.key),className:`flex items-center justify-center gap-1.5 rounded-lg border px-2 py-2 text-xs font-semibold transition-colors ${t===r.key?"border-crimson-600 bg-crimson-600 text-white":"border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800"}`,children:[r.icon,r.label]},r.key))}),bc=({value:t,onChange:e})=>_e("div",{children:[de(Vn,{children:"Thickness"}),de("div",{className:"flex gap-1.5",children:Oh.map(n=>_e("button",{type:"button",onClick:()=>e(n),className:`flex h-8 flex-1 items-center justify-center rounded-lg border text-xs font-bold transition-colors ${t===n?"border-crimson-600 bg-crimson-600 text-white":"border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800"}`,children:[n,"px"]},n))})]});function Bi(t){var a,c,l;let{tool:e,annotStyle:n,setAnnotStyle:r}=t,o=(a=gc[e])!=null?a:gc.select,i=e==="edit-text"||e==="add-text",s=t.drawShape==="rect"||t.drawShape==="ellipse"||t.drawShape==="polygon";return _e("aside",{className:"flex w-64 shrink-0 flex-col border-l border-ink-line bg-paper-card dark:border-white/10 dark:bg-[#1a1712]",children:[_e("div",{className:"flex items-center gap-2 border-b border-ink-line px-4 py-3 text-crimson-600 dark:border-white/10",children:[o.icon,de("span",{className:"font-display text-sm font-bold text-ink dark:text-white",children:o.title})]}),_e("div",{className:"flex-1 overflow-y-auto",children:[_e("div",{className:"flex flex-col gap-4 p-4",children:[i&&_e(uo,{children:[!t.textActive&&de("p",{className:"rounded-lg bg-paper px-3 py-2 text-xs text-ink-soft dark:bg-zinc-800/60 dark:text-zinc-400",children:e==="add-text"?"Click the page to add a text box.":"Click any text on the page to start editing."}),_e("div",{children:[de(Vn,{children:"Font"}),_e("div",{className:"flex items-center justify-between rounded-lg border border-ink-line-strong bg-paper px-3 py-2 text-sm text-ink-soft dark:border-white/10 dark:bg-zinc-800/60 dark:text-zinc-400",title:"Changing the font family is coming soon",children:[de("span",{className:"truncate",children:((c=t.fontName)!=null?c:"Helvetica").replace(/^[A-Z]{6}\+/,"")}),de("span",{className:"ml-2 shrink-0 text-[9px] font-semibold uppercase tracking-wide text-ink-muted dark:text-zinc-500",children:"soon"})]})]})]}),e==="annotate"&&_e(uo,{children:[_e("div",{children:[de(Vn,{children:"Tool"}),de(xc,{value:t.annotSubtool,options:jh,onChange:t.setAnnotSubtool})]}),t.annotSubtool==="highlight"&&_e("div",{children:[de(Vn,{children:"Mode"}),de(xc,{value:t.highlightMode,options:[{key:"select",label:"Select text"},{key:"box",label:"Box / region"}],onChange:t.setHighlightMode})]}),de(Bt,{color:n.color,onColor:d=>r({color:d}),opacity:n.opacity,onOpacity:d=>r({opacity:d})}),t.annotSubtool==="brush"&&de(bc,{value:n.strokeWidth,onChange:d=>r({strokeWidth:d})})]}),e==="draw"&&_e(uo,{children:[_e("div",{children:[de(Vn,{children:"Shape"}),de("div",{className:"grid grid-cols-3 gap-1.5",children:$h.map(d=>de("button",{type:"button",title:d.label,onClick:()=>t.setDrawShape(d.key),className:`flex h-10 items-center justify-center rounded-lg border transition-colors ${t.drawShape===d.key?"border-crimson-600 bg-crimson-600 text-white":"border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800"}`,children:d.icon},d.key))})]}),de(Bt,{label:"Stroke",color:n.color,onColor:d=>r({color:d}),opacity:n.opacity,onOpacity:d=>r({opacity:d})}),de(bc,{value:n.strokeWidth,onChange:d=>r({strokeWidth:d})}),s&&de(Bt,{label:"Fill",color:(l=n.fill)!=null?l:{r:1,g:1,b:1},onColor:d=>r({fill:d}),allowNone:!0,isNone:n.fill===null,onNone:()=>r({fill:null})})]}),e==="form"&&_e(uo,{children:[_e("div",{children:[de(Vn,{children:"Add field"}),de("div",{className:"grid grid-cols-2 gap-1.5",children:Ih.map(d=>_e("button",{type:"button",onClick:()=>t.setAddFieldType(t.addFieldType===d.key?null:d.key),className:`flex items-center justify-center gap-1.5 rounded-lg border px-2 py-2 text-xs font-semibold transition-colors ${t.addFieldType===d.key?"border-crimson-600 bg-crimson-600 text-white":"border-ink-line-strong text-ink-soft hover:bg-paper dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800"}`,children:[d.icon,d.label]},d.key))}),t.addFieldType&&_e("p",{className:"mt-1.5 text-xs font-semibold text-crimson-600",children:["Drag on the page to place the ",t.addFieldType," field."]})]}),t.selectedField?de(ji,{field:t.selectedField,onChange:t.onUpdateField,onDelete:t.onDeleteField}):de("p",{className:"rounded-lg bg-paper px-3 py-2 text-xs text-ink-soft dark:bg-zinc-800/60 dark:text-zinc-400",children:t.hasFormFields?"Click a field on the page to edit its properties.":"No fields yet, add one above."}),_e("button",{type:"button",onClick:t.onFlattenForm,disabled:!t.hasFormFields,title:"Bake all field values into the page (no longer editable)",className:"flex items-center justify-center gap-1.5 rounded-lg border border-ink-line-strong px-3 py-2 text-xs font-semibold text-ink-soft transition-colors hover:bg-paper disabled:opacity-40 dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:[de(Th,{className:"h-3.5 w-3.5"})," Flatten form"]})]}),(e==="annotate"||e==="draw")&&t.annotationCount>0&&_e("button",{type:"button",onClick:t.onClearAnnotations,className:"flex items-center justify-center gap-1.5 rounded-lg border border-red-200 px-3 py-2 text-xs font-semibold text-red-500 transition-colors hover:bg-red-50 dark:border-red-500/30 dark:hover:bg-red-500/10",children:[de(vh,{className:"h-3.5 w-3.5"})," Clear all annotations"]})]}),i&&de(mr,{value:t.textStyle,onToggle:t.onToggle,onSize:t.onSize,onColor:t.onColor,variant:"panel",fallbackSizePt:t.fallbackSizePt})]}),_e("div",{className:"border-t border-ink-line bg-[#F3ECDD] px-4 py-3 dark:border-white/10 dark:bg-zinc-800/30",children:[de("p",{className:"mb-1 text-[10px] font-bold uppercase tracking-widest text-ink-muted dark:text-zinc-500",children:"How to use"}),de("p",{className:"text-xs leading-relaxed text-ink-soft dark:text-zinc-400",children:o.help})]})]})}var ut=(t,e,n,r,o)=>{let i=t-n.left,s=e-n.top;return{x:i/r,y:o-s/r}},Ge=(t,e,n,r)=>({x:t*n,y:(r-e)*n});import{Fragment as Xh,jsx as We,jsxs as br}from"react/jsx-runtime";var ho=t=>`rgb(${Math.round(t.r*255)},${Math.round(t.g*255)},${Math.round(t.b*255)})`,kc=(t,e,n)=>{let r=Math.atan2(e.y-t.y,e.x-t.x),o=Math.PI/7,i={x:e.x-n*Math.cos(r-o),y:e.y-n*Math.sin(r-o)},s={x:e.x-n*Math.cos(r+o),y:e.y-n*Math.sin(r+o)};return`${i.x},${i.y} ${e.x},${e.y} ${s.x},${s.y}`},Bh=(t,e,n)=>{let r=1.5*n,o=4*n,i=t(e.x,e.y+1),s=[`M ${i.x} ${i.y}`],a=t(e.x+e.width,e.y).x,c=!0;for(let l=i.x+o;l<=a;l+=o)s.push(`L ${l} ${i.y+(c?-r:r)}`),c=!c;return s.join(" ")},Pc=(t,e,n,r,o,i)=>e.map((s,a)=>{if(t==="highlight"){let m=n(s.x,s.y+s.height);return We("rect",{x:m.x,y:m.y,width:s.width*r,height:s.height*r,fill:o,opacity:Math.min(.4,i),style:{mixBlendMode:"multiply"}},a)}if(t==="squiggly")return We("path",{d:Bh(n,s,r),stroke:o,strokeWidth:Math.max(.75,r),fill:"none",opacity:i},a);let c=t==="strikeout"?s.y+s.height*.5:s.baselineY-Math.max(1,s.height*.12),l=n(s.x,c),d=n(s.x+s.width,c);return We("line",{x1:l.x,y1:l.y,x2:d.x,y2:d.y,stroke:o,strokeWidth:Math.max(1.5,r),opacity:i},a)}),Lh=(t,e,n)=>{var l;let r=ho(t.style.color),o=Math.max(.5,((l=t.style.strokeWidth)!=null?l:1.5)*n),i=t.style.fill?ho(t.style.fill):"none";if(t.kind==="highlight"||t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly")return Pc(t.kind,t.quads,e,n,r,t.style.opacity);if(t.kind==="ink")return t.strokes.map((d,m)=>{let h=d.map((f,p)=>{let w=e(f.x,f.y);return`${p===0?"M":"L"} ${w.x} ${w.y}`}).join(" ");return We("path",{d:h,stroke:r,strokeWidth:o,fill:"none",strokeLinecap:"round",strokeLinejoin:"round",opacity:t.style.opacity},m)});if(t.kind==="rect"){let d=ct(t),m=e(d.x,d.y+d.height);return We("rect",{x:m.x,y:m.y,width:d.width*n,height:d.height*n,stroke:r,strokeWidth:o,fill:i,opacity:t.style.opacity})}if(t.kind==="ellipse"){let d=ct(t),m=e(d.x+d.width/2,d.y+d.height/2);return We("ellipse",{cx:m.x,cy:m.y,rx:d.width/2*n,ry:d.height/2*n,stroke:r,strokeWidth:o,fill:i,opacity:t.style.opacity})}if(t.kind==="polygon"||t.kind==="polyline"){let d=t.points.map(m=>{let h=e(m.x,m.y);return`${h.x},${h.y}`}).join(" ");return t.kind==="polygon"?We("polygon",{points:d,stroke:r,strokeWidth:o,fill:i,opacity:t.style.opacity}):We("polyline",{points:d,stroke:r,strokeWidth:o,fill:"none",opacity:t.style.opacity})}let s=t,a=e(s.points[0].x,s.points[0].y),c=e(s.points[1].x,s.points[1].y);return br("g",{opacity:t.style.opacity,children:[We("line",{x1:a.x,y1:a.y,x2:c.x,y2:c.y,stroke:r,strokeWidth:o,strokeLinecap:"round"}),t.kind==="arrow"&&We("polyline",{points:kc(a,c,Math.max(8,o*3)),stroke:r,strokeWidth:o,fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})]})},Uh=(t,e,n,r,o)=>{let i=ho(r.color),s=Math.max(.5,r.strokeWidth*n),a=r.fill?ho(r.fill):"none";if(t.kind==="quads")return Pc(o,t.quads,e,n,i,r.opacity);if(t.kind==="box"){let d=e(t.rect.x,t.rect.y+t.rect.height);return We("rect",{x:d.x,y:d.y,width:t.rect.width*n,height:t.rect.height*n,stroke:i,strokeWidth:s,fill:a,opacity:r.opacity,strokeDasharray:"4 3"})}if(t.kind==="line"){let d=e(t.a.x,t.a.y),m=e(t.b.x,t.b.y);return br("g",{opacity:r.opacity,children:[We("line",{x1:d.x,y1:d.y,x2:m.x,y2:m.y,stroke:i,strokeWidth:s,strokeLinecap:"round"}),t.arrow&&We("polyline",{points:kc(d,m,Math.max(8,s*3)),stroke:i,strokeWidth:s,fill:"none"})]})}if(t.kind==="ink"){let d=t.points.map((m,h)=>{let f=e(m.x,m.y);return`${h===0?"M":"L"} ${f.x} ${f.y}`}).join(" ");return We("path",{d,stroke:i,strokeWidth:s,fill:"none",strokeLinecap:"round",strokeLinejoin:"round",opacity:r.opacity})}let c=t.points.map(d=>{let m=e(d.x,d.y);return`${m.x},${m.y}`}).join(" "),l=t.cursor?e(t.cursor.x,t.cursor.y):null;return br("g",{opacity:r.opacity,children:[We("polyline",{points:c,stroke:i,strokeWidth:s,fill:"none"}),l&&t.points.length>0&&(()=>{let d=e(t.points[t.points.length-1].x,t.points[t.points.length-1].y);return We("line",{x1:d.x,y1:d.y,x2:l.x,y2:l.y,stroke:i,strokeWidth:s,strokeDasharray:"4 3"})})(),t.points.map((d,m)=>{let h=e(d.x,d.y);return We("circle",{cx:h.x,cy:h.y,r:3,fill:i},m)})]})},_h=[{key:"nw",cursor:"nwse-resize"},{key:"ne",cursor:"nesw-resize"},{key:"sw",cursor:"nesw-resize"},{key:"se",cursor:"nwse-resize"}];function Li({pageIndex:t,pageHeight:e,scale:n,annots:r,live:o,liveStyle:i,selectedId:s,interactive:a,liveMarkupKind:c,onBeginResize:l}){var f;let d=(p,w)=>Ge(p,w,n,e),m=r.filter(p=>p.pageIndex===t),h=(f=m.find(p=>p.id===s))!=null?f:null;return br(Xh,{children:[br("svg",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"visible",zIndex:11,pointerEvents:"none"},xmlns:"http://www.w3.org/2000/svg",children:[m.map(p=>We("g",{children:Lh(p,d,n)},p.id)),(o==null?void 0:o.pageIndex)===t&&Uh(o,d,n,i,c),h&&(()=>{let p=ct(h),w=d(p.x,p.y+p.height);return We("rect",{x:w.x-3,y:w.y-3,width:p.width*n+6,height:p.height*n+6,fill:"none",stroke:"#D6002F",strokeWidth:1,strokeDasharray:"4 3"})})()]}),a&&h&&(()=>{let p=ct(h),w={nw:d(p.x,p.y+p.height),ne:d(p.x+p.width,p.y+p.height),sw:d(p.x,p.y),se:d(p.x+p.width,p.y)};return We("div",{style:{position:"absolute",inset:0,zIndex:12,pointerEvents:"none"},children:_h.map(({key:y,cursor:v})=>We("div",{onMouseDown:b=>{b.stopPropagation(),b.preventDefault(),l(h.id,y,b)},style:{position:"absolute",left:w[y].x-5,top:w[y].y-5,width:10,height:10,background:"#fff",border:"1.5px solid #D6002F",borderRadius:2,cursor:v,pointerEvents:"auto"}},y))})})()]})}var zh=t=>{var r;let e=Array.from(t.text);if((r=t.glyphs)!=null&&r.length){let o=[];for(let i of t.glyphs){let s=Math.max(1,Array.from(i.char).length);for(let a=0;a<s;a++)o.push({x:i.pdfX,y:i.pdfY,width:i.width,height:i.height,baselineY:i.pdfBaselineY})}if(o.length===e.length)return e.map((i,s)=>({char:i,...o[s]}))}let n=t.width/Math.max(1,e.length);return e.map((o,i)=>({char:o,x:t.pdfX+i*n,y:t.pdfY,width:n,height:t.height,baselineY:t.pdfBaselineY}))},Yh=t=>{let e=[],n=0;for(let r of t)for(let o of zh(r))e.push({...o,order:n++});return e},Sc=(t,e)=>{if(!t.length)return-1;let n=t.filter(s=>e.y>=s.y-2&&e.y<=s.y+s.height+2),r=n.length?n:t,o=-1,i=Number.POSITIVE_INFINITY;for(let s of r){let a=e.x<s.x?s.x:e.x>s.x+s.width?s.x+s.width:e.x,c=e.y<s.y?s.y:e.y>s.y+s.height?s.y+s.height:e.y,l=Math.hypot(e.x-a,e.y-c);l<i&&(i=l,o=s.order)}return o},Wh=t=>{if(!t.length)return[];let e=[],n=[];for(let r of t){if(n.length){let o=Math.max(2,r.height*.5);Math.abs(r.baselineY-n[0].baselineY)>o&&(e.push(n),n=[])}n.push(r)}return n.length&&e.push(n),e.map(r=>{let o=Math.min(...r.map(d=>d.x)),i=Math.min(...r.map(d=>d.y)),s=Math.max(...r.map(d=>d.x+d.width)),a=Math.max(...r.map(d=>d.y+d.height)),c=r.map(d=>d.baselineY).sort((d,m)=>d-m),l=c[Math.floor(c.length/2)];return{x:o,y:i,width:s-o,height:a-i,baselineY:l}})},Dc=(t,e,n)=>{let r=Yh(t);if(!r.length)return{quads:[],text:""};let o=Sc(r,e),i=Sc(r,n);if(o<0||i<0)return{quads:[],text:""};let s=Math.min(o,i),a=Math.max(o,i),c=r.slice(s,a+1);return{quads:Wh(c),text:c.map(l=>l.char).join("")}};function Ve(t,e){if(t){if(!Be(t))return t;try{return e(t)}catch{return}}}function Hh(t,e){if(!t)return;let n=Ve(t.entries.get("AcroForm"),e);if(!(!n||!Q(n)))return n}function Gh(t,e){if(!t)return[];let n=Ve(t.entries.get("Annots"),e);if(!n)return[];let r=[];if(he(n))for(let o of n.items){let i=Ve(o,e);i&&Q(i)&&r.push(i)}return r}var Ui=t=>t&&typeof t=="object"&&"type"in t&&t.type==="name"?t.value:null,An=t=>{if(!t||typeof t!="object"||!("type"in t)||t.type!=="string")return null;let e=t.value;if(e.length>=2&&e[0]===254&&e[1]===255){let r="";for(let o=2;o+1<e.length;o+=2)r+=String.fromCharCode(e[o]<<8|e[o+1]);return r}let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return n},Fc=t=>t&&typeof t=="object"&&"type"in t&&(t.type==="integer"||t.type==="real")?t.value:null,Kh=1,Vh=2,qh=4096,Jh=32768,Zh=65536,Wx=1<<17,Qh=t=>{if(!t||!he(t)||t.items.length<4)return null;let e=t.items.slice(0,4).map(s=>Fc(s));if(e.some(s=>s===null))return null;let[n,r,o,i]=e;return{x:Math.min(n,o),y:Math.min(r,i),width:Math.abs(o-n),height:Math.abs(i-r)}},Cc=(t,e)=>{let n=Ve(t.entries.get("AP"),e);if(!n||!Q(n))return[];let r=Ve(n.entries.get("N"),e);return!r||!Q(r)?[]:Array.from(r.entries.keys()).filter(o=>o!=="Off")},ef=(t,e)=>{var o,i,s;let n=Ve(t,e);if(!n||!he(n))return[];let r=[];for(let a of n.items){let c=Ve(a,e);c&&he(c)&&c.items.length>0?r.push((i=(o=An(c.items[0]))!=null?o:An(c.items[1]))!=null?i:""):r.push((s=An(c))!=null?s:"")}return r.filter(a=>a.length>0)},tf=t=>{if(!t)return;let e=t.match(/([\d.]+)\s+Tf/);if(!e)return;let n=parseFloat(e[1]);return Number.isFinite(n)?n:void 0},nf=(t,e)=>{switch(t){case"Tx":return"text";case"Ch":return"dropdown";case"Sig":return"signature";case"Btn":return e&Zh?null:e&Jh?"radio":"checkbox";default:return null}},rf=(t,e)=>{let n=new Map;for(let[r,o]of t)for(let i of Gh(o,e))n.has(i)||n.set(i,r);return n};function Mc(t,e,n){let r=Hh(t,n);if(!r)return[];let o=Ve(r.entries.get("Fields"),n);if(!o||!he(o))return[];let i=An(r.entries.get("DA")),s=rf(e,n),a=[],c=(l,d)=>{var le,pe,De,_,K;let m=An(l.entries.get("T")),h=m?d.namePrefix?`${d.namePrefix}.${m}`:m:d.namePrefix,f=Fc(l.entries.get("Ff")),p=f!==null?f:d.flags,w=(le=Ui(l.entries.get("FT")))!=null?le:d.ft,y=(pe=An(l.entries.get("DA")))!=null?pe:d.da,v=(_=(De=An(l.entries.get("V")))!=null?De:Ui(l.entries.get("V")))!=null?_:d.value,b={flags:p,namePrefix:h,ft:w,da:y,value:v!=null?v:void 0},C=Ve(l.entries.get("Kids"),n),S=C&&he(C)?C.items.map(G=>Ve(G,n)).filter(G=>!!G&&Q(G)):[],T=Ui(l.entries.get("Subtype"))==="Widget"||S.length===0&&l.entries.has("Rect"),N=S.some(G=>G.entries.has("T"));if(S.length>0&&N){for(let G of S)c(G,b);return}let O=nf(w,p);if(!O){for(let G of S)c(G,b);return}let A=tf(y!=null?y:i),H=(p&Kh)!==0,ne=(p&Vh)!==0,ie=(p&qh)!==0,I=O==="dropdown"?ef(l.entries.get("Opt"),n):void 0,ce=S.length>0?S:T?[l]:[];for(let G of ce){let ae=Qh(Ve(G.entries.get("Rect"),n));if(!ae)continue;let me=(K=s.get(G))!=null?K:0,Te=(O==="checkbox"||O==="radio"?Cc(G,n):[])[0];a.push({id:`${h}__${a.length}`,name:h,type:O,pageIndex:me,rect:ae,value:v!=null?v:void 0,options:O==="radio"?ce.map(Me=>Cc(Me,n)[0]).filter(Me=>!!Me):I,onState:Te,fontSize:A,multiline:ie,readOnly:H,required:ne})}};for(let l of o.items){let d=Ve(l,n);d&&Q(d)&&c(d,{flags:0,namePrefix:""})}return a}var Rc=t=>t&&typeof t=="object"&&"type"in t&&t.type==="name"?t.value:null,of=t=>t&&typeof t=="object"&&"type"in t&&(t.type==="integer"||t.type==="real")?t.value:null,sf=t=>{if(!t||typeof t!="object"||!("type"in t)||t.type!=="string")return null;let e=t.value;if(e.length>=2&&e[0]===254&&e[1]===255){let r="";for(let o=2;o+1<e.length;o+=2)r+=String.fromCharCode(e[o]<<8|e[o+1]);return r}let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return n},af=t=>{if(!t||!he(t)||t.items.length<4)return null;let e=t.items.slice(0,4).map(s=>of(s));if(e.some(s=>s===null))return null;let[n,r,o,i]=e;return{x:Math.min(n,o),y:Math.min(r,i),width:Math.abs(o-n),height:Math.abs(i-r)}},Ac=(t,e,n)=>{let r=Be(t)?t:Ve(t,n);if(!r||!he(r)||r.items.length===0)return;let o=r.items[0];if(Be(o))return e.get(`${o.objNum}:${o.genNum}`)};function _i(t,e,n){var i;if(!t)return[];let r=Ve(t.entries.get("Annots"),n);if(!r||!he(r))return[];let o=[];for(let s of r.items){let a=Ve(s,n);if(!a||!Q(a)||Rc(a.entries.get("Subtype"))!=="Link")continue;let c=af(Ve(a.entries.get("Rect"),n));if(!c||c.width<1||c.height<1)continue;let l,d,m=Ve(a.entries.get("A"),n);if(m&&Q(m)){let h=Rc(m.entries.get("S"));h==="URI"?l=(i=sf(m.entries.get("URI")))!=null?i:void 0:h==="GoTo"&&(d=Ac(m.entries.get("D"),e,n))}l===void 0&&d===void 0&&(d=Ac(a.entries.get("Dest"),e,n)),(l||d!==void 0)&&o.push({rect:c,uri:l,destPageIndex:d})}return o}import{useLayoutEffect as cf,useRef as lf}from"react";import{jsx as Nc,jsxs as df}from"react/jsx-runtime";function Xi({runs:t,scale:e,pageHeight:n}){let r=lf(null);return cf(()=>{let o=r.current;if(!o)return;o.querySelectorAll("span[data-w]").forEach(s=>{var l;let a=parseFloat((l=s.dataset.w)!=null?l:"0"),c=s.offsetWidth;a>0&&c>0&&(s.style.transform=`scaleX(${a/c})`)})},[t,e,n]),df("div",{ref:r,className:"pdf-text-layer",style:{position:"absolute",inset:0,zIndex:4,cursor:"text",userSelect:"text",WebkitUserSelect:"text",lineHeight:1},children:[Nc("style",{children:".pdf-text-layer ::selection{background:rgba(37,99,235,0.30)}"}),t.map((o,i)=>{var a;if(!o.text)return null;let s=Ge(o.pdfX,o.pdfY+o.height,e,n);return Nc("span",{"data-w":o.width*e,style:{position:"absolute",left:`${s.x}px`,top:`${s.y}px`,fontSize:`${Math.max(1,o.fontSize*e)}px`,fontFamily:(a=o.fontFamily)!=null?a:"sans-serif",color:"transparent",whiteSpace:"pre",transformOrigin:"0 0",pointerEvents:"auto"},children:o.text},i)})]})}var zi=(t,e,n,r=0)=>t>=n.pdfX-r&&t<=n.pdfX+n.width+r&&e>=n.pdfY-r&&e<=n.pdfY+n.height+r,Ec=(t,e,n)=>{let r=Math.max(n.pdfX-t,0,t-(n.pdfX+n.width)),o=Math.max(n.pdfY-e,0,e-(n.pdfY+n.height));return Math.hypot(r,o)},Tc=(t,e,n=5)=>{var a,c;if(!e||e.length===0)return null;let r=[...e].sort((l,d)=>{var h,f;let m=((h=d.contentStreamIndex)!=null?h:0)-((f=l.contentStreamIndex)!=null?f:0);return m!==0?m:l.width*l.height-d.width*d.height});for(let l of r){let d=Math.max(n,l.fontSize*.35);if((a=l.glyphs)==null?void 0:a.some(h=>zi(t.x,t.y,h,d)))return l}let o=r.find(l=>zi(t.x,t.y,l,Math.max(n,l.fontSize*.25)));if(o)return o;let i=null,s=Number.POSITIVE_INFINITY;for(let l of e){let d=(c=l.glyphs)==null?void 0:c.reduce((p,w)=>Math.min(p,Ec(t.x,t.y,w)),Number.POSITIVE_INFINITY),m=Ec(t.x,t.y,l),h=Math.abs(t.y-l.pdfBaselineY)*.2,f=Math.min(d!=null?d:Number.POSITIVE_INFINITY,m+h);f<s&&(s=f,i=l)}return i&&s<=Math.max(n,i.fontSize*.5)?i:null},fo=(t,e,n=3)=>{if(!e||e.length===0)return null;let r=e.filter(o=>zi(t.x,t.y,o,n));return r.length===0?null:(r.sort((o,i)=>i.spanEnd!==o.spanEnd?i.spanEnd-o.spanEnd:o.width*o.height-i.width*i.height),r[0])};var uf=(t,e,n)=>{let r=t.canvasX/n,o=Math.max(1,t.canvasWidth/n),i=Math.max(1,t.canvasHeight/n),s=e-(t.canvasY+t.canvasHeight)/n,a=e-t.canvasBaselineY/n;return{x:r,y:s,width:o,height:i,baselineY:a}},Oc=(t,e,n,r,o,i)=>({pdfX:t/i,pdfY:o-(e+r)/i,width:Math.max(.5,n/i),height:Math.max(.5,r/i)}),Ic=(t,e,n,r)=>({kind:"image",pageIndex:e,...Oc(t.canvasX,t.canvasY,t.canvasWidth,t.canvasHeight,n,r),spanStart:t.streamOperatorIndex,spanEnd:t.streamOperatorIndex,ctm:[...t.ctm],fromXObject:t.fromXObject,xobjectName:t.xobjectName}),jc=(t,e,n,r)=>({kind:"graphic",pageIndex:e,...Oc(t.canvasX,t.canvasY,t.canvasWidth,t.canvasHeight,n,r),spanStart:t.operatorStart,spanEnd:t.operatorEnd,ctm:[...t.ctmAtStart],fromXObject:t.fromXObject}),$c=(t,e,n,r)=>{let o=uf(t,n,r);return{pageIndex:e,text:t.text,pdfX:o.x,pdfY:o.y,pdfBaselineY:o.baselineY,width:o.width,height:o.height,fontSize:Math.max(6,t.fontSize),fontName:t.fontName,fontFamily:t.fontFamily,color:t.fillColor,streamOperatorIndices:[t.streamOperatorIndex],fromXObject:t.fromXObject,glyphs:t.glyphs.map(i=>({char:i.char,pdfX:i.canvasX/r,pdfY:n-(i.canvasY+i.canvasHeight)/r,pdfBaselineY:n-i.canvasBaselineY/r,width:Math.max(1,i.canvasWidth/r),height:Math.max(1,i.canvasHeight/r)}))}};var Bc=t=>{var r;let e=t.color,n=e?`${Math.round(e.r*255)},${Math.round(e.g*255)},${Math.round(e.b*255)}`:"-";return`${(r=t.fontName)!=null?r:"-"}|${Math.round(t.fontSize)}|${n}`},Lc=(t,e,n)=>{var o,i;if(!((o=t.glyphs)!=null&&o.length)||!((i=e.glyphs)!=null&&i.length))return;let r=[...t.glyphs];if(n){let s=t.pdfX+t.width;r.push({char:" ",pdfX:s,pdfY:t.pdfY,width:Math.max(0,e.pdfX-s),height:t.height,pdfBaselineY:t.pdfBaselineY})}return r.push(...e.glyphs),r},mo=t=>{if(!t.length)return[];let e=[...t].sort((o,i)=>Math.abs(i.pdfBaselineY-o.pdfBaselineY)>2?i.pdfBaselineY-o.pdfBaselineY:o.pdfX-i.pdfX),n=[];e.forEach(o=>{let i=Math.max(2,o.height*.45),s=n[n.length-1];if(!s||Math.abs(s.baselineY-o.pdfBaselineY)>i){n.push({baselineY:o.pdfBaselineY,runs:[o]});return}s.runs.push(o),s.baselineY=(s.baselineY*(s.runs.length-1)+o.pdfBaselineY)/s.runs.length});let r=[];return n.forEach(o=>{var a,c,l,d,m,h,f,p,w,y;let i=[...o.runs].sort((v,b)=>v.pdfX-b.pdfX);if(!i.length)return;let s={...i[0]};for(let v=1;v<i.length;v+=1){let b=i[v],C=b.pdfX-(s.pdfX+s.width),S=Math.max(1,s.fontSize*.15),F=Math.max(2,s.fontSize*.6);if(!(((a=s.contentStreamIndex)!=null?a:0)===((c=b.contentStreamIndex)!=null?c:0))){r.push(s),s={...b};continue}if(Bc(s)!==Bc(b)){r.push(s),s={...b};continue}C<=S?s={...s,text:`${s.text}${b.text}`,width:b.pdfX+b.width-s.pdfX,height:Math.max(s.height,b.height),glyphs:Lc(s,b,!1),streamOperatorIndices:[...(l=s.streamOperatorIndices)!=null?l:[],...(d=b.streamOperatorIndices)!=null?d:[]],fromXObject:((m=s.fromXObject)!=null?m:!1)||((h=b.fromXObject)!=null?h:!1)}:C<=F?s={...s,text:`${s.text} ${b.text}`,width:b.pdfX+b.width-s.pdfX,height:Math.max(s.height,b.height),glyphs:Lc(s,b,!0),streamOperatorIndices:[...(f=s.streamOperatorIndices)!=null?f:[],...(p=b.streamOperatorIndices)!=null?p:[]],fromXObject:((w=s.fromXObject)!=null?w:!1)||((y=b.fromXObject)!=null?y:!1)}:(r.push(s),s={...b})}r.push(s)}),r};function Uc(t,e,n,r){var s;let o=r>0?r:1,i=[];for(let a of t){let c=((s=a.text)!=null?s:"").trim();if(!c)continue;let l=Math.max(1,a.width/o),d=Math.max(1,a.height/o),m=a.x/o,h=n-(a.y+a.height)/o,f=h+d*.2;i.push({text:c,pdfX:m,pdfY:h,width:l,height:d,pdfBaselineY:f,fontSize:Math.max(4,d*.78),fontName:"Helvetica",color:{r:0,g:0,b:0},pageIndex:e,ocr:!0})}return i}var po=()=>({ctm:[1,0,0,1,0,0],font:"",fontSize:12,charSpacing:0,wordSpacing:0,horizScale:100,leading:0,textRise:0,textRenderMode:0,textMatrix:[1,0,0,1,0,0],textLineMatrix:[1,0,0,1,0,0],fillColorSpace:"DeviceGray",strokeColorSpace:"DeviceGray",fillColor:{space:"gray",gray:0},strokeColor:{space:"gray",gray:0},fillPatternName:null,strokePatternName:null,fillPattern:null,strokePattern:null,lineWidth:1,lineCap:0,lineJoin:0,miterLimit:10,dashArray:[],dashPhase:0,fillAlpha:1,strokeAlpha:1,blendMode:"Normal"});var _c=t=>t===" "||t===" "||t==="\r"||t===`
|
|
39
|
+
`||t==="\f"||t==="\0";function zc(t){let e=[],n=[e],r=0;for(;r<t.length;){let o=t[r];if(_c(o)){r++;continue}if(o==="%"){for(;r<t.length&&t[r]!==`
|
|
40
|
+
`&&t[r]!=="\r";)r++;continue}if(o==="{"){let c=[];n[n.length-1].push(c),n.push(c),r++;continue}if(o==="}"){if(n.length===1)throw new Error("Unbalanced } in PostScript function");n.pop(),r++;continue}let i=r;for(;i<t.length&&!_c(t[i])&&t[i]!=="{"&&t[i]!=="}"&&t[i]!=="%";)i++;let s=t.slice(r,i);r=i;let a=Number(s);Number.isFinite(a)&&/^[-+.0-9eE]+$/.test(s)?n[n.length-1].push(a):n[n.length-1].push(s.toLowerCase())}if(n.length!==1)throw new Error("Unbalanced { in PostScript function");return e.length===1&&Array.isArray(e[0])?e[0]:e}var Yi=Math.PI/180;function ve(t,e){if(typeof t!="number")throw new Error(`${e}: expected number`);return t}function Ze(t,e){if(typeof t!="number")throw new Error(`${e}: expected integer`);return Math.trunc(t)}function Xc(t,e){if(typeof t!="boolean")throw new Error(`${e}: expected boolean`);return t}function Yc(t,e,n){let r=[...e],o=0,i=m=>{if(r.length>=100)throw new Error("PostScript stack overflow");r.push(m)},s=m=>{let h=r.pop();if(h===void 0)throw new Error(`${m}: stack underflow`);return h},a=m=>{let h=s(m);if(!Array.isArray(h))throw new Error(`${m}: expected procedure`);return h},c=m=>{for(let h of m){if(++o>1e4)throw new Error("PostScript op budget exceeded");if(typeof h=="number"){i(h);continue}if(Array.isArray(h)){i(h);continue}switch(h){case"add":{let f=ve(s(h),h),p=ve(s(h),h);i(p+f);break}case"sub":{let f=ve(s(h),h),p=ve(s(h),h);i(p-f);break}case"mul":{let f=ve(s(h),h),p=ve(s(h),h);i(p*f);break}case"div":{let f=ve(s(h),h),p=ve(s(h),h);i(f===0?0:p/f);break}case"idiv":{let f=Ze(s(h),h),p=Ze(s(h),h);i(f===0?0:Math.trunc(p/f));break}case"mod":{let f=Ze(s(h),h),p=Ze(s(h),h);i(f===0?0:p%f);break}case"neg":i(-ve(s(h),h));break;case"abs":i(Math.abs(ve(s(h),h)));break;case"ceiling":i(Math.ceil(ve(s(h),h)));break;case"floor":i(Math.floor(ve(s(h),h)));break;case"round":i(Math.round(ve(s(h),h)));break;case"truncate":i(Math.trunc(ve(s(h),h)));break;case"sqrt":i(Math.sqrt(Math.max(0,ve(s(h),h))));break;case"sin":i(Math.sin(ve(s(h),h)*Yi));break;case"cos":i(Math.cos(ve(s(h),h)*Yi));break;case"atan":{let f=ve(s(h),h),p=ve(s(h),h),w=Math.atan2(p,f)/Yi;w<0&&(w+=360),i(w);break}case"exp":{let f=ve(s(h),h),p=ve(s(h),h);i(Math.pow(p,f));break}case"ln":i(Math.log(Math.max(Number.MIN_VALUE,ve(s(h),h))));break;case"log":i(Math.log10(Math.max(Number.MIN_VALUE,ve(s(h),h))));break;case"cvi":i(Math.trunc(ve(s(h),h)));break;case"cvr":i(ve(s(h),h));break;case"eq":{let f=s(h),p=s(h);i(p===f);break}case"ne":{let f=s(h),p=s(h);i(p!==f);break}case"gt":{let f=ve(s(h),h),p=ve(s(h),h);i(p>f);break}case"ge":{let f=ve(s(h),h),p=ve(s(h),h);i(p>=f);break}case"lt":{let f=ve(s(h),h),p=ve(s(h),h);i(p<f);break}case"le":{let f=ve(s(h),h),p=ve(s(h),h);i(p<=f);break}case"and":{let f=s(h),p=s(h);i(typeof p=="boolean"&&typeof f=="boolean"?p&&f:Ze(p,h)&Ze(f,h));break}case"or":{let f=s(h),p=s(h);i(typeof p=="boolean"&&typeof f=="boolean"?p||f:Ze(p,h)|Ze(f,h));break}case"xor":{let f=s(h),p=s(h);i(typeof p=="boolean"&&typeof f=="boolean"?p!==f:Ze(p,h)^Ze(f,h));break}case"not":{let f=s(h);i(typeof f=="boolean"?!f:~Ze(f,h));break}case"bitshift":{let f=Ze(s(h),h),p=Ze(s(h),h);i(f>=0?p<<f:p>>-f);break}case"true":i(!0);break;case"false":i(!1);break;case"pop":s(h);break;case"exch":{let f=s(h),p=s(h);i(f),i(p);break}case"dup":{let f=s(h);i(f),i(f);break}case"copy":{let f=Ze(s(h),h);if(f<0||f>r.length)throw new Error("copy: bad count");let p=r.length-f;for(let w=0;w<f;w++)i(r[p+w]);break}case"index":{let f=Ze(s(h),h);if(f<0||f>=r.length)throw new Error("index: out of range");i(r[r.length-1-f]);break}case"roll":{let f=Ze(s(h),h),p=Ze(s(h),h);if(p<0||p>r.length)throw new Error("roll: bad count");if(p>0&&f!==0){let w=r.splice(r.length-p,p),y=(f%p+p)%p;r.push(...w.slice(p-y),...w.slice(0,p-y))}break}case"if":{let f=a(h);Xc(s(h),h)&&c(f);break}case"ifelse":{let f=a(h),p=a(h),w=Xc(s(h),h);c(w?p:f);break}default:throw new Error(`Unknown PostScript operator: ${h}`)}}};c(t);let l=Math.floor(n.length/2);if(r.length<l)throw new Error("PostScript function returned too few values");return r.slice(r.length-l).map((m,h)=>{if(typeof m!="number"&&typeof m!="boolean")throw new Error("PostScript function returned a non-numeric value");let f=typeof m=="number"?m:m?1:0,p=n[h*2],w=n[h*2+1];return Math.max(p,Math.min(w,f))})}var go=q,Lt=t=>!t||!he(t)?null:t.items.map(e=>{var n;return(n=go(e))!=null?n:0}),nt=(t,e)=>{if(t){if(!Be(t))return t;try{return e(t)}catch{return}}},Wc=new WeakMap,hf=(t,e,n)=>{var c;let r=e*n,o=r>>3,i=r&7,s=n,a=0;for(;s>0;){let l=8-i,d=Math.min(l,s),h=((c=t[o])!=null?c:0)>>l-d&(1<<d)-1;a=a*(1<<d)+h,s-=d,i+=d,i===8&&(i=0,o++)}return a},ff=(t,e)=>t.map((n,r)=>{let o=e[r*2],i=e[r*2+1];return o===void 0||i===void 0?n:Math.max(o,Math.min(i,n))}),xo=(t,e,n)=>{var l,d,m,h,f,p,w,y,v,b,C,S,F,T,N,O,A,H,ne,ie,I,ce,le,pe,De,_;let r=nt(t,n);if(!r)return null;let o=fe(r)?r.dict:Q(r)?r:null;if(!o)return null;let i=Math.floor((l=go(nt(o.entries.get("FunctionType"),n)))!=null?l:-1),s=(d=Lt(nt(o.entries.get("Domain"),n)))!=null?d:[0,1],a=Math.max(1,Math.floor(s.length/2)),c=[];for(let K=0;K<a;K++){let G=(m=e[K])!=null?m:0,ae=(h=s[K*2])!=null?h:0,me=(f=s[K*2+1])!=null?f:1;c.push(Math.max(Math.min(ae,me),Math.min(Math.max(ae,me),G)))}if(i===2){let K=(p=go(nt(o.entries.get("N"),n)))!=null?p:1,G=(w=Lt(nt(o.entries.get("C0"),n)))!=null?w:[0],ae=(y=Lt(nt(o.entries.get("C1"),n)))!=null?y:[1],me=Math.pow(c[0],K);return G.map((Xe,Te)=>{var Me;return Xe+me*(((Me=ae[Te])!=null?Me:1)-Xe)})}if(i===0){if(!fe(r))return null;let K=((v=Lt(nt(o.entries.get("Size"),n)))!=null?v:[2]).map(ke=>Math.max(1,Math.floor(ke)));if(K.length<a||a>8)return null;let G=Math.floor((b=go(nt(o.entries.get("BitsPerSample"),n)))!=null?b:8);if(![1,2,4,8,12,16,24,32].includes(G))return null;let ae=Lt(nt(o.entries.get("Range"),n));if(!ae||ae.length<2)return null;let me=Math.floor(ae.length/2),Xe=[];for(let ke=0;ke<a;ke++)Xe.push(0,K[ke]-1);let Te=(C=Lt(nt(o.entries.get("Encode"),n)))!=null?C:Xe,Me=(S=Lt(nt(o.entries.get("Decode"),n)))!=null?S:ae,lt=G===32?4294967295:(1<<G)-1,rt;try{rt=we.decodeStreamSync(r)}catch{return null}let ot=[],Mt=[];for(let ke=0;ke<a;ke++){let Je=(F=s[ke*2])!=null?F:0,Qe=(T=s[ke*2+1])!=null?T:1,Re=(N=Te[ke*2])!=null?N:0,Rt=(O=Te[ke*2+1])!=null?O:K[ke]-1,En=Qe!==Je?(c[ke]-Je)/(Qe-Je):0,Xt=Math.max(0,Math.min(K[ke]-1,Re+En*(Rt-Re))),Pr=Math.min(K[ke]-1,Math.floor(Xt));ot.push(Pr),Mt.push(Math.max(0,Math.min(1,Xt-Pr)))}let ft=[],bn=1;for(let ke=0;ke<a;ke++)ft.push(bn),bn*=K[ke];let ye=new Array(me).fill(0),Ke=1<<a;for(let ke=0;ke<Ke;ke++){let Je=1,Qe=0;for(let Re=0;Re<a;Re++)if(ke>>Re&1){if(Mt[Re]===0){Je=0;break}Je*=Mt[Re],Qe+=Math.min(K[Re]-1,ot[Re]+1)*ft[Re]}else Je*=1-Mt[Re],Qe+=ot[Re]*ft[Re];if(Je!==0)for(let Re=0;Re<me;Re++)ye[Re]+=Je*hf(rt,Qe*me+Re,G)}let _t=ye.map((ke,Je)=>{var Rt,En;let Qe=(Rt=Me[Je*2])!=null?Rt:0,Re=(En=Me[Je*2+1])!=null?En:1;return Qe+ke/lt*(Re-Qe)});return ff(_t,ae)}if(i===3){let K=(A=Lt(nt(o.entries.get("Bounds"),n)))!=null?A:[],G=(H=Lt(nt(o.entries.get("Encode"),n)))!=null?H:[],ae=nt(o.entries.get("Functions"),n);if(!ae||!he(ae))return null;let me=ae.items,Xe=c[0],Te=0;for(let ft=0;ft<K.length&&Xe>=K[ft];ft++)Te=ft+1;let Me=Te===0?(ne=s[0])!=null?ne:0:(I=(ie=K[Te-1])!=null?ie:s[0])!=null?I:0,lt=Te<K.length?(le=(ce=K[Te])!=null?ce:s[1])!=null?le:1:(pe=s[1])!=null?pe:1,rt=(De=G[Te*2])!=null?De:0,ot=(_=G[Te*2+1])!=null?_:1,Mt=Me===lt?rt:rt+(Xe-Me)/(lt-Me)*(ot-rt);return xo(me[Te],[Mt],n)}if(i===4){if(!fe(r))return null;let K=Lt(nt(o.entries.get("Range"),n));if(!K||K.length<2)return null;try{let G=Wc.get(r);if(!G){let ae=new TextDecoder("latin1").decode(we.decodeStreamSync(r));G=zc(ae),Wc.set(r,G)}return Yc(G,c,K)}catch{return null}}return null},bo=(t,e,n)=>xo(t,[e],n),Wi=(t,e,n)=>{let r=nt(t,n);if(!r)return null;if(he(r)){let o=[];for(let i of r.items){let s=xo(i,e,n);if(!s)return null;o.push(...s)}return o}return xo(r,e,n)};var Hc=t=>Math.max(1,Math.min(2048,Math.ceil(t)));function Gc(t,e,n,r){if(![...t,e,n,...r].every(Number.isFinite)||Math.abs(e)<1e-9||Math.abs(n)<1e-9)return null;let o=Math.hypot(r[0],r[1]),i=Math.hypot(r[2],r[3]);if(o<1e-12||i<1e-12)return null;let s=Hc(Math.abs(e)*o),a=Hc(Math.abs(n)*i),[c,l]=t,d=[s/e,0,0,-a/n,-c*s/e,(l+n)*a/n],m=Gn(d);return m?{cellPxW:s,cellPxH:a,contentTransform:d,paintTransform:m}:null}var qn=5e4,Gi=class{constructor(e){this.bytes=e;this.bitPos=0}get hasData(){return this.bitPos<this.bytes.length*8}get remainingBits(){return Math.max(0,this.bytes.length*8-this.bitPos)}read(e){var o;let n=0,r=e;for(;r>0;){let i=this.bitPos>>3,a=8-(this.bitPos&7),c=Math.min(a,r),d=((o=this.bytes[i])!=null?o:0)>>a-c&(1<<c)-1;n=n*(1<<c)+d,this.bitPos+=c,r-=c}return n}alignToByte(){this.bitPos=this.bitPos+7&-8}},mf=t=>t>=32?4294967295:(1<<t)-1,Hi=(t,e,n,r)=>n+t/mf(e)*(r-n);function Kc(t,e,n,r){var S;let o=new Gi(n),i=[],{bitsPerCoordinate:s,bitsPerComponent:a,bitsPerFlag:c,decode:l,numColorComponents:d}=e;if(l.length<4+d*2)return[];let m=()=>[Hi(o.read(s),s,l[0],l[1]),Hi(o.read(s),s,l[2],l[3])],h=()=>{let F=[];for(let T=0;T<d;T++)F.push(Hi(o.read(a),a,l[4+T*2],l[5+T*2]));return r(F)},f=2*s+d*a;if(t===4){let F=c+f,T=null,N=null,O=null,A=()=>{let H=o.read(c),[ne,ie]=m(),I=h();return o.alignToByte(),{flag:H,v:{x:ne,y:ie,color:I}}};for(;o.remainingBits>=F&&i.length<qn;){let H=A();if(H.flag===0||T===null||N===null||O===null){if(T=H.v,o.remainingBits<F||(N=A().v,o.remainingBits<F))break;O=A().v}else H.flag===1?(T=N,N=O,O=H.v):(N=O,O=H.v);yr(i,T,N,O)}return i}if(t===5){let F=Math.max(2,Math.floor((S=e.verticesPerRow)!=null?S:2)),T=[];for(;o.remainingBits>=F*f;){let N=[];for(let O=0;O<F;O++){let[A,H]=m();N.push({x:A,y:H,color:h()})}if(T.push(N),T.length*F>qn)break}for(let N=0;N+1<T.length&&i.length<qn;N++)for(let O=0;O+1<F&&i.length<qn;O++)yr(i,T[N][O],T[N][O+1],T[N+1][O]),yr(i,T[N][O+1],T[N+1][O+1],T[N+1][O]);return i}let p=t===6?12:16,w=t===6?8:12,y=null,v=null,b=p*2*s+4*d*a,C=w*2*s+2*d*a;for(;o.remainingBits>=c+C&&i.length<qn;){let F=o.read(c),T,N;if(F===0||!y||!v){if(o.remainingBits<b)break;T=[];for(let O=0;O<p;O++)T.push(m());N=[h(),h(),h(),h()]}else{let O=[];for(let I=0;I<w;I++)O.push(m());let A=h(),H=h(),ne,ie;F===1?(ne=[y[3],y[4],y[5],y[6]],ie=[v[1],v[2]]):F===2?(ne=[y[6],y[7],y[8],y[9]],ie=[v[2],v[3]]):(ne=[y[9],y[10],y[11],y[0]],ie=[v[3],v[0]]),T=[...ne,...O],N=[ie[0],ie[1],A,H]}if(!Number.isFinite(T[0][0]))break;gf(i,T,N),y=T,v=N}return i}var yr=(t,e,n,r)=>{t.push({p:[[e.x,e.y],[n.x,n.y],[r.x,r.y]],c:[e.color,n.color,r.color]})},yo=(t,e,n,r,o)=>{let i=1-o,s=i*i*i,a=3*i*i*o,c=3*i*o*o,l=o*o*o;return[s*t[0]+a*e[0]+c*n[0]+l*r[0],s*t[1]+a*e[1]+c*n[1]+l*r[1]]},pf=6,gf=(t,e,n)=>{let[r,o,i,s,a,c,l,d,m,h,f,p]=e,[w,y,v,b]=n,C=(N,O)=>{let A=yo(r,o,i,s,O),H=yo(h,m,d,l,O),ne=yo(r,p,f,h,N),ie=yo(s,a,c,l,N),I=(1-N)*A[0]+N*H[0]+(1-O)*ne[0]+O*ie[0]-((1-N)*(1-O)*r[0]+N*(1-O)*h[0]+(1-N)*O*s[0]+N*O*l[0]),ce=(1-N)*A[1]+N*H[1]+(1-O)*ne[1]+O*ie[1]-((1-N)*(1-O)*r[1]+N*(1-O)*h[1]+(1-N)*O*s[1]+N*O*l[1]);return[I,ce]},S=(N,O)=>[(1-N)*(1-O)*w[0]+(1-N)*O*y[0]+N*O*v[0]+N*(1-O)*b[0],(1-N)*(1-O)*w[1]+(1-N)*O*y[1]+N*O*v[1]+N*(1-O)*b[1],(1-N)*(1-O)*w[2]+(1-N)*O*y[2]+N*O*v[2]+N*(1-O)*b[2]],F=pf,T=[];for(let N=0;N<=F;N++){let O=[];for(let A=0;A<=F;A++){let H=A/F,ne=N/F,[ie,I]=C(H,ne);O.push({x:ie,y:I,color:S(H,ne)})}T.push(O)}for(let N=0;N<F;N++)for(let O=0;O<F;O++){if(t.length+2>qn)return;yr(t,T[N][O],T[N][O+1],T[N+1][O]),yr(t,T[N][O+1],T[N+1][O+1],T[N+1][O])}};function Vc(t,e,n,r){let o=new Uint8ClampedArray(n*r*4),i=(s,a)=>[e[0]*s+e[2]*a+e[4],e[1]*s+e[3]*a+e[5]];for(let s of t){let[a,c,l]=s.p.map(([w,y])=>i(w,y)),d=(c[0]-a[0])*(l[1]-a[1])-(c[1]-a[1])*(l[0]-a[0]);if(Math.abs(d)<1e-9)continue;let m=Math.max(0,Math.floor(Math.min(a[0],c[0],l[0]))),h=Math.min(n-1,Math.ceil(Math.max(a[0],c[0],l[0]))),f=Math.max(0,Math.floor(Math.min(a[1],c[1],l[1]))),p=Math.min(r-1,Math.ceil(Math.max(a[1],c[1],l[1])));for(let w=f;w<=p;w++)for(let y=m;y<=h;y++){let v=y+.5,b=w+.5,C=((c[0]-v)*(l[1]-b)-(c[1]-b)*(l[0]-v))/d,S=((l[0]-v)*(a[1]-b)-(l[1]-b)*(a[0]-v))/d,F=1-C-S;if(C<-1e-6||S<-1e-6||F<-1e-6)continue;let T=(w*n+y)*4;o[T]=255*(C*s.c[0][0]+S*s.c[1][0]+F*s.c[2][0]),o[T+1]=255*(C*s.c[0][1]+S*s.c[1][1]+F*s.c[2][1]),o[T+2]=255*(C*s.c[0][2]+S*s.c[1][2]+F*s.c[2][2]),o[T+3]=255}}return o}var xf=12,bf=(t,e,n)=>t.minX-n<=e.maxX&&e.minX-n<=t.maxX&&t.minY-n<=e.maxY&&e.minY-n<=t.maxY,yf=(t,e)=>({minX:Math.min(t.minX,e.minX),minY:Math.min(t.minY,e.minY),maxX:Math.max(t.maxX,e.maxX),maxY:Math.max(t.maxY,e.maxY)});function qc(t,e,n,r){if(!t.length)return[];let o=Math.max(2,.01*Math.hypot(n,r)),i=[...e].sort((d,m)=>d-m),s=(d,m)=>{let h=0,f=i.length-1;for(;h<=f;){let p=h+f>>1,w=i[p];if(w<=d)h=p+1;else if(w>=m)f=p-1;else return!0}return!1},a=[],c=null;for(let d of t)c!==null&&d.fromXObject===c.fromXObject&&d.pathStartIndex-c.operatorEnd<=xf&&!s(c.operatorEnd,d.pathStartIndex)&&bf(c.bbox,d.bbox,o)&&c?(c.bbox=yf(c.bbox,d.bbox),c.operatorEnd=Math.max(c.operatorEnd,d.paintIndex),c.operatorStart=Math.min(c.operatorStart,d.pathStartIndex),c.paintOperatorIndices.push(d.paintIndex)):(c&&a.push(c),c={bbox:{...d.bbox},operatorStart:d.pathStartIndex,operatorEnd:d.paintIndex,paintOperatorIndices:[d.paintIndex],ctmAtStart:[...d.ctmAtStart],fromXObject:d.fromXObject});c&&a.push(c);let l=n*r;return a.filter(d=>{let m=d.bbox.maxX-d.bbox.minX,h=d.bbox.maxY-d.bbox.minY;return m>0&&h>0&&m*h<=.9*l})}function wf(t){return t&&typeof t=="object"&&"type"in t&&t.type==="name"&&"value"in t?String(t.value):""}function Jc(t,e){if(!t)return null;let n=s=>{let a=e(s);if(!a||!fe(a))return null;try{return we.decodeStreamSync(a)}catch{return null}},r=n(t.entries.get("FontFile2"));if(r&&r.length>0)return{bytes:r,kind:"truetype"};let o=e(t.entries.get("FontFile3"));if(o&&fe(o)){let s=n(o);if(s&&s.length>0){let c=wf(o.dict.entries.get("Subtype"))==="OpenType"?"opentype":"cff";return{bytes:s,kind:c}}}let i=n(t.entries.get("FontFile"));return i&&i.length>0?{bytes:i,kind:"type1"}:null}function vf(t){return t==="truetype"||t==="opentype"}var wo=(t,e)=>t[e]<<8|t[e+1],kf=(t,e)=>t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];function Pf(t){if(t.length<12)return!1;let e=wo(t,4),n=-1;for(let o=0;o<e;o+=1){let i=12+o*16;if(i+16>t.length)return!1;if(t[i]===99&&t[i+1]===109&&t[i+2]===97&&t[i+3]===112){n=kf(t,i+8);break}}if(n<0||n+4>t.length)return!1;let r=wo(t,n+2);for(let o=0;o<r;o+=1){let i=n+4+o*8;if(i+8>t.length)break;let s=wo(t,i),a=wo(t,i+2);if(s===3&&(a===1||a===10)||s===0)return!0}return!1}function Sf(t){let e=2166136261,n=t.length,r=Math.max(1,Math.floor(n/4096));for(let o=0;o<n;o+=r)e^=t[o],e=Math.imul(e,16777619);return e^=n,e=Math.imul(e,16777619),`npf-${(e>>>0).toString(16)}`}var Ki=new Map,Vi=new Map,Df=()=>typeof document!="undefined"&&typeof globalThis.FontFace!="undefined"&&!!document.fonts;async function Zc(t){if(!Df()||!vf(t.kind)||!Pf(t.bytes))return null;let e=Sf(t.bytes),n=Ki.get(e);if(n==="loaded")return e;if(n==="failed")return null;let r=Vi.get(e);if(r)return r;let o=(async()=>{try{let i=t.bytes.slice().buffer,s=new FontFace(e,i);return await s.load(),document.fonts.add(s),Ki.set(e,"loaded"),e}catch{return Ki.set(e,"failed"),null}finally{Vi.delete(e)}})();return Vi.set(e,o),o}var qi=null,vo=()=>qi!=null?qi:qi=import("./pdf.image_decoders.min-ABCYWBEM.js"),Qc=new Set,el=new Set,tl=new Set(["F1","F3","F4"]),nl=new WeakMap,Cf=()=>new Promise(t=>setTimeout(t,0)),Jn=class Jn{constructor(e,n,r,o,i){this.canvas=e;this.pageWidth=n;this.pageHeight=r;this.scale=o;this.stateStack=[];this.state=po();this.atomicLogCount=0;this.commandIndex=0;this.xobjectDepth=0;this.pageResources=null;this.objectLoader=null;this.fontCache=new Map;this.embeddedFamilies=new Map;this.glyphWidthCache=new Map;this.separationColorCache=new Map;this.fillColorResolver=null;this.strokeColorResolver=null;this.resolverStack=[];this.capturedTextRuns=[];this.fontDiagnosticsLogged=new Set;this.rawByteDiagnosticsLogged=new Set;this.currentPathX=0;this.currentPathY=0;this.pathStartX=0;this.pathStartY=0;this.initialTransform=null;this.forcedColor=null;this.patternDepth=0;this.patternCache=new Map;this.meshCache=new Map;this.layerStack=[];this.layerPool=[];this.capturedImages=[];this.paintRecords=[];this.breakerIndices=[];this.pendingPath=null;this.captureSuppressed=0;var c,l,d,m,h,f,p;let s=(c=i==null?void 0:i.debugAtomic)!=null?c:!1,a=e.getContext("2d",{willReadFrequently:s});if(!a)throw new Error("2D context unavailable");this.ctx=a,this.baseCtx=a,this.disableClip=(l=i==null?void 0:i.disableClip)!=null?l:!1,this.debug=(d=i==null?void 0:i.debug)!=null?d:!1,this.debugAtomic=s,this.maxAtomicLogs=(m=i==null?void 0:i.maxAtomicLogs)!=null?m:500,this.initialTransform=(h=i==null?void 0:i.initialTransform)!=null?h:null,this.forcedColor=(f=i==null?void 0:i.forcedColor)!=null?f:null,this.patternDepth=(p=i==null?void 0:i.patternDepth)!=null?p:0,e.width=Math.ceil(n*o),e.height=Math.ceil(r*o),i!=null&&i.transparentBackground||(this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.fillStyle="white",this.ctx.fillRect(0,0,e.width,e.height),this.ctx.restore()),this.forcedColor&&(this.state.fillColor=this.forcedColor,this.state.strokeColor=this.forcedColor,this.ctx.fillStyle=Zt(this.forcedColor),this.ctx.strokeStyle=Zt(this.forcedColor)),this.applyCurrentTransform(),this.logDebug("init",{pageWidth:n,pageHeight:r,scale:o,canvasWidth:e.width,canvasHeight:e.height,disableClip:this.disableClip})}render(e){this.commandIndex=0,this.capturedTextRuns=[],this.applyCurrentTransform(),this.logDebug("render:start",{commandCount:e.length}),this.logDebug("orientation",{flipYApplied:!0});for(let n of e){let r=this.commandIndex++;this.debug&&this.logDebug("command",{index:r,op:n.op,payload:this.commandPayload(n)});let i=this.debugAtomic&&this.atomicLogCount<this.maxAtomicLogs?this.captureAtomicState():null;this.execute(n),i&&this.logAtomic(r,n,i,this.captureAtomicState())}this.logDebug("render:end",{renderedCommands:e.length,capturedTextRuns:this.capturedTextRuns.length,finalTextMatrix:this.state.textMatrix,finalLineMatrix:this.state.textLineMatrix,finalCTM:this.state.ctm,stackDepth:this.stateStack.length})}async renderAsync(e){for(this.commandIndex=0,this.xobjectDepth=0,this.capturedTextRuns=[],this.capturedImages=[],this.paintRecords=[],this.breakerIndices=[],this.pendingPath=null,this.patternCache.clear(),this.meshCache.clear(),this.glyphWidthCache.clear(),this.ctx=this.baseCtx,this.layerStack=[],this.applyCurrentTransform(),this.logDebug("render:start",{commandCount:e.length,async:!0}),await this.preloadEmbeddedFonts(),await this.runCommandsAsync(e);this.layerStack.length>0;)this.popLayer();this.logDebug("render:end",{renderedCommands:e.length,capturedTextRuns:this.capturedTextRuns.length,finalTextMatrix:this.state.textMatrix,finalLineMatrix:this.state.textLineMatrix,finalCTM:this.state.ctm,stackDepth:this.stateStack.length,async:!0})}async renderAnnotations(e){if(!e)return;let n=this.resolveObject(e.entries.get("Annots"));if(!n||!he(n))return;let r=this.state;this.state=po(),this.applyCurrentTransform();try{for(let o of n.items){let i=this.resolveObject(o);if(!(!i||!Q(i)))try{await this.renderOneAnnotation(i)}catch(s){this.logDebug("annot:render-failed",{error:s instanceof Error?s.message:String(s)})}}}finally{this.state=r,this.applyCurrentTransform()}}async renderOneAnnotation(e){var l,d;let n=Fe(e.entries.get("Subtype"));if(n==="Popup"||n==="Link"||n==="Widget")return;let r=Math.floor((l=q(e.entries.get("F")))!=null?l:0);if((r&2)!==0||(r&32)!==0)return;let o=this.resolveAppearanceStream(e);if(!o)return;let i=ht(this.resolveObject(e.entries.get("Rect")));if(!i||i.length<4)return;let s=ht(o.dict.entries.get("BBox"));if(!s||s.length<4)return;let a=(d=wr(o.dict.entries.get("Matrix")))!=null?d:[1,0,0,1,0,0],c=Af(i,s,a);if(c){this.execute({op:"save_state"}),this.execute({op:"set_ctm",matrix:c});try{await this.renderFormStreamInline(o)}finally{this.execute({op:"restore_state"})}}}resolveAppearanceStream(e){let n=this.resolveObject(e.entries.get("AP"));if(!n||!Q(n))return null;let r=this.resolveObject(n.entries.get("N"));if(r&&Q(r)){let o=Fe(e.entries.get("AS"));r=o?this.resolveObject(r.entries.get(o)):void 0}return r&&fe(r)?r:null}async runCommandsAsync(e){let n=()=>typeof performance!="undefined"?performance.now():Date.now(),r=n();for(let o of e){let i=this.commandIndex++;this.debug&&this.logDebug("command",{index:i,op:o.op,payload:this.commandPayload(o)}),n()-r>12&&(await Cf(),r=n());let a=this.debugAtomic&&this.atomicLogCount<this.maxAtomicLogs?this.captureAtomicState():null;o.op==="xobject"?await this.renderXObject(o.name):o.op==="inline_image"?await this.renderInlineImage(o.params,o.data):(o.op==="set_fill_color"||o.op==="set_stroke_color")&&o.patternName&&!this.forcedColor&&(o.op==="set_fill_color"?this.state.fillColorSpace:this.state.strokeColorSpace)==="Pattern"?await this.applyPatternColor(o.op==="set_fill_color"?"fill":"stroke",o.patternName,o.values):o.op==="set_graphics_state"?(this.execute(o),await this.applySoftMaskFromExtGState(o.name)):this.execute(o),a&&this.logAtomic(i,o,a,this.captureAtomicState())}}getCapturedTextRuns(){return this.capturedTextRuns.map(e=>({...e,glyphs:e.glyphs.map(n=>({...n}))}))}getCapturedImages(){return this.capturedImages.map(e=>({...e,ctm:[...e.ctm]}))}getCapturedGraphics(){return qc(this.paintRecords,this.breakerIndices,this.canvas.width,this.canvas.height).map(e=>({canvasX:e.bbox.minX,canvasY:e.bbox.minY,canvasWidth:e.bbox.maxX-e.bbox.minX,canvasHeight:e.bbox.maxY-e.bbox.minY,operatorStart:e.operatorStart,operatorEnd:e.operatorEnd,paintOperatorIndices:e.paintOperatorIndices,ctmAtStart:e.ctmAtStart,fromXObject:e.fromXObject}))}extendPendingPath(e){if(this.captureSuppressed>0)return;this.pendingPath||(this.pendingPath={bbox:{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},startIndex:Math.max(0,this.commandIndex-1),ctmAtStart:[...this.state.ctm]});let n=Pe(this.deviceBase(),this.state.ctm),r=this.pendingPath.bbox;for(let[o,i]of e){let s=Ue(n,o,i);s.x<r.minX&&(r.minX=s.x),s.x>r.maxX&&(r.maxX=s.x),s.y<r.minY&&(r.minY=s.y),s.y>r.maxY&&(r.maxY=s.y)}}recordPaintForCapture(){let e=this.pendingPath;this.pendingPath=null,!(this.captureSuppressed>0||!e)&&(e.bbox.minX>e.bbox.maxX||this.paintRecords.push({bbox:{...e.bbox},pathStartIndex:e.startIndex,paintIndex:Math.max(0,this.commandIndex-1),ctmAtStart:e.ctmAtStart,fromXObject:this.xobjectDepth>0}))}recordBreaker(){this.captureSuppressed>0||this.breakerIndices.push(Math.max(0,this.commandIndex-1))}captureImageBox(e,n){if(this.recordBreaker(),this.captureSuppressed>0)return;let r=Pe(this.deviceBase(),this.state.ctm),o=[Ue(r,0,0),Ue(r,1,0),Ue(r,0,1),Ue(r,1,1)],i=o.map(l=>l.x),s=o.map(l=>l.y),a=Math.min(...i),c=Math.min(...s);this.capturedImages.push({canvasX:a,canvasY:c,canvasWidth:Math.max(...i)-a,canvasHeight:Math.max(...s)-c,ctm:[...this.state.ctm],kind:e,xobjectName:n,streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0})}setFontContext(e,n){this.pageResources=e!=null?e:null,this.objectLoader=n!=null?n:null,this.fontCache.clear(),this.fontDiagnosticsLogged.clear(),this.rawByteDiagnosticsLogged.clear(),this.patternCache.clear()}execute(e){var n,r;switch(e.op){case"save_state":this.stateStack.push(Kf(this.state)),this.resolverStack.push({fill:this.fillColorResolver,stroke:this.strokeColorResolver}),this.ctx.save();break;case"restore_state":for(;this.layerStack.length>0&&this.stateStack.length>0;){let o=this.layerStack[this.layerStack.length-1];if(o.kind==="smask"&&o.stateDepthAtPush>=this.stateStack.length)this.popLayer();else break}if(this.stateStack.length>0&&(this.state=this.stateStack.pop()),this.resolverStack.length>0){let o=this.resolverStack.pop();this.fillColorResolver=o.fill,this.strokeColorResolver=o.stroke}this.ctx.restore();break;case"set_ctm":this.state.ctm=Pe(this.state.ctm,e.matrix),this.applyCurrentTransform(),this.logDebug("ctm:update",{ctm:this.state.ctm,cmd:e.matrix});break;case"set_line_width":this.state.lineWidth=e.width,this.ctx.lineWidth=e.width;break;case"set_line_cap":{let o=["butt","round","square"];this.state.lineCap=e.cap,this.ctx.lineCap=(n=o[e.cap])!=null?n:"butt";break}case"set_line_join":{let o=["miter","round","bevel"];this.state.lineJoin=e.join,this.ctx.lineJoin=(r=o[e.join])!=null?r:"miter";break}case"set_miter_limit":this.state.miterLimit=e.limit,this.ctx.miterLimit=e.limit;break;case"set_dash":this.state.dashArray=e.array,this.state.dashPhase=e.phase,this.ctx.setLineDash(e.array),this.ctx.lineDashOffset=e.phase;break;case"set_rendering_intent":break;case"set_graphics_state":this.applyExtGState(e.name);break;case"set_fill_color_rgb":if(this.forcedColor)break;this.state.fillColorSpace="DeviceRGB",this.state.fillColor={space:"rgb",r:e.r,g:e.g,b:e.b},this.state.fillPatternName=null,this.state.fillPattern=null,this.ctx.fillStyle=Ct(e.r,e.g,e.b);break;case"set_stroke_color_rgb":if(this.forcedColor)break;this.state.strokeColorSpace="DeviceRGB",this.state.strokeColor={space:"rgb",r:e.r,g:e.g,b:e.b},this.state.strokePatternName=null,this.state.strokePattern=null,this.ctx.strokeStyle=Ct(e.r,e.g,e.b);break;case"set_fill_gray":if(this.forcedColor)break;this.state.fillColorSpace="DeviceGray",this.state.fillColor={space:"gray",gray:e.gray},this.state.fillPatternName=null,this.state.fillPattern=null,this.ctx.fillStyle=Ct(e.gray,e.gray,e.gray);break;case"set_stroke_gray":if(this.forcedColor)break;this.state.strokeColorSpace="DeviceGray",this.state.strokeColor={space:"gray",gray:e.gray},this.state.strokePatternName=null,this.state.strokePattern=null,this.ctx.strokeStyle=Ct(e.gray,e.gray,e.gray);break;case"set_fill_cmyk":{if(this.forcedColor)break;this.state.fillColorSpace="DeviceCMYK",this.state.fillColor={space:"cmyk",c:e.c,m:e.m,y:e.y,k:e.k},this.state.fillPatternName=null,this.state.fillPattern=null;let o=Qn(e.c,e.m,e.y,e.k);this.ctx.fillStyle=Ct(o.r,o.g,o.b);break}case"set_stroke_cmyk":{if(this.forcedColor)break;this.state.strokeColorSpace="DeviceCMYK",this.state.strokeColor={space:"cmyk",c:e.c,m:e.m,y:e.y,k:e.k},this.state.strokePatternName=null,this.state.strokePattern=null;let o=Qn(e.c,e.m,e.y,e.k);this.ctx.strokeStyle=Ct(o.r,o.g,o.b);break}case"move_to":this.ctx.beginPath(),this.ctx.moveTo(e.x,e.y),this.currentPathX=e.x,this.currentPathY=e.y,this.pathStartX=e.x,this.pathStartY=e.y,this.extendPendingPath([[e.x,e.y]]);break;case"line_to":this.ctx.lineTo(e.x,e.y),this.currentPathX=e.x,this.currentPathY=e.y,this.extendPendingPath([[e.x,e.y]]);break;case"curve_to":this.ctx.bezierCurveTo(e.x1,e.y1,e.x2,e.y2,e.x3,e.y3),this.extendPendingPath([[e.x1,e.y1],[e.x2,e.y2],[e.x3,e.y3]]),this.currentPathX=e.x3,this.currentPathY=e.y3;break;case"curve_to_v":this.ctx.bezierCurveTo(this.currentPathX,this.currentPathY,e.x2,e.y2,e.x3,e.y3),this.extendPendingPath([[e.x2,e.y2],[e.x3,e.y3]]),this.currentPathX=e.x3,this.currentPathY=e.y3;break;case"rect":this.ctx.beginPath(),this.ctx.rect(e.x,e.y,e.w,e.h),this.currentPathX=e.x,this.currentPathY=e.y,this.pathStartX=e.x,this.pathStartY=e.y,this.extendPendingPath([[e.x,e.y],[e.x+e.w,e.y+e.h]]);break;case"close_path":this.ctx.closePath(),this.currentPathX=this.pathStartX,this.currentPathY=this.pathStartY;break;case"end_path":this.ctx.beginPath(),this.pendingPath=null;break;case"stroke":this.paintStroke(),this.recordPaintForCapture();break;case"close_stroke":this.ctx.closePath(),this.currentPathX=this.pathStartX,this.currentPathY=this.pathStartY,this.paintStroke(),this.recordPaintForCapture();break;case"fill":this.paintFill(),this.recordPaintForCapture();break;case"fill_stroke":this.paintFill(),this.paintStroke(),this.recordPaintForCapture();break;case"fill_even_odd":this.paintFill("evenodd"),this.recordPaintForCapture();break;case"fill_stroke_even_odd":this.paintFill("evenodd"),this.paintStroke(),this.recordPaintForCapture();break;case"close_fill_stroke":this.ctx.closePath(),this.paintFill(),this.paintStroke(),this.recordPaintForCapture();break;case"close_fill_stroke_even_odd":this.ctx.closePath(),this.paintFill("evenodd"),this.paintStroke(),this.recordPaintForCapture();break;case"clip":this.disableClip?this.logDebug("clip:skipped",{rule:"nonzero"}):this.ctx.clip();break;case"clip_even_odd":this.disableClip?this.logDebug("clip:skipped",{rule:"evenodd"}):this.ctx.clip("evenodd");break;case"begin_text":this.state.textMatrix=[1,0,0,1,0,0],this.state.textLineMatrix=[1,0,0,1,0,0];break;case"end_text":break;case"set_font":this.state.font=e.name,this.state.fontSize=e.size;break;case"set_text_matrix":this.state.textMatrix=[...e.matrix],this.state.textLineMatrix=[...e.matrix];break;case"move_text":this.state.textLineMatrix=Pe(this.state.textLineMatrix,[1,0,0,1,e.tx,e.ty]),this.state.textMatrix=[...this.state.textLineMatrix];break;case"move_text_set_leading":this.state.leading=-e.ty,this.state.textLineMatrix=Pe(this.state.textLineMatrix,[1,0,0,1,e.tx,e.ty]),this.state.textMatrix=[...this.state.textLineMatrix];break;case"next_line":this.state.textLineMatrix=Pe(this.state.textLineMatrix,[1,0,0,1,0,-this.state.leading]),this.state.textMatrix=[...this.state.textLineMatrix];break;case"set_char_spacing":this.state.charSpacing=e.spacing;break;case"set_word_spacing":this.state.wordSpacing=e.spacing;break;case"set_horiz_scale":this.state.horizScale=e.scale;break;case"set_leading":this.state.leading=e.leading;break;case"set_text_render":this.state.textRenderMode=e.mode;break;case"set_text_rise":this.state.textRise=e.rise;break;case"show_string":this.recordBreaker(),this.renderText(e.data);break;case"show_strings":this.recordBreaker();for(let o of e.items)if(o instanceof Uint8Array)this.renderText(o);else{let i=-(o/1e3)*this.state.fontSize*(this.state.horizScale/100);this.state.textMatrix=Pe(this.state.textMatrix,[1,0,0,1,i,0])}break;case"next_line_show_string":this.recordBreaker(),this.moveToNextTextLine(),this.renderText(e.data);break;case"set_spacing_next_line_show_string":this.recordBreaker(),this.state.wordSpacing=e.wordSpacing,this.state.charSpacing=e.charSpacing,this.moveToNextTextLine(),this.renderText(e.data);break;case"xobject":case"inline_image":break;case"set_fill_color_space":this.state.fillColorSpace=this.resolveColorSpaceName(e.name),this.fillColorResolver=this.buildComplexColorResolver(e.name);break;case"set_stroke_color_space":this.state.strokeColorSpace=this.resolveColorSpaceName(e.name),this.strokeColorResolver=this.buildComplexColorResolver(e.name);break;case"set_fill_color":if(this.forcedColor)break;if(this.state.fillColorSpace==="Pattern"&&e.patternName){this.state.fillPatternName=e.patternName;let o=this.resolvePatternFillStyle(e.patternName,"fill");this.ctx.fillStyle=o}else this.state.fillPatternName=null,this.state.fillPattern=null,this.state.fillColor=this.fillColorResolver?this.fillColorResolver(e.values):pn(this.state.fillColorSpace,e.values),this.ctx.fillStyle=Zt(this.state.fillColor);break;case"set_stroke_color":if(this.forcedColor)break;if(this.state.strokeColorSpace==="Pattern"&&e.patternName){this.state.strokePatternName=e.patternName;let o=this.resolvePatternFillStyle(e.patternName,"stroke");this.ctx.strokeStyle=o}else this.state.strokePatternName=null,this.state.strokePattern=null,this.state.strokeColor=this.strokeColorResolver?this.strokeColorResolver(e.values):pn(this.state.strokeColorSpace,e.values),this.ctx.strokeStyle=Zt(this.state.strokeColor);break;case"shade":this.renderShadeOperator(e.name);break;case"type3_glyph_width":case"begin_marked_content":case"end_marked_content":case"unknown":break}}moveToNextTextLine(){this.state.textLineMatrix=Pe(this.state.textLineMatrix,[1,0,0,1,0,-this.state.leading]),this.state.textMatrix=[...this.state.textLineMatrix]}renderText(e){var bn;if(e.length===0)return;let n=this.getCurrentFontInfo();if(n.isType3){this.renderType3Text(e,n);return}let r=this.decodeTextWithFont(e,n),o=Math.max(1,this.state.fontSize);this.ctx.font=cl(n,o);let i=ye=>this.measureGlyphWidthCached(ye),s=$f(e,r,n,o,this.state.charSpacing,this.state.wordSpacing,i),a=s.glyphs,c=a.map(ye=>ye.text).join("")||r;this.logDebug("text:before",{text:c,textLength:c.length,font:this.state.font,fontSize:o,textMatrix:this.state.textMatrix,fillColor:Zt(this.state.fillColor),textRise:this.state.textRise,horizScale:this.state.horizScale}),this.ctx.save();let l=this.state.textMatrix;this.ctx.transform(l[0],l[1],l[2],l[3],l[4],l[5]);let d=this.state.horizScale/100;d!==1&&this.ctx.scale(d,1);let m=this.state.textRise;this.ctx.font=cl(n,o),this.ctx.fillStyle=Zt(this.state.fillColor),this.ctx.globalAlpha=this.state.fillAlpha;let h=this.ctx.measureText(c),f=Math.max(1e-4,h.width),p=s.hasPdfMetrics?a.reduce((ye,Ke)=>ye+Ke.advance,0)*d:null,w=p!=null?p:f*d,y=Math.max(1,h.actualBoundingBoxAscent||o*.8),v=Math.max(1,h.actualBoundingBoxDescent||o*.2);this.ctx.scale(1,-1);let b=s.hasPdfMetrics&&a.length>0,C=f*Math.max(1e-4,d),S=p?Gf(w/C,.5,1.8):1;!b&&S!==1&&this.ctx.scale(S,1);let F=this.state.textRenderMode,T=F===0||F===2||F===4||F===6,N=F===1||F===2||F===5||F===6;T&&(this.ctx.fillStyle=Zt(this.state.fillColor)),N&&(this.ctx.strokeStyle=Zt(this.state.strokeColor),this.ctx.lineWidth=Math.max(.01,this.state.lineWidth/o));let O=(ye,Ke)=>{T&&(this.ctx.globalAlpha=this.state.fillAlpha,this.ctx.fillText(ye,Ke,-m)),N&&(this.ctx.globalAlpha=this.state.strokeAlpha,this.ctx.strokeText(ye,Ke,-m))};if(b){let ye=0;for(let Ke of a)Ke.text&&O(Ke.text,ye),ye+=Ke.advance}else O(c,0);this.ctx.restore();let A=[1,0,0,-1,0,this.pageHeight],H=Pe(Pe(A,this.state.ctm),l),ne=w,ie=Ue(H,0,m),I=[Ue(H,0,m+y),Ue(H,ne,m+y),Ue(H,ne,m-v),Ue(H,0,m-v)],ce=Math.min(...I.map(ye=>ye.x)),le=Math.max(...I.map(ye=>ye.x)),pe=Math.min(...I.map(ye=>ye.y)),De=Math.max(...I.map(ye=>ye.y)),_=ce*this.scale,K=pe*this.scale,G=Math.max(1,(le-ce)*this.scale),ae=Math.max(1,(De-pe)*this.scale),me=mn(this.state.fillColor),Xe=(bn=n.baseFontName)!=null?bn:this.state.font,Te=Pe(this.state.ctm,l),Me=Math.hypot(Te[1],Te[3]),lt=Math.max(1,o*(Me>.01?Me:1)),rt=this.capturedTextRuns.length,ot=0,Mt=a.map(ye=>{let Ke=s.hasPdfMetrics?ye.advance:f>0?this.measureGlyphWidthCached(ye.text)/f*(w/Math.max(1e-4,d)):0,_t=Ue(H,ot*d,m),ke=Ue(H,(ot+Ke)*d,m),Je=Math.min(_t.x,ke.x)*this.scale,Qe=Math.max(1,Math.abs(ke.x-_t.x)*this.scale);return ot+=Ke,{canvasX:Je,canvasY:K,canvasWidth:Qe,canvasHeight:ae,canvasBaselineY:ie.y*this.scale,char:ye.text,charCode:ye.code,runIndex:rt}});this.capturedTextRuns.push({index:rt,text:c,fontName:Xe,fontSize:lt,canvasX:_,canvasY:K,canvasWidth:G,canvasHeight:ae,canvasBaselineX:ie.x*this.scale,canvasBaselineY:ie.y*this.scale,fillColor:me,streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0,glyphs:Mt,fontFamily:ns(n)});let ft=p!=null?p:w;this.state.textMatrix=Pe(this.state.textMatrix,[1,0,0,1,ft,0]),this.logDebug("text:after",{text:c,measuredWidth:f,advance:ft,needsTextFlip:!0,bytesHexPreview:Array.from(e.slice(0,12)).map(ye=>ye.toString(16).padStart(2,"0")).join(" "),printableChars:Array.from(r).filter(ye=>ye>=" "&&ye<="~").length,totalChars:r.length,nextTextMatrix:this.state.textMatrix})}renderType3Text(e,n){var T,N,O,A,H,ne,ie,I;let r=n.type3CharProcs,o=n.type3Encoding;if(!r)return;let i=Math.max(1,this.state.fontSize),s=this.state.horizScale/100,a=this.state.textRise,c=(T=n.fontMatrix)!=null?T:[.001,0,0,.001,0,0],l=this.capturedTextRuns.length,d="";for(let ce=0;ce<e.length;ce++){let le=e[ce],pe=(N=n.encodingMap)==null?void 0:N.get(le);d+=pe!=null?pe:o&&(O=o.get(le))!=null?O:String.fromCharCode(le)}let m=[...this.state.textMatrix],h=[1,0,0,-1,0,this.pageHeight],f=this.pageResources;for(let ce=0;ce<e.length;ce++){let le=e[ce],pe=(A=o==null?void 0:o.get(le))!=null?A:".notdef",_=((ie=(ne=(H=n.widths)==null?void 0:H.get(le))!=null?ne:n.defaultWidth)!=null?ie:1e3)/1e3*i+this.state.charSpacing+(le===32?this.state.wordSpacing:0),K=r.entries.get(pe),G=K?this.resolveObject(K):void 0;if(G&&fe(G)){let ae=this.state.textMatrix,me=[i*s,0,0,i,0,a],Xe=Pe(Pe(ae,me),c),Te=[...this.state.textMatrix],Me=[...this.state.textLineMatrix];this.execute({op:"save_state"}),this.execute({op:"set_ctm",matrix:Xe}),n.type3Resources&&(this.pageResources=n.type3Resources),this.captureSuppressed+=1;try{let lt=we.decodeStreamSync(G),rt=qt(lt);for(let ot of rt)ot.op!=="type3_glyph_width"&&this.execute(ot)}catch{}finally{this.captureSuppressed-=1}this.pageResources=f,this.execute({op:"restore_state"}),this.state.textMatrix=Te,this.state.textLineMatrix=Me}this.state.textMatrix=Pe(this.state.textMatrix,[1,0,0,1,_,0])}let p=Pe(Pe(h,this.state.ctm),m),w=Ue(p,0,a),y=Pe(Pe(h,this.state.ctm),this.state.textMatrix),v=Ue(y,0,a),b=Math.min(w.x,v.x)*this.scale,C=(Math.min(w.y,v.y)-i)*this.scale,S=Math.max(1,Math.abs(v.x-w.x)*this.scale),F=Math.max(1,i*this.scale);this.capturedTextRuns.push({index:l,text:d,fontName:(I=n.baseFontName)!=null?I:this.state.font,fontSize:i,canvasX:b,canvasY:C,canvasWidth:S,canvasHeight:F,canvasBaselineX:w.x*this.scale,canvasBaselineY:w.y*this.scale,fillColor:mn(this.state.fillColor),streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0,glyphs:[],fontFamily:ns(n)})}commandPayload(e){return e.op==="show_string"?{text:this.decodeText(e.data),bytes:e.data.length}:e.op==="show_strings"?{items:e.items.map(n=>n instanceof Uint8Array?{type:"text",text:this.decodeText(n),bytes:n.length}:{type:"adjust",value:n})}:e}decodeText(e){return this.decodeTextWithFont(e,this.getCurrentFontInfo())}measureGlyphWidthCached(e){let n=`${this.ctx.font}|${e}`,r=this.glyphWidthCache.get(n);if(r!==void 0)return r;let o=this.ctx.measureText(e).width;return this.glyphWidthCache.set(n,o),o}async preloadEmbeddedFonts(){if(this.embeddedFamilies.clear(),!this.pageResources)return;let e=this.resolveObject(this.pageResources.entries.get("Font"));if(!e||!Q(e))return;let n=r=>this.resolveObject(r);for(let[r,o]of e.entries)try{let i=this.resolveObject(o);if(!i||!Q(i))continue;let a=Fe(i.entries.get("Subtype"))==="Type0"?sl(i,n):void 0,c=al(i,a,n),l=Jc(c,n);if(!l)continue;let d=await Zc(l);d&&this.embeddedFamilies.set(r,d)}catch{}}getCurrentFontInfo(){let e=this.state.font;if(!e)return Po();let n=this.fontCache.get(e);if(n)return n;let r=this.loadFontInfo(e);return this.fontCache.set(e,r),r}loadFontInfo(e){var H,ne,ie,I,ce,le,pe,De,_;if(!this.pageResources)return Po();let n=this.resolveObject(this.pageResources.entries.get("Font"));if(!n||!Q(n))return Po();let r=n.entries.get(e),o=this.resolveObject(r);if(!o||!Q(o))return Po();let i=nl.get(o);if(i)return i;let s=o.entries.get("Subtype"),a=(H=Fe(s))!=null?H:"Unknown",c=(ne=Fe(o.entries.get("BaseFont")))!=null?ne:void 0,l=a==="Type0",d=Math.floor((ie=q(o.entries.get("FirstChar")))!=null?ie:0),m=l?sl(o,K=>this.resolveObject(K)):void 0,h=al(o,m,K=>this.resolveObject(K)),f=l?Of(m):Tf(o,d),p=l?If(m):jf(o),w=o.entries.get("ToUnicode"),y=o.entries.get("Encoding"),v=null,b=this.resolveObject(w);if(b&&fe(b))try{let K=we.decodeStreamSync(b),G=new TextDecoder("latin1").decode(K),ae=vm(G);this.logFontDiagnostic(e,{subtype:a,isComposite:l,hasRawToUnicode:!!w,rawToUnicodeType:Qt(w),resolvedToUnicodeType:Qt(b),encoding:Qt(y),cmapRaw:ae}),this.debug&&tl.has(e)&&!el.has(e)&&(el.add(e),console.log(`=== Raw CMap text for ${e} (first 500 chars) ===`),console.log(G.slice(0,500)),console.log("===")),v=Vf(G),this.logDebug("font:cmap-parsed",{fontName:e,cmapType:v.cmapType,isUsable:v.isUsable,bfChar:v.bfChar.size,bfRange:v.bfRange.length,codeSpaceRanges:v.codeSpaceRanges.length}),v&&tl.has(e)&&Qf(v,e)}catch(K){this.logDebug("font:toUnicode-failed",{fontName:e,subtype:a,error:K instanceof Error?K.message:String(K)}),this.logFontDiagnostic(e,{subtype:a,isComposite:l,hasRawToUnicode:!!w,rawToUnicodeType:Qt(w),resolvedToUnicodeType:Qt(b),encoding:Qt(y),toUnicodeError:K instanceof Error?K.message:String(K)})}else this.logFontDiagnostic(e,{subtype:a,isComposite:l,hasRawToUnicode:!!w,rawToUnicodeType:Qt(w),resolvedToUnicodeType:Qt(b),encoding:Qt(y),note:l?"Composite font without resolved ToUnicode stream":"No ToUnicode stream"});if(!v&&l){let K=o.entries.get("Encoding");K&&K.type==="name"&&(K.value==="Identity-H"||K.value==="Identity-V")&&this.logDebug("font:identity-no-tounicode",{fontName:e,subtype:a,encoding:K.value})}let C;l||(C=Wf(y,K=>this.resolveObject(K)));let S=!1,F,T,N,O;if(a==="Type3"){S=!0;let K=this.resolveObject(o.entries.get("CharProcs"));K&&Q(K)&&(F=K);let G=o.entries.get("FontMatrix");if(G&&he(G)){let me=G.items;N=[(I=q(me[0]))!=null?I:.001,(ce=q(me[1]))!=null?ce:0,(le=q(me[2]))!=null?le:0,(pe=q(me[3]))!=null?pe:.001,(De=q(me[4]))!=null?De:0,(_=q(me[5]))!=null?_:0]}let ae=this.resolveObject(o.entries.get("Resources"));ae&&Q(ae)&&(O=ae),T=Hf(y,me=>this.resolveObject(me))}let A={subtype:a,baseFontName:c,fontWeight:Bf(c,h),fontStyle:Lf(c,h),isComposite:l,firstChar:d,widths:f,defaultWidth:p,toUnicode:v,encodingMap:C,isType3:S,type3CharProcs:F,type3Encoding:T,fontMatrix:N,type3Resources:O,registeredFamily:this.embeddedFamilies.get(e)};return this.logDebug("font:loaded",{fontName:e,subtype:a,isComposite:l,hasToUnicode:!!v}),nl.set(o,A),A}logFontDiagnostic(e,n){if(!this.debug)return;let r=`${e}|${String(n.subtype)}|${String(n.rawToUnicodeType)}|${String(n.resolvedToUnicodeType)}`;this.fontDiagnosticsLogged.has(r)||(this.fontDiagnosticsLogged.add(r),console.info("[PageRenderer][FontDiag]",{font:e,...n}))}resolveObject(e){if(e){if(!Be(e))return e;if(this.objectLoader)try{return this.objectLoader(e)}catch{return}}}resolveColorSpaceName(e){var i;let n=Ft(e);if(n)return n;if(!this.pageResources)return e;let r=this.resolveObject(this.pageResources.entries.get("ColorSpace"));if(!r||!Q(r))return e;let o=this.resolveObject(r.entries.get(e));return(i=ol(o))!=null?i:e}buildComplexColorResolver(e){var f;if(Ft(e))return null;let n=this.separationColorCache.get(e);if(n)return n;if(!this.pageResources||!this.objectLoader)return null;let r=this.resolveObject(this.pageResources.entries.get("ColorSpace"));if(!r||!Q(r))return null;let o=this.resolveObject(r.entries.get(e));if(!o||!he(o)||o.items.length<2)return null;let i=Fe(o.items[0]);if(i!=="Separation"&&i!=="DeviceN")return null;let s=2,a=3,c=o.items[s]?this.resolveObject(o.items[s]):void 0,l=(f=ol(c))!=null?f:"DeviceGray",d=o.items[a],m=this.objectLoader,h=p=>{var v;let w=(v=p[0])!=null?v:0,y=bo(d,w,m);return y&&y.length>0?pn(l,y):l==="DeviceCMYK"?{space:"cmyk",c:0,m:0,y:0,k:w}:{space:"gray",gray:1-w}};return this.separationColorCache.set(e,h),h}async renderXObject(e){if(!this.pageResources)return;let n=this.resolveObject(this.pageResources.entries.get("XObject"));if(!n||!Q(n))return;let r=this.resolveObject(n.entries.get(e));if(!r||!fe(r))return;let o=Fe(r.dict.entries.get("Subtype"));if(o==="Image"){this.captureImageBox("xobject",e),await this.renderImageXObject(r);return}if(o==="Form")try{let i=r,s=this.resolveObject(i.dict.entries.get("Resources")),c=await(i.decode?i.decode():Promise.resolve(we.decodeStreamSync(i))),l=qt(c instanceof Uint8Array?c:new Uint8Array(await c)),d=this.pageResources,m=this.objectLoader,h=this.patternCache;this.patternCache=new Map,this.pageResources=s&&Q(s)?s:this.pageResources;let f=this.resolveObject(i.dict.entries.get("Group")),y=!!f&&Q(f)&&Fe(f.entries.get("S"))==="Transparency"&&(this.state.fillAlpha<1||this.state.strokeAlpha<1||this.state.blendMode!=="Normal")&&this.pushLayer("group",this.state.fillAlpha,this.state.blendMode,null);this.execute({op:"save_state"}),y&&(this.state.fillAlpha=1,this.state.strokeAlpha=1,this.state.blendMode="Normal",this.ctx.globalAlpha=1,this.ctx.globalCompositeOperation="source-over");let v=i.dict.entries.get("Matrix");if(v&&Array.isArray(v.items))try{let C=v.items.map(S=>{var F;return Number((F=q(S))!=null?F:0)});this.execute({op:"set_ctm",matrix:C})}catch{}let b=this.commandIndex;this.xobjectDepth+=1;try{await this.runCommandsAsync(l)}finally{this.xobjectDepth-=1,this.commandIndex=b}this.execute({op:"restore_state"}),y&&this.popLayer(),this.pageResources=d,this.objectLoader=m,this.patternCache=h;return}catch(i){this.logDebug("xobject:form-failed",{name:e,error:i instanceof Error?i.message:String(i)});return}}resolveImageColorSpace(e){var r,o,i;if(!e)return"DeviceRGB";let n=Fe(e);if(n)return(r=Ft(n))!=null?r:n;if(he(e)&&e.items.length>0){let s=Fe(e.items[0]);if(s==="ICCBased"){let a=this.resolveObject(e.items[1]);if(a&&fe(a)){let c=Math.floor((o=q(a.dict.entries.get("N")))!=null?o:3);return c===1?"DeviceGray":c===4?"DeviceCMYK":"DeviceRGB"}return"DeviceRGB"}if(s==="Indexed")return"Indexed";if(s==="CalRGB")return"DeviceRGB";if(s==="CalGray")return"DeviceGray";if(s)return(i=Ft(s))!=null?i:s}return"DeviceRGB"}resolveDecodeParms(e){var r;let n=this.resolveObject((r=e.entries.get("DecodeParms"))!=null?r:e.entries.get("DP"));if(!n)return null;if(Q(n))return n;if(he(n))for(let o of n.items){let i=this.resolveObject(o);if(i&&Q(i))return i}return null}async decodeJbig2(e){var r;let n=(r=e.rawBytes)!=null?r:e.data;if(!n||n.length===0)return null;try{let{Jbig2Image:o}=await vo(),i,s=this.resolveDecodeParms(e.dict);if(s){let l=this.resolveObject(s.entries.get("JBIG2Globals"));if(l&&fe(l))try{i=we.decodeStreamSync(l)}catch{}}let a=[];i&&i.length>0&&a.push({data:i,start:0,end:i.length}),a.push({data:n,start:0,end:n.length});let c=new o().parseChunks(a);for(let l=0;l<c.length;l++)c[l]^=255;return c}catch(o){return this.logDebug("xobject:jbig2-failed",{error:o instanceof Error?o.message:String(o)}),null}}async decodeCcitt(e,n,r){var i;let o=(i=e.rawBytes)!=null?i:e.data;if(!o||o.length===0)return null;try{let{CCITTFaxDecoder:s}=await vo(),a=this.resolveDecodeParms(e.dict),c=(S,F)=>{var T;return a?Math.floor((T=q(a.entries.get(S)))!=null?T:F):F},l=(S,F)=>{let T=a==null?void 0:a.entries.get(S);return T&&typeof T=="object"&&"type"in T&&T.type==="boolean"?T.value:F},d=c("Columns",1728),m=c("Rows",r),h=0,f={next:()=>h<o.length?o[h++]:-1},p=new s(f,{K:c("K",0),EndOfLine:l("EndOfLine",!1),EncodedByteAlign:l("EncodedByteAlign",!1),Columns:d,Rows:m,EndOfBlock:l("EndOfBlock",!0),BlackIs1:l("BlackIs1",!1)}),y=(d+7>>3)*(m>0?m:r),v=new Uint8Array(y),b=0,C;for(;b<y&&(C=p.readNextChar())!==-1;)v[b++]=C;return b>0?v.subarray(0,b):null}catch(s){return this.logDebug("xobject:ccitt-failed",{error:s instanceof Error?s.message:String(s)}),null}}drawRgbaImageData(e,n,r){let o=document.createElement("canvas");o.width=n,o.height=r;let i=o.getContext("2d");i&&(i.putImageData(e,0,0),this.drawImageBitmapLike(o))}async renderImageXObject(e){var h,f,p,w;let n=e.dict,r=Math.floor((h=q(n.entries.get("Width")))!=null?h:0),o=Math.floor((f=q(n.entries.get("Height")))!=null?f:0);if(r<=0||o<=0)return;let i=il(n.entries.get("Filter")),s=Math.floor((p=q(n.entries.get("BitsPerComponent")))!=null?p:8),a=n.entries.get("ImageMask"),c=a!=null&&typeof a=="object"&&"type"in a&&a.type==="boolean"&&a.value===!0||Fe(a)==="true",l=this.resolveImageColorSpace(n.entries.get("ColorSpace")),d=i.includes("JBIG2Decode"),m=i.includes("CCITTFaxDecode")||i.includes("CCF");try{let y=null;if(d?y=await this.decodeJbig2(e):m&&(y=await this.decodeCcitt(e,r,o)),(d||m)&&!y)return;if(c){await this.renderStencilMask(e,r,o,y);return}if(!d&&!m&&(i.includes("DCTDecode")||i.includes("DCT"))){let v=(w=e.rawBytes)!=null?w:e.data;if(!v)return;if(l==="DeviceCMYK"){await this.renderJpegViaPdfjs(e,v,r,o);return}let b=this.resolveObject(n.entries.get("SMask"));if(b&&fe(b))await this.renderImageWithSMask(v,"image/jpeg",b,r,o);else{let C=await Ji(v,"image/jpeg");this.drawImageBitmapLike(C),Zi(C)}return}if(!d&&!m&&i.includes("JPXDecode")){await this.renderJpxViaPdfjs(e,r,o);return}if(!y&&i.some(v=>!Mf.has(v)))return;if(s===1||s===2||s===4||s===8||s===16){let v=y!=null?y:we.decodeStreamSync(e),b=null;if(l==="Indexed"){let S=n.entries.get("ColorSpace"),F=N=>this.resolveObject(N),T=Qi(v,r,o,1,s,!1);b=zf(T,r,o,S&&he(S)?S.items:[],F)}else{let S=_f(l),F=Qi(v,r,o,S,s,!0);b=Xf(F,r,o,l)}if(!b)return;Rf(b,ht(n.entries.get("Decode")),l);let C=this.resolveObject(n.entries.get("SMask"));if(C&&fe(C))try{let S=await this.decodeSMaskAlpha(C,r,o);ko(b,S,r,o)}catch{}this.drawRgbaImageData(b,r,o)}}catch(y){this.logDebug("xobject:image-failed",{width:r,height:o,colorSpace:l,bitsPerComponent:s,filters:i,error:y instanceof Error?y.message:String(y)})}}async renderJpegViaPdfjs(e,n,r,o){let{JpegImage:i}=await vo(),s=new i;s.parse(n);let a=s.getData({width:r,height:o,forceRGBA:!0,isSourcePDF:!0});if(a.length<r*o*4)return;let c=new ImageData(new Uint8ClampedArray(a.subarray(0,r*o*4)),r,o),l=this.resolveObject(e.dict.entries.get("SMask"));if(l&&fe(l))try{let d=await this.decodeSMaskAlpha(l,r,o);ko(c,d,r,o)}catch{}this.drawRgbaImageData(c,r,o)}async renderJpxViaPdfjs(e,n,r){var w,y,v;let o=(w=e.rawBytes)!=null?w:e.data;if(!o)return;let{JpxImage:i}=await vo(),s=new i;s.parse(o);let a=s.width||n,c=s.height||r,l=s.componentsCount||1,d=(v=(y=s.tiles)==null?void 0:y[0])==null?void 0:v.items;if(!d)return;let m=a*c,h=new Uint8ClampedArray(m*4);for(let b=0,C=0;b<m;b++,C+=4){let S=b*l;if(l>=4){let F=d[S],T=d[S+1],N=d[S+2],O=d[S+3];h[C]=255-Math.min(255,F+O),h[C+1]=255-Math.min(255,T+O),h[C+2]=255-Math.min(255,N+O)}else l===3?(h[C]=d[S],h[C+1]=d[S+1],h[C+2]=d[S+2]):h[C]=h[C+1]=h[C+2]=d[S];h[C+3]=255}let f=new ImageData(h,a,c),p=this.resolveObject(e.dict.entries.get("SMask"));if(p&&fe(p))try{let b=await this.decodeSMaskAlpha(p,a,c);ko(f,b,a,c)}catch{}this.drawRgbaImageData(f,a,c)}async renderInlineImage(e,n){var l;this.captureImageBox("inline",null);let r={W:"Width",H:"Height",BPC:"BitsPerComponent",CS:"ColorSpace",F:"Filter",IM:"ImageMask",D:"Decode",DP:"DecodeParms",I:"Interpolate"},o={AHx:"ASCIIHexDecode",A85:"ASCII85Decode",LZW:"LZWDecode",Fl:"FlateDecode",RL:"RunLengthDecode",CCF:"CCITTFaxDecode",DCT:"DCTDecode"},i={G:"DeviceGray",RGB:"DeviceRGB",CMYK:"DeviceCMYK",I:"Indexed"},s=(d,m)=>d&&"type"in d&&d.type==="name"&&m[d.value]?{type:"name",value:m[d.value]}:d,a=new Map;for(let[d,m]of e.entries){let h=(l=r[d])!=null?l:d,f=m;if(h==="Filter")f=he(m)?{type:"array",items:m.items.map(p=>s(p,o))}:s(m,o);else if(h==="ColorSpace")if(m&&"type"in m&&m.type==="name"&&!i[m.value]&&!["DeviceGray","DeviceRGB","DeviceCMYK","Indexed"].includes(m.value)){let p=this.lookupResource("ColorSpace",m.value);f=p!=null?p:m}else f=s(m,i);a.set(h,f)}let c={type:"stream",dict:{type:"dict",entries:a},data:n,rawBytes:n};await this.renderImageXObject(c)}lookupResource(e,n){if(!this.pageResources)return;let r=this.resolveObject(this.pageResources.entries.get(e));if(!(!r||!Q(r)))return this.resolveObject(r.entries.get(n))}async decodeSMaskAlpha(e,n,r){var m,h,f,p;let o=il(e.dict.entries.get("Filter")),i=o.includes("JPXDecode");if(o.includes("DCTDecode")||o.includes("DCT")||i){let w=(m=e.rawBytes)!=null?m:e.data;if(w&&w.length>0){let y=await Ji(w,i?"image/jp2":"image/jpeg");try{let v=document.createElement("canvas");v.width=n,v.height=r;let b=v.getContext("2d");if(b){b.drawImage(y,0,0,n,r);let{data:C}=b.getImageData(0,0,n,r),S=new Uint8Array(n*r);for(let F=0;F<S.length;F++)S[F]=C[F*4];return S}}finally{Zi(y)}}}let a=we.decodeStreamSync(e),c=Math.floor((h=q(e.dict.entries.get("BitsPerComponent")))!=null?h:8);if(c===8)return a;let l=Math.floor((f=q(e.dict.entries.get("Width")))!=null?f:n),d=Math.floor((p=q(e.dict.entries.get("Height")))!=null?p:r);return Qi(a,l,d,1,c,!0)}async renderImageWithSMask(e,n,r,o,i){let s=await Ji(e,n);try{let a=document.createElement("canvas");a.width=o,a.height=i;let c=a.getContext("2d");if(!c){this.drawImageBitmapLike(s);return}c.drawImage(s,0,0,o,i);let l=c.getImageData(0,0,o,i);try{let d=await this.decodeSMaskAlpha(r,o,i);ko(l,d,o,i)}catch{}c.putImageData(l,0,0),this.drawImageBitmapLike(a)}finally{Zi(s)}}async renderStencilMask(e,n,r,o){try{let i=o!=null?o:we.decodeStreamSync(e),s=mn(this.state.fillColor),a=Math.round(s.r*255),c=Math.round(s.g*255),l=Math.round(s.b*255),d=n*r,m=new Uint8ClampedArray(d*4),h=ht(e.dict.entries.get("Decode")),f=!!h&&h.length>=2&&h[0]===1&&h[1]===0,p=0;for(let v=0;v<i.length&&p<d;v++){let b=i[v];for(let C=7;C>=0&&p<d;C--){let S=b>>C&1,F=p*4;S===1!==f&&(m[F]=a,m[F+1]=c,m[F+2]=l,m[F+3]=255),p++}}let w=document.createElement("canvas");w.width=n,w.height=r;let y=w.getContext("2d");if(!y)return;y.putImageData(new ImageData(m,n,r),0,0),this.drawImageBitmapLike(w)}catch(i){this.logDebug("xobject:stencil-mask-failed",{error:i instanceof Error?i.message:String(i)})}}drawImageBitmapLike(e){this.ctx.save(),this.ctx.transform(1,0,0,-1,0,1),this.ctx.drawImage(e,0,0,1,1),this.ctx.restore()}decodeTextWithFont(e,n){var r;if(e.length===0)return"";if(this.debug){let o=String(this.state.font||"").toLowerCase();if(o==="f1"||o==="f2"){let i=Array.from(e.subarray(0,24)).map(a=>a.toString(16).padStart(2,"0")).join(" "),s=`${o}|${i}`;this.rawByteDiagnosticsLogged.has(s)||(this.rawByteDiagnosticsLogged.add(s),console.log(`[${o} RAW BYTES] ${i}`))}}if(n.toUnicode)return!n.toUnicode.isUsable&&n.isComposite?tm(e,n.toUnicode):em(e,n.toUnicode,n.isComposite,this.state.font,this.debug);if(n.isComposite)return gl(e);if(n.encodingMap&&n.encodingMap.size>0){let o="";for(let i of e)o+=(r=n.encodingMap.get(i))!=null?r:String.fromCharCode(i);return o}return new TextDecoder("latin1").decode(e)}logDebug(e,n){this.debug&&console.debug(`[PageRenderer] ${e}`,n)}captureAtomicState(){return{transform:this.ctx.getTransform(),lineWidth:this.ctx.lineWidth,fillStyle:String(this.ctx.fillStyle),strokeStyle:String(this.ctx.strokeStyle),stackDepth:this.stateStack.length,samples:this.samplePixels()}}samplePixels(){let e=this.canvas.width,n=this.canvas.height;if(e<=0||n<=0)return[];let r=[[1,1],[Math.max(1,Math.floor(e/2)),Math.max(1,Math.floor(n/2))],[Math.max(1,e-2),Math.max(1,n-2)],[Math.max(1,Math.floor(e*.25)),Math.max(1,Math.floor(n*.25))],[Math.max(1,Math.floor(e*.75)),Math.max(1,Math.floor(n*.75))]],o=[],i=this.ctx.getTransform();this.ctx.setTransform(1,0,0,1,0,0);try{for(let[s,a]of r){let c=this.ctx.getImageData(Math.min(e-1,s),Math.min(n-1,a),1,1).data;o.push([c[0],c[1],c[2],c[3]])}}finally{this.ctx.setTransform(i.a,i.b,i.c,i.d,i.e,i.f)}return o}logAtomic(e,n,r,o){if(!this.debugAtomic||this.atomicLogCount>=this.maxAtomicLogs)return;let i=JSON.stringify(r.samples),s=JSON.stringify(o.samples),a=i!==s;!(n.op==="stroke"||n.op==="fill"||n.op==="fill_even_odd"||n.op==="fill_stroke"||n.op==="show_string"||n.op==="show_strings")&&!a||(this.atomicLogCount+=1,console.debug("[PageRenderer][atomic]",{index:e,op:n.op,stackDepthBefore:r.stackDepth,stackDepthAfter:o.stackDepth,transformBefore:[r.transform.a,r.transform.b,r.transform.c,r.transform.d,r.transform.e,r.transform.f],transformAfter:[o.transform.a,o.transform.b,o.transform.c,o.transform.d,o.transform.e,o.transform.f],lineWidthBefore:r.lineWidth,lineWidthAfter:o.lineWidth,fillStyleBefore:r.fillStyle,fillStyleAfter:o.fillStyle,strokeStyleBefore:r.strokeStyle,strokeStyleAfter:o.strokeStyle,pixelChanged:a,samplesBefore:r.samples,samplesAfter:o.samples}))}applyExtGState(e){var p,w,y;if(!this.pageResources)return;let n=this.resolveObject(this.pageResources.entries.get("ExtGState"));if(!n||!Q(n))return;let r=this.resolveObject(n.entries.get(e));if(!r||!Q(r))return;let o=r,i=q(o.entries.get("LW"));i!==null&&(this.state.lineWidth=i,this.ctx.lineWidth=i);let s=q(o.entries.get("LC"));if(s!==null){let v=Math.floor(s),b=["butt","round","square"];this.state.lineCap=v,this.ctx.lineCap=(p=b[v])!=null?p:"butt"}let a=q(o.entries.get("LJ"));if(a!==null){let v=Math.floor(a),b=["miter","round","bevel"];this.state.lineJoin=v,this.ctx.lineJoin=(w=b[v])!=null?w:"miter"}let c=q(o.entries.get("ML"));c!==null&&(this.state.miterLimit=c,this.ctx.miterLimit=c);let l=o.entries.get("D");if(l&&he(l)&&l.items.length>=1){let v=l.items[0],b=(y=q(l.items[1]))!=null?y:0;if(he(v)){let C=v.items.map(S=>{var F;return(F=q(S))!=null?F:0});this.state.dashArray=C,this.state.dashPhase=b,this.ctx.setLineDash(C),this.ctx.lineDashOffset=b}}let d=q(o.entries.get("CA"));d!==null&&(this.state.strokeAlpha=qe(d));let m=q(o.entries.get("ca"));m!==null&&(this.state.fillAlpha=qe(m));let h=o.entries.get("BM"),f=Fe(h);f&&(this.state.blendMode=f,this.ctx.globalCompositeOperation=rl(f))}deviceBase(){if(this.initialTransform)return this.initialTransform;let e=this.scale;return[e,0,0,-e,0,e*this.pageHeight]}applyCurrentTransform(){let e=Pe(this.deviceBase(),this.state.ctm);this.ctx.setTransform(e[0],e[1],e[2],e[3],e[4],e[5])}resolvePatternFillStyle(e,n){var r,o,i;try{if(!this.pageResources||!this.objectLoader)return"transparent";let s=this.resolveObject(this.pageResources.entries.get("Pattern"));if(!s||!Q(s))return"transparent";let a=this.resolveObject(s.entries.get(e));if(!a||!Q(a)||Math.floor((r=q(a.entries.get("PatternType")))!=null?r:0)!==2)return"transparent";let l=this.resolveObject(a.entries.get("Shading"));if(!l||!Q(l))return"transparent";let d=(o=wr(a.entries.get("Matrix")))!=null?o:[1,0,0,1,0,0];return(i=this.createCanvasGradient(l,d))!=null?i:"transparent"}catch{return"transparent"}}async resolvePattern(e,n){var s,a;let r=`${e}|${Zt(n)}`,o=this.patternCache.get(r);if(o!==void 0)return o;let i=null;try{if(this.pageResources&&this.objectLoader){let c=this.resolveObject(this.pageResources.entries.get("Pattern")),l=c&&Q(c)?this.resolveObject(c.entries.get(e)):void 0,d=l?fe(l)?l.dict:Q(l)?l:null:null;if(d){let m=Math.floor((s=q(d.entries.get("PatternType")))!=null?s:0),h=(a=wr(d.entries.get("Matrix")))!=null?a:[1,0,0,1,0,0];if(m===2){let f=this.resolveObject(d.entries.get("Shading")),p=f?fe(f)?f.dict:Q(f)?f:null:null;p&&(i={kind:"shading",shading:p,stream:f&&fe(f)?f:null,matrix:h})}else m===1&&l&&fe(l)&&(i=await this.renderTilingCell(l,d,h,n))}}}catch{i=null}return this.patternCache.set(r,i),i}async applyPatternColor(e,n,r){let o=e==="fill"?this.state.fillColor:this.state.strokeColor,i=r.length>=4?{space:"cmyk",c:r[0],m:r[1],y:r[2],k:r[3]}:r.length===3?{space:"rgb",r:r[0],g:r[1],b:r[2]}:r.length===1?{space:"gray",gray:r[0]}:o,s=await this.resolvePattern(n,i);e==="fill"?(this.state.fillPatternName=n,this.state.fillPattern=s,s||(this.ctx.fillStyle="transparent")):(this.state.strokePatternName=n,this.state.strokePattern=s,s||(this.ctx.strokeStyle="transparent"))}async renderTilingCell(e,n,r,o){var T,N,O,A;if(this.patternDepth>=4)return null;let i=ht(n.entries.get("BBox"));if(!i||i.length<4)return null;let s=[i[0],i[1],i[2],i[3]],a=s[2]-s[0],c=s[3]-s[1],l=(T=q(n.entries.get("XStep")))!=null?T:a,d=(N=q(n.entries.get("YStep")))!=null?N:c,m=Math.abs(l)<1e-9?a:l,h=Math.abs(d)<1e-9?c:d,f=Math.floor((O=q(n.entries.get("PaintType")))!=null?O:1),p=Pe(this.deviceBase(),r),w=Gc(s,m,h,p);if(!w)return null;let y=document.createElement("canvas"),v=new Jn(y,w.cellPxW,w.cellPxH,1,{disableClip:this.disableClip,transparentBackground:!0,initialTransform:w.contentTransform,forcedColor:f===2?o:void 0,patternDepth:this.patternDepth+1}),b=this.resolveObject(n.entries.get("Resources"));v.setFontContext(b&&Q(b)?b:void 0,(A=this.objectLoader)!=null?A:void 0);let C=e.decode?await e.decode():we.decodeStreamSync(e),S=qt(C),F=a>0&&c>0?[{op:"rect",x:s[0],y:s[1],w:a,h:c},{op:"clip"},{op:"end_path"}]:[];return await v.renderAsync([...F,...S]),{kind:"tiling",cell:y,layout:w,matrix:r}}paintFill(e){let n=this.state.fillPattern;if(!n){this.ctx.globalAlpha=this.state.fillAlpha,e?this.ctx.fill(e):this.ctx.fill();return}this.paintPatternThroughPath(n,this.state.fillAlpha,e!=null?e:"nonzero")}paintStroke(){let e=this.state.strokePattern;if(this.ctx.globalAlpha=this.state.strokeAlpha,e)if(e.kind==="tiling"){let c=this.ctx.createPattern(e.cell,"repeat");c&&(this.ctx.strokeStyle=c)}else{let c=this.createCanvasGradient(e.shading,e.matrix);c&&(this.ctx.strokeStyle=c)}let n=this.deviceBase(),r=Math.sqrt(Math.abs(n[0]*n[3]-n[1]*n[2]))||1,o=this.state.ctm,i=Math.sqrt(Math.abs(o[0]*o[3]-o[1]*o[2]))||1,s=r*i,a=this.state.lineWidth*s;this.ctx.lineWidth=this.state.lineWidth===0||a<1?1/s:this.state.lineWidth,this.ctx.stroke()}paintPatternThroughPath(e,n,r){this.ctx.save();try{this.ctx.globalAlpha=n,this.ctx.clip(r);let o=Pe(this.deviceBase(),e.matrix);if(e.kind==="tiling"){let i=this.ctx.createPattern(e.cell,"repeat");if(!i)return;let s=Pe(o,e.layout.paintTransform);this.ctx.setTransform(s[0],s[1],s[2],s[3],s[4],s[5]),this.ctx.fillStyle=i,this.floodCanvasExtent(s,Math.max(e.layout.cellPxW,e.layout.cellPxH))}else this.paintShadingBackground(e.shading,o),this.paintShadingWithBase(e.shading,e.stream,o)}finally{this.ctx.restore()}}paintShadingBackground(e,n){var a,c;let r=ht(e.entries.get("Background"));if(!r||!r.length)return;let o=(a=Fe(e.entries.get("ColorSpace")))!=null?a:"DeviceRGB",i=(c=Ft(o))!=null?c:"DeviceRGB",s=mn(pn(i,r));this.ctx.save(),this.ctx.setTransform(n[0],n[1],n[2],n[3],n[4],n[5]),this.ctx.fillStyle=Ct(s.r,s.g,s.b),this.floodCanvasExtent(n,0),this.ctx.restore()}paintShadingWithBase(e,n,r){var i;let o=Math.floor((i=q(e.entries.get("ShadingType")))!=null?i:0);if(o===2||o===3){let s=this.createCanvasGradient(e);if(!s)return;this.ctx.save(),this.ctx.setTransform(r[0],r[1],r[2],r[3],r[4],r[5]),this.ctx.fillStyle=s,this.floodCanvasExtent(r,0),this.ctx.restore();return}if(o===1){this.paintFunctionShading(e,r);return}o>=4&&o<=7&&n&&this.paintMeshShading(o,e,n,r)}paintFunctionShading(e,n){var C,S,F,T,N,O,A,H;if(!this.objectLoader)return;let r=e.entries.get("Function");if(!r)return;let o=(C=ht(e.entries.get("Domain")))!=null?C:[0,1,0,1],[i,s,a,c]=[(S=o[0])!=null?S:0,(F=o[1])!=null?F:1,(T=o[2])!=null?T:0,(N=o[3])!=null?N:1];if(!(s>i)||!(c>a))return;let l=(O=wr(e.entries.get("Matrix")))!=null?O:[1,0,0,1,0,0],d=(A=Fe(e.entries.get("ColorSpace")))!=null?A:"DeviceRGB",m=(H=Ft(d))!=null?H:"DeviceRGB",h=128,f=128,p=new ImageData(h,f);for(let ne=0;ne<f;ne++){let ie=a+(ne+.5)/f*(c-a);for(let I=0;I<h;I++){let ce=i+(I+.5)/h*(s-i),le=Wi(r,[ce,ie],this.objectLoader);if(!le)continue;let pe=mn(pn(m,le)),De=(ne*h+I)*4;p.data[De]=Math.round(pe.r*255),p.data[De+1]=Math.round(pe.g*255),p.data[De+2]=Math.round(pe.b*255),p.data[De+3]=255}}let w=document.createElement("canvas");w.width=h,w.height=f;let y=w.getContext("2d");if(!y)return;y.putImageData(p,0,0);let v=[(s-i)/h,0,0,(c-a)/f,i,a],b=Pe(Pe(n,l),v);this.ctx.save(),this.ctx.setTransform(b[0],b[1],b[2],b[3],b[4],b[5]),this.ctx.drawImage(w,0,0),this.ctx.restore()}paintMeshShading(e,n,r,o){var v,b,C,S,F,T;if(!this.objectLoader)return;let i=this.objectLoader,s=this.meshCache.get(n);if(!s){try{let N=we.decodeStreamSync(r),O=(v=Fe(n.entries.get("ColorSpace")))!=null?v:"DeviceRGB",A=(b=Ft(O))!=null?b:"DeviceRGB",H=n.entries.get("Function"),ne=H?1:Ff(A),ie=ht(n.entries.get("Decode"));if(!ie)return;let I=ce=>{var De;let le=H&&(De=Wi(H,ce,i))!=null?De:ce,pe=mn(pn(A,le));return[pe.r,pe.g,pe.b]};s=Kc(e,{bitsPerCoordinate:Math.floor((C=q(n.entries.get("BitsPerCoordinate")))!=null?C:16),bitsPerComponent:Math.floor((S=q(n.entries.get("BitsPerComponent")))!=null?S:8),bitsPerFlag:Math.floor((F=q(n.entries.get("BitsPerFlag")))!=null?F:8),decode:ie,numColorComponents:ne,verticesPerRow:(T=q(n.entries.get("VerticesPerRow")))!=null?T:void 0},N,I)}catch{s=[]}this.meshCache.set(n,s)}if(!s.length)return;let a=1/0,c=1/0,l=-1/0,d=-1/0;for(let N of s)for(let[O,A]of N.p){let H=Ue(o,O,A);H.x<a&&(a=H.x),H.x>l&&(l=H.x),H.y<c&&(c=H.y),H.y>d&&(d=H.y)}a=Math.max(0,Math.floor(a)),c=Math.max(0,Math.floor(c)),l=Math.min(this.canvas.width,Math.ceil(l)),d=Math.min(this.canvas.height,Math.ceil(d));let m=Math.min(4096,l-a),h=Math.min(4096,d-c);if(m<=0||h<=0)return;let f=Pe([1,0,0,1,-a,-c],o),p=Vc(s,f,m,h),w=document.createElement("canvas");w.width=m,w.height=h;let y=w.getContext("2d");y&&(y.putImageData(new ImageData(p,m,h),0,0),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(w,a,c),this.ctx.restore())}floodCanvasExtent(e,n){let r=Gn(e);if(!r)return;let o=this.canvas.width,i=this.canvas.height,s=[Ue(r,0,0),Ue(r,o,0),Ue(r,0,i),Ue(r,o,i)],a=s.map(f=>f.x),c=s.map(f=>f.y),l=Math.min(...a)-n,d=Math.min(...c)-n,m=Math.max(...a)+n,h=Math.max(...c)+n;this.ctx.fillRect(l,d,m-l,h-d)}createCanvasGradient(e,n){var y,v,b,C;let r=Math.floor((y=q(e.entries.get("ShadingType")))!=null?y:0),o=(v=Fe(e.entries.get("ColorSpace")))!=null?v:"DeviceRGB",i=(b=Ft(o))!=null?b:"DeviceRGB",s=e.entries.get("Function"),a=(C=ht(e.entries.get("Domain")))!=null?C:[0,1],[c,l]=Nf(e.entries.get("Extend")),d=S=>{var N,O;let F=a[0]+S*(((N=a[1])!=null?N:1)-a[0]),T=this.objectLoader?(O=bo(s,F,this.objectLoader))!=null?O:[0]:[0];return mn(pn(i,T))},m=S=>`rgb(${Math.round(S.r*255)},${Math.round(S.g*255)},${Math.round(S.b*255)})`,h=S=>`rgba(${Math.round(S.r*255)},${Math.round(S.g*255)},${Math.round(S.b*255)},0)`,f=ht(e.entries.get("Coords"));if(!f)return null;let p=(S,F)=>n?[n[0]*S+n[2]*F+n[4],n[1]*S+n[3]*F+n[5]]:[S,F],w=S=>{let T=.000244140625,N=c?0:T,O=l?1:1-T;c||S.addColorStop(0,h(d(0)));for(let A=0;A<=64;A++){let H=A/64;S.addColorStop(N+H*(O-N),m(d(H)))}l||S.addColorStop(1,h(d(1)))};try{if(r===2){let[S,F,T,N]=f,[O,A]=p(S,F),[H,ne]=p(T,N),ie=this.ctx.createLinearGradient(O,A,H,ne);return w(ie),ie}if(r===3){let[S,F,T,N,O,A]=f,[H,ne]=p(S,F),[ie,I]=p(N,O),ce=n?(Math.hypot(n[0],n[1])+Math.hypot(n[2],n[3]))/2:1,le=this.ctx.createRadialGradient(H,ne,Math.max(0,T*ce),ie,I,Math.max(0,A*ce));return w(le),le}}catch{return null}return null}acquireLayerCanvas(){var n;let e=(n=this.layerPool.pop())!=null?n:document.createElement("canvas");if(e.width!==this.canvas.width||e.height!==this.canvas.height)e.width=this.canvas.width,e.height=this.canvas.height;else{let r=e.getContext("2d");if(!r)return null;r.save(),r.setTransform(1,0,0,1,0,0),r.clearRect(0,0,e.width,e.height),r.restore()}return e}releaseLayerCanvas(e){this.layerPool.length<Jn.MAX_LAYER_DEPTH&&this.layerPool.push(e)}pushLayer(e,n,r,o){if(this.layerStack.length>=Jn.MAX_LAYER_DEPTH)return!1;let i=this.acquireLayerCanvas(),s=i==null?void 0:i.getContext("2d");return!i||!s?!1:(s.setTransform(this.ctx.getTransform()),s.lineWidth=this.ctx.lineWidth,s.lineCap=this.ctx.lineCap,s.lineJoin=this.ctx.lineJoin,s.miterLimit=this.ctx.miterLimit,s.setLineDash(this.ctx.getLineDash()),s.lineDashOffset=this.ctx.lineDashOffset,s.fillStyle=this.ctx.fillStyle,s.strokeStyle=this.ctx.strokeStyle,s.globalAlpha=1,s.globalCompositeOperation="source-over",this.layerStack.push({savedCtx:this.ctx,canvas:i,alpha:n,blend:r,mask:o,kind:e,stateDepthAtPush:this.stateStack.length}),this.ctx=s,!0)}popLayer(){let e=this.layerStack.pop();if(!e)return;let n=e.canvas.getContext("2d");n&&e.mask&&(n.save(),n.setTransform(1,0,0,1,0,0),n.globalAlpha=1,n.globalCompositeOperation="destination-in",n.drawImage(e.mask,0,0),n.restore(),this.releaseLayerCanvas(e.mask)),this.ctx=e.savedCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.globalAlpha=e.alpha,this.ctx.globalCompositeOperation=rl(e.blend),this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.releaseLayerCanvas(e.canvas)}async applySoftMaskFromExtGState(e){try{if(!this.pageResources)return;let n=this.resolveObject(this.pageResources.entries.get("ExtGState"));if(!n||!Q(n))return;let r=this.resolveObject(n.entries.get(e));if(!r||!Q(r))return;let o=r.entries.get("SMask");if(!o)return;if(Fe(o)==="None"){for(;this.layerStack.length>0;){let a=this.layerStack[this.layerStack.length-1];if(a.kind==="smask"&&a.stateDepthAtPush===this.stateStack.length)this.popLayer();else break}return}let i=this.resolveObject(o);if(!i||!Q(i))return;let s=await this.renderSMaskCanvas(i);if(!s)return;this.pushLayer("smask",1,"Normal",s)}catch{}}async renderSMaskCanvas(e){var m;let n=this.resolveObject(e.entries.get("G"));if(!n||!fe(n))return null;let r=((m=Fe(e.entries.get("S")))!=null?m:"Alpha")==="Luminosity",o=this.acquireLayerCanvas(),i=o==null?void 0:o.getContext("2d",{willReadFrequently:!0});if(!o||!i)return null;if(r){let h=ht(e.entries.get("BC"));if(i.save(),i.setTransform(1,0,0,1,0,0),h&&h.length){let f=mn(pn(h.length===1?"DeviceGray":h.length===4?"DeviceCMYK":"DeviceRGB",h));i.fillStyle=Ct(f.r,f.g,f.b)}else i.fillStyle="black";i.fillRect(0,0,o.width,o.height),i.restore()}i.setTransform(this.ctx.getTransform());let s=this.ctx,a=this.capturedTextRuns.length;this.ctx=i,this.captureSuppressed+=1;try{await this.renderFormStreamInline(n)}finally{this.captureSuppressed-=1,this.ctx=s,this.capturedTextRuns.length=a}let c=e.entries.get("TR"),l=this.objectLoader,d=c&&l&&Fe(c)!=="Identity"?h=>{let f=bo(c,h,l);return f&&f.length?Math.max(0,Math.min(1,f[0])):h}:null;try{let h=i.getImageData(0,0,o.width,o.height),f=h.data;for(let p=0;p<f.length;p+=4){let w=r?(.3*f[p]+.59*f[p+1]+.11*f[p+2])/255:f[p+3]/255,y=d?d(w):w;f[p+3]=Math.round(y*255)}i.putImageData(h,0,0)}catch{return this.releaseLayerCanvas(o),null}return o}async renderFormStreamInline(e){let n=e.decode?await e.decode():we.decodeStreamSync(e),r=qt(n),o=this.pageResources,i=this.objectLoader,s=this.patternCache;this.patternCache=new Map;let a=this.resolveObject(e.dict.entries.get("Resources"));this.pageResources=a&&Q(a)?a:this.pageResources,this.execute({op:"save_state"});let c=wr(e.dict.entries.get("Matrix"));c&&this.execute({op:"set_ctm",matrix:c});let l=ht(e.dict.entries.get("BBox"));l&&l.length>=4&&(this.ctx.beginPath(),this.ctx.rect(l[0],l[1],l[2]-l[0],l[3]-l[1]),this.ctx.clip());let d=this.commandIndex;this.xobjectDepth+=1;try{await this.runCommandsAsync(r)}finally{this.xobjectDepth-=1,this.commandIndex=d,this.execute({op:"restore_state"}),this.pageResources=o,this.objectLoader=i,this.patternCache=s}}renderShadeOperator(e){try{if(!this.pageResources||!this.objectLoader)return;let n=this.resolveObject(this.pageResources.entries.get("Shading"));if(!n||!Q(n))return;let r=this.resolveObject(n.entries.get(e)),o=r?fe(r)?r.dict:Q(r)?r:null:null;if(!o)return;let i=r&&fe(r)?r:null;this.ctx.save();try{this.ctx.globalAlpha=this.state.fillAlpha;let s=ht(o.entries.get("BBox"));s&&s.length>=4&&(this.ctx.beginPath(),this.ctx.rect(s[0],s[1],s[2]-s[0],s[3]-s[1]),this.ctx.clip());let a=Pe(this.deviceBase(),this.state.ctm);this.paintShadingWithBase(o,i,a)}finally{this.ctx.restore()}}catch{}}};Jn.MAX_LAYER_DEPTH=6;var kr=Jn,Ff=t=>t==="DeviceGray"||t==="CalGray"?1:t==="DeviceCMYK"?4:3,rl=t=>{switch(t){case"Normal":case"Compatible":return"source-over";case"Multiply":return"multiply";case"Screen":return"screen";case"Overlay":return"overlay";case"Darken":return"darken";case"Lighten":return"lighten";case"ColorDodge":return"color-dodge";case"ColorBurn":return"color-burn";case"HardLight":return"hard-light";case"SoftLight":return"soft-light";case"Difference":return"difference";case"Exclusion":return"exclusion";case"Hue":return"hue";case"Saturation":return"saturation";case"Color":return"color";case"Luminosity":return"luminosity";default:return"source-over"}},ht=t=>!t||!he(t)?null:t.items.map(e=>{var n;return(n=q(e))!=null?n:0}),Mf=new Set(["FlateDecode","Fl","LZWDecode","LZW","ASCII85Decode","A85","ASCIIHexDecode","AHx","RunLengthDecode","RL","Crypt"]),Rf=(t,e,n)=>{if(!e||e.length<2||n!=="DeviceGray"&&n!=="DeviceRGB"||!(e[0]===1&&e[1]===0))return;let r=t.data;for(let o=0;o<r.length;o+=4)r[o]=255-r[o],r[o+1]=255-r[o+1],r[o+2]=255-r[o+2]},wr=t=>{let e=ht(t);return!e||e.length<6?null:[e[0],e[1],e[2],e[3],e[4],e[5]]},Af=(t,e,n)=>{let r=[Ue(n,e[0],e[1]),Ue(n,e[2],e[1]),Ue(n,e[2],e[3]),Ue(n,e[0],e[3])],o=r.map(b=>b.x),i=r.map(b=>b.y),s=Math.min(...o),a=Math.max(...o),c=Math.min(...i),l=Math.max(...i),d=Math.min(t[0],t[2]),m=Math.max(t[0],t[2]),h=Math.min(t[1],t[3]),f=Math.max(t[1],t[3]),p=a-s,w=l-c;if(!(p>1e-6)||!(w>1e-6))return null;let y=(m-d)/p,v=(f-h)/w;return[y,0,0,v,d-y*s,h-v*c]},Nf=t=>{if(!t||!he(t))return[!1,!1];let e=n=>!!n&&typeof n=="object"&&"type"in n&&n.type==="boolean"&&n.value;return[e(t.items[0]),e(t.items[1])]},Ct=(t,e,n)=>`rgb(${Math.round(qe(t)*255)},${Math.round(qe(e)*255)},${Math.round(qe(n)*255)})`,Zt=t=>{if(t.space==="rgb")return Ct(t.r,t.g,t.b);if(t.space==="gray")return Ct(t.gray,t.gray,t.gray);let e=Qn(t.c,t.m,t.y,t.k);return Ct(e.r,e.g,e.b)},mn=t=>{if(t.space==="rgb")return{r:qe(t.r),g:qe(t.g),b:qe(t.b)};if(t.space==="gray"){let e=qe(t.gray);return{r:e,g:e,b:e}}return Qn(t.c,t.m,t.y,t.k)},Ft=t=>{switch(t){case"DeviceRGB":case"RGB":return"DeviceRGB";case"DeviceGray":case"G":case"Gray":return"DeviceGray";case"DeviceCMYK":case"CMYK":return"DeviceCMYK";default:return null}},ol=t=>{var r;let e=Fe(t),n=e?Ft(e):null;if(n)return n;if(t&&he(t)&&t.items.length>0){let o=Fe(t.items[0]),i=o?Ft(o):null;if(i)return i;if(o==="ICCBased"){let s=t.items[1];if(s&&fe(s)){let a=Math.floor((r=q(s.dict.entries.get("N")))!=null?r:0);if(a===1)return"DeviceGray";if(a===3)return"DeviceRGB";if(a===4)return"DeviceCMYK"}}if(o==="CalGray")return"DeviceGray";if(o==="CalRGB")return"DeviceRGB";if(o==="Lab")return"Lab";if(o==="Separation")return"Separation";if(o==="DeviceN")return"DeviceN";if(o==="Indexed")return"Indexed";if(o==="Pattern")return"Pattern"}return null},Ef=(t,e,n)=>{let r=(t+16)/116,o=e/500+r,i=r-n/200,s=p=>p>.206897?p*p*p:(p-16/116)/7.787,a=.9642*s(o),c=1*s(r),l=.8249*s(i),d=3.1338561*a-1.6168667*c-.4906146*l,m=-.9787684*a+1.9161415*c+.033454*l,h=.0719453*a-.2289914*c+1.4052427*l,f=p=>p<=.0031308?12.92*p:1.055*Math.pow(Math.max(0,p),1/2.4)-.055;return{r:qe(f(d)),g:qe(f(m)),b:qe(f(h))}},pn=(t,e)=>{var r,o,i,s,a,c,l,d,m,h,f,p,w,y,v,b,C;let n=Ft(t);if(n==="DeviceGray")return{space:"gray",gray:(r=e[0])!=null?r:0};if(n==="DeviceCMYK")return{space:"cmyk",c:(o=e[0])!=null?o:0,m:(i=e[1])!=null?i:0,y:(s=e[2])!=null?s:0,k:(a=e[3])!=null?a:0};if(n==="DeviceRGB"||!n&&e.length===3)return{space:"rgb",r:(c=e[0])!=null?c:0,g:(l=e[1])!=null?l:0,b:(d=e[2])!=null?d:0};if(t==="Lab"){let S=Ef((m=e[0])!=null?m:0,(h=e[1])!=null?h:0,(f=e[2])!=null?f:0);return{space:"rgb",r:S.r,g:S.g,b:S.b}}return t==="Separation"||t==="DeviceN"?{space:"gray",gray:1-((p=e[0])!=null?p:0)}:e.length>=4?{space:"cmyk",c:(w=e[0])!=null?w:0,m:(y=e[1])!=null?y:0,y:(v=e[2])!=null?v:0,k:(b=e[3])!=null?b:0}:{space:"gray",gray:(C=e[0])!=null?C:0}},il=t=>{if(!t)return[];let e=Fe(t);return e?[e]:he(t)?t.items.map(n=>Fe(n)).filter(n=>n!==null):[]},Ji=async(t,e)=>typeof createImageBitmap=="function"?createImageBitmap(new Blob([t.slice().buffer],{type:e})):new Promise((n,r)=>{let o=new Image,i=URL.createObjectURL(new Blob([t.slice().buffer],{type:e}));o.onload=()=>{URL.revokeObjectURL(i),n(o)},o.onerror=()=>{URL.revokeObjectURL(i),r(new Error(`Could not decode image ${e}`))},o.src=i}),Zi=t=>{"close"in t&&typeof t.close=="function"&&t.close()},Tf=(t,e)=>{let n=t.entries.get("Widths");if(!n||!he(n))return;let r=new Map;return n.items.forEach((o,i)=>{let s=q(o);s!==null&&r.set(e+i,s)}),r.size>0?r:void 0},sl=(t,e)=>{let n=t.entries.get("DescendantFonts");if(!n||!he(n)||n.items.length===0)return;let r=e(n.items[0]);return r&&Q(r)?r:void 0},al=(t,e,n)=>{let r=n(t.entries.get("FontDescriptor"));if(r&&Q(r))return r;let o=n(e==null?void 0:e.entries.get("FontDescriptor"));return o&&Q(o)?o:void 0},Of=t=>{let e=t==null?void 0:t.entries.get("W");if(!e||!he(e))return;let n=new Map,r=e.items;for(let o=0;o<r.length;o+=1){let i=q(r[o]);if(i===null)continue;let s=r[o+1];if(s&&he(s)){s.items.forEach((l,d)=>{let m=q(l);m!==null&&n.set(i+d,m)}),o+=1;continue}let a=q(s),c=q(r[o+2]);if(!(a===null||c===null)){for(let l=i;l<=a;l+=1)n.set(l,c);o+=2}}return n.size>0?n:void 0},If=t=>{let e=q(t==null?void 0:t.entries.get("DW"));return e!=null?e:void 0},jf=t=>{let e=t.entries.get("FontDescriptor");if(!e||!Q(e))return;let n=q(e.entries.get("MissingWidth"));return n!=null?n:void 0},$f=(t,e,n,r,o,i,s)=>{let a=n.isComposite?Uf(t,n.toUnicode):Array.from(t).map((h,f)=>({code:h,bytes:t.slice(f,f+1)})),c=Array.from(e),l=!!n.widths||n.defaultWidth!==void 0,d=0;return{glyphs:a.map(h=>{var b,C,S;let f=n.toUnicode?en(h.code,n.toUnicode):null,p=(b=f!=null?f:c[d])!=null?b:"";d+=Math.max(1,Array.from(p).length);let w=(S=(C=n.widths)==null?void 0:C.get(h.code))!=null?S:n.defaultWidth,y;w!==void 0?y=w/1e3*r:s?y=s(p):y=(n.isComposite?1e3:500)/1e3*r,y>0||(y=s?Math.max(.01,s(p||" ")):r*.5);let v=o+(p===" "||h.code===32?i:0);return{text:p,code:h.code,bytes:h.bytes,glyphWidth:y,advance:y+v}}),hasPdfMetrics:l}},ns=t=>{var r;let e=Co((r=t.baseFontName)!=null?r:"").toLowerCase(),n=ml(e);return t.registeredFamily?`"${t.registeredFamily}", ${n}`:n},cl=(t,e)=>{var s,a,c;let r=Co((s=t.baseFontName)!=null?s:"").toLowerCase(),o=(a=t.fontStyle)!=null?a:r.includes("italic")||r.includes("oblique")?"italic":"normal",i=String((c=t.fontWeight)!=null?c:r.includes("bold")||r.includes("black")?700:400);return t.registeredFamily?`${e}px ${ns(t)}`:`${o} ${i} ${e}px ${ml(r)}`},Bf=(t,e)=>{var s;let n=Co(t!=null?t:"").toLowerCase(),r=q(e==null?void 0:e.entries.get("FontWeight"));if(r!==null)return Math.max(100,Math.min(900,Math.round(r/100)*100));let o=Math.floor((s=q(e==null?void 0:e.entries.get("Flags")))!=null?s:0),i=q(e==null?void 0:e.entries.get("StemV"));if(n.includes("bold")||n.includes("black")||n.includes("heavy")||(o&262144)!==0||i!==null&&i>=120)return 700},Lf=(t,e)=>{var i;let n=Co(t!=null?t:"").toLowerCase(),r=Math.floor((i=q(e==null?void 0:e.entries.get("Flags")))!=null?i:0),o=q(e==null?void 0:e.entries.get("ItalicAngle"));if(n.includes("italic")||n.includes("oblique")||(r&64)!==0||o!==null&&o!==0)return"italic"},Co=t=>/^[A-Z]{6}\+/.test(t)?t.slice(7):t,ml=t=>t.includes("courier")?'"Courier New", Courier, monospace':t.includes("times")||t.includes("serif")?'"Times New Roman", Times, serif':t.includes("symbol")?'Symbol, "Times New Roman", serif':t.includes("zapfdingbats")||t.includes("dingbats")?'ZapfDingbats, "Times New Roman", serif':(t.includes("helvetica")||t.includes("arial"),"Helvetica, Arial, sans-serif"),Uf=(t,e)=>{var r,o;if(t.length===0)return[];if(e!=null&&e.codeSpaceRanges.length){let i=Array.from(new Set(e.codeSpaceRanges.map(a=>a.byteLength))).sort((a,c)=>c-a),s=[];for(let a=0;a<t.length;){let c=0,l=0;for(let d of i){if(a+d>t.length)continue;let m=Zn(t,a,d);if(m!==null&&xl(m,d,e.codeSpaceRanges)){c=d,l=m;break}}c===0&&(c=Math.min(2,t.length-a),l=(r=Zn(t,a,c))!=null?r:t[a]),s.push({code:l,bytes:t.slice(a,a+c)}),a+=c}return s}let n=[];for(let i=0;i<t.length;){let s=Math.min(2,t.length-i);n.push({code:(o=Zn(t,i,s))!=null?o:t[i],bytes:t.slice(i,i+s)}),i+=s}return n},_f=t=>t==="DeviceCMYK"?4:t==="DeviceGray"||t==="Separation"?1:3,Qi=(t,e,n,r,o,i)=>{var d,m,h,f;if(o===8)return t;let s=e*r,a=new Uint8Array(s*n);if(o===16){for(let p=0,w=0;p<a.length;p++,w+=2)a[p]=(d=t[w])!=null?d:0;return a}let c=(1<<o)-1,l=Math.ceil(s*o/8);for(let p=0;p<n;p++){let w=p*l,y=0;for(let v=0;v<s;v++){let b=w+(y>>3),S=8-(y&7),F;if(o<=S)F=((m=t[b])!=null?m:0)>>S-o&c;else{let T=o-S,N=((h=t[b])!=null?h:0)&(1<<S)-1,O=((f=t[b+1])!=null?f:0)>>8-T;F=N<<T|O}a[p*s+v]=i?Math.round(F*255/c):F,y+=o}}return a},Xf=(t,e,n,r)=>{let o=e*n,i=new Uint8ClampedArray(o*4);if(r==="DeviceRGB"){if(t.length<o*3)return null;for(let a=0,c=0;c<i.length;a+=3,c+=4)i[c]=t[a],i[c+1]=t[a+1],i[c+2]=t[a+2],i[c+3]=255;return new ImageData(i,e,n)}if(r==="DeviceGray"){if(t.length<o)return null;for(let a=0,c=0;c<i.length;a+=1,c+=4){let l=t[a];i[c]=l,i[c+1]=l,i[c+2]=l,i[c+3]=255}return new ImageData(i,e,n)}if(r==="DeviceCMYK"){if(t.length<o*4)return null;for(let a=0,c=0;c<i.length;a+=4,c+=4){let l=Qn(t[a]/255,t[a+1]/255,t[a+2]/255,t[a+3]/255);i[c]=Math.round(l.r*255),i[c+1]=Math.round(l.g*255),i[c+2]=Math.round(l.b*255),i[c+3]=255}return new ImageData(i,e,n)}let s=Math.floor(t.length/Math.max(1,o));if(s>=3){let a=s;for(let c=0,l=0;c<o;c++,l+=4){let d=c*a;i[l]=t[d],i[l+1]=t[d+1],i[l+2]=t[d+2],i[l+3]=255}return new ImageData(i,e,n)}if(s>=1){let a=r==="Separation"||r==="DeviceN";for(let c=0,l=0;c<o;c++,l+=4){let d=a?255-t[c]:t[c];i[l]=d,i[l+1]=d,i[l+2]=d,i[l+3]=255}return new ImageData(i,e,n)}return null},ko=(t,e,n,r)=>{let o=t.data,i=n*r;for(let s=0;s<i&&s<e.length;s++)o[s*4+3]=e[s]},zf=(t,e,n,r,o)=>{var h,f,p,w,y,v,b,C,S,F,T;if(r.length<4)return null;let i=(h=Fe(r[1]))!=null?h:"DeviceRGB",s=Math.floor((f=q(r[2]))!=null?f:255),a=o(r[3]),c=null;if(a&&fe(a))try{c=we.decodeStreamSync(a)}catch{}else a&&typeof a=="object"&&"type"in a&&a.type==="string"&&(c=a.value);if(!c)return null;let l=i==="DeviceCMYK"?4:i==="DeviceGray"?1:3,d=e*n,m=new Uint8ClampedArray(d*4);for(let N=0;N<d;N++){let A=Math.min((p=t[N])!=null?p:0,s)*l,H=0,ne=0,ie=0;if(l===3)H=(w=c[A])!=null?w:0,ne=(y=c[A+1])!=null?y:0,ie=(v=c[A+2])!=null?v:0;else if(l===1)H=ne=ie=(b=c[A])!=null?b:0;else if(l===4){let ce=Qn(((C=c[A])!=null?C:0)/255,((S=c[A+1])!=null?S:0)/255,((F=c[A+2])!=null?F:0)/255,((T=c[A+3])!=null?T:0)/255);H=Math.round(ce.r*255),ne=Math.round(ce.g*255),ie=Math.round(ce.b*255)}let I=N*4;m[I]=H,m[I+1]=ne,m[I+2]=ie,m[I+3]=255}return new ImageData(m,e,n)},Yf=t=>{var o;if(!t)return null;let e=t.match(/^uni([0-9A-Fa-f]{4,6})$/);if(e){let i=parseInt(e[1],16);try{return String.fromCodePoint(i)}catch{return null}}let n=t.match(/^u([0-9A-Fa-f]{5,6})$/);if(n){let i=parseInt(n[1],16);try{return String.fromCodePoint(i)}catch{return null}}return t.length===1?t:(o={space:" ",exclam:"!",quotedbl:'"',numbersign:"#",dollar:"$",percent:"%",ampersand:"&",quotesingle:"'",parenleft:"(",parenright:")",asterisk:"*",plus:"+",comma:",",hyphen:"-",period:".",slash:"/",zero:"0",one:"1",two:"2",three:"3",four:"4",five:"5",six:"6",seven:"7",eight:"8",nine:"9",colon:":",semicolon:";",less:"<",equal:"=",greater:">",question:"?",at:"@",A:"A",B:"B",C:"C",D:"D",E:"E",F:"F",G:"G",H:"H",I:"I",J:"J",K:"K",L:"L",M:"M",N:"N",O:"O",P:"P",Q:"Q",R:"R",S:"S",T:"T",U:"U",V:"V",W:"W",X:"X",Y:"Y",Z:"Z",bracketleft:"[",backslash:"\\",bracketright:"]",asciicircum:"^",underscore:"_",grave:"`",a:"a",b:"b",c:"c",d:"d",e:"e",f:"f",g:"g",h:"h",i:"i",j:"j",k:"k",l:"l",m:"m",n:"n",o:"o",p:"p",q:"q",r:"r",s:"s",t:"t",u:"u",v:"v",w:"w",x:"x",y:"y",z:"z",braceleft:"{",bar:"|",braceright:"}",asciitilde:"~",exclamdown:"\xA1",cent:"\xA2",sterling:"\xA3",currency:"\xA4",yen:"\xA5",brokenbar:"\xA6",section:"\xA7",dieresis:"\xA8",copyright:"\xA9",ordfeminine:"\xAA",guillemotleft:"\xAB",logicalnot:"\xAC",minus:"\u2212",registered:"\xAE",macron:"\xAF",degree:"\xB0",plusminus:"\xB1",twosuperior:"\xB2",threesuperior:"\xB3",acute:"\xB4",mu:"\xB5",paragraph:"\xB6",periodcentered:"\xB7",cedilla:"\xB8",onesuperior:"\xB9",ordmasculine:"\xBA",guillemotright:"\xBB",onequarter:"\xBC",onehalf:"\xBD",threequarters:"\xBE",questiondown:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acircumflex:"\xC2",Atilde:"\xC3",Adieresis:"\xC4",Aring:"\xC5",AE:"\xC6",Ccedilla:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecircumflex:"\xCA",Edieresis:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icircumflex:"\xCE",Idieresis:"\xCF",Eth:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocircumflex:"\xD4",Otilde:"\xD5",Odieresis:"\xD6",multiply:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucircumflex:"\xDB",Udieresis:"\xDC",Yacute:"\xDD",Thorn:"\xDE",germandbls:"\xDF",agrave:"\xE0",aacute:"\xE1",acircumflex:"\xE2",atilde:"\xE3",adieresis:"\xE4",aring:"\xE5",ae:"\xE6",ccedilla:"\xE7",egrave:"\xE8",eacute:"\xE9",ecircumflex:"\xEA",edieresis:"\xEB",igrave:"\xEC",iacute:"\xED",icircumflex:"\xEE",idieresis:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocircumflex:"\xF4",otilde:"\xF5",odieresis:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucircumflex:"\xFB",udieresis:"\xFC",yacute:"\xFD",thorn:"\xFE",ydieresis:"\xFF",OE:"\u0152",oe:"\u0153",Scaron:"\u0160",scaron:"\u0161",Ydieresis:"\u0178",Zcaron:"\u017D",zcaron:"\u017E",florin:"\u0192",circumflex:"\u02C6",tilde:"\u02DC",endash:"\u2013",emdash:"\u2014",quotedblleft:"\u201C",quotedblright:"\u201D",quoteleft:"\u2018",quoteright:"\u2019",quotesinglbase:"\u201A",quotedblbase:"\u201E",dagger:"\u2020",daggerdbl:"\u2021",bullet:"\u2022",ellipsis:"\u2026",perthousand:"\u2030",guilsinglleft:"\u2039",guilsinglright:"\u203A",fraction:"\u2044",Euro:"\u20AC",trademark:"\u2122",fi:"\uFB01",fl:"\uFB02",ff:"\uFB00",ffi:"\uFB03",ffl:"\uFB04",lslash:"\u0142",Lslash:"\u0141",dotaccent:"\u02D9",ring:"\u02DA",caron:"\u02C7",breve:"\u02D8",dotlessi:"\u0131",hungarumlaut:"\u02DD",ogonek:"\u02DB",Delta:"\u2206",Omega:"\u03A9",pi:"\u03C0",infinity:"\u221E",lessequal:"\u2264",greaterequal:"\u2265",notequal:"\u2260",approxequal:"\u2248",radical:"\u221A",summation:"\u2211",product:"\u220F",integral:"\u222B",partialdiff:"\u2202",lozenge:"\u25CA",apple:"\uF8FF"}[t])!=null?o:null},ll=(()=>{let t=[[128,196],[129,197],[130,199],[131,201],[132,209],[133,214],[134,220],[135,225],[136,224],[137,226],[138,228],[139,227],[140,229],[141,231],[142,233],[143,232],[144,234],[145,235],[146,237],[147,236],[148,238],[149,239],[150,241],[151,243],[152,242],[153,244],[154,246],[155,250],[156,249],[157,251],[158,252],[159,8224],[160,176],[161,162],[162,163],[163,167],[164,8226],[165,182],[166,223],[167,174],[168,169],[169,8482],[170,180],[171,168],[172,8800],[173,198],[174,216],[175,8734],[176,177],[177,8804],[178,8805],[179,165],[180,181],[181,8706],[182,8721],[183,8719],[184,960],[185,8747],[186,170],[187,186],[188,937],[189,230],[190,248],[191,191],[192,161],[193,172],[194,8730],[195,402],[196,8776],[197,8710],[198,171],[199,187],[200,8230],[201,160],[202,192],[203,195],[204,213],[205,338],[206,339],[207,8211],[208,8212],[209,8220],[210,8221],[211,8216],[212,8217],[213,247],[214,9674],[215,255],[216,376],[217,8260],[218,8364],[219,8249],[220,8250],[221,64257],[222,64258],[223,8225],[224,183],[225,8218],[226,8222],[227,8240],[228,194],[229,202],[230,193],[231,203],[232,200],[233,205],[234,206],[235,207],[236,204],[237,211],[238,212],[239,210],[240,218],[241,219],[242,217],[243,305],[244,710],[245,732],[246,175],[247,728],[248,729],[249,730],[250,184],[251,733],[252,731],[253,711],[254,254],[255,255]],e=new Map;for(let[n,r]of t)e.set(n,String.fromCodePoint(r));return e})(),dl=(()=>{let t=[[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]],e=new Map;for(let[n,r]of t)e.set(n,String.fromCodePoint(r));return e})(),Wf=(t,e)=>{if(!t)return;let n=e(t);if(!n)return;let r=Fe(n);if(r)return r==="MacRomanEncoding"?new Map(ll):r==="WinAnsiEncoding"?new Map(dl):void 0;if(!Q(n))return;let o=n,i=Fe(o.entries.get("BaseEncoding")),s;i==="MacRomanEncoding"?s=new Map(ll):i==="WinAnsiEncoding"?s=new Map(dl):s=new Map;let a=o.entries.get("Differences");if(!a||!he(a))return s.size>0?s:void 0;let c=0;for(let l of a.items){let d=q(l);if(d!==null)c=Math.floor(d);else{let m=Fe(l);if(m){let h=Yf(m);h&&s.set(c,h),c++}}}return s.size>0?s:void 0},Hf=(t,e)=>{let n=new Map;if(!t)return n;let r=e(t);if(!r||!Q(r))return n;let o=r.entries.get("Differences");if(!o||!he(o))return n;let i=0;for(let s of o.items){let a=q(s);if(a!==null)i=Math.floor(a);else{let c=Fe(s);c&&(n.set(i,c),i++)}}return n},Qn=(t,e,n,r)=>({r:(1-qe(t))*(1-qe(r)),g:(1-qe(e))*(1-qe(r)),b:(1-qe(n))*(1-qe(r))}),qe=t=>!Number.isFinite(t)||t<0?0:t>1?1:t,Gf=(t,e,n)=>Number.isFinite(t)?Math.min(n,Math.max(e,t)):e,Kf=t=>({...t,ctm:[...t.ctm],textMatrix:[...t.textMatrix],textLineMatrix:[...t.textLineMatrix],fillColor:{...t.fillColor},strokeColor:{...t.strokeColor},dashArray:[...t.dashArray]}),Ue=(t,e,n)=>({x:t[0]*e+t[2]*n+t[4],y:t[1]*e+t[3]*n+t[5]}),Po=()=>({subtype:"Unknown",baseFontName:void 0,isComposite:!1,firstChar:void 0,widths:void 0,defaultWidth:void 0,toUnicode:null}),Vf=t=>{let e={bfChar:new Map,bfRange:[],codeSpaceRanges:[],cmapType:0,isUsable:!0},n=t.match(/\/CMapType\s+(\d+)\s+def/);n&&(e.cmapType=Number.parseInt(n[1],10),e.isUsable=e.cmapType!==0);let r=t.replace(/\r\n/g,`
|
|
41
41
|
`).replace(/\r/g,`
|
|
42
|
-
`),o=
|
|
43
|
-
`;)n+=1;continue}if(t[n]==="<"){let o=n;for(n+=1;n<t.length&&t[n]!==">";)n+=1;n<t.length&&(n+=1),e.push(t.slice(o,n));continue}if(t[n]==="["||t[n]==="]"){e.push(t[n]),n+=1;continue}let r=n;for(;n<t.length&&!/[\s<\[\]%]/.test(t[n]);)n+=1;if(r<n){let o=t.slice(r,n),i=qf(o);i?(i.count&&e.push(i.count),e.push(i.keyword)):e.push(o)}}return e},qf=t=>{let e=t.match(/^(\d+)?(begin\w+|end\w+|usecmap|begincmap|endcmap)$/i);return e?{count:e[1],keyword:e[2]}:null},Jf=t=>t?t==="beginbfchar"||t==="endbfchar"||t==="beginbfrange"||t==="endbfrange"||t==="begincidchar"||t==="endcidchar"||t==="begincidrange"||t==="endcidrange"||t==="begincodespacerange"||t==="endcodespacerange":!1,_t=t=>!!t&&t.startsWith("<")&&t.endsWith(">"),wr=t=>!!t&&/^\d+$/.test(t),Nn=t=>t.slice(1,-1),So=t=>Number.parseInt(Nn(t),16),dl=t=>_t(t)?So(t):wr(t)?Number.parseInt(t,10):null,Po=t=>{let e=t.length%2===0?t:`0${t}`;if(e.length===0)return"";if(e.length<=4){let r=Number.parseInt(e,16);if(!Number.isFinite(r))return"\uFFFD";try{return String.fromCodePoint(r)}catch{return"\uFFFD"}}let n="";for(let r=0;r<e.length;r+=4){let o=e.slice(r,r+4).padStart(4,"0"),i=Number.parseInt(o,16);if(!Number.isFinite(i)){n+="\uFFFD";continue}try{n+=String.fromCodePoint(i)}catch{n+="\uFFFD"}}return n},Zf=(t,e)=>{var r;console.log(`=== CMap debug for font ${e} ===`),console.log(`cmapType: ${t.cmapType}`),console.log(`isUsable: ${t.isUsable}`),console.log(`bfChar entries: ${t.bfChar.size}`),console.log(`bfRange entries: ${t.bfRange.length}`),console.log(`codespace ranges: ${t.codeSpaceRanges.length}`);let n=0;for(let[o,i]of t.bfChar.entries()){if(n>=10)break;let s=i.codePointAt(0);console.log(` 0x${o.toString(16).padStart(4,"0")} -> "${i}" (U+${(r=s==null?void 0:s.toString(16).toUpperCase())!=null?r:"????"})`),n+=1}for(let o of t.bfRange.slice(0,5))typeof o.unicodeStart=="number"?console.log(` range 0x${o.start.toString(16).padStart(4,"0")}-0x${o.end.toString(16).padStart(4,"0")} -> U+${o.unicodeStart.toString(16).toUpperCase()}`):o.mapped&&console.log(` range 0x${o.start.toString(16).padStart(4,"0")}-0x${o.end.toString(16).padStart(4,"0")} -> [mapped:${o.mapped.length}]`);for(let o of t.codeSpaceRanges.slice(0,5))console.log(` codespace ${o.byteLength}b 0x${o.start.toString(16).padStart(o.byteLength*2,"0")}-0x${o.end.toString(16).padStart(o.byteLength*2,"0")}`)},Qt=(t,e)=>{let n=e.bfChar.get(t);if(n!==void 0)return n;for(let r of e.bfRange)if(!(t<r.start||t>r.end)){if(r.mapped){let o=t-r.start;return o>=0&&o<r.mapped.length?r.mapped[o]:null}if(typeof r.unicodeStart=="number"){let o=r.unicodeStart+(t-r.start);return String.fromCodePoint(o)}}return null},Qf=(t,e,n,r,o=!1)=>{var s,a;if(n){let c=hm(e),l=rm(e),m=(l?[{mode:"raw",bytes:t}]:nm(t)).map(b=>({mode:b.mode,attempt:tm(b.bytes,e,c)})),h=om(m),f=h.attempt,p=pm(f)?gm(t):null,w=xm(f,p);if(o&&console.debug("[PageRenderer][CMap] decode strategy",{font:r!=null?r:"?",mapped:f.mapped,unmapped:f.unmapped,utf16Score:(s=p==null?void 0:p.score)!=null?s:null,codespaceRanges:e.codeSpaceRanges.length,inferredCodeLengths:c,payloadMode:h.mode,sparseToUnicode:l,chosen:w===p?"utf16be":"cmap"}),o&&f.unmappedGlyphs.length>0){let b=f.unmappedGlyphs.slice(0,12).map(C=>`0x${C.toString(16).padStart(4,"0")}`),y=fm(f.unmappedGlyphs,c),k=l?`${r!=null?r:"?"}|sparse-tounicode`:`${r!=null?r:"?"}|${h.mode}`;Zc.has(k)||(Zc.add(k),console.warn("[PageRenderer][CMap] unmapped composite glyphs",{font:r!=null?r:"?",count:f.unmappedGlyphs.length,payloadMode:h.mode,sparseToUnicode:l,rootCause:l?`ToUnicode is too sparse (bfChar=${e.bfChar.size}, bfRange=${e.bfRange.length}); Unicode recovery is fundamentally limited for this font.`:void 0,sample:b,topMissing:y.topMissing,mappingHints:y.mappingHints,note:"Use mappingHints as candidate ToUnicode entries (<src> <dst>) for manual verification."}))}return(a=w==null?void 0:w.text)!=null?a:f.text}let i="";for(let c=0;c<t.length;c++){let l=Qt(t[c],e);i+=l!==null?l:String.fromCharCode(t[c])}return i},em=(t,e)=>{let n="",r=0;for(;r+1<t.length;){let o=t[r],i=t[r+1],s=o<<8|i,a=Qt(s,e);if(a!==null){n+=a,r+=2;continue}if(i>=32&&i<=126){n+=String.fromCharCode(i),r+=2;continue}if(o>=32&&o<=126){n+=String.fromCharCode(o),r+=2;continue}r+=2}if(r<t.length){let o=t[r];o>=32&&o<=126&&(n+=String.fromCharCode(o))}return n},tm=(t,e,n)=>e.codeSpaceRanges.length>0?dm(t,e):um(t,e,n),nm=t=>{var s;let e=[{mode:"raw",bytes:t}],n=new Set([`raw:${t.length}:${(s=t[0])!=null?s:-1}`]),r=(a,c)=>{var d,m;if(!c||c.length===0)return;let l=`${a}:${c.length}:${(d=c[0])!=null?d:-1}:${(m=c[1])!=null?m:-1}`;n.has(l)||(n.add(l),e.push({mode:a,bytes:c}))},o=im(t);r("zero-stripped",o);let i=sm(t);return r("pair-swapped",i),r("ascii-hex",Qi(t)),o&&r("zero-stripped+ascii-hex",Qi(o)),i&&r("pair-swapped+ascii-hex",Qi(i)),e},rm=t=>t.bfChar.size+t.bfRange.length<=2,om=t=>{let e=t[0],n=ul(e.attempt);for(let r=1;r<t.length;r+=1){let o=t[r],i=ul(o.attempt);i>n+1&&(e=o,n=i)}return e},im=t=>{if(t.length<4||t.length%2!==0)return null;let e=0,n=0;for(let a=0;a<t.length;a+=2)t[a]===0&&(e+=1),t[a+1]===0&&(n+=1);let r=t.length/2,o=e>=Math.floor(r*.7),i=n>=Math.floor(r*.7);if(!o&&!i)return null;let s=new Uint8Array(r);for(let a=0;a<r;a+=1)s[a]=o?t[a*2+1]:t[a*2];return s},sm=t=>{if(t.length<2||t.length%2!==0)return null;let e=new Uint8Array(t.length);for(let n=0;n<t.length;n+=2)e[n]=t[n+1],e[n+1]=t[n];return e},ul=t=>t.mapped*2-t.unmapped,Qi=t=>{if(t.length<8)return null;let e=0,n=0,r=0,o=[];for(let s of t)if(!am(s)){if(n+=1,!cm(s))return null;(s>=65&&s<=70||s>=97&&s<=102)&&(r+=1),e+=1,o.push(String.fromCharCode(s))}if(n<8||e!==n||e%2!==0||r===0)return null;let i=new Uint8Array(e/2);for(let s=0;s<i.length;s+=1){let a=hl(o[s*2]),c=hl(o[s*2+1]);if(a<0||c<0)return null;i[s]=a<<4|c}return i},am=t=>t===32||t===9||t===10||t===13,cm=t=>t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102,hl=t=>t>="0"&&t<="9"?t.charCodeAt(0)-48:t>="a"&&t<="f"?t.charCodeAt(0)-97+10:t>="A"&&t<="F"?t.charCodeAt(0)-65+10:-1,lm=(t,e)=>{let n="",r=0,o=0,i=[];for(let s=0;s<t.length;){if(s+1<t.length){let c=t[s]<<8|t[s+1],l=Qt(c,e);if(l!==null){n+=l,r+=1,s+=2;continue}let d=Qt(t[s],e),m=Qt(t[s+1],e);if(d!==null||m!==null){n+="\uFFFD\uFFFD",o+=1,i.push(c),s+=2;continue}n+="\uFFFD",o+=1,i.push(c),s+=2;continue}let a=Qt(t[s],e);a!==null?(n+=a,r+=1):(n+="\uFFFD",o+=1,i.push(t[s])),s+=1}return{text:n,mapped:r,unmapped:o,unmappedGlyphs:i}},dm=(t,e)=>{let n=Array.from(new Set(e.codeSpaceRanges.map(a=>a.byteLength))).sort((a,c)=>c-a);if(n.length===0)return lm(t,e);let r="",o=0,i=0,s=[];for(let a=0;a<t.length;){let c=0,l=null;for(let m of n){if(a+m>t.length)continue;let h=Jn(t,a,m);if(h!==null&&gl(h,m,e.codeSpaceRanges)){c=m,l=h;break}}if(c>0&&l!==null){let m=Qt(l,e);m!==null?(r+=m,o+=1):(r+="\uFFFD",i+=1,s.push(l)),a+=c;continue}let d=a+1<t.length?t[a]<<8|t[a+1]:t[a];r+="\uFFFD",i+=1,s.push(d),a+=1}return{text:r,mapped:o,unmapped:i,unmappedGlyphs:s}},um=(t,e,n)=>{var c,l;let r=n.length>0?[...n].sort((d,m)=>m-d):[2,1],o="",i=0,s=0,a=[];for(let d=0;d<t.length;){let m=0,h=null;for(let w of r){if(d+w>t.length)continue;let b=Jn(t,d,w);if(b===null)continue;let y=Qt(b,e);if(y!==null){h=y,m=w;break}}if(h!==null&&m>0){o+=h,i+=1,d+=m;continue}let f=(c=r[r.length-1])!=null?c:1,p=(l=Jn(t,d,Math.min(f,t.length-d)))!=null?l:t[d];o+="\uFFFD",s+=1,a.push(p),d+=Math.min(f,t.length-d)}return{text:o,mapped:i,unmapped:s,unmappedGlyphs:a}},hm=t=>{let e=new Set;for(let r of t.codeSpaceRanges)r.byteLength>=1&&r.byteLength<=4&&e.add(r.byteLength);for(let r of t.bfChar.keys())e.add(es(r));for(let r of t.bfRange)e.add(es(r.start)),e.add(es(r.end));let n=Array.from(e).filter(r=>r>=1&&r<=4);return n.length===0?[2,1]:n.sort((r,o)=>o-r)},es=t=>t<=255?1:t<=65535?2:t<=16777215?3:4,fm=(t,e)=>{var c;let n=new Map;for(let l of t)n.set(l,((c=n.get(l))!=null?c:0)+1);let o=Array.from(n.entries()).sort((l,d)=>d[1]-l[1]).slice(0,8),i=o.map(([l,d])=>({glyph:`0x${l.toString(16).padStart(4,"0")}`,count:d})),s=e.length>0?e[e.length-1]:2,a=o.map(([l])=>mm(l,s)).filter(l=>l!==null);return{topMissing:i,mappingHints:a}},mm=(t,e)=>{let n=t.toString(16).padStart(Math.max(4,e*2),"0"),r=t&255;if(r>=32&&r<=126){let o=r.toString(16).toUpperCase().padStart(4,"0");return{glyph:`0x${n}`,candidateUnicode:`U+${o} (${String.fromCharCode(r)})`,reason:"Printable ASCII low-byte candidate",cmapLine:`<${n}> <${o}>`}}if(t>=32&&t<=126){let o=t.toString(16).toUpperCase().padStart(4,"0");return{glyph:`0x${n}`,candidateUnicode:`U+${o} (${String.fromCharCode(t)})`,reason:"Direct ASCII glyph code candidate",cmapLine:`<${n}> <${o}>`}}return null},pm=t=>t.text.length===0?!1:t.mapped>0?t.unmapped>=t.mapped*3:t.unmapped>0,gm=t=>{var i;let e=pl(t),n=ml(e),r=((i=e.match(/\uFFFD/g))!=null?i:[]).length,o=n-r*3;return{text:e,mapped:n,unmapped:r,unmappedGlyphs:[],printable:n,score:o}},xm=(t,e)=>{if(!e)return t;let n=bm(t.text);return ym(e.text)&&e.score>=n+8?e:t},bm=t=>{var r;let e=ml(t),n=((r=t.match(/\uFFFD/g))!=null?r:[]).length;return e-n*3},ml=t=>{var n;let e=0;for(let r of t){let o=(n=r.codePointAt(0))!=null?n:0;if(o===9||o===10||o===13){e+=1;continue}if(o>=32&&o<=126){e+=2;continue}if(o>=160&&o<=591){e+=1;continue}}return e},ym=t=>{var o,i;if(!t||((o=t.match(/\uFFFD/g))!=null?o:[]).length>Math.floor(t.length*.2))return!1;let n=0,r=0;for(let s of t){let a=(i=s.codePointAt(0))!=null?i:0;if(a>=32&&a<=126){n+=1;continue}(a>=12288&&a<=12351||a>=8592&&a<=8703)&&(r+=1)}return n>=8&&n*2>=t.length?!0:(r>0&&r*2>=t.length,!1)},Me=t=>t?typeof t=="string"?t:typeof t=="object"&&"type"in t&&t.type==="name"&&"value"in t?String(t.value):null:null,pl=t=>{if(t.length<2)return new TextDecoder("latin1").decode(t);let e="";for(let n=0;n+1<t.length;n+=2){let r=t[n]<<8|t[n+1];e+=String.fromCharCode(r)}return t.length%2!==0&&(e+="\uFFFD"),e},wm=t=>{var e,n,r,o,i,s,a;return{length:t.length,beginbfchar:((e=t.match(/beginbfchar/g))!=null?e:[]).length,beginbfrange:((n=t.match(/beginbfrange/g))!=null?n:[]).length,begincidchar:((r=t.match(/begincidchar/g))!=null?r:[]).length,begincidrange:((o=t.match(/begincidrange/g))!=null?o:[]).length,begincodespacerange:((i=t.match(/begincodespacerange/g))!=null?i:[]).length,usecmap:((s=t.match(/usecmap/g))!=null?s:[]).length,hexTokens:((a=t.match(/<[0-9a-fA-F]+>/g))!=null?a:[]).length,preview:t.slice(0,220)}},Zt=t=>{var e,n,r;if(!t)return"undefined";if(typeof t=="string")return`string:${t}`;if(typeof t=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&"type"in t){let o=String((e=t.type)!=null?e:"unknown");return o==="ref"&&"objectNumber"in t?`ref:${String((n=t.objectNumber)!=null?n:"?")}`:o==="name"&&"value"in t?`name:${String((r=t.value)!=null?r:"")}`:o}return typeof t},Jn=(t,e,n)=>{if(n<1||n>4||e+n>t.length)return null;let r=0;for(let o=0;o<n;o+=1)r=r<<8|t[e+o];return r>>>0},gl=(t,e,n)=>{for(let r of n)if(r.byteLength===e&&t>=r.start&&t<=r.end)return!0;return!1};import{useState as xl}from"react";function bl(){let[t,e]=xl(!1),[n,r]=xl(null),o=async(s,a)=>{e(!0),r(null);try{let c=new FormData;c.append("file",s),a&&c.append("password",a);let l=await fetch("/api/decrypt-pdf",{method:"POST",body:c});if(l.ok){let h=new Uint8Array(await l.arrayBuffer());return e(!1),{success:!0,pdfBytes:h,isEncrypted:!1,requiresPassword:!1}}l.status===401&&typeof window!="undefined"&&window.dispatchEvent(new Event("namaha:needs-auth"));let d=await l.json().catch(()=>null);if(d!=null&&d.isEncrypted&&(d!=null&&d.requiresPassword))return e(!1),{success:!1,isEncrypted:!0,requiresPassword:!0,error:d.error||"This PDF is password protected"};let m=(d==null?void 0:d.error)||"Failed to process PDF";return r(m),e(!1),{success:!1,isEncrypted:!1,requiresPassword:!1,error:m}}catch(c){let l=c instanceof Error?c.message:"Unknown error";return r(l),e(!1),{success:!1,isEncrypted:!1,requiresPassword:!1,error:l}}};return{uploadPdf:o,uploadPdfWithPasswordPrompt:async(s,a=`${s.name} is password protected. Enter the PDF password:`)=>{let c=await o(s);for(let l=0;c.requiresPassword&&l<3;l+=1){let d=window.prompt(l===0?a:`That password did not unlock ${s.name}. Try again:`);if(!d){let m="Password required to process this PDF.";return r(m),{success:!1,isEncrypted:!0,requiresPassword:!0,error:m}}c=await o(s,d)}return c},isLoading:t,error:n}}import{useEffect as vm}from"react";var km=t=>{if(!t)return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||t.isContentEditable===!0};function yl({enabled:t=!0,onUndo:e,onSave:n}){vm(()=>{if(!t)return;let r=o=>{if(!(o.ctrlKey||o.metaKey)||o.altKey)return;let i=o.key.toLowerCase();if(i==="s"){o.preventDefault(),n==null||n();return}if(i==="z"&&!o.shiftKey){if(km(document.activeElement))return;o.preventDefault(),e==null||e()}};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,e,n])}import{ArrowLeft as Sm,ArrowRight as Dm,Check as Co,ChevronUp as Cm,ChevronDown as Fm,Clock as Mm,Download as Rm,Edit3 as Am,Eraser as ns,Eye as kl,FilePlus2 as Nm,FileText as Fo,Highlighter as Em,Maximize2 as Tm,Shapes as Om,History as Pl,Lock as Im,MessageSquareText as Sl,MousePointer as jm,PenTool as rs,Replace as $m,RotateCw as Bm,ScanText as Dl,Search as os,Image as Lm,Share2 as Um,StickyNote as Cl,Trash2 as is,Type as Fl,Upload as ss,X as pn,ZoomIn as _m,ZoomOut as Xm}from"lucide-react";import{Fragment as en,jsx as v,jsxs as Y}from"react/jsx-runtime";var zm={se:"0% 0%",sw:"100% 0%",ne:"0% 100%",nw:"100% 100%",n:"50% 100%",s:"50% 0%",e:"0% 50%",w:"100% 50%"},Ym=30,gn=2,Ml=50,Wm=15,Hm=2,Rl=t=>{let e=new Uint8Array(t);return new Blob([e.buffer],{type:"application/pdf"})},Gm=t=>{var e;try{let n=t.getContext("2d"),r=t.width,o=t.height;if(!n||r<4||o<4)return"#ffffff";let i=[[2,2],[r-3,2],[2,o-3],[r-3,o-3],[Math.floor(r/2),2],[2,Math.floor(o/2)],[r-3,Math.floor(o/2)],[Math.floor(r/2),o-3]],s=new Map;for(let[c,l]of i){let d=n.getImageData(c,l,1,1).data;if(d[3]<200)continue;let m=`${d[0]>>4}-${d[1]>>4}-${d[2]>>4}`,h=(e=s.get(m))!=null?e:{n:0,r:0,g:0,b:0};h.n++,h.r+=d[0],h.g+=d[1],h.b+=d[2],s.set(m,h)}let a=null;for(let c of s.values())(!a||c.n>a.n)&&(a=c);return a?`rgb(${Math.round(a.r/a.n)},${Math.round(a.g/a.n)},${Math.round(a.b/a.n)})`:"#ffffff"}catch{return"#ffffff"}},as=(t,e)=>({id:crypto.randomUUID(),name:e,blob:t,type:"pdf",size:t.size,metadata:{},history:[]}),Km=({license:t}={})=>{var Ws,Hs;let{uploadPdf:e,isLoading:n}=bl(),[r,o]=ae(null),[i,s]=ae(null),[a,c]=ae([]),[l,d]=ae({}),[m,h]=ae(!1),[f,p]=ae(!1),[w,b]=ae(""),[y,k]=ae("view"),[C,S]=ae(""),[F,O]=ae(14),[N,I]=ae({r:.84,g:0,b:.19}),R=1.4,[H,te]=ae(1),T=R*H,ce=we(null),[se,fe]=ae(0),pe=we({}),[ie,J]=ae({}),[_,Q]=ae(null),le=we(null),[ge,Xe]=ae({}),[Ce,Te]=ae(!1),[ht,et]=ae(0),[ct,Rt]=ae(!1),[ft,xn]=ae(!1),[be,Ve]=ae(null),bn=we(new Set),Pe=we(new Set),Ge=we({}),[Ze,Ne]=ae(""),[yn,vt]=ae(!1),[kr,At]=ae(!1),Mo=we(null),Pr=we(null),Sr=we(!1),cs=we(null),tn=we(null),He=we({}),ze=we({}),ot=we({}),kt=we({}),Ro=we({}),nn=we(null),Dr=we(new Set),[wn,Nt]=ae([]),[Re,bt]=ae(null),[Ol,ls]=ae(!1),Xt=we(null),Qn=we(!1),[Pt,vn]=ae([]),Ao=we(null),[je,Et]=ae(null),[mt,kn]=ae(null),[yt,ds]=ae(null),En=we(null),[Tn,us]=ae(null),er=we(null),Tt=we({}),[hs,Cr]=ae(0),[Il,Fr]=ae({}),[Pn,No]=ae(null),[Mr,Eo]=ae(null),[jl,To]=ae(!1),[On,Rr]=ae(null),tr=we(null),In=we({}),Oo=we(null),Io=we(!1),[jn,jo]=ae(null),fs=we(null),[Ar,nr]=ae(!1),[rn,ms]=ae(""),[ps,$l]=ae(""),[Nr,Er]=ae(0),[it,Tr]=ae([]),Or=we(null),[pt,$n]=ae([]),[tt,zt]=ae([]),[Ot,Bl]=ae({color:{r:1,g:.85,b:0},opacity:1,strokeWidth:2,fill:null}),Ll=u=>Bl(g=>({...g,...u})),[Sn,Ul]=ae("highlight"),[gs,_l]=ae("select"),[It,Xl]=ae("rect"),[rr,jt]=ae(null),[xs,St]=ae(null),[bs,Ir]=ae(!1),on=we(null),Yt=we(null),$o=we(!1),[ys,jr]=ae(null),[zl,Bn]=ae(!1),[ws,vs]=ae(null),[ks,$r]=ae(!1),Ln=we(null),Br=we(!1),Ps=we(null),[Un,Bo]=ae([]),[Ss,Ds]=ae(!1),Lo=()=>{var u;return{blob:(u=i!=null?i:r)!=null?u:null,annotations:pt,annots:tt}},Uo=(u,g,x,P,E)=>Bo(A=>{let B=[...A,{id:crypto.randomUUID(),time:new Date,action:u,icon:g,pageIndex:x,detail:P,snapshot:E}],M=B.length-Ym;return M<=0?B:B.map((L,j)=>j<M?{...L,snapshot:null}:L)}),Wt=(u,g,x,P)=>Uo(u,g,x,P,Lo()),Cs=u=>{var x;if(!u.snapshot)return;let g=u.snapshot;nn.current=null,Q(null),Et(null),kn(null),Nt([]),bt(null),$n(g.annotations),zt((x=g.annots)!=null?x:[]),jt(null),Bo(P=>{let E=P.findIndex(A=>A.id===u.id);return E<0?P:P.slice(0,E)}),s(g.blob===r?null:g.blob),b("Reverted to an earlier state.")},Yl=()=>{for(let u=Un.length-1;u>=0;u--)if(Un[u].snapshot){Cs(Un[u]);return}},[Wl,qm]=ae(90),[Fs,Jm]=ae(0),$t=we(0);wt(()=>{_n.getAvailableProcessors().includes("pdf-editor-core")||_n.registerProcessor(new so)},[]),wt(()=>{Pi(t!=null?t:{})},[t]);let Ms=wl(async u=>{if(!no())return u;try{let g=await yi(new Uint8Array(await u.arrayBuffer()));return new Blob([g],{type:"application/pdf"})}catch{return u}},[]),Ae=vl(()=>i!=null?i:r,[i,r]),_o=(Ws=r==null?void 0:r.name)!=null?Ws:"document.pdf",Xo=u=>{let g=Ro.current,x=u!=null?u:Object.keys(g).map(Number);for(let P of x){let E=g[P];E&&URL.revokeObjectURL(E),delete g[P]}},Rs=async(u,g)=>{var A,B;let x=g==null?void 0:g.onlyPages,P=!!x&&x.length>0,E=++$t.current;P||h(!0);try{let M=new Uint8Array(await u.arrayBuffer()),L=new Gt(M),j=L.parse(),$=Yn.getAllPages(j,{objectLoader:ee=>L.loadObject(ee)}).pages,G=$.map(ee=>{var ue;let q=(ue=ee.mediaBox)!=null?ue:[0,0,612,792];return{pageIndex:ee.pageNum-1,pageNum:ee.pageNum,width:Math.max(1,q[2]-q[0]),height:Math.max(1,q[3]-q[1]),mediaBox:q}});c(G);try{let ee=L.loadObject(j.rootRef),q=new Map;for(let xe of $)q.set(xe.pageNum-1,xe.dict);let ue=ee&&"entries"in ee?Fc(ee,q,xe=>L.loadObject(xe)):[],ye={},Oe={};for(let xe of ue)((B=ye[A=xe.pageIndex])!=null?B:ye[A]=[]).push(xe),xe.value!==void 0&&(Oe[xe.id]=xe.value);if(Tt.current=ye,tr.current){let xe=ue.find(Bt=>Bt.name===tr.current);Eo(xe?xe.id:null),xe&&(In.current[xe.id]=xe.name)}Fr(xe=>P?{...Oe,...xe}:Oe),To(ue.length>0),Cr(xe=>xe+1);let Ye=new Map;for(let xe of $)Ye.set(`${xe.ref.objNum}:${xe.ref.genNum}`,xe.pageNum-1);let Ie={};for(let xe of $){let Bt=Ui(xe.dict,Ye,Fe=>L.loadObject(Fe));Bt.length&&(Ie[xe.pageNum-1]=Bt)}pe.current=Ie}catch{Tt.current={},pe.current={},To(!1)}if(P||(Xo(),d({}),J({}),ze.current={},ot.current={},kt.current={}),$.length===0){b("No pages were found in this PDF.");return}P||b($.length>gn?`Loading first ${gn} pages...`:"Rendering pages...");let D=async ee=>{var Vs,qs;let q=ee.pageNum-1,ue=(Vs=ee.mediaBox)!=null?Vs:[0,0,612,792],ye=Math.max(1,ue[2]-ue[0]),Oe=Math.max(1,ue[3]-ue[1]),Ye=ee.dict.entries.get("Contents"),Ie=await fi(Ye,$e=>L.loadObject($e)),xe=Vt(Ie.combinedBytes),Bt=xe.length;if(Ie.streamCount>1&&Ie.streamByteLengths.length>0){let $e=Ie.combinedBytes.subarray(0,Ie.streamByteLengths[0]);Bt=Vt($e).length}let Fe=document.createElement("canvas"),Dt=new vr(Fe,Math.ceil(ye),Math.ceil(Oe),R,{disableClip:!1,debug:!1});Dt.setFontContext(ee.resources,$e=>L.loadObject($e)),await Dt.renderAsync(xe),await Dt.renderAnnotations(ee.dict);let _r=Dt.getCapturedTextRuns().filter($e=>$e.text.trim().length>0).map($e=>{let Js=jc($e,q,Oe,R);return Ie.streamCount>1&&$e.streamOperatorIndex>=Bt?{...Js,contentStreamIndex:1}:Js}),Fd=fo(_r),Md=[...Dt.getCapturedImages().map($e=>Oc($e,q,Oe,R)),...Dt.getCapturedGraphics().map($e=>Ic($e,q,Oe,R))];if(no()){let $e=Fe.getContext("2d");$e&&bi($e,Fe.width,Fe.height)}let Jo=await new Promise($e=>Fe.toBlob($e,"image/png"));Xo([q]);let Gs=Jo?URL.createObjectURL(Jo):Fe.toDataURL("image/png");Jo&&(Ro.current[q]=Gs);let Rd={pageIndex:q,pageNum:ee.pageNum,canvasDataUrl:Gs,canvasWidth:Fe.width,canvasHeight:Fe.height,mediaBox:ue,textRuns:_r,bgCss:Gm(Fe)},Zo=(qs=Ge.current[q])!=null?qs:[],Ks=Zo.length?[..._r,...Zo]:_r,Ad=Zo.length?fo(Ks):Fd;d($e=>({...$e,[q]:Rd})),J($e=>({...$e,[q]:{width:ye,height:Oe}})),ze.current={...ze.current,[q]:Ks},ot.current={...ot.current,[q]:Ad},kt.current={...kt.current,[q]:Md}};if(P){let ee=new Set(x);for(let ue of $)if(ee.has(ue.pageNum-1)){if($t.current!==E)return;await D(ue)}let q=$.filter(ue=>{let ye=ue.pageNum-1;return!ee.has(ye)&&!ze.current[ye]});for(let ue of q){if($t.current!==E||(await new Promise(ye=>setTimeout(ye,Ml)),$t.current!==E))return;await D(ue)}return}let z=$.slice(0,gn);for(let ee of z){if($t.current!==E)return;await D(ee)}$t.current===E&&(h(!1),At(!1),$.length>gn&&b(`Showing ${gn} of ${$.length} pages, loading remaining pages in background...`));let U=new Map($.slice(gn).map(ee=>[ee.pageNum-1,ee])),W=$.length>Wm,V=()=>{let ee=[...U.keys()];if(W&&Dr.current.size>0){let q,ue=1/0;for(let ye of ee)for(let Oe of Dr.current){let Ye=Math.abs(ye-Oe);Ye<=Hm&&Ye<ue&&(q=ye,ue=Ye)}if(q!==void 0)return q}return Math.min(...ee)},ne=0;for(;U.size>0;){if($t.current!==E||(await new Promise(ye=>setTimeout(ye,Ml)),$t.current!==E))return;let ee=V(),q=U.get(ee);if(U.delete(ee),!q)continue;await D(q),ne+=1;let ue=gn+ne;b(`Loaded ${ue}/${$.length} pages...`)}if($t.current!==E)return;$.length>gn&&b(`All ${$.length} pages loaded.`)}catch(M){P||(c([]),d({}),J({}),ze.current={},ot.current={},kt.current={}),b(M instanceof Error?`Engine render failed: ${M.message}`:"Engine render failed")}finally{$t.current===E&&(h(!1),At(!1))}};wt(()=>{let u=g=>{(g.ctrlKey||g.metaKey)&&g.key==="f"&&(g.preventDefault(),nr(!0),setTimeout(()=>{var x;return(x=Or.current)==null?void 0:x.focus()},50)),g.key==="Escape"&&nr(!1)};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[]),wt(()=>{if(!rn.trim()){Tr([]),Er(0);return}let u=rn.toLowerCase(),g=[];for(let x of Object.values(ze.current))for(let P of x)P.text.toLowerCase().includes(u)&&g.push(P);Tr(g),Er(0)},[rn]),wt(()=>{if(!Ae){Xo(),c([]),d({}),J({}),ze.current={},ot.current={},kt.current={};return}let u=nn.current;nn.current=null,u?Rs(Ae,{onlyPages:u}):Rs(Ae)},[Ae]),wt(()=>{let u=Ro.current;return()=>{for(let g of Object.values(u))URL.revokeObjectURL(g)}},[]),wt(()=>{if(typeof IntersectionObserver=="undefined")return;let u=Dr.current,g=new IntersectionObserver(x=>{for(let P of x){let E=P.target.dataset.pageIndex;if(E===void 0)continue;let A=Number(E);P.isIntersecting?u.add(A):u.delete(A)}u.size&&fe(Math.min(...u))},{rootMargin:"300px"});for(let[x,P]of Object.entries(He.current))P&&(P.dataset.pageIndex=x,g.observe(P));return()=>{g.disconnect(),u.clear()}},[a]);let Hl=u=>{switch(u.type){case"insert-text":return`"${u.text}"`;case"replace-text":return`\u2192 "${u.newText}"`;case"create-form-field":return`${u.fieldType} "${u.name}"`;case"set-form-values":return u.values.map(g=>`${g.name} = "${g.value}"`).join(", ");case"delete-form-field":return`"${u.name}"`;case"rotate-page":return`${u.degrees}\xB0`;case"redact-area":return`${Math.round(u.width)}\xD7${Math.round(u.height)} area`;default:return}},st=async(u,g)=>{var P,E,A,B;if(!Ae)return;let x=Lo();p(!0),b("Applying change...");try{let M=(P=r==null?void 0:r.name)!=null?P:"document.pdf",L=as(Ae,M),j=await _n.runPipeline(L,{tasks:[{processorName:"pdf-editor-core",params:{operations:[u]}}]}),X=j[j.length-1];if(!(X!=null&&X.success)){b((E=X==null?void 0:X.error)!=null?E:"Operation failed");return}nn.current=u.type==="replace-text"||u.type==="insert-text"||u.type==="redact-area"||u.type==="delete-object"||u.type==="transform-object"||u.type==="insert-image"||u.type==="create-form-field"?[u.pageIndex]:u.type==="set-form-values"&&u.pageIndex!==void 0?[u.pageIndex]:null,s(X.document.blob),Et(null),kn(null),b("Saved");let $={"replace-text":"\u270F\uFE0F","insert-text":"\u{1F4DD}","redact-area":"\u2B1B","delete-object":"\u{1F9F9}","transform-object":"\u2194\uFE0F","insert-image":"\u{1F5BC}\uFE0F","rotate-page":"\u21BB","delete-page":"\u{1F5D1}\uFE0F","create-form-field":"\u{1F532}","set-form-values":"\u270D\uFE0F","delete-form-field":"\u{1F5D1}\uFE0F","flatten-form":"\u{1F4CB}"},G={"replace-text":"Edited text","insert-text":"Added text","redact-area":"Redacted area","delete-object":"Deleted object","transform-object":"Moved object","insert-image":"Inserted image","rotate-page":"Rotated page","delete-page":"Deleted page","create-form-field":"Added form field","set-form-values":"Filled form","delete-form-field":"Deleted form field","flatten-form":"Flattened form"},D="pageIndex"in u?u.pageIndex:void 0;Uo((A=G[u.type])!=null?A:u.type,(B=$[u.type])!=null?B:"\u2699\uFE0F",D,g!=null?g:Hl(u),x)}catch(M){b(M instanceof Error?M.message:"Operation failed")}finally{p(!1)}},Gl=async(u,g,x,P)=>{var A,B;if(!Ae||u.length===0)return;let E=Lo();p(!0),b("Applying change...");try{let M=(A=r==null?void 0:r.name)!=null?A:"document.pdf",L=as(Ae,M),j=await _n.runPipeline(L,{tasks:[{processorName:"pdf-editor-core",params:{operations:u}}]}),X=j[j.length-1];if(!(X!=null&&X.success)){b((B=X==null?void 0:X.error)!=null?B:"Operation failed");return}let $=Array.from(new Set(u.map(D=>"pageIndex"in D?D.pageIndex:-1).filter(D=>D>=0)));nn.current=$.length?$:null,s(X.document.blob),Et(null),kn(null),b("Saved");let G=$.length?$[0]:void 0;Uo(g,x,G,P,E)}catch(M){b(M instanceof Error?M.message:"Operation failed")}finally{p(!1)}},As=(u,g,x,P)=>{var j,X;P.stopPropagation(),P.preventDefault();let E=ie[u.pageIndex],A=(j=E==null?void 0:E.width)!=null?j:612,B=(X=E==null?void 0:E.height)!=null?X:792;Ao.current={id:u.id,pageIndex:u.pageIndex,mode:g,handle:x,startClientX:P.clientX,startClientY:P.clientY,startRect:{x:u.x,y:u.y,width:u.width,height:u.height}};let M=$=>{var ue;let G=Ao.current;if(!G)return;let D=($.clientX-G.startClientX)/T,z=-($.clientY-G.startClientY)/T,U=G.startRect,W=U.x,V=U.y,ne=U.width,ee=U.height;if(G.mode==="move")W=U.x+D,V=U.y+z;else{let ye=(ue=G.handle)!=null?ue:"se",Oe=U.x,Ye=U.x+U.width,Ie=U.y,xe=U.y+U.height;ye.includes("e")&&(Ye=U.x+U.width+D),ye.includes("w")&&(Oe=U.x+D),ye.includes("n")&&(xe=U.y+U.height+z),ye.includes("s")&&(Ie=U.y+z),W=Math.min(Oe,Ye),ne=Math.abs(Ye-Oe),V=Math.min(Ie,xe),ee=Math.abs(xe-Ie)}let q=4;ne=Math.max(q,ne),ee=Math.max(q,ee),W=Math.max(0,Math.min(A-ne,W)),V=Math.max(0,Math.min(B-ee,V)),vn(ye=>ye.map(Oe=>Oe.id===G.id?{...Oe,x:W,y:V,width:ne,height:ee}:Oe))},L=()=>{window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",L),Ao.current=null};window.addEventListener("mousemove",M),window.addEventListener("mouseup",L)},Kl=u=>vn(g=>g.filter(x=>x.id!==u)),Vl=async()=>{if(Pt.length===0)return;let u=Pt.map(x=>{var X;let P=x.x,E=x.x+x.width,A=x.y,B=x.y+x.height,M=(X=ze.current[x.pageIndex])!=null?X:[],L=$=>$.pdfX<E&&$.pdfX+$.width>P&&$.pdfY<B&&$.pdfY+$.height>A,j=M.filter($=>!$.fromXObject&&L($)).flatMap($=>{var G;return(G=$.streamOperatorIndices)!=null?G:[]});return{type:"redact-area",pageIndex:x.pageIndex,x:P,y:A,width:x.width,height:x.height,color:{r:0,g:0,b:0},padding:1.5,removeOperators:j.length?{streamOperatorIndices:j}:void 0}}),g=u.length;vn([]),await Gl(u,"Redacted area","\u2B1B",`${g} area${g>1?"s":""} redacted`)},zo=(u,g,x,P,E)=>new Promise(A=>{let B=l[u],M=ie[u];if(!B||!M)return A({r:1,g:1,b:1});let L=new Image;L.onload=()=>{try{let j=document.createElement("canvas");j.width=L.width,j.height=L.height;let X=j.getContext("2d");if(!X)return A({r:1,g:1,b:1});X.drawImage(L,0,0);let $=L.width/M.width,G=L.height/M.height,D=E*.5,z=x-D,U=E+D*2,W=Math.max(0,Math.floor(g*$)),V=Math.max(0,Math.floor((M.height-z-U)*G)),ne=Math.max(1,Math.min(Math.ceil(P*$),L.width-W)),ee=Math.max(1,Math.min(Math.ceil(U*G),L.height-V)),q=X.getImageData(W,V,ne,ee).data,ue=0,ye=0,Oe=0,Ye=0;for(let Ie=0;Ie<q.length;Ie+=4)(q[Ie]+q[Ie+1]+q[Ie+2])/3>160&&(ue+=q[Ie],ye+=q[Ie+1],Oe+=q[Ie+2],Ye++);if(Ye===0)return A({r:1,g:1,b:1});A({r:ue/Ye/255,g:ye/Ye/255,b:Oe/Ye/255})}catch{A({r:1,g:1,b:1})}},L.onerror=()=>A({r:1,g:1,b:1}),L.src=B.canvasDataUrl}),ql=u=>{let[g,x]=u.split(","),P=atob(x!=null?x:""),E=new Uint8Array(P.length);for(let A=0;A<P.length;A++)E[A]=P.charCodeAt(A);return{bytes:E,format:g.includes("image/png")?"png":"jpeg"}},Ns=async()=>{var g,x,P,E;if(!Ae)return;let u=((g=r==null?void 0:r.name)!=null?g:"document").replace(/\.pdf$/i,"");if(tt.length===0&&pt.length===0){let A=await Ms(Ae),B=URL.createObjectURL(A),M=document.createElement("a");M.href=B,M.download=`${u}-edited.pdf`,M.click(),URL.revokeObjectURL(B),Wt("Downloaded PDF","\u2B07\uFE0F");return}p(!0),b("Writing annotations\u2026");try{let A=[];for(let z of tt)A.push({type:"add-annotation",annotation:z});for(let z of pt){let U=ie[z.pageIndex];if(U){if(z.kind==="comment"){let W={id:z.id,pageIndex:z.pageIndex,kind:"note",rect:{x:z.x/T,y:U.height-(z.y+22)/T,width:22/T,height:22/T},text:(x=z.text)!=null?x:"",style:{color:{r:.96,g:.62,b:.04},opacity:1},createdAt:Date.now()};A.push({type:"add-annotation",annotation:W})}else if(z.kind==="sign"){let{bytes:W,format:V}=ql(z.dataUrl);A.push({type:"insert-image",pageIndex:z.pageIndex,bytes:W,format:V,x:z.x/T,y:U.height-(z.y+z.height)/T,width:z.width/T,height:z.height/T})}}}let B=as(Ae,(P=r==null?void 0:r.name)!=null?P:"document.pdf"),M=await _n.runPipeline(B,{tasks:[{processorName:"pdf-editor-core",params:{operations:A}}]}),L=M[M.length-1];if(!(L!=null&&L.success)){b((E=L==null?void 0:L.error)!=null?E:"Could not write annotations.");return}let j=L.document.blob,X=A.length;s(j),zt([]),$n([]),jt(null),nn.current=null;let $=await Ms(j),G=URL.createObjectURL($),D=document.createElement("a");D.href=G,D.download=`${u}-annotated.pdf`,D.click(),URL.revokeObjectURL(G),Wt(`Downloaded with ${X} annotation${X!==1?"s":""}`,"\u2B07\uFE0F")}catch(A){b("Download failed: "+(A instanceof Error?A.message:String(A)))}finally{p(!1),b("")}};yl({enabled:!!Ae,onUndo:Yl,onSave:()=>{f||Ns()}});let Jl=async(u,g)=>{if(!Ae||y!=="add-text"&&y!=="stamp")return;let x=ie[g];if(!x)return;let P=He.current[g];if(!P)return;let E=P.getBoundingClientRect(),A=dt(u.clientX,u.clientY,E,T,x.height);if(y==="add-text"){Ql(g,A.x,A.y);return}let B=C.trim();if(!B){b("Type or pick a stamp first.");return}await st({type:"insert-text",pageIndex:g,text:B,x:A.x,y:A.y,size:F,color:N},`"${B}" stamp`)},Es=(u,g,x,P,E)=>{var G;let A=Jr(u,(G=ze.current[x])!=null?G:[],P.width),B=Math.max(1,g*.1),M=Math.max(0,u.x-B),L=Math.max(0,u.y-B),j={x:M,y:L,width:Math.min(P.width,u.x+u.width+B)-M,height:Math.min(P.height,u.y+u.height+B)-L},X=Zr(j,A),$=Ke(X.x,X.y+X.height,T,P.height);return{eraseClamp:A,maskRect:{x:$.x-E.x,y:$.y-E.y,w:X.width*T,h:X.height*T}}},Ts=(u,g)=>{zo(u,g.x,g.y,g.width,Math.max(8,g.height)).then(x=>{Q(P=>P&&P.pageIndex===u&&P.pdfX===g.x&&P.pdfY===g.y?{...P,bgColor:x}:P)})},Zl=()=>{let u=Array.from(Dr.current);return u.length?Math.min(...u):0},Os=async u=>{var P;let g=l[u],x=ie[u];if(!g||!x){b("Page not ready yet.");return}Te(!0),b(`Recognizing text on page ${u+1}\u2026`);try{let E=await(await fetch(g.canvasDataUrl)).blob(),A=new FormData;A.append("file",new File([E],`page-${u+1}.png`,{type:"image/png"}));let B=await fetch("/api/ocr",{method:"POST",body:A});if(!B.ok){B.status===401&&window.dispatchEvent(new Event("namaha:needs-auth"));let $=await B.json().catch(()=>({}));throw new Error($.error||`OCR failed (${B.status})`)}let{words:M}=await B.json(),L=g.canvasWidth/Math.max(1,x.width),j=Lc(M!=null?M:[],u,x.height,L);if(Pe.current.add(u),j.length===0){b("No text recognized on this page."),et($=>$+1);return}Ge.current[u]=j;let X=[...(P=ze.current[u])!=null?P:[],...j];ze.current={...ze.current,[u]:X},ot.current={...ot.current,[u]:fo(X)},et($=>$+1),b(`Recognized ${j.length} line${j.length===1?"":"s"}, text is now selectable & editable.`)}catch(E){b(E instanceof Error?E.message:"OCR failed.")}finally{Te(!1)}},Yo=u=>{var x;let g=((x=u.fontName)!=null?x:"").toLowerCase();return{bold:/bold|black|heavy|semibold/.test(g),italic:/italic|oblique/.test(g),color:u.color}},Wo=()=>{_&&le.current&&le.current.commit()},Is=(u,g)=>{let x=ie[g];if(!x)return;Wo();let P=Ke(u.pdfX,u.pdfY+u.height,T,x.height),E={x:u.pdfX,y:u.pdfY,width:u.width,height:u.height},{eraseClamp:A,maskRect:B}=Es(E,u.fontSize,g,x,P),M=(x.height-u.pdfBaselineY)*T;Q({pageIndex:g,value:u.text,spans:[{text:u.text,style:Yo(u)}],pdfX:u.pdfX,pdfY:u.pdfY,pdfBaselineY:u.pdfBaselineY,width:u.width,height:u.height,fontSize:u.fontSize,fontName:u.fontName,fontFamily:u.fontFamily,color:u.color,containerX:P.x,containerY:P.y,screenWidth:Math.max(60,u.width*T),screenHeight:Math.max(16,u.height*T),baselineOffsetPx:M-P.y,maxWidth:Math.max(60,x.width*T-P.x-2),eraseClamp:A,maskRect:B,streamOperatorIndices:u.streamOperatorIndices,fromXObject:u.fromXObject,originalText:u.text,ocr:u.ocr}),Ts(g,E)},Ql=(u,g,x)=>{let P=ie[u];if(!P)return;Wo();let E=F,A=Ke(g,x+E,T,P.height);Q({pageIndex:u,value:"",spans:[],isNew:!0,pdfX:g,pdfY:x,pdfBaselineY:x,width:120,height:E,fontSize:E,color:{r:0,g:0,b:0},containerX:A.x,containerY:A.y,screenWidth:Math.max(60,120*T),screenHeight:Math.max(16,E*T),baselineOffsetPx:E*T,maxWidth:Math.max(60,P.width*T-A.x-2)})},ed=(u,g)=>{var L;if(y!=="edit-text")return;let x=ie[g],P=He.current[g];if(!x||!P)return;let E=P.getBoundingClientRect(),A=dt(u.clientX,u.clientY,E,T,x.height),B=(L=ot.current[g])!=null?L:ze.current[g],M=Ec(A,B,6);M&&Is(M,g)},js=async u=>{var B,M,L,j;if(!rn.trim())return;let g=u.text.replace(new RegExp(rn.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),ps);if(g===u.text)return;let x=await zo(u.pageIndex,u.pdfX,u.pdfY,u.width,u.height),P=Jr({x:u.pdfX,y:u.pdfY,width:u.width,height:u.height},(B=ze.current[u.pageIndex])!=null?B:[],(L=(M=ie[u.pageIndex])==null?void 0:M.width)!=null?L:612);await st({type:"replace-text",pageIndex:u.pageIndex,x:u.pdfX,y:u.pdfY,width:u.width,height:u.height,baselineY:u.pdfBaselineY,newText:g,erasePadding:Math.max(1,u.fontSize*.1),eraseClamp:P,removeOperators:!u.fromXObject&&((j=u.streamOperatorIndices)!=null&&j.length)?{streamOperatorIndices:u.streamOperatorIndices}:void 0,size:u.fontSize,backgroundColor:x,font:u.fontName?{pdfName:u.fontName,sizePt:u.fontSize}:void 0,color:u.color});let E=rn.toLowerCase(),A=[];for(let X of Object.values(ze.current))for(let $ of X)$.text.toLowerCase().includes(E)&&A.push($);Tr(A)},td=async()=>{let u=[...it];for(let g of u)await js(g)},$s=async u=>{var P,E,A,B,M,L,j;let g=(P=u.bgColor)!=null?P:await zo(u.pageIndex,u.x,u.y,u.width,Math.max(8,u.height)),x=(M=u.eraseClamp)!=null?M:Jr({x:u.x,y:u.y,width:u.width,height:u.height},(E=ze.current[u.pageIndex])!=null?E:[],(B=(A=ie[u.pageIndex])==null?void 0:A.width)!=null?B:612);await st({type:"replace-text",pageIndex:u.pageIndex,x:u.x,y:u.y,width:u.width,height:u.height,baselineY:u.baselineY,newText:u.newText,erasePadding:Math.max(1,u.fontSize*.1),eraseClamp:x,removeOperators:!u.fromXObject&&((L=u.streamOperatorIndices)!=null&&L.length)?{streamOperatorIndices:u.streamOperatorIndices}:void 0,size:u.fontSize,backgroundColor:g,font:u.fontName?{pdfName:u.fontName,sizePt:u.fontSize,color:u.color}:void 0,color:u.color,spans:(j=u.spans)!=null&&j.length?u.spans:void 0},u.detail)},nd=u=>{if(!u)return!0;let g=u.replace(/^[A-Z]{6}\+/,"").toLowerCase();return/(helvetica|arial|times|courier|symbol|zapf|calibri|cambria|verdana|georgia|tahoma|segoe|roboto|liberation|dejavu|noto|sans|serif|mono)/.test(g)},Bs=async u=>{if(u.ocr){let g=Ge.current[u.pageIndex];g&&(Ge.current[u.pageIndex]=g.filter(x=>!(Math.abs(x.pdfX-u.pdfX)<.6&&Math.abs(x.pdfY-u.pdfY)<.6)))}await $s({pageIndex:u.pageIndex,x:u.pdfX,y:u.pdfY,baselineY:u.pdfBaselineY,width:u.width,height:u.height,newText:u.value,spans:u.spans,fontSize:u.fontSize,fontName:u.fontName,color:u.color,streamOperatorIndices:u.streamOperatorIndices,fromXObject:u.fromXObject,bgColor:u.bgColor,eraseClamp:u.eraseClamp,detail:u.originalText!==void 0&&u.originalText!==u.value?`"${u.originalText}" \u2192 "${u.value}"`:`"${u.value}"`})},rd=async(u,g)=>{var X;let x=_;if(Q(null),!x)return;let P=Cn(u),E=x.isNew?{}:Yo({fontName:x.fontName,color:x.color}),A=wa(P,E);if(x.isNew){if(g.trim().length===0)return;await st({type:"insert-text",pageIndex:x.pageIndex,text:g,x:x.pdfX,y:x.pdfBaselineY,size:x.fontSize,spans:A?P:void 0},`"${g}"`);return}let B=$=>Cn($).map(G=>`${G.text}\0${cn(G.style)}`).join("");if(B(P)===B((X=x.spans)!=null?X:[]))return;let M={...x,spans:A?P:void 0,value:g},L=x.fontName;if(!x.ocr&&!!L&&!nd(L)&&!bn.current.has(L)){Ve(M);return}await Bs(M)},od=(u,g,x,P)=>{var B;let E=x/T,A=-P/T;$s({pageIndex:g,x:u.pdfX+E,y:u.pdfY+A,baselineY:((B=u.pdfBaselineY)!=null?B:u.pdfY)+A,width:u.width,height:u.height,newText:u.text,fontSize:u.fontSize,fontName:u.fontName,color:u.color,streamOperatorIndices:u.streamOperatorIndices,fromXObject:u.fromXObject,detail:`moved "${u.text}"`})},id=(u,g,x)=>{var X;let P=x.clientX,E=x.clientY,A=!u.fromXObject&&!!((X=u.streamOperatorIndices)!=null&&X.length);er.current={pageIndex:g,run:u,dxPx:0,dyPx:0},us({pageIndex:g,run:u,dxPx:0,dyPx:0});let B=$=>{if(!er.current)return;let G=$.clientX-P,D=$.clientY-E;er.current={pageIndex:g,run:u,dxPx:G,dyPx:D},Pr.current&&(Pr.current.style.transform=`translate(${G}px, ${D}px)`)},M=$=>{window.removeEventListener("mousemove",B),window.removeEventListener("mouseup",L),window.removeEventListener("keydown",j);let G=er.current;if(er.current=null,Pr.current=null,us(null),Sr.current=!0,!G)return;let D=Math.abs(G.dxPx)>=3||Math.abs(G.dyPx)>=3;$&&(D?A&&od(u,g,G.dxPx,G.dyPx):Is(u,g))},L=()=>M(!0),j=$=>{$.key==="Escape"&&($.stopPropagation(),M(!1))};window.addEventListener("mousemove",B),window.addEventListener("mouseup",L),window.addEventListener("keydown",j)},Lr=(u,g)=>{Fr(x=>({...x,[u.id]:g})),u.value=g,st({type:"set-form-values",pageIndex:u.pageIndex,values:[{name:u.name,fieldType:u.type,value:g}]})},sd=(u,g,x)=>{var j,X;let P={x:x.x,y:x.y,width:Math.max(12,x.width),height:Math.max(g==="checkbox"||g==="radio"?12:16,x.height)},E=`${g}_${Date.now().toString(36)}`,A=g==="dropdown"?["Option 1","Option 2"]:g==="radio"?["Choice 1","Choice 2"]:void 0,B=g==="checkbox"?"Yes":void 0,M={id:`${E}__new`,name:E,type:g,pageIndex:u,rect:P,value:g==="checkbox"?"Off":"",options:A,onState:B,fontSize:0,isNew:!0};((X=(j=Tt.current)[u])!=null?X:j[u]=[]).push(M),In.current[M.id]=E,Cr($=>$+1),To(!0),Ho(M),No(null);let L=g==="radio"?(A!=null?A:[]).map(($,G)=>({x:P.x,y:P.y-G*(P.height+4),width:P.width,height:P.height})):void 0;st({type:"create-form-field",pageIndex:u,fieldType:g,name:E,rect:P,value:M.value,options:A,optionRects:L,fontSize:0})},Ls=u=>{var P,E;let g=(P=In.current[u.id])!=null?P:u.name,x=(E=Tt.current[u.pageIndex])!=null?E:[];Tt.current[u.pageIndex]=x.filter(A=>A.id!==u.id),delete In.current[u.id],Ho(null),Cr(A=>A+1),st({type:"delete-form-field",name:g})},ad=async()=>{await st({type:"flatten-form"}),b("Form flattened, values are now baked into the page.")},Ho=u=>{var g,x;Eo((g=u==null?void 0:u.id)!=null?g:null),tr.current=(x=u==null?void 0:u.name)!=null?x:null},or=vl(()=>{if(!Mr)return null;for(let u of Object.values(Tt.current)){let g=u.find(x=>x.id===Mr);if(g)return g}return null},[Mr,hs]),cd=(u,g)=>{var M,L;let x=(M=Tt.current[u.pageIndex])!=null?M:[],P={...u,...g,rect:{...u.rect,...(L=g.rect)!=null?L:{}}};Tt.current[u.pageIndex]=x.map(j=>j.id===u.id?P:j),g.value!==void 0&&Fr(j=>{var X;return{...j,[u.id]:String((X=g.value)!=null?X:"")}}),g.name!==void 0&&(tr.current=P.name),Cr(j=>j+1),Oo.current&&clearTimeout(Oo.current);let E=u.id,A=P.pageIndex,B=u.name;Oo.current=setTimeout(()=>{var G,D,z;let j=((G=Tt.current[A])!=null?G:[]).find(U=>U.id===E);if(!j)return;let X=(D=In.current[E])!=null?D:B,$=j.type==="radio"?((z=j.options)!=null?z:[]).map((U,W)=>({x:j.rect.x,y:j.rect.y-W*(j.rect.height+4),width:j.rect.width,height:j.rect.height})):void 0;In.current[E]=j.name,st({type:"update-form-field",oldName:X,pageIndex:j.pageIndex,fieldType:j.type,name:j.name,rect:j.rect,value:j.value,options:j.options,optionRects:$,fontSize:j.fontSize,required:j.required,readOnly:j.readOnly,multiline:j.multiline,align:j.align,maxLength:j.maxLength,editable:j.editable})},400)},ld=.25,dd=5,Go=u=>Math.max(ld,Math.min(dd,u)),Us=u=>te(g=>Go(g*u)),ud=()=>{var x;let u=ce.current,g=(x=ie[se])!=null?x:ie[0];!u||!g||te(Go((u.clientWidth-96)/(g.width*R)))},hd=()=>{var x;let u=ce.current,g=(x=ie[se])!=null?x:ie[0];!u||!g||te(Go((u.clientHeight-96)/(g.height*R)))},Ur=u=>{var x;let g=Math.max(0,Math.min(a.length-1,u));(x=He.current[g])==null||x.scrollIntoView({behavior:"smooth",block:"start"})},fd=(u,g)=>{if(!Pn)return;let x=He.current[u],P=ie[u];if(!x||!P)return;g.preventDefault(),g.stopPropagation();let E=x.getBoundingClientRect(),A=g.clientX-E.left,B=g.clientY-E.top,M=Pn,L=X=>{let $=Math.min(A,X.clientX-E.left),G=Math.min(B,X.clientY-E.top),D=Math.abs(X.clientX-E.left-A),z=Math.abs(X.clientY-E.top-B);Rr({pageIndex:u,x:$,y:G,w:D,h:z})},j=X=>{window.removeEventListener("mousemove",L),window.removeEventListener("mouseup",j),Rr(null);let $=X.clientX-E.left,G=X.clientY-E.top,D=Math.min(A,$),z=Math.min(B,G),U=Math.max(Math.abs($-A),80),W=Math.max(Math.abs(G-B),M==="checkbox"||M==="radio"?16:22),V=D/T,ne=P.height-(z+W)/T;sd(u,M,{x:V,y:ne,width:U/T,height:W/T})};Rr({pageIndex:u,x:A,y:B,w:0,h:0}),window.addEventListener("mousemove",L),window.addEventListener("mouseup",j)},md=(u,g)=>{let x=ze.current[u];if(!x)return[];let P=Math.min(g.startPdfX,g.endPdfX),E=Math.max(g.startPdfX,g.endPdfX),A=Math.min(g.startPdfY,g.endPdfY),B=Math.max(g.startPdfY,g.endPdfY);return x.filter(M=>M.pdfX<E&&M.pdfX+M.width>P&&M.pdfY<B&&M.pdfY+M.height>A)},_s=(u,g)=>{for(let x=tt.length-1;x>=0;x--){let P=tt[x];if(P.pageIndex===u&&Ga(g,P))return P}return null},Xs=(u,g,x,P)=>{let E=P.clientX,A=P.clientY,B=!1,M=j=>{let X=(j.clientX-E)/T,$=-(j.clientY-A)/T;(Math.abs(j.clientX-E)>2||Math.abs(j.clientY-A)>2)&&(B=!0),zt(G=>G.map(D=>{if(D.id!==u.id)return D;if(g==="move")return Ka(u,X,$);let z=at(u),U=z.x,W=z.y,V=z.width,ne=z.height;return x==="ne"?(V=z.width+X,ne=z.height+$):x==="nw"?(U=z.x+X,V=z.width-X,ne=z.height+$):x==="se"?(W=z.y+$,V=z.width+X,ne=z.height-$):x==="sw"&&(U=z.x+X,W=z.y+$,V=z.width-X,ne=z.height-$),V<5||ne<5?D:Va(u,{x:U,y:W,width:V,height:ne})}))},L=()=>{window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",L),B&&($o.current=!0,Wt(g==="move"?"Moved annotation":"Resized annotation","\u2725"))};window.addEventListener("mousemove",M),window.addEventListener("mouseup",L)},pd=(u,g,x)=>{let P=tt.find(E=>E.id===u);P&&Xs(P,"resize",g,x)},gd=(u,g)=>{if(u.button!==0||y==="view"||y==="form")return;if(y==="annotate"||y==="draw"){let B=ie[g],M=He.current[g];if(!B||!M)return;u.preventDefault();let L=M.getBoundingClientRect(),j=dt(u.clientX,u.clientY,L,T,B.height);if(y==="annotate"){Sn==="brush"?(on.current={pageIndex:g,pt:j},St({kind:"ink",pageIndex:g,points:[j]})):Sn==="highlight"&&gs==="box"?(on.current={pageIndex:g,pt:j},St({kind:"box",pageIndex:g,rect:{x:j.x,y:j.y,width:0,height:0}})):(on.current={pageIndex:g,pt:j},St({kind:"quads",pageIndex:g,quads:[]})),Ir(!0);return}if(It==="polygon")return;on.current={pageIndex:g,pt:j},St(It==="line"||It==="arrow"?{kind:"line",pageIndex:g,a:j,b:j,arrow:It==="arrow"}:{kind:"box",pageIndex:g,rect:{x:j.x,y:j.y,width:0,height:0}}),Ir(!0);return}if(y==="select"){let B=ie[g],M=He.current[g];if(B&&M){let L=M.getBoundingClientRect(),j=dt(u.clientX,u.clientY,L,T,B.height),X=_s(g,j);if(X){u.preventDefault(),jt(X.id),Et(null),Xs(X,"move",void 0,u);return}}if(je&&!je.fromXObject&&je.pageIndex===g){let L=ie[g],j=He.current[g];if(!L||!j)return;let X=j.getBoundingClientRect(),$=dt(u.clientX,u.clientY,X,T,L.height);ho($,kt.current[g])===je&&(u.preventDefault(),zs(je,"move",null,u))}return}if(y!=="edit-text"&&y!=="redact")return;u.preventDefault();let x=ie[g],P=He.current[g];if(!x||!P)return;let E=P.getBoundingClientRect(),A=dt(u.clientX,u.clientY,E,T,x.height);Qn.current=!1,Sr.current=!1,Xt.current={pageIndex:g,pdfX:A.x,pdfY:A.y},ls(!0),Nt([]),bt(null),Q(null)},xd=(u,g)=>{var B;if(y==="select"){if(En.current)return;let M=ie[g],L=He.current[g];if(!M||!L)return;let j=L.getBoundingClientRect(),X=dt(u.clientX,u.clientY,j,T,M.height),$=ho(X,kt.current[g]);kn(G=>G===$?G:$);return}if(y==="draw"&&It==="polygon"&&((B=Yt.current)==null?void 0:B.pageIndex)===g){let M=ie[g],L=He.current[g];if(!M||!L)return;let j=L.getBoundingClientRect(),X=dt(u.clientX,u.clientY,j,T,M.height);St({kind:"polygon",pageIndex:g,points:Yt.current.points,cursor:X});return}if(bs&&on.current&&on.current.pageIndex===g){let M=ie[g],L=He.current[g];if(!M||!L)return;let j=L.getBoundingClientRect(),X=dt(u.clientX,u.clientY,j,T,M.height),$=on.current.pt;St(G=>{var D,z;if(!G)return G;if(G.kind==="quads"){let U=(z=(D=ot.current[g])!=null?D:ze.current[g])!=null?z:[];return{kind:"quads",pageIndex:g,quads:Sc(U,$,X).quads}}return G.kind==="box"?{kind:"box",pageIndex:g,rect:{x:Math.min($.x,X.x),y:Math.min($.y,X.y),width:Math.abs(X.x-$.x),height:Math.abs(X.y-$.y)}}:G.kind==="line"?{...G,b:X}:G.kind==="ink"?{...G,points:[...G.points,X]}:G});return}if(!Ol||!Xt.current||Xt.current.pageIndex!==g)return;let x=ie[g],P=He.current[g];if(!x||!P)return;let E=P.getBoundingClientRect(),A=dt(u.clientX,u.clientY,E,T,x.height);if(!Qn.current){let M=Math.abs(A.x-Xt.current.pdfX)*T,L=Math.abs(A.y-Xt.current.pdfY)*T;if(M<6&&L<6)return;Qn.current=!0,bt({pageIndex:g,startPdfX:Xt.current.pdfX,startPdfY:Xt.current.pdfY,endPdfX:A.x,endPdfY:A.y});return}bt({pageIndex:g,startPdfX:Xt.current.pdfX,startPdfY:Xt.current.pdfY,endPdfX:A.x,endPdfY:A.y})},bd=(u,g)=>{if(bs){Ir(!1),on.current=null;let P=xs;if(St(null),!P||P.pageIndex!==g)return;let E={color:Ot.color,opacity:Ot.opacity,strokeWidth:Ot.strokeWidth,fill:Ot.fill},A={id:crypto.randomUUID(),pageIndex:g,style:E,createdAt:Date.now()},B=(M,L,j)=>{zt(X=>[...X,M]),Wt(L,j,g)};if(P.kind==="quads"){if(!P.quads.length)return;let M=Sn==="underline"?"underline":Sn==="strikeout"?"strikeout":"highlight",L=M==="underline"?"Underlined text":M==="strikeout"?"Struck through text":"Highlighted text";B({...A,kind:M,quads:P.quads,text:""},L,"\u{1F58A}\uFE0F")}else if(P.kind==="box"){if(P.rect.width<3||P.rect.height<3)return;if(y==="annotate"){let M=P.rect;B({...A,kind:"highlight",quads:[{x:M.x,y:M.y,width:M.width,height:M.height,baselineY:M.y+M.height*.2}],text:""},"Added highlight","\u{1F7E1}")}else{let M=[{x:P.rect.x,y:P.rect.y},{x:P.rect.x+P.rect.width,y:P.rect.y+P.rect.height}];B({...A,kind:It==="ellipse"?"ellipse":"rect",points:M},It==="ellipse"?"Added ellipse":"Added rectangle","\u25FB\uFE0F")}}else if(P.kind==="line"){if(Math.hypot(P.b.x-P.a.x,P.b.y-P.a.y)<3)return;B({...A,kind:P.arrow?"arrow":"line",points:[P.a,P.b]},P.arrow?"Added arrow":"Added line","\u2197\uFE0F")}else if(P.kind==="ink"){if(P.points.length<2)return;B({...A,kind:"ink",strokes:[P.points]},"Freehand drawing","\u270F\uFE0F")}return}if(ls(!1),!Qn.current){Nt([]),bt(null);return}if(!Re||Re.pageIndex!==g)return;if(y==="redact"){let P=Math.min(Re.startPdfX,Re.endPdfX),E=Math.max(Re.startPdfX,Re.endPdfX),A=Math.min(Re.startPdfY,Re.endPdfY),B=Math.max(Re.startPdfY,Re.endPdfY),M=E-P,L=B-A;if(bt(null),Nt([]),M<3||L<3)return;vn(j=>[...j,{id:crypto.randomUUID(),pageIndex:g,x:P,y:A,width:M,height:L}]),b("Adjust the box, then press \u201CApply redactions\u201D. Add more boxes as needed.");return}let x=md(g,Re);Nt(x),x.length>0?b(`Selected ${x.length} text run(s). Click Edit or drag to re-select.`):(b("No text selected in that area."),bt(null))},yd=(u,g)=>{var x;if(y==="draw"&&It==="polygon"&&((x=Yt.current)==null?void 0:x.pageIndex)===g){let P=Yt.current.points;if(Yt.current=null,St(null),P.length>=3){let E={color:Ot.color,opacity:Ot.opacity,strokeWidth:Ot.strokeWidth,fill:Ot.fill};zt(A=>[...A,{id:crypto.randomUUID(),pageIndex:g,style:E,createdAt:Date.now(),kind:"polygon",points:P}]),Wt("Added polygon","\u2B21",g)}}},wd=(u,g)=>{if(Io.current){Io.current=!1;return}if($o.current){$o.current=!1;return}let x=ie[g],P=He.current[g];if(!x||!P)return;let E=P.getBoundingClientRect(),A=dt(u.clientX,u.clientY,E,T,x.height),B=_s(g,A);if(B){jt(B.id),Et(null);return}jt(null);let M=ho(A,kt.current[g]);Et(M),M!=null&&M.fromXObject?b("This object is part of a reusable form and is locked in this version."):M&&b(`Selected ${M.kind==="image"?"image":"graphic"}, press Delete to remove it.`)},Ko=wl(()=>{if(!je||je.fromXObject)return;let u=je;Et(null),kn(null),st({type:"delete-object",pageIndex:u.pageIndex,spans:[{start:u.spanStart,end:u.spanEnd}]})},[je,Ae]),vd=async u=>{try{let g=new Uint8Array(await u.arrayBuffer()),x=g[0]===137&&g[1]===80&&g[2]===78&&g[3]===71,P=g[0]===255&&g[1]===216;if(!x&&!P){b("Only PNG and JPEG images can be inserted.");return}let E=await new Promise((A,B)=>{let M=URL.createObjectURL(u),L=new window.Image;L.onload=()=>{A({w:L.naturalWidth,h:L.naturalHeight}),URL.revokeObjectURL(M)},L.onerror=()=>{B(new Error("unreadable image")),URL.revokeObjectURL(M)},L.src=M});jo({bytes:g,format:x?"png":"jpeg",naturalWidth:Math.max(1,E.w),naturalHeight:Math.max(1,E.h)}),b("Click on a page to place the image (Esc to cancel).")}catch{b("Could not read that image file.")}},kd=(u,g)=>{let x=jn,P=ie[g],E=He.current[g];if(!x||!P||!E)return;let A=E.getBoundingClientRect(),B=dt(u.clientX,u.clientY,A,T,P.height),M=P.width*.5,L=x.naturalWidth*.75,j=Math.min(M,Math.max(16,L)),X=j*(x.naturalHeight/x.naturalWidth),$=Math.max(0,Math.min(P.width-j,B.x-j/2)),G=Math.max(0,Math.min(P.height-X,B.y-X/2));jo(null),st({type:"insert-image",pageIndex:g,x:$,y:G,width:j,height:X,bytes:x.bytes,format:x.format})};wt(()=>{if(!jn)return;let u=g=>{g.key==="Escape"&&(jo(null),b("Image placement cancelled."))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[jn]);let Pd=u=>{let g=u.object,x=null;if(u.mode==="move"){if(Math.abs(u.dxPx)<2&&Math.abs(u.dyPx)<2)return;let P=u.dxPx/T,E=-u.dyPx/T;x=[1,0,0,1,P,E]}else if(u.handle){let P=u.scaleX,E=u.scaleY;if(Math.abs(P-1)<.01&&Math.abs(E-1)<.01)return;let A=g.pdfX,B=g.pdfX+g.width,M=g.pdfY,L=g.pdfY+g.height,j=u.handle.includes("w")?B:A,X=u.handle.includes("n")?M:L;x=[P,0,0,E,j-P*j,X-E*X]}x&&(Io.current=!0,Et(null),kn(null),st({type:"transform-object",pageIndex:g.pageIndex,span:{start:g.spanStart,end:g.spanEnd},matrix:x,baseCtm:g.ctm}))},zs=(u,g,x,P)=>{let E={object:u,mode:g,handle:x,startClientX:P.clientX,startClientY:P.clientY,dxPx:0,dyPx:0,scaleX:1,scaleY:1};En.current=E,ds(E);let A=Math.max(1,u.width*T),B=Math.max(1,u.height*T),M=$=>{var V;let G=En.current;if(!G)return;let D=$.clientX-G.startClientX,z=$.clientY-G.startClientY,U,W;if(G.mode==="move")U={...G,dxPx:D,dyPx:z},W=`translate(${D}px, ${z}px)`;else{let ne=(V=G.handle)!=null?V:"se",ee=1,q=1;if(ne.includes("e")&&(ee=(A+D)/A),ne.includes("w")&&(ee=(A-D)/A),ne.includes("s")&&(q=(B+z)/B),ne.includes("n")&&(q=(B-z)/B),G.object.kind==="image"&&ne.length===2){let ue=Math.max(Math.abs(ee),Math.abs(q));ee=ue,q=ue}U={...G,scaleX:Math.max(.05,ee),scaleY:Math.max(.05,q)},W=`scale(${U.scaleX}, ${U.scaleY})`}En.current=U,Mo.current&&(Mo.current.style.transform=W)},L=$=>{window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",j),window.removeEventListener("keydown",X);let G=En.current;En.current=null,ds(null),$&&G&&Pd(G)},j=()=>L(!0),X=$=>{$.key==="Escape"&&($.stopPropagation(),L(!1))};window.addEventListener("mousemove",M),window.addEventListener("mouseup",j),window.addEventListener("keydown",X)};wt(()=>{if(!je)return;let u=g=>{let x=g.target;x&&(x.tagName==="INPUT"||x.tagName==="TEXTAREA")||(g.key==="Delete"||g.key==="Backspace"?(g.preventDefault(),Ko()):g.key==="Escape"&&Et(null))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[je,Ko]),wt(()=>{if(!rr)return;let u=g=>{let x=g.target;x&&(x.tagName==="INPUT"||x.tagName==="TEXTAREA")||(g.key==="Delete"||g.key==="Backspace"?(g.preventDefault(),zt(P=>P.filter(E=>E.id!==rr)),jt(null),Wt("Deleted annotation","\u{1F5D1}\uFE0F")):g.key==="Escape"&&jt(null))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[rr]),wt(()=>{Et(null),kn(null),No(null),Eo(null),tr.current=null,Rr(null),vn([]),jt(null),St(null),Ir(!1),Yt.current=null},[y]),wt(()=>{if(y!=="redact"||Pt.length===0)return;let u=g=>{g.key==="Escape"&&(vn([]),b("Redaction marks cleared."))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[y,Pt.length]);let Sd=()=>{if(wn.length===0||!Re)return;Wo();let u=[...wn].sort((W,V)=>W.pageIndex!==V.pageIndex?W.pageIndex-V.pageIndex:Math.abs(V.pdfY-W.pdfY)>10?V.pdfY-W.pdfY:W.pdfX-V.pdfX),g=u[0].pageIndex,x=ie[g],P=He.current[g];if(!x||!P)return;let E=u.map(W=>W.text).join(" "),A=Math.min(...u.map(W=>W.pdfX)),B=Math.min(...u.map(W=>W.pdfY)),M=Math.max(...u.map(W=>W.pdfX+W.width)),L=Math.max(...u.map(W=>W.pdfY+W.height)),j=u.reduce((W,V)=>W+V.fontSize,0)/u.length,X=u.reduce((W,V)=>W+V.pdfBaselineY,0)/u.length,$=u.find(W=>W.fontName||W.color),G=Ke(A,B+(L-B),T,x.height),D={x:A,y:B,width:M-A,height:L-B},{eraseClamp:z,maskRect:U}=Es(D,j,g,x,G);Q({pageIndex:g,value:E,spans:[{text:E,style:Yo({fontName:$==null?void 0:$.fontName,color:$==null?void 0:$.color})}],pdfX:A,pdfY:B,pdfBaselineY:X,width:M-A,height:L-B,fontSize:j,fontName:$==null?void 0:$.fontName,fontFamily:$==null?void 0:$.fontFamily,color:$==null?void 0:$.color,containerX:G.x,containerY:G.y,screenWidth:Math.max(150,(M-A)*T+12),screenHeight:Math.max(30,(L-B)*T+8),maxWidth:Math.max(60,x.width*T-G.x-2),eraseClamp:z,maskRect:U,streamOperatorIndices:u.every(W=>{var V;return((V=W.streamOperatorIndices)!=null?V:[]).length>0})?u.flatMap(W=>{var V;return(V=W.streamOperatorIndices)!=null?V:[]}):void 0,fromXObject:u.some(W=>W.fromXObject)}),Ts(g,D),Nt([]),bt(null)},Dd=async()=>{if(wn.length===0||!Re)return;let u=Re.pageIndex;if(!ie[u])return;let x=wn.filter(M=>M.pageIndex===u),P=x.length>0?Math.min(...x.map(M=>M.pdfX)):Math.min(Re.startPdfX,Re.endPdfX),E=x.length>0?Math.max(...x.map(M=>M.pdfX+M.width)):Math.max(Re.startPdfX,Re.endPdfX),A=x.length>0?Math.min(...x.map(M=>M.pdfY)):Math.min(Re.startPdfY,Re.endPdfY),B=x.length>0?Math.max(...x.map(M=>M.pdfY+M.height)):Math.max(Re.startPdfY,Re.endPdfY);Nt([]),bt(null),await st({type:"redact-area",pageIndex:u,x:P,y:A,width:E-P,height:B-A,color:{r:0,g:0,b:0},padding:x.length>0?Math.max(1.75,x.reduce((M,L)=>M+L.fontSize,0)/x.length*.14):1.75})},Vo=()=>{var u;(u=cs.current)==null||u.click()},Ys=async()=>{if(!tn.current||!Ze.trim())return;At(!0);let u=await e(tn.current,Ze);if(u.success&&u.pdfBytes){let g=Rl(u.pdfBytes);nn.current=null,o(tn.current),s(g),c([]),d({}),J({}),ze.current={},ot.current={},kt.current={},Nt([]),bt(null),Q(null),b("Rendering PDF..."),Ne(""),vt(!1),tn.current=null}else b("Incorrect password. Please try again."),At(!1),vt(!0)},Cd=Ae?`${(Ae.size/1024).toFixed(1)} KB`:"No file loaded",qo=(()=>{var u,g,x;if(!Ae||ct)return null;for(let P of Object.keys(l)){let E=Number(P);if(Pe.current.has(E))continue;let A=((u=ze.current[E])!=null?u:[]).filter(M=>!M.ocr).length,B=(x=(g=kt.current[E])==null?void 0:g.length)!=null?x:0;if(A===0&&B>0)return E}return null})();return Y("div",{className:"paper-grain flex h-screen flex-col overflow-hidden bg-paper-editor text-ink dark:bg-[#16130f] dark:text-white",children:[Y("header",{className:"flex h-14 shrink-0 items-center gap-3.5 border-b border-ink-line bg-paper-card px-4 dark:border-white/10 dark:bg-[#1a1712]",children:[Y("div",{className:"flex items-center gap-2.5 pr-4 border-r border-ink-line dark:border-white/10",children:[v("div",{className:"flex h-7 w-7 items-center justify-center rounded-lg bg-crimson-600 shadow-[0_2px_7px_-2px_rgba(162,7,48,0.5)]",children:v(Fo,{className:"h-4 w-4 text-white"})}),Y("span",{className:"font-display text-[18px] font-semibold tracking-[-0.01em] text-ink dark:text-white",children:["Namaha",v("span",{className:"text-crimson-600",children:"PDF"})]})]}),v("div",{className:"flex min-w-0 items-center gap-2",children:Ae?Y(en,{children:[v("span",{className:"truncate text-[13.5px] font-semibold text-ink dark:text-zinc-200",children:_o}),v("span",{className:"shrink-0 rounded bg-surface-container-high px-1.5 py-0.5 text-[10px] font-semibold text-ink-soft dark:bg-zinc-800 dark:text-zinc-400",children:Cd}),f&&v("span",{className:"shrink-0 text-xs text-crimson-600 animate-pulse",children:"saving\u2026"}),!f&&w&&Y("span",{className:"shrink-0 inline-flex items-center gap-1 text-xs text-emerald-700 dark:text-green-400",children:[v(Co,{className:"h-3 w-3"}),w]})]}):v("span",{className:"text-sm text-ink-muted",children:"No document open"})}),v("div",{className:"flex-1"}),Y("div",{title:"Private. Stays on your device.",className:"hidden items-center rounded-full border border-emerald-200 bg-emerald-50 p-1.5 lg:flex dark:border-emerald-900/40 dark:bg-emerald-950/30",children:[v(Im,{className:"h-3.5 w-3.5 text-emerald-700 dark:text-emerald-400"}),v("span",{className:"sr-only",children:"Private. Stays on your device."})]}),Y("div",{className:"flex items-center gap-1.5",children:[Ae&&v("button",{type:"button",title:"Activity log",onClick:()=>Ds(u=>!u),className:`flex h-8 w-8 items-center justify-center rounded-lg transition-colors ${Ss?"bg-crimson-100 text-crimson-600":"text-ink-soft hover:bg-paper hover:text-ink dark:text-zinc-400 dark:hover:bg-zinc-800"}`,children:v(Pl,{className:"h-4 w-4"})}),Ae&&v("button",{type:"button",title:"Recognize text (OCR), for scanned/outlined pages",disabled:Ce,onClick:()=>{Os(Zl())},className:"flex h-8 w-8 items-center justify-center rounded-lg text-ink-soft transition-colors hover:bg-paper hover:text-ink disabled:opacity-50 dark:text-zinc-400 dark:hover:bg-zinc-800",children:v(Dl,{className:`h-4 w-4 ${Ce?"animate-pulse":""}`})}),Y("button",{type:"button",onClick:Vo,className:"flex h-8 items-center gap-1.5 rounded-lg border border-ink-line-strong bg-paper-raised px-3 text-xs font-semibold text-ink-soft transition-colors hover:bg-paper dark:border-white/10 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700",children:[v(ss,{className:"h-3.5 w-3.5"}),"Open"]}),Y("button",{type:"button",className:"flex h-8 items-center gap-1.5 rounded-lg border border-ink-line-strong bg-paper-raised px-3 text-xs font-semibold text-ink-soft transition-colors hover:bg-paper dark:border-white/10 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700",children:[v(Um,{className:"h-3.5 w-3.5"}),"Share"]}),Y("button",{type:"button",onClick:Ae?()=>{Ns()}:Vo,disabled:f,className:"flex h-8 items-center gap-1.5 rounded-lg bg-crimson-600 px-4 text-xs font-bold text-white shadow-crimson transition-all hover:bg-crimson-700 active:scale-95 disabled:cursor-not-allowed disabled:opacity-60",children:[v(Rm,{className:"h-3.5 w-3.5"}),Ae?tt.length+pt.length>0?`Download (${tt.length+pt.length} annot.)`:"Download":"Open PDF"]})]})]}),qo!==null&&Y("div",{className:"flex items-center gap-3 border-b border-amber-200 bg-amber-50 px-4 py-2 text-xs text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300",children:[v(Dl,{className:"h-4 w-4 shrink-0"}),Y("span",{className:"flex-1",children:["Page ",qo+1," looks scanned or has outlined text. Recognize it to make the text selectable and editable."]}),v("button",{type:"button",disabled:Ce,onClick:()=>{Os(qo)},className:"rounded-md bg-amber-600 px-2.5 py-1 font-semibold text-white transition hover:brightness-110 disabled:opacity-60",children:Ce?"Recognizing\u2026":"Recognize text"}),v("button",{type:"button",onClick:()=>Rt(!0),className:"rounded p-1 hover:bg-amber-100 dark:hover:bg-amber-900/40",title:"Dismiss",children:v(pn,{className:"h-3.5 w-3.5"})})]}),Ae&&!ft&&Y("div",{className:"flex items-center gap-3 border-b border-blue-200 bg-blue-50 px-4 py-2 text-xs text-blue-800 dark:border-blue-900/50 dark:bg-blue-950/30 dark:text-blue-300",children:[v("span",{className:"flex-1",children:"Heads-up: if some text looks overlapped or crowded here, it's only a preview/display quirk in the editor, you can still select and edit it normally, and your downloaded PDF will look correct."}),v("button",{type:"button",onClick:()=>xn(!0),className:"rounded p-1 hover:bg-blue-100 dark:hover:bg-blue-900/40",title:"Dismiss",children:v(pn,{className:"h-3.5 w-3.5"})})]}),be&&v("div",{className:"fixed inset-0 z-[120] flex items-center justify-center bg-black/50 p-4",onClick:()=>Ve(null),children:Y("div",{className:"w-full max-w-sm rounded-2xl border border-zinc-200 bg-white p-6 shadow-2xl dark:border-white/10 dark:bg-zinc-900",onClick:u=>u.stopPropagation(),children:[v("h2",{className:"text-lg font-bold text-zinc-900 dark:text-white",children:"Switch font for this edit?"}),Y("p",{className:"mt-2 text-sm text-zinc-600 dark:text-zinc-400",children:["This text uses a custom font",be.fontName?Y(en,{children:[" (",v("span",{className:"font-medium",children:be.fontName.replace(/^[A-Z]{6}\+/,"")}),")"]}):null," ","that can't be edited reliably, keeping it can render your edit as garbled characters (\u25A1 / \uFFFD). Save your change using the closest matching standard font instead?"]}),Y("div",{className:"mt-5 flex gap-2",children:[v("button",{type:"button",onClick:()=>{let u=be;u.fontName&&bn.current.add(u.fontName),Ve(null),Bs(u)},className:"flex-1 rounded-full bg-primary px-4 py-2.5 text-sm font-semibold text-white transition hover:brightness-110",children:"Save with closest font"}),v("button",{type:"button",onClick:()=>Ve(null),className:"rounded-full border border-zinc-300 px-4 py-2.5 text-sm font-medium text-zinc-600 transition hover:bg-black/[0.04] dark:border-white/15 dark:text-zinc-300 dark:hover:bg-white/[0.06]",children:"Cancel"})]})]})}),!Ae&&v("div",{className:"flex flex-1 items-center justify-center p-8",children:Y("div",{className:"w-full max-w-xl text-center",children:[v("h1",{className:"mb-2 font-display text-[34px] font-medium tracking-[-0.02em] text-ink dark:text-white",children:"Open a document to begin"}),v("p",{className:"mb-7 text-[15px] leading-relaxed text-ink-soft dark:text-zinc-400",children:"Everything happens on your device, your file is never uploaded."}),Y("button",{type:"button",onClick:Vo,className:"group flex w-full flex-col items-center gap-4 rounded-2xl border-2 border-dashed border-ink-line-strong bg-paper-raised p-11 text-center shadow-paper-lg transition-all hover:border-crimson-400 hover:bg-crimson-50/40 dark:border-white/10 dark:bg-zinc-900 dark:hover:border-crimson-500",children:[Y("div",{className:"relative flex h-[76px] w-[76px] items-center justify-center",style:{animation:"floaty 4s ease-in-out infinite"},children:[v("div",{className:"absolute inset-0 -rotate-[7deg] rounded-xl bg-gradient-to-br from-crimson-200 to-crimson-400 shadow-[0_8px_18px_-6px_rgba(162,7,48,0.4)]"}),v("div",{className:"absolute inset-0 flex items-center justify-center rounded-xl border border-[#E7DECB] bg-paper-raised text-crimson-600",children:v(Nm,{className:"h-8 w-8"})})]}),Y("div",{children:[v("p",{className:"font-display text-[21px] font-semibold text-ink dark:text-white",children:"Drag & drop your PDF here"}),v("p",{className:"mt-1 text-sm text-ink-muted",children:"or click to browse"})]}),Y("span",{className:"flex items-center gap-2 rounded-xl bg-crimson-600 px-6 py-3 text-sm font-bold text-white shadow-crimson transition-all group-hover:bg-crimson-700",children:[v(ss,{className:"h-4 w-4"}),"Choose a file"]}),v("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-x-5 gap-y-2 text-xs text-ink-muted",children:["Up to 2 GB","Never uploaded","Works offline"].map(u=>Y("span",{className:"inline-flex items-center gap-1.5",children:[v(Co,{className:"h-3 w-3 text-emerald-700"}),u]},u))})]})]})}),Y("div",{className:"sr-only",children:[v("input",{ref:cs,type:"file",accept:"application/pdf",onChange:async u=>{var P,E;let g=(E=(P=u.target.files)==null?void 0:P[0])!=null?E:null;if(!g)return;tn.current=g,At(!0),vt(!1),Ne(""),b("Rendering PDF...");let x=await e(g);if(x.success&&x.pdfBytes){let A=Rl(x.pdfBytes);nn.current=null,o(g),s(A),c([]),d({}),J({}),ze.current={},ot.current={},kt.current={},Nt([]),bt(null),Q(null),b("Rendering PDF...")}else x.requiresPassword?(vt(!0),At(!1),b("")):(b(x.error||"Failed to load PDF"),At(!1),vt(!1),tn.current=null)},className:"p-2 border rounded"}),Ae&&Y("p",{className:"text-sm",style:{color:"var(--footer-muted)"},children:["Current file: ",_o," \xB7 ",(Ae.size/1024).toFixed(1)," KB"]})]}),Ae&&Y("div",{className:"flex flex-1 flex-col overflow-hidden",children:[Y("div",{className:"flex shrink-0 items-center gap-3 border-b border-ink-line bg-paper-card px-4 py-1.5 text-xs dark:border-white/10 dark:bg-[#1a1712]",children:[v(Fo,{className:"h-3.5 w-3.5 shrink-0 text-ink-muted"}),v("span",{className:"truncate font-medium text-ink-soft dark:text-zinc-300",children:_o}),Y("span",{className:"shrink-0 rounded bg-surface-container-high px-1.5 py-0.5 font-semibold text-ink-soft dark:bg-zinc-800 dark:text-zinc-400",children:[a.length," ",a.length===1?"page":"pages"]}),m&&v("span",{className:"shrink-0 animate-pulse text-crimson-600",children:"Rendering\u2026"}),v("div",{className:"flex-1"}),v("span",{className:"shrink-0 font-semibold capitalize text-ink-muted dark:text-zinc-400",children:y.replace(/-/g," ")})]}),Ar&&Y("div",{className:"flex shrink-0 flex-wrap items-center gap-2 border-b border-amber-400/20 bg-amber-50/80 px-4 py-2 dark:bg-amber-950/30",children:[v(os,{className:"h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),v("input",{ref:Or,type:"text",placeholder:"Find\u2026",value:rn,onChange:u=>ms(u.target.value),className:"h-7 w-40 rounded-md border border-amber-200 bg-paper-raised px-2 text-xs text-ink outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400/30 dark:border-white/10 dark:bg-zinc-900 dark:text-white"}),v("input",{type:"text",placeholder:"Replace with\u2026",value:ps,onChange:u=>$l(u.target.value),className:"h-7 w-40 rounded-md border border-amber-200 bg-paper-raised px-2 text-xs text-ink outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400/30 dark:border-white/10 dark:bg-zinc-900 dark:text-white"}),it.length>0&&Y(en,{children:[Y("span",{className:"text-xs font-semibold text-amber-700 dark:text-amber-400",children:[Nr+1," / ",it.length]}),v("button",{type:"button",onClick:()=>Er(u=>(u-1+it.length)%it.length),className:"flex h-6 w-6 items-center justify-center rounded hover:bg-amber-200/60 dark:hover:bg-amber-900/40",title:"Previous",children:v(Sm,{className:"h-3.5 w-3.5 text-amber-700 dark:text-amber-400"})}),v("button",{type:"button",onClick:()=>Er(u=>(u+1)%it.length),className:"flex h-6 w-6 items-center justify-center rounded hover:bg-amber-200/60 dark:hover:bg-amber-900/40",title:"Next",children:v(Dm,{className:"h-3.5 w-3.5 text-amber-700 dark:text-amber-400"})})]}),rn&&it.length===0&&v("span",{className:"text-xs text-zinc-400",children:"No matches"}),Y("div",{className:"flex gap-1",children:[Y("button",{type:"button",onClick:()=>{it[Nr]&&js(it[Nr])},disabled:it.length===0,className:"flex h-7 items-center gap-1 rounded-md bg-amber-500 px-2.5 text-xs font-semibold text-white transition-colors hover:bg-amber-400 disabled:opacity-40",children:[v($m,{className:"h-3 w-3"}),"Replace"]}),Y("button",{type:"button",onClick:()=>{td()},disabled:it.length===0,className:"flex h-7 items-center gap-1 rounded-md border border-amber-300 bg-white px-2.5 text-xs font-semibold text-amber-700 transition-colors hover:bg-amber-50 disabled:opacity-40 dark:border-amber-700 dark:bg-zinc-900 dark:text-amber-400",children:["All (",it.length,")"]})]}),v("button",{type:"button",onClick:()=>{nr(!1),ms(""),Tr([])},className:"ml-auto flex h-6 w-6 items-center justify-center rounded hover:bg-amber-200/60 dark:hover:bg-amber-900/40",children:v(pn,{className:"h-3.5 w-3.5 text-amber-700 dark:text-amber-400"})})]}),y==="sign"&&ks&&Y("div",{className:"flex items-center gap-2 border-b border-amber-500/30 bg-amber-500/10 px-4 py-2 text-xs text-amber-600 dark:text-amber-300",children:[v(rs,{className:"h-3.5 w-3.5"}),v("span",{className:"font-semibold",children:"Click anywhere on the page to place your signature"}),v("button",{type:"button",onClick:()=>$r(!1),className:"ml-auto text-amber-500 hover:text-amber-400",children:v(pn,{className:"h-3.5 w-3.5"})})]}),(y==="stamp"||y==="add-text")&&Y("div",{className:"flex flex-wrap items-center gap-2 border-b border-ink-line bg-paper-card px-4 py-2 text-xs text-ink-soft",children:[y==="stamp"?v(Sl,{className:"h-3.5 w-3.5 text-primary"}):v(Fl,{className:"h-3.5 w-3.5 text-primary"}),y==="stamp"&&Y(en,{children:[v("span",{className:"font-semibold text-ink-muted",children:"Presets:"}),["APPROVED","CONFIDENTIAL","DRAFT","REVIEWED"].map(u=>v("button",{type:"button",onClick:()=>S(u),className:`rounded px-2 py-0.5 text-[10px] font-bold tracking-wide transition-colors ${C===u?"bg-primary text-white":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:u},u)),v("span",{className:"mx-1 h-4 w-px bg-ink-line"})]}),y==="stamp"&&v("input",{type:"text",value:C,onChange:u=>S(u.target.value),placeholder:"Custom stamp text\u2026",className:"h-7 w-44 rounded border border-ink-line bg-paper-raised px-2 text-xs text-ink placeholder:text-ink-muted focus:border-crimson-600 focus:outline-none"}),v("span",{className:"font-semibold text-ink-muted",children:y==="add-text"?"Default size:":"Size:"}),[10,14,18,24,36].map(u=>v("button",{type:"button",onClick:()=>O(u),className:`rounded px-1.5 py-0.5 text-xs font-bold ${F===u?"bg-primary text-white":"text-ink-muted hover:text-ink"}`,children:u},u)),y==="stamp"&&Y(en,{children:[v("span",{className:"font-semibold text-ink-muted",children:"Color:"}),[{hex:"#D6002F",rgb:{r:.84,g:0,b:.19}},{hex:"#1A1A2E",rgb:{r:.1,g:.1,b:.18}},{hex:"#1D4ED8",rgb:{r:.11,g:.31,b:.85}},{hex:"#047857",rgb:{r:.02,g:.47,b:.34}}].map(({hex:u,rgb:g})=>v("button",{type:"button",title:u,onClick:()=>I(g),style:{background:u,width:18,height:18,borderRadius:4,border:N.r===g.r&&N.b===g.b?"2px solid white":"1px solid rgba(255,255,255,0.2)"}},u))]}),v("span",{className:"ml-1 font-semibold text-primary",children:y==="add-text"?"Click the page to add a text box, then type & format":"Click the page to place"})]}),y==="view"&&Y("div",{className:"flex flex-wrap items-center gap-2 border-b border-ink-line bg-paper-card px-4 py-1.5 text-xs text-ink-soft dark:border-white/10 dark:bg-[#1a1712]",children:[v(kl,{className:"h-3.5 w-3.5 text-crimson-600"}),v("button",{type:"button",onClick:()=>Us(1/1.2),title:"Zoom out",className:"flex h-7 w-7 items-center justify-center rounded hover:bg-paper dark:hover:bg-zinc-800",children:v(Xm,{className:"h-3.5 w-3.5"})}),Y("span",{className:"w-12 text-center font-semibold text-ink-muted",children:[Math.round(H*100),"%"]}),v("button",{type:"button",onClick:()=>Us(1.2),title:"Zoom in",className:"flex h-7 w-7 items-center justify-center rounded hover:bg-paper dark:hover:bg-zinc-800",children:v(_m,{className:"h-3.5 w-3.5"})}),Y("button",{type:"button",onClick:ud,title:"Fit width",className:"flex h-7 items-center gap-1 rounded px-2 font-semibold hover:bg-paper dark:hover:bg-zinc-800",children:[v(Tm,{className:"h-3.5 w-3.5"})," Width"]}),v("button",{type:"button",onClick:hd,title:"Fit page",className:"flex h-7 items-center rounded px-2 font-semibold hover:bg-paper dark:hover:bg-zinc-800",children:"Page"}),v("span",{className:"mx-1 h-4 w-px bg-ink-line dark:bg-white/10"}),v("button",{type:"button",onClick:()=>Ur(se-1),disabled:se<=0,title:"Previous page",className:"flex h-7 w-7 items-center justify-center rounded hover:bg-paper disabled:opacity-30 dark:hover:bg-zinc-800",children:v(Cm,{className:"h-3.5 w-3.5"})}),v("input",{type:"number",min:1,max:a.length,value:se+1,onChange:u=>Ur((Number(u.target.value)||1)-1),className:"h-7 w-12 rounded border border-ink-line bg-paper-raised px-1.5 text-center text-xs text-ink outline-none focus:border-crimson-600 dark:border-white/10 dark:bg-zinc-900 dark:text-white"}),Y("span",{className:"text-ink-muted",children:["/ ",a.length]}),v("button",{type:"button",onClick:()=>Ur(se+1),disabled:se>=a.length-1,title:"Next page",className:"flex h-7 w-7 items-center justify-center rounded hover:bg-paper disabled:opacity-30 dark:hover:bg-zinc-800",children:v(Fm,{className:"h-3.5 w-3.5"})}),Y("div",{className:"ml-auto flex items-center gap-2",children:[Y("button",{type:"button",onClick:()=>{nr(u=>!u),setTimeout(()=>{var u;return(u=Or.current)==null?void 0:u.focus()},50)},className:`flex h-7 items-center gap-1 rounded px-2 font-semibold transition-colors ${Ar?"bg-amber-500 text-white":"hover:bg-paper dark:hover:bg-zinc-800"}`,children:[v(os,{className:"h-3.5 w-3.5"})," Find"]}),v("span",{className:"text-ink-muted",children:"Drag to select \xB7 Ctrl+C to copy"})]})]}),y==="redact"&&Y("div",{className:"flex flex-wrap items-center gap-2 border-b border-ink-line bg-paper-card px-4 py-2 text-xs text-ink-soft",children:[v(ns,{className:"h-3.5 w-3.5 text-primary"}),v("span",{className:"font-semibold text-ink-muted",children:"Redact:"}),v("span",{children:"Drag over text to mark it. Resize the green boxes, then apply, text is deleted and a black box is drawn."}),Y("div",{className:"ml-auto flex items-center gap-3",children:[v("span",{className:"text-ink-muted",children:Pt.length?`${Pt.length} mark${Pt.length>1?"s":""}`:"No marks yet"}),v("button",{type:"button",onClick:()=>vn([]),disabled:Pt.length===0||f,className:"rounded bg-paper px-2.5 py-1 font-semibold text-ink-soft hover:bg-ink-line disabled:opacity-40",children:"Clear marks"}),Y("button",{type:"button",onClick:()=>{Vl()},disabled:Pt.length===0||f,title:"Permanently delete the marked text and draw black boxes",className:"flex items-center gap-1 rounded bg-red-600 px-2.5 py-1 font-semibold text-white hover:bg-red-700 disabled:opacity-40",children:[v(ns,{className:"h-3 w-3"})," Apply redactions"]})]})]}),Y("div",{className:"relative flex flex-1 overflow-hidden",children:[Y("aside",{className:"z-30 flex w-[72px] shrink-0 flex-col items-center gap-0.5 self-stretch overflow-y-auto overflow-x-hidden border-r border-ink-line bg-paper-card px-1.5 py-3 [scrollbar-width:thin] [&>*]:shrink-0 dark:border-white/10 dark:bg-[#1a1712]",children:[v("div",{className:"mb-2 flex h-8 w-8 items-center justify-center rounded-lg bg-crimson-100",children:v(Fo,{className:"h-4 w-4 text-crimson-600"})}),v("div",{className:"mb-1 h-px w-10 bg-ink-line"}),Y("button",{type:"button",title:"Find & Replace (Ctrl+F)",onClick:()=>{nr(u=>!u),setTimeout(()=>{var u;return(u=Or.current)==null?void 0:u.focus()},50)},className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${Ar?"bg-amber-500 text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[v(os,{className:"h-4 w-4"}),v("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:"Find"})]}),v("div",{className:"my-1 h-px w-10 bg-ink-line"}),[{t:"view",icon:v(kl,{className:"h-4 w-4"}),label:"View",hint:"Read, select text, zoom, navigate & follow links"},{t:"select",icon:v(jm,{className:"h-4 w-4"}),label:"Select",hint:"Select, move, resize or delete images and graphics"},{t:"edit-text",icon:v(Am,{className:"h-4 w-4"}),label:"Edit",hint:"Edit text"},{t:"add-text",icon:v(Fl,{className:"h-4 w-4"}),label:"Add Text",hint:"Add new text"}].map(({t:u,icon:g,label:x,hint:P})=>Y("button",{type:"button",title:P!=null?P:x,onClick:()=>k(u),className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${y===u?"bg-primary text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[g,v("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:x})]},u)),v("div",{className:"my-1.5 h-px w-10 bg-ink-line"}),v("span",{className:"mb-0.5 text-[7px] font-bold uppercase tracking-widest text-ink-muted",children:"Annotate"}),[{t:"annotate",icon:v(Em,{className:"h-4 w-4"}),label:"Annotate"},{t:"draw",icon:v(Om,{className:"h-4 w-4"}),label:"Draw"},{t:"comment",icon:v(Cl,{className:"h-4 w-4"}),label:"Comment"}].map(({t:u,icon:g,label:x})=>Y("button",{type:"button",title:x,onClick:()=>k(u),className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${y===u?"bg-primary text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[g,v("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:x})]},u)),v("div",{className:"my-1.5 h-px w-10 bg-ink-line"}),v("span",{className:"mb-0.5 text-[7px] font-bold uppercase tracking-widest text-ink-muted",children:"Edit"}),[{t:"sign",icon:v(rs,{className:"h-4 w-4"}),label:"Sign"},{t:"redact",icon:v(ns,{className:"h-4 w-4"}),label:"Redact"},{t:"stamp",icon:v(Sl,{className:"h-4 w-4"}),label:"Stamp"},{t:"form",icon:v(Fo,{className:"h-4 w-4"}),label:"Forms"}].map(({t:u,icon:g,label:x})=>Y("button",{type:"button",title:x,onClick:()=>k(u),className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${y===u?"bg-primary text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[g,v("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:x})]},u)),Y("button",{type:"button",title:"Insert image (PNG/JPEG)",onClick:()=>{var u;return(u=fs.current)==null?void 0:u.click()},disabled:f,className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${jn?"bg-primary text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"} disabled:opacity-30`,children:[v(Lm,{className:"h-4 w-4"}),v("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:"Image"})]}),v("input",{ref:fs,type:"file",accept:"image/png,image/jpeg",className:"hidden",onChange:u=>{var x;let g=(x=u.target.files)==null?void 0:x[0];u.target.value="",g&&vd(g)}}),v("div",{className:"flex-1"}),v("div",{className:"mt-1 h-px w-10 bg-ink-line"}),Y("button",{type:"button",title:"Rotate page",onClick:()=>st({type:"rotate-page",pageIndex:Fs,degrees:Wl}),disabled:f,className:"flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-ink-muted transition-all hover:bg-paper hover:text-ink disabled:opacity-30",children:[v(Bm,{className:"h-4 w-4"}),v("span",{className:"mt-1 text-[8px] font-semibold",children:"Rotate"})]}),Y("button",{type:"button",title:"Delete page",onClick:()=>st({type:"delete-page",pageIndex:Fs}),disabled:f,className:"flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-red-500/70 transition-all hover:bg-red-50 hover:text-red-600 disabled:opacity-30",children:[v(is,{className:"h-4 w-4"}),v("span",{className:"mt-1 text-[8px] font-semibold",children:"Delete"})]}),tt.length+pt.length>0&&Y("div",{className:"mt-2 w-full rounded-lg bg-primary/20 py-1 text-center text-[8px] font-bold text-primary",children:[tt.length+pt.length," annot."]})]}),Y("main",{ref:ce,className:"flex-1 overflow-auto p-6 md:p-12",style:{backgroundImage:"radial-gradient(#d8cdb8 1px, transparent 1px)",backgroundSize:"20px 20px"},children:[m&&v("div",{className:"mx-auto mb-6 max-w-4xl rounded-xl border border-outline-variant/40 bg-surface-container-lowest p-4 text-sm text-on-secondary-container shadow-sm",children:"Rendering with Avni engine..."}),!m&&a.length===0&&v("div",{className:"mx-auto max-w-4xl rounded-xl border border-outline-variant/40 bg-surface-container-lowest p-4 text-sm text-on-secondary-container shadow-sm",children:"No engine-rendered pages available."}),a.map(u=>{var B,M,L,j,X,$,G;let g=l[u.pageIndex],x=u.pageIndex,P=!!g,E=`${Math.ceil(u.width*T)}px`,A=`${Math.ceil(u.height*T)}px`;return Y("div",{className:"relative mx-auto mb-10 overflow-hidden rounded-[3px] shadow-[0_12px_40px_-10px_rgba(33,29,23,0.28)]",ref:D=>{He.current[x]=D},style:{width:E,minHeight:A,background:(B=g==null?void 0:g.bgCss)!=null?B:"#ffffff",cursor:jn?"crosshair":y==="form"?Pn?"crosshair":"default":["add-text","annotate","stamp","draw","comment","sign"].includes(y)?"crosshair":y==="select"?mt&&mt.pageIndex===x?mt.fromXObject?"not-allowed":"pointer":"default":"text",userSelect:y==="view"?"text":"none"},onMouseDown:D=>gd(D,x),onMouseMove:D=>xd(D,x),onMouseUp:D=>bd(D,x),onDoubleClick:D=>yd(D,x),onClick:D=>{var z;if(jn){kd(D,x);return}if(y!=="view"){if(y==="select"){wd(D,x);return}if(y==="comment"){let U=He.current[x];if(!U)return;let W=U.getBoundingClientRect(),V={id:crypto.randomUUID(),kind:"comment",pageIndex:x,x:D.clientX-W.left,y:D.clientY-W.top,text:"",color:"#F59E0B"};Wt("Added comment","\u{1F4AC}",x),$n(ne=>[...ne,V]),jr(V.id);return}if(y==="sign"){if(ws&&ks){let U=He.current[x];if(!U)return;let W=U.getBoundingClientRect();Wt("Placed signature","\u2712\uFE0F",x),$n(V=>[...V,{id:crypto.randomUUID(),kind:"sign",pageIndex:x,x:D.clientX-W.left-100,y:D.clientY-W.top-40,width:200,height:80,dataUrl:ws}]),$r(!1)}else Bn(!0);return}if(y==="draw"&&It==="polygon"){let U=ie[x],W=He.current[x];if(!U||!W)return;let V=W.getBoundingClientRect(),ne=dt(D.clientX,D.clientY,V,T,U.height),q=[...((z=Yt.current)==null?void 0:z.pageIndex)===x?Yt.current.points:[],ne];Yt.current={pageIndex:x,points:q},St({kind:"polygon",pageIndex:x,points:q,cursor:ne});return}if(y==="add-text"||y==="stamp"){Jl(D,x);return}if(Sr.current){Sr.current=!1;return}!Qn.current&&wn.length===0&&ed(D,x)}},children:[P?v("img",{src:g.canvasDataUrl,alt:`Engine rendered page ${g.pageNum}`,draggable:!1,decoding:"async",style:{display:"block",width:E,height:A,background:(M=g.bgCss)!=null?M:"#fff"}}):v("div",{className:"flex h-full w-full items-center justify-center",style:{minHeight:A,background:"linear-gradient(90deg, rgba(127,127,127,0.08) 25%, rgba(127,127,127,0.16) 37%, rgba(127,127,127,0.08) 63%)",backgroundSize:"400% 100%",animation:"avni-skeleton 1.4s ease-in-out infinite"},children:Y("div",{className:"rounded-full bg-white px-3 py-1 text-xs font-medium text-on-secondary-container shadow-sm",children:["Loading page ",u.pageNum,"..."]})}),ie[x]&&v(Bi,{pageIndex:x,pageHeight:ie[x].height,scale:T,annots:tt,live:xs,liveStyle:Ot,selectedId:rr,interactive:y==="select",liveMarkupKind:Sn==="underline"?"underline":Sn==="strikeout"?"strikeout":"highlight",onBeginResize:pd}),Y("svg",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"visible",zIndex:10,pointerEvents:"none"},xmlns:"http://www.w3.org/2000/svg",children:[pt.filter(D=>D.pageIndex===x&&D.kind==="sign").map(D=>v("image",{href:D.dataUrl,x:D.x,y:D.y,width:D.width,height:D.height},D.id)),pt.filter(D=>D.pageIndex===x&&D.kind==="comment").map(D=>Y("g",{style:{pointerEvents:"auto",cursor:"pointer"},onClick:z=>{z.stopPropagation(),jr(ys===D.id?null:D.id)},children:[v("rect",{x:D.x,y:D.y,width:22,height:22,rx:4,fill:D.color}),v("text",{x:D.x+11,y:D.y+15,textAnchor:"middle",fontSize:13,fill:"white",style:{fontFamily:"sans-serif",userSelect:"none"},children:"\u270E"})]},D.id))]}),pt.filter(D=>D.pageIndex===x&&D.kind==="comment"&&D.id===ys).map(D=>v("div",{style:{position:"absolute",left:D.x+26,top:D.y,zIndex:60,minWidth:220},onClick:z=>z.stopPropagation(),children:Y("div",{className:"rounded-xl bg-white shadow-xl ring-1 ring-black/10 overflow-hidden",children:[Y("div",{className:"flex items-center gap-2 bg-amber-400 px-3 py-2",children:[v(Cl,{className:"h-3.5 w-3.5 text-white"}),v("span",{className:"text-xs font-bold text-white",children:"Comment"}),v("div",{className:"flex-1"}),v("button",{className:"text-white/70 hover:text-white",onClick:()=>{$n(z=>z.filter(U=>U.id!==D.id)),jr(null)},children:v(pn,{className:"h-3.5 w-3.5"})})]}),v("textarea",{className:"block w-full resize-none px-3 py-2 text-xs text-on-surface outline-none",rows:3,placeholder:"Add a comment...",defaultValue:D.text,autoFocus:!0,onBlur:z=>$n(U=>U.map(W=>W.id===D.id?{...W,text:z.target.value}:W))}),v("div",{className:"flex justify-end gap-1 border-t border-outline-variant/20 px-3 py-1.5",children:Y("button",{className:"rounded-lg px-3 py-1 text-xs font-bold text-primary hover:bg-primary/10",onClick:()=>jr(null),children:[v(Co,{className:"mr-1 inline h-3 w-3"}),"Done"]})})]})},D.id)),y==="select"&&ie[x]&&(()=>{var ee;let D=tt.find(q=>q.id===rr&&q.pageIndex===x);if(!D)return null;let z=at(D),U=Ke(z.x,z.y+z.height,T,ie[x].height),W=D.kind==="highlight"||D.kind==="underline"||D.kind==="strikeout"||D.kind==="squiggly",V=D.kind==="rect"||D.kind==="ellipse"||D.kind==="polygon",ne=q=>zt(ue=>ue.map(ye=>ye.id===D.id?{...ye,style:{...ye.style,...q}}:ye));return v("div",{style:{position:"absolute",left:Math.max(0,U.x),top:Math.max(0,U.y-12),zIndex:60,width:230},onMouseDown:q=>q.stopPropagation(),onClick:q=>q.stopPropagation(),children:Y("div",{className:"flex flex-col gap-3 rounded-xl bg-white p-3 shadow-xl ring-1 ring-black/10 dark:bg-zinc-800 dark:ring-white/10",children:[v(Lt,{label:W?"Color":"Stroke",color:D.style.color,onColor:q=>ne({color:q}),opacity:D.style.opacity,onOpacity:q=>ne({opacity:q})}),V&&v(Lt,{label:"Fill",color:(ee=D.style.fill)!=null?ee:{r:1,g:1,b:1},onColor:q=>ne({fill:q}),allowNone:!0,isNone:!D.style.fill,onNone:()=>ne({fill:null})}),Y("button",{type:"button",onClick:()=>{zt(q=>q.filter(ue=>ue.id!==D.id)),jt(null),Wt("Deleted annotation","\u{1F5D1}\uFE0F")},className:"flex items-center justify-center gap-1.5 rounded-lg border border-red-200 px-3 py-1.5 text-xs font-semibold text-red-500 transition-colors hover:bg-red-50 dark:border-red-500/30 dark:hover:bg-red-500/10",children:[v(is,{className:"h-3.5 w-3.5"})," Delete"]})]})})})(),y==="select"&&P?Y("div",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:6},children:[mt&&!yt&&mt.pageIndex===x&&mt!==je?(()=>{var z;let D=Ke(mt.pdfX,mt.pdfY+mt.height,T,((z=ie[x])==null?void 0:z.height)||792);return v("div",{style:{position:"absolute",left:`${D.x}px`,top:`${D.y}px`,width:`${mt.width*T}px`,height:`${mt.height*T}px`,border:"1.5px dashed rgba(59, 130, 246, 0.8)",borderRadius:"2px",background:"rgba(59, 130, 246, 0.05)",cursor:mt.fromXObject?"not-allowed":"move"},children:!mt.fromXObject&&v("span",{className:"pointer-events-none absolute left-0 -top-6 whitespace-nowrap rounded bg-blue-600/90 px-2 py-0.5 text-[10px] font-medium text-white shadow",children:"\u270B Drag to move \xB7 handles to resize"})})})():null,je&&!yt&&je.pageIndex===x?(()=>{var W;let D=Ke(je.pdfX,je.pdfY+je.height,T,((W=ie[x])==null?void 0:W.height)||792),z=je.width*T,U=je.height*T;return Y("div",{style:{position:"absolute",left:`${D.x}px`,top:`${D.y}px`,width:`${z}px`,height:`${U}px`,border:je.fromXObject?"2px solid rgba(156, 163, 175, 0.9)":"2px solid rgba(59, 130, 246, 0.9)",borderRadius:"2px",background:"rgba(59, 130, 246, 0.06)",pointerEvents:"none"},children:[v("div",{style:{position:"absolute",top:"-30px",right:0,display:"flex",gap:"4px",pointerEvents:"auto"},children:je.fromXObject?v("span",{className:"rounded bg-gray-700 px-2 py-1 text-[10px] font-medium text-white shadow",title:"This object lives inside a reusable form XObject and cannot be edited in this version.",children:"\u{1F512} Locked (inside form)"}):Y(en,{children:[v("span",{className:"rounded bg-blue-600/90 px-2 py-1 text-[10px] font-medium text-white shadow",children:"\u270B Drag to move \xB7 handles to resize"}),Y("button",{className:"flex items-center gap-1 rounded bg-red-600 px-2 py-1 text-[11px] font-medium text-white shadow hover:bg-red-700",onClick:V=>{V.stopPropagation(),Ko()},children:[v(is,{className:"h-3 w-3"})," Delete"]})]})}),je.fromXObject?null:["nw","n","ne","e","se","s","sw","w"].filter(V=>je.kind==="image"||V.length===2).map(V=>{let ne={position:"absolute",width:"9px",height:"9px",background:"#fff",border:"1.5px solid rgba(59, 130, 246, 0.95)",borderRadius:"2px",pointerEvents:"auto",cursor:`${V}-resize`};return V.includes("n")?ne.top="-5px":V.includes("s")?ne.bottom="-5px":ne.top="calc(50% - 5px)",V.includes("w")?ne.left="-5px":V.includes("e")?ne.right="-5px":ne.left="calc(50% - 5px)",v("div",{style:ne,onMouseDown:ee=>{ee.stopPropagation(),ee.preventDefault(),zs(je,"resize",V,ee)}},V)})]})})():null,yt&&yt.object.pageIndex===x&&g?(()=>{var V,ne,ee;let D=yt.object,z=Ke(D.pdfX,D.pdfY+D.height,T,((V=ie[x])==null?void 0:V.height)||792),U=D.width*T,W=D.height*T;return Y(en,{children:[v("div",{style:{position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:`${U}px`,height:`${W}px`,background:(ne=g.bgCss)!=null?ne:"#fff"}}),v("div",{ref:q=>{Mo.current=q},style:{position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:`${U}px`,height:`${W}px`,backgroundImage:`url(${g.canvasDataUrl})`,backgroundPosition:`-${z.x}px -${z.y}px`,backgroundSize:`${g.canvasWidth}px ${g.canvasHeight}px`,transform:yt.mode==="move"?`translate(${yt.dxPx}px, ${yt.dyPx}px)`:`scale(${yt.scaleX}, ${yt.scaleY})`,transformOrigin:yt.mode==="resize"?zm[(ee=yt.handle)!=null?ee:"se"]:void 0,willChange:"transform",outline:"2px solid rgba(59, 130, 246, 0.9)",boxShadow:"0 8px 24px rgba(0,0,0,0.25)",opacity:.95}})]})})():null]}):null,y==="edit-text"&&P&&((L=ot.current[x])!=null&&L.length)?v("div",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:5},children:ot.current[x].map((D,z)=>{var ee,q;let U=Ke(D.pdfX,D.pdfY+D.height,T,((ee=ie[x])==null?void 0:ee.height)||792),W=!D.fromXObject&&!!((q=D.streamOperatorIndices)!=null&&q.length),V=(Tn==null?void 0:Tn.run)===D&&Tn.pageIndex===x,ne=V?`translate(${Tn.dxPx}px, ${Tn.dyPx}px)`:void 0;return v("div",{ref:V?ue=>{Pr.current=ue}:void 0,title:W?"Click to edit \xB7 drag to move":"Click to edit",onMouseDown:ue=>{ue.button===0&&(ue.stopPropagation(),ue.preventDefault(),id(D,x,ue))},style:{position:"absolute",left:`${U.x}px`,top:`${U.y}px`,width:`${D.width*T}px`,height:`${D.height*T}px`,cursor:W?"move":"text",pointerEvents:"auto",border:"1px solid rgba(16, 185, 129, 0.5)",borderBottom:"2px solid rgba(16, 185, 129, 0.7)",borderRadius:"1px",background:V?"rgba(16, 185, 129, 0.18)":"rgba(16, 185, 129, 0.04)",transform:ne,transition:V?"none":"background 0.12s",willChange:V?"transform":void 0,zIndex:V?20:void 0},onMouseEnter:ue=>{V||(ue.currentTarget.style.background="rgba(16, 185, 129, 0.12)")},onMouseLeave:ue=>{V||(ue.currentTarget.style.background="rgba(16, 185, 129, 0.04)")}},z)})}):null,(y==="form"||y==="view")&&P?(()=>{var z;let D=y==="form";return Y("div",{"data-fv":hs,style:{position:"absolute",inset:0,zIndex:6,pointerEvents:"none"},children:[D&&Pn&&v("div",{style:{position:"absolute",inset:0,cursor:"crosshair",pointerEvents:"auto"},onMouseDown:U=>fd(x,U)}),D&&On&&On.pageIndex===x&&v("div",{style:{position:"absolute",left:`${On.x}px`,top:`${On.y}px`,width:`${On.w}px`,height:`${On.h}px`,border:"2px dashed rgba(99,102,241,0.9)",background:"rgba(99,102,241,0.12)",pointerEvents:"none"}}),((z=Tt.current[x])!=null?z:[]).map(U=>{var Oe,Ye,Ie,xe,Bt;let W=Ke(U.rect.x,U.rect.y+U.rect.height,T,((Oe=ie[x])==null?void 0:Oe.height)||792),V=U.rect.width*T,ne=U.rect.height*T,ee=Mr===U.id,q=(Ie=(Ye=Il[U.id])!=null?Ye:U.value)!=null?Ie:"",ue={position:"absolute",left:`${W.x}px`,top:`${W.y}px`,width:`${V}px`,height:`${ne}px`,outline:D?ee?"2px solid rgba(99,102,241,0.95)":"1px solid rgba(99,102,241,0.55)":"1px solid rgba(99,102,241,0.35)",background:"rgba(99,102,241,0.06)",borderRadius:"2px",pointerEvents:D&&Pn?"none":"auto",boxSizing:"border-box"},ye=()=>{D&&Ho(U)};return Y(Pm.Fragment,{children:[U.type==="text"||U.type==="signature"?v("input",{type:"text",value:q,readOnly:U.readOnly||U.type==="signature",placeholder:U.type==="signature"?"Signature":"",onFocus:ye,onChange:Fe=>Fr(Dt=>({...Dt,[U.id]:Fe.target.value})),onBlur:Fe=>Lr(U,Fe.target.value),style:{...ue,padding:"0 4px",fontSize:`${Math.min(ne*.7,14)}px`,color:"#111",fontStyle:U.type==="signature"?"italic":"normal"}}):U.type==="checkbox"?v("input",{type:"checkbox",checked:q===U.onState||q==="Yes"||q==="On"||q==="true",onFocus:ye,onChange:Fe=>{var Dt;return Lr(U,Fe.target.checked?(Dt=U.onState)!=null?Dt:"Yes":"Off")},style:{...ue,padding:0,accentColor:"#6366f1"}}):U.type==="dropdown"?Y("select",{value:q,onFocus:ye,onChange:Fe=>Lr(U,Fe.target.value),style:{...ue,padding:"0 4px",fontSize:`${Math.min(ne*.7,14)}px`,color:"#111"},children:[v("option",{value:""}),((xe=U.options)!=null?xe:[]).map(Fe=>v("option",{value:Fe,children:Fe},Fe))]}):U.type==="radio"?v("div",{style:{...ue,display:"flex",flexDirection:"column",justifyContent:"space-around",padding:"2px 4px",fontSize:"11px",color:"#111"},onClick:ye,children:((Bt=U.options)!=null?Bt:[]).map(Fe=>Y("label",{style:{display:"flex",alignItems:"center",gap:4},children:[v("input",{type:"radio",name:`${U.id}`,checked:q===Fe,onChange:()=>Lr(U,Fe),style:{accentColor:"#6366f1"}}),Fe]},Fe))}):null,D&&ee&&!Pn&&v("button",{type:"button",title:"Delete field",onClick:()=>Ls(U),style:{position:"absolute",left:`${W.x+V-8}px`,top:`${W.y-10}px`,zIndex:7,pointerEvents:"auto"},className:"flex h-5 w-5 items-center justify-center rounded-full bg-red-600 text-white shadow hover:bg-red-700",children:v(pn,{className:"h-3 w-3"})})]},U.id)})]})})():null,y==="view"&&P&&Math.abs(x-se)<=2&&((j=ot.current[x])!=null&&j.length)?v(_i,{runs:ot.current[x],scale:T,pageHeight:((X=ie[x])==null?void 0:X.height)||792}):null,y==="view"&&P&&(($=pe.current[x])!=null&&$.length)?v("div",{style:{position:"absolute",inset:0,zIndex:7,pointerEvents:"none"},children:pe.current[x].map((D,z)=>{var V,ne;let U=Ke(D.rect.x,D.rect.y+D.rect.height,T,((V=ie[x])==null?void 0:V.height)||792),W={position:"absolute",left:`${U.x}px`,top:`${U.y}px`,width:`${D.rect.width*T}px`,height:`${D.rect.height*T}px`,cursor:"pointer",pointerEvents:"auto",borderRadius:"2px"};return D.uri?v("a",{href:D.uri,target:"_blank",rel:"noopener noreferrer",title:D.uri,style:W},z):v("div",{title:`Go to page ${((ne=D.destPageIndex)!=null?ne:0)+1}`,style:W,onClick:()=>{var ee;return Ur((ee=D.destPageIndex)!=null?ee:0)}},z)})}):null,Ar&&it.filter(D=>D.pageIndex===x).length>0&&v("div",{style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:8},children:it.filter(D=>D.pageIndex===x).map((D,z)=>{var V;let U=Ke(D.pdfX,D.pdfY+D.height,T,((V=ie[x])==null?void 0:V.height)||792),W=it.indexOf(D)===Nr;return v("div",{style:{position:"absolute",left:`${U.x}px`,top:`${U.y}px`,width:`${D.width*T}px`,height:`${D.height*T}px`,background:W?"rgba(245, 158, 11, 0.45)":"rgba(245, 158, 11, 0.2)",outline:W?"2px solid rgba(245, 158, 11, 0.8)":"none",borderRadius:"1px"}},z)})}),y==="redact"&&Pt.some(D=>D.pageIndex===x)&&v("div",{style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:11},children:Pt.filter(D=>D.pageIndex===x).map(D=>{var V;let z=Ke(D.x,D.y+D.height,T,((V=ie[x])==null?void 0:V.height)||792),U=D.width*T,W=D.height*T;return Y("div",{style:{position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:`${U}px`,height:`${W}px`,border:"2px solid rgba(22, 163, 74, 0.95)",background:"rgba(22, 163, 74, 0.18)",borderRadius:"2px",pointerEvents:"auto",cursor:"move"},title:"Drag to move \xB7 handles to resize \xB7 \xD7 to remove",onMouseDown:ne=>As(D,"move",null,ne),children:[v("button",{onMouseDown:ne=>ne.stopPropagation(),onClick:ne=>{ne.stopPropagation(),Kl(D.id)},title:"Remove this mark",style:{position:"absolute",top:"-10px",right:"-10px",width:"20px",height:"20px",borderRadius:"9999px",background:"#dc2626",color:"#fff",fontSize:"12px",lineHeight:"18px",textAlign:"center",border:"1.5px solid #fff",boxShadow:"0 1px 4px rgba(0,0,0,0.3)",cursor:"pointer"},children:"\xD7"}),["nw","n","ne","e","se","s","sw","w"].map(ne=>{let ee={position:"absolute",width:"9px",height:"9px",background:"#fff",border:"1.5px solid rgba(22, 163, 74, 0.95)",borderRadius:"2px",cursor:`${ne}-resize`};return ne.includes("n")?ee.top="-5px":ne.includes("s")?ee.bottom="-5px":ee.top="calc(50% - 5px)",ne.includes("w")?ee.left="-5px":ne.includes("e")?ee.right="-5px":ee.left="calc(50% - 5px)",v("div",{style:ee,onMouseDown:q=>As(D,"resize",ne,q)},ne)})]},D.id)})}),Re&&Re.pageIndex===x&&v("div",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:10},children:wn.map((D,z)=>{var W;let U=Ke(D.pdfX,D.pdfY+D.height,T,((W=ie[x])==null?void 0:W.height)||792);return v("div",{style:{position:"absolute",left:`${U.x}px`,top:`${U.y}px`,width:`${D.width*T}px`,height:`${D.height*T}px`,background:"rgba(186, 0, 48, 0.12)",border:"2px solid rgba(186, 0, 48, 0.55)",borderRadius:"2px"}},z)})}),wn.length>0&&(Re==null?void 0:Re.pageIndex)===x&&Y("div",{className:"absolute right-3 top-3 z-[100] flex items-center gap-1 rounded-full bg-inverse-surface px-2 py-1 text-inverse-on-surface shadow-2xl",children:[v("button",{onClick:()=>Sd(),disabled:y==="redact",className:"rounded-full px-3 py-1 text-[10px] font-bold transition-colors hover:text-primary disabled:opacity-40",children:"Edit"}),v("span",{className:"h-3 w-px bg-inverse-on-surface/20"}),v("button",{onClick:()=>Dd(),className:"rounded-full px-3 py-1 text-[10px] font-bold transition-colors hover:text-error",children:"Delete"}),v("span",{className:"h-3 w-px bg-inverse-on-surface/20"}),v("button",{onClick:()=>{Nt([]),bt(null)},className:"rounded-full px-3 py-1 text-[10px] font-bold opacity-70 transition-opacity hover:opacity-100",children:"Clear"})]}),(_==null?void 0:_.pageIndex)===x&&v(mc,{ref:le,containerX:_.containerX,containerY:_.containerY,screenWidth:_.screenWidth,screenHeight:_.screenHeight,scale:T,fontSizePt:_.fontSize,fontFamily:_.fontFamily,baselineOffsetPx:_.baselineOffsetPx,maxWidth:_.maxWidth,initialSpans:(G=_.spans)!=null?G:[],baseColor:_.color,maskRect:_.maskRect,bgColor:_.bgColor,ocr:_.ocr,onCommit:(D,z)=>{rd(D,z)},onCancel:()=>Q(null),onActiveStyleChange:Xe},`rt-${x}-${Math.round(_.pdfX)}-${Math.round(_.pdfY)}-${_.isNew?"n":"e"}`)]},u.pageNum)})]}),v($i,{tool:y,textActive:!!_,textStyle:ge,fallbackSizePt:(Hs=_==null?void 0:_.fontSize)!=null?Hs:F,fontName:_==null?void 0:_.fontName,onToggle:u=>{var g;return(g=le.current)==null?void 0:g.toggle(u)},onSize:u=>{var g;return(g=le.current)==null?void 0:g.setSize(u)},onColor:u=>{var g;return(g=le.current)==null?void 0:g.setColor(u)},annotSubtool:Sn,setAnnotSubtool:Ul,highlightMode:gs,setHighlightMode:_l,drawShape:It,setDrawShape:Xl,annotStyle:Ot,setAnnotStyle:Ll,annotationCount:tt.length,onClearAnnotations:()=>{zt([]),jt(null)},addFieldType:Pn,setAddFieldType:No,hasFormFields:jl,selectedField:or,onUpdateField:u=>{or&&cd(or,u)},onDeleteField:()=>{or&&Ls(or)},onFlattenForm:()=>{ad()}}),Ss&&Y("aside",{className:"flex w-72 shrink-0 flex-col border-l border-ink-line bg-paper-card dark:border-white/10 dark:bg-[#1a1712]",children:[Y("div",{className:"flex items-center gap-2 border-b border-ink-line px-4 py-3 dark:border-white/10",children:[v(Pl,{className:"h-4 w-4 text-crimson-600"}),v("span",{className:"font-display text-sm font-bold text-ink dark:text-white",children:"Activity"}),v("div",{className:"flex-1"}),v("button",{type:"button",onClick:()=>Ds(!1),className:"rounded-lg p-1 text-ink-muted hover:bg-paper hover:text-ink dark:hover:bg-zinc-800",children:v(pn,{className:"h-3.5 w-3.5"})})]}),v("div",{className:"flex-1 overflow-y-auto",children:Un.length===0?Y("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[v(Mm,{className:"h-8 w-8 text-ink-muted dark:text-zinc-600"}),v("p",{className:"text-xs text-ink-muted dark:text-zinc-500",children:"No activity yet"})]}):v("ul",{className:"divide-y divide-ink-line/60 dark:divide-white/5",children:[...Un].reverse().map(u=>Y("li",{className:"group flex items-start gap-3 px-4 py-3",children:[v("span",{className:"mt-0.5 text-base leading-none",children:u.icon}),Y("div",{className:"min-w-0 flex-1",children:[v("p",{className:"truncate text-xs font-medium text-ink dark:text-zinc-200",children:u.action}),u.detail&&v("p",{className:"mt-0.5 truncate text-[11px] text-ink-soft dark:text-zinc-400",title:u.detail,children:u.detail}),Y("p",{className:"mt-0.5 text-[10px] text-ink-muted dark:text-zinc-500",children:[u.time.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),u.pageIndex!==void 0&&` \xB7 p.${u.pageIndex+1}`]})]}),u.snapshot?v("button",{type:"button",onClick:()=>Cs(u),disabled:f,title:"Undo this action and everything after it",className:"mt-0.5 shrink-0 rounded-md border border-ink-line-strong px-2 py-1 text-[10px] font-semibold text-ink-soft opacity-0 transition-opacity hover:border-crimson-300 hover:text-crimson-600 group-hover:opacity-100 disabled:opacity-30 dark:border-white/10 dark:text-zinc-400",children:"Undo to here"}):v("span",{className:"mt-0.5 shrink-0 text-[9px] text-ink-muted dark:text-zinc-600",title:"Too old to undo",children:"-"})]},u.id))})}),Un.length>0&&v("div",{className:"border-t border-ink-line px-4 py-2 dark:border-white/10",children:v("button",{type:"button",onClick:()=>Bo([]),className:"text-[11px] text-ink-muted hover:text-crimson-600 dark:text-zinc-500",children:"Clear history"})})]})]}),Y("div",{className:"flex h-6 shrink-0 items-center gap-3 border-t border-ink-line bg-paper-card px-4 text-[11px] text-ink-muted dark:border-white/10 dark:bg-[#1a1712] dark:text-zinc-500",children:[Y("span",{children:[a.length," ",a.length===1?"page":"pages"]}),v("span",{className:"opacity-40",children:"\xB7"}),v("span",{className:"capitalize",children:y.replace(/-/g," ")}),tt.length+pt.length>0&&Y(en,{children:[v("span",{className:"opacity-40",children:"\xB7"}),Y("span",{className:"text-primary",children:[tt.length+pt.length," annotation",tt.length+pt.length!==1?"s":""]})]}),f&&Y(en,{children:[v("span",{className:"opacity-40",children:"\xB7"}),v("span",{className:"animate-pulse text-primary",children:"Saving\u2026"})]})]})]}),kr&&v("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:Y("div",{className:"flex flex-col items-center gap-4",children:[Y("div",{className:"relative h-16 w-16",children:[v("div",{className:"absolute inset-0 rounded-full border-4 border-white/20"}),v("div",{className:"absolute inset-0 animate-spin rounded-full border-4 border-transparent border-t-primary border-r-primary"})]}),Y("div",{className:"text-center",children:[v("p",{className:"font-semibold text-white",children:"Rendering PDF..."}),v("p",{className:"text-sm text-white/70",children:"Please wait while we process your document"})]})]})}),yn&&tn.current&&v("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",children:Y("div",{className:"rounded-2xl bg-surface dark:bg-zinc-900 p-8 shadow-2xl max-w-md w-full mx-4",children:[v("h2",{className:"text-xl font-bold text-on-surface dark:text-white mb-2",children:"Password Protected PDF"}),v("p",{className:"text-on-surface-variant dark:text-zinc-400 mb-6",children:"This PDF requires a password to unlock. Please enter it below."}),w&&w.includes("Incorrect")&&v("div",{className:"mb-4 rounded-lg bg-red-50 dark:bg-red-950/20 p-3 border border-red-200 dark:border-red-800",children:v("p",{className:"text-sm text-red-700 dark:text-red-400",children:w})}),v("input",{type:"password",value:Ze,onChange:u=>Ne(u.target.value),onKeyDown:u=>{u.key==="Enter"&&Ze.trim()&&Ys()},className:"w-full rounded-xl border border-outline-variant/40 dark:border-white/10 bg-surface-container-lowest dark:bg-zinc-950 px-4 py-3 text-sm text-on-surface dark:text-zinc-100 outline-none focus:border-primary focus:ring-1 focus:ring-primary/50 mb-6",placeholder:"Enter password",autoFocus:!0}),Y("div",{className:"flex gap-3",children:[v("button",{type:"button",onClick:()=>{Ne(""),vt(!1),tn.current=null,b("")},className:"flex-1 rounded-full border border-outline-variant/40 dark:border-white/10 px-4 py-3 text-sm font-semibold text-on-surface dark:text-white hover:bg-surface-container-highest dark:hover:bg-zinc-800 transition-colors",children:"Cancel"}),v("button",{type:"button",onClick:Ys,disabled:!Ze.trim(),className:"flex-1 rounded-full bg-primary px-4 py-3 text-sm font-semibold text-white disabled:opacity-60 disabled:cursor-not-allowed hover:bg-primary/90 transition-colors",children:"Unlock"})]})]})}),zl&&v("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:()=>Bn(!1),children:Y("div",{className:"w-[480px] max-w-[95vw] rounded-2xl bg-paper-raised shadow-2xl dark:bg-zinc-900",onClick:u=>u.stopPropagation(),children:[Y("div",{className:"flex items-center gap-3 border-b border-ink-line px-6 py-4 dark:border-white/10",children:[v(rs,{className:"h-5 w-5 text-primary"}),v("h2",{className:"font-headline text-lg font-bold text-on-surface dark:text-white",children:"Add Signature"}),v("div",{className:"flex-1"}),v("button",{type:"button",onClick:()=>Bn(!1),className:"rounded-full p-1 text-on-surface-variant hover:bg-surface-container-high dark:text-zinc-400 dark:hover:bg-zinc-800",children:v(pn,{className:"h-4 w-4"})})]}),Y("div",{className:"px-6 py-4",children:[Y("div",{className:"mb-3 flex items-center justify-between",children:[v("p",{className:"text-sm text-on-secondary-container dark:text-zinc-400",children:"Draw your signature below:"}),Y("button",{type:"button",onClick:()=>{var u;return(u=Ps.current)==null?void 0:u.click()},className:"inline-flex items-center gap-1.5 rounded-lg border border-outline-variant/40 px-3 py-1.5 text-xs font-semibold text-on-secondary-container hover:bg-surface-container-high dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:[v(ss,{className:"h-3.5 w-3.5"})," Upload image"]}),v("input",{ref:Ps,type:"file",accept:"image/png,image/jpeg",className:"hidden",onChange:u=>{var P;let g=(P=u.target.files)==null?void 0:P[0];if(u.target.value="",!g)return;let x=new FileReader;x.onload=()=>{typeof x.result=="string"&&(vs(x.result),Bn(!1),$r(!0))},x.readAsDataURL(g)}})]}),v("canvas",{ref:Ln,width:420,height:150,className:"w-full rounded-lg border-2 border-dashed border-outline-variant/60 bg-white dark:border-white/10 dark:bg-zinc-800",style:{cursor:"crosshair",touchAction:"none"},onMouseDown:u=>{let g=u.currentTarget.getBoundingClientRect(),x=u.currentTarget.getContext("2d");x&&(x.beginPath(),x.moveTo((u.clientX-g.left)*(u.currentTarget.width/g.width),(u.clientY-g.top)*(u.currentTarget.height/g.height)),x.strokeStyle="#1a1a2e",x.lineWidth=2.5,x.lineCap="round",x.lineJoin="round",Br.current=!0)},onMouseMove:u=>{if(!Br.current)return;let g=u.currentTarget.getBoundingClientRect(),x=u.currentTarget.getContext("2d");x&&(x.lineTo((u.clientX-g.left)*(u.currentTarget.width/g.width),(u.clientY-g.top)*(u.currentTarget.height/g.height)),x.stroke())},onMouseUp:()=>{Br.current=!1},onMouseLeave:()=>{Br.current=!1}}),v("p",{className:"mt-2 text-xs text-on-secondary-container/60 dark:text-zinc-500",children:"After applying, click on the page to place it"})]}),Y("div",{className:"flex items-center gap-3 border-t border-ink-line px-6 py-4 dark:border-white/10",children:[v("button",{type:"button",onClick:()=>{var g;let u=(g=Ln.current)==null?void 0:g.getContext("2d");u&&Ln.current&&u.clearRect(0,0,Ln.current.width,Ln.current.height)},className:"rounded-xl border border-outline-variant/40 px-4 py-2 text-sm font-semibold text-on-secondary-container hover:bg-surface-container-high dark:border-white/10 dark:text-zinc-400 dark:hover:bg-zinc-800",children:"Clear"}),v("div",{className:"flex-1"}),v("button",{type:"button",onClick:()=>Bn(!1),className:"rounded-xl border border-outline-variant/40 px-4 py-2 text-sm font-semibold text-on-secondary-container hover:bg-surface-container-high dark:border-white/10 dark:text-zinc-400",children:"Cancel"}),Y("button",{type:"button",onClick:()=>{let u=Ln.current;u&&(vs(u.toDataURL("image/png")),Bn(!1),$r(!0))},className:"inline-flex items-center gap-2 rounded-xl bg-primary px-5 py-2 text-sm font-bold text-on-primary hover:brightness-110",children:[v(Co,{className:"h-4 w-4"}),"Apply Signature"]})]})]})})]})},Al=Km;import{jsx as Nl}from"react/jsx-runtime";function Tl({licenseKey:t,activationUrl:e,className:n,style:r}){let o=El.useMemo(()=>({licenseKey:t,activationUrl:e}),[t,e]);return Nl("div",{className:n?`namahapdf-root ${n}`:"namahapdf-root",style:r,children:Nl(Al,{license:o})})}var Vm=Tl;export{Tl as NamahaEditor,Pi as configureLicense,Vm as default,Mu as getLicenseState,za as isFeatureEnabled,Ru as onLicenseChange,no as shouldWatermark};
|
|
42
|
+
`),o=qf(r);for(let i=0;i<o.length;){let s=o[i];if(s==="usecmap"){let a=i>0?o[i-1]:"(unknown)";console.warn("[PageRenderer][CMap] usecmap reference not resolved",{inheritedName:a}),i+=1;continue}if(s==="begincmap"){for(i+=1;i<o.length&&o[i]!=="endcmap";){let a=o[i];if(Zf(a))break;let c=o[i+1];if(Ut(a)&&Ut(c)){e.bfChar.set(Do(a),So(Nn(c))),i+=2;continue}i+=1}continue}if(s==="beginbfchar"||s==="begincidchar"){for(i+=1;i<o.length&&o[i]!=="endbfchar"&&o[i]!=="endcidchar";){let a=o[i],c=o[i+1];if(Ut(a)&&Ut(c)){e.bfChar.set(Do(a),So(Nn(c))),i+=2;continue}if(vr(a)&&Ut(c)){e.bfChar.set(Number.parseInt(a,10),So(Nn(c))),i+=2;continue}if(vr(a)&&vr(c)){let l=Number.parseInt(a,10),d=Number.parseInt(c,10);if(Number.isFinite(l)&&Number.isFinite(d))try{e.bfChar.set(l,String.fromCodePoint(d))}catch{e.bfChar.set(l,"\uFFFD")}i+=2;continue}i+=1}i<o.length&&(i+=1);continue}if(s==="begincodespacerange"){for(i+=1;i<o.length&&o[i]!=="endcodespacerange";){let a=o[i],c=o[i+1];if(!Ut(a)||!Ut(c)){i+=1;continue}let l=Nn(a),d=Nn(c),m=Math.max(l.length,d.length)/2;m>0&&e.codeSpaceRanges.push({start:Number.parseInt(l,16),end:Number.parseInt(d,16),byteLength:m}),i+=2}i<o.length&&(i+=1);continue}if(s==="beginbfrange"||s==="begincidrange"){for(i+=1;i<o.length&&o[i]!=="endbfrange"&&o[i]!=="endcidrange";){let a=o[i],c=o[i+1];if(!a||!c){i+=1;continue}let l=ul(a),d=ul(c);if(l===null||d===null){i+=1;continue}let m=o[i+2];if(!m){i+=2;continue}if(m==="["){let h=[],f=i+3;for(;f<o.length&&o[f]!=="]";)Ut(o[f])&&h.push(So(Nn(o[f]))),f+=1;e.bfRange.push({start:l,end:d,mapped:h}),i=f<o.length?f+1:f;continue}if(Ut(m)){e.bfRange.push({start:l,end:d,unicodeStart:Do(m)}),i+=3;continue}if(vr(m)){e.bfRange.push({start:l,end:d,unicodeStart:Number.parseInt(m,10)}),i+=3;continue}i+=1}i<o.length&&(i+=1);continue}i+=1}return e},qf=t=>{let e=[],n=0;for(;n<t.length;){for(;n<t.length&&/\s/.test(t[n]);)n+=1;if(n>=t.length)break;if(t[n]==="%"){for(;n<t.length&&t[n]!==`
|
|
43
|
+
`;)n+=1;continue}if(t[n]==="<"){let o=n;for(n+=1;n<t.length&&t[n]!==">";)n+=1;n<t.length&&(n+=1),e.push(t.slice(o,n));continue}if(t[n]==="["||t[n]==="]"){e.push(t[n]),n+=1;continue}let r=n;for(;n<t.length&&!/[\s<\[\]%]/.test(t[n]);)n+=1;if(r<n){let o=t.slice(r,n),i=Jf(o);i?(i.count&&e.push(i.count),e.push(i.keyword)):e.push(o)}}return e},Jf=t=>{let e=t.match(/^(\d+)?(begin\w+|end\w+|usecmap|begincmap|endcmap)$/i);return e?{count:e[1],keyword:e[2]}:null},Zf=t=>t?t==="beginbfchar"||t==="endbfchar"||t==="beginbfrange"||t==="endbfrange"||t==="begincidchar"||t==="endcidchar"||t==="begincidrange"||t==="endcidrange"||t==="begincodespacerange"||t==="endcodespacerange":!1,Ut=t=>!!t&&t.startsWith("<")&&t.endsWith(">"),vr=t=>!!t&&/^\d+$/.test(t),Nn=t=>t.slice(1,-1),Do=t=>Number.parseInt(Nn(t),16),ul=t=>Ut(t)?Do(t):vr(t)?Number.parseInt(t,10):null,So=t=>{let e=t.length%2===0?t:`0${t}`;if(e.length===0)return"";if(e.length<=4){let r=Number.parseInt(e,16);if(!Number.isFinite(r))return"\uFFFD";try{return String.fromCodePoint(r)}catch{return"\uFFFD"}}let n="";for(let r=0;r<e.length;r+=4){let o=e.slice(r,r+4).padStart(4,"0"),i=Number.parseInt(o,16);if(!Number.isFinite(i)){n+="\uFFFD";continue}try{n+=String.fromCodePoint(i)}catch{n+="\uFFFD"}}return n},Qf=(t,e)=>{var r;console.log(`=== CMap debug for font ${e} ===`),console.log(`cmapType: ${t.cmapType}`),console.log(`isUsable: ${t.isUsable}`),console.log(`bfChar entries: ${t.bfChar.size}`),console.log(`bfRange entries: ${t.bfRange.length}`),console.log(`codespace ranges: ${t.codeSpaceRanges.length}`);let n=0;for(let[o,i]of t.bfChar.entries()){if(n>=10)break;let s=i.codePointAt(0);console.log(` 0x${o.toString(16).padStart(4,"0")} -> "${i}" (U+${(r=s==null?void 0:s.toString(16).toUpperCase())!=null?r:"????"})`),n+=1}for(let o of t.bfRange.slice(0,5))typeof o.unicodeStart=="number"?console.log(` range 0x${o.start.toString(16).padStart(4,"0")}-0x${o.end.toString(16).padStart(4,"0")} -> U+${o.unicodeStart.toString(16).toUpperCase()}`):o.mapped&&console.log(` range 0x${o.start.toString(16).padStart(4,"0")}-0x${o.end.toString(16).padStart(4,"0")} -> [mapped:${o.mapped.length}]`);for(let o of t.codeSpaceRanges.slice(0,5))console.log(` codespace ${o.byteLength}b 0x${o.start.toString(16).padStart(o.byteLength*2,"0")}-0x${o.end.toString(16).padStart(o.byteLength*2,"0")}`)},en=(t,e)=>{let n=e.bfChar.get(t);if(n!==void 0)return n;for(let r of e.bfRange)if(!(t<r.start||t>r.end)){if(r.mapped){let o=t-r.start;return o>=0&&o<r.mapped.length?r.mapped[o]:null}if(typeof r.unicodeStart=="number"){let o=r.unicodeStart+(t-r.start);return String.fromCodePoint(o)}}return null},em=(t,e,n,r,o=!1)=>{var s,a;if(n){let c=fm(e),l=om(e),m=(l?[{mode:"raw",bytes:t}]:rm(t)).map(y=>({mode:y.mode,attempt:nm(y.bytes,e,c)})),h=im(m),f=h.attempt,p=gm(f)?xm(t):null,w=bm(f,p);if(o&&console.debug("[PageRenderer][CMap] decode strategy",{font:r!=null?r:"?",mapped:f.mapped,unmapped:f.unmapped,utf16Score:(s=p==null?void 0:p.score)!=null?s:null,codespaceRanges:e.codeSpaceRanges.length,inferredCodeLengths:c,payloadMode:h.mode,sparseToUnicode:l,chosen:w===p?"utf16be":"cmap"}),o&&f.unmappedGlyphs.length>0){let y=f.unmappedGlyphs.slice(0,12).map(C=>`0x${C.toString(16).padStart(4,"0")}`),v=mm(f.unmappedGlyphs,c),b=l?`${r!=null?r:"?"}|sparse-tounicode`:`${r!=null?r:"?"}|${h.mode}`;Qc.has(b)||(Qc.add(b),console.warn("[PageRenderer][CMap] unmapped composite glyphs",{font:r!=null?r:"?",count:f.unmappedGlyphs.length,payloadMode:h.mode,sparseToUnicode:l,rootCause:l?`ToUnicode is too sparse (bfChar=${e.bfChar.size}, bfRange=${e.bfRange.length}); Unicode recovery is fundamentally limited for this font.`:void 0,sample:y,topMissing:v.topMissing,mappingHints:v.mappingHints,note:"Use mappingHints as candidate ToUnicode entries (<src> <dst>) for manual verification."}))}return(a=w==null?void 0:w.text)!=null?a:f.text}let i="";for(let c=0;c<t.length;c++){let l=en(t[c],e);i+=l!==null?l:String.fromCharCode(t[c])}return i},tm=(t,e)=>{let n="",r=0;for(;r+1<t.length;){let o=t[r],i=t[r+1],s=o<<8|i,a=en(s,e);if(a!==null){n+=a,r+=2;continue}if(i>=32&&i<=126){n+=String.fromCharCode(i),r+=2;continue}if(o>=32&&o<=126){n+=String.fromCharCode(o),r+=2;continue}r+=2}if(r<t.length){let o=t[r];o>=32&&o<=126&&(n+=String.fromCharCode(o))}return n},nm=(t,e,n)=>e.codeSpaceRanges.length>0?um(t,e):hm(t,e,n),rm=t=>{var s;let e=[{mode:"raw",bytes:t}],n=new Set([`raw:${t.length}:${(s=t[0])!=null?s:-1}`]),r=(a,c)=>{var d,m;if(!c||c.length===0)return;let l=`${a}:${c.length}:${(d=c[0])!=null?d:-1}:${(m=c[1])!=null?m:-1}`;n.has(l)||(n.add(l),e.push({mode:a,bytes:c}))},o=sm(t);r("zero-stripped",o);let i=am(t);return r("pair-swapped",i),r("ascii-hex",es(t)),o&&r("zero-stripped+ascii-hex",es(o)),i&&r("pair-swapped+ascii-hex",es(i)),e},om=t=>t.bfChar.size+t.bfRange.length<=2,im=t=>{let e=t[0],n=hl(e.attempt);for(let r=1;r<t.length;r+=1){let o=t[r],i=hl(o.attempt);i>n+1&&(e=o,n=i)}return e},sm=t=>{if(t.length<4||t.length%2!==0)return null;let e=0,n=0;for(let a=0;a<t.length;a+=2)t[a]===0&&(e+=1),t[a+1]===0&&(n+=1);let r=t.length/2,o=e>=Math.floor(r*.7),i=n>=Math.floor(r*.7);if(!o&&!i)return null;let s=new Uint8Array(r);for(let a=0;a<r;a+=1)s[a]=o?t[a*2+1]:t[a*2];return s},am=t=>{if(t.length<2||t.length%2!==0)return null;let e=new Uint8Array(t.length);for(let n=0;n<t.length;n+=2)e[n]=t[n+1],e[n+1]=t[n];return e},hl=t=>t.mapped*2-t.unmapped,es=t=>{if(t.length<8)return null;let e=0,n=0,r=0,o=[];for(let s of t)if(!cm(s)){if(n+=1,!lm(s))return null;(s>=65&&s<=70||s>=97&&s<=102)&&(r+=1),e+=1,o.push(String.fromCharCode(s))}if(n<8||e!==n||e%2!==0||r===0)return null;let i=new Uint8Array(e/2);for(let s=0;s<i.length;s+=1){let a=fl(o[s*2]),c=fl(o[s*2+1]);if(a<0||c<0)return null;i[s]=a<<4|c}return i},cm=t=>t===32||t===9||t===10||t===13,lm=t=>t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102,fl=t=>t>="0"&&t<="9"?t.charCodeAt(0)-48:t>="a"&&t<="f"?t.charCodeAt(0)-97+10:t>="A"&&t<="F"?t.charCodeAt(0)-65+10:-1,dm=(t,e)=>{let n="",r=0,o=0,i=[];for(let s=0;s<t.length;){if(s+1<t.length){let c=t[s]<<8|t[s+1],l=en(c,e);if(l!==null){n+=l,r+=1,s+=2;continue}let d=en(t[s],e),m=en(t[s+1],e);if(d!==null||m!==null){n+="\uFFFD\uFFFD",o+=1,i.push(c),s+=2;continue}n+="\uFFFD",o+=1,i.push(c),s+=2;continue}let a=en(t[s],e);a!==null?(n+=a,r+=1):(n+="\uFFFD",o+=1,i.push(t[s])),s+=1}return{text:n,mapped:r,unmapped:o,unmappedGlyphs:i}},um=(t,e)=>{let n=Array.from(new Set(e.codeSpaceRanges.map(a=>a.byteLength))).sort((a,c)=>c-a);if(n.length===0)return dm(t,e);let r="",o=0,i=0,s=[];for(let a=0;a<t.length;){let c=0,l=null;for(let m of n){if(a+m>t.length)continue;let h=Zn(t,a,m);if(h!==null&&xl(h,m,e.codeSpaceRanges)){c=m,l=h;break}}if(c>0&&l!==null){let m=en(l,e);m!==null?(r+=m,o+=1):(r+="\uFFFD",i+=1,s.push(l)),a+=c;continue}let d=a+1<t.length?t[a]<<8|t[a+1]:t[a];r+="\uFFFD",i+=1,s.push(d),a+=1}return{text:r,mapped:o,unmapped:i,unmappedGlyphs:s}},hm=(t,e,n)=>{var c,l;let r=n.length>0?[...n].sort((d,m)=>m-d):[2,1],o="",i=0,s=0,a=[];for(let d=0;d<t.length;){let m=0,h=null;for(let w of r){if(d+w>t.length)continue;let y=Zn(t,d,w);if(y===null)continue;let v=en(y,e);if(v!==null){h=v,m=w;break}}if(h!==null&&m>0){o+=h,i+=1,d+=m;continue}let f=(c=r[r.length-1])!=null?c:1,p=(l=Zn(t,d,Math.min(f,t.length-d)))!=null?l:t[d];o+="\uFFFD",s+=1,a.push(p),d+=Math.min(f,t.length-d)}return{text:o,mapped:i,unmapped:s,unmappedGlyphs:a}},fm=t=>{let e=new Set;for(let r of t.codeSpaceRanges)r.byteLength>=1&&r.byteLength<=4&&e.add(r.byteLength);for(let r of t.bfChar.keys())e.add(ts(r));for(let r of t.bfRange)e.add(ts(r.start)),e.add(ts(r.end));let n=Array.from(e).filter(r=>r>=1&&r<=4);return n.length===0?[2,1]:n.sort((r,o)=>o-r)},ts=t=>t<=255?1:t<=65535?2:t<=16777215?3:4,mm=(t,e)=>{var c;let n=new Map;for(let l of t)n.set(l,((c=n.get(l))!=null?c:0)+1);let o=Array.from(n.entries()).sort((l,d)=>d[1]-l[1]).slice(0,8),i=o.map(([l,d])=>({glyph:`0x${l.toString(16).padStart(4,"0")}`,count:d})),s=e.length>0?e[e.length-1]:2,a=o.map(([l])=>pm(l,s)).filter(l=>l!==null);return{topMissing:i,mappingHints:a}},pm=(t,e)=>{let n=t.toString(16).padStart(Math.max(4,e*2),"0"),r=t&255;if(r>=32&&r<=126){let o=r.toString(16).toUpperCase().padStart(4,"0");return{glyph:`0x${n}`,candidateUnicode:`U+${o} (${String.fromCharCode(r)})`,reason:"Printable ASCII low-byte candidate",cmapLine:`<${n}> <${o}>`}}if(t>=32&&t<=126){let o=t.toString(16).toUpperCase().padStart(4,"0");return{glyph:`0x${n}`,candidateUnicode:`U+${o} (${String.fromCharCode(t)})`,reason:"Direct ASCII glyph code candidate",cmapLine:`<${n}> <${o}>`}}return null},gm=t=>t.text.length===0?!1:t.mapped>0?t.unmapped>=t.mapped*3:t.unmapped>0,xm=t=>{var i;let e=gl(t),n=pl(e),r=((i=e.match(/\uFFFD/g))!=null?i:[]).length,o=n-r*3;return{text:e,mapped:n,unmapped:r,unmappedGlyphs:[],printable:n,score:o}},bm=(t,e)=>{if(!e)return t;let n=ym(t.text);return wm(e.text)&&e.score>=n+8?e:t},ym=t=>{var r;let e=pl(t),n=((r=t.match(/\uFFFD/g))!=null?r:[]).length;return e-n*3},pl=t=>{var n;let e=0;for(let r of t){let o=(n=r.codePointAt(0))!=null?n:0;if(o===9||o===10||o===13){e+=1;continue}if(o>=32&&o<=126){e+=2;continue}if(o>=160&&o<=591){e+=1;continue}}return e},wm=t=>{var o,i;if(!t||((o=t.match(/\uFFFD/g))!=null?o:[]).length>Math.floor(t.length*.2))return!1;let n=0,r=0;for(let s of t){let a=(i=s.codePointAt(0))!=null?i:0;if(a>=32&&a<=126){n+=1;continue}(a>=12288&&a<=12351||a>=8592&&a<=8703)&&(r+=1)}return n>=8&&n*2>=t.length?!0:(r>0&&r*2>=t.length,!1)},Fe=t=>t?typeof t=="string"?t:typeof t=="object"&&"type"in t&&t.type==="name"&&"value"in t?String(t.value):null:null,gl=t=>{if(t.length<2)return new TextDecoder("latin1").decode(t);let e="";for(let n=0;n+1<t.length;n+=2){let r=t[n]<<8|t[n+1];e+=String.fromCharCode(r)}return t.length%2!==0&&(e+="\uFFFD"),e},vm=t=>{var e,n,r,o,i,s,a;return{length:t.length,beginbfchar:((e=t.match(/beginbfchar/g))!=null?e:[]).length,beginbfrange:((n=t.match(/beginbfrange/g))!=null?n:[]).length,begincidchar:((r=t.match(/begincidchar/g))!=null?r:[]).length,begincidrange:((o=t.match(/begincidrange/g))!=null?o:[]).length,begincodespacerange:((i=t.match(/begincodespacerange/g))!=null?i:[]).length,usecmap:((s=t.match(/usecmap/g))!=null?s:[]).length,hexTokens:((a=t.match(/<[0-9a-fA-F]+>/g))!=null?a:[]).length,preview:t.slice(0,220)}},Qt=t=>{var e,n,r;if(!t)return"undefined";if(typeof t=="string")return`string:${t}`;if(typeof t=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&"type"in t){let o=String((e=t.type)!=null?e:"unknown");return o==="ref"&&"objectNumber"in t?`ref:${String((n=t.objectNumber)!=null?n:"?")}`:o==="name"&&"value"in t?`name:${String((r=t.value)!=null?r:"")}`:o}return typeof t},Zn=(t,e,n)=>{if(n<1||n>4||e+n>t.length)return null;let r=0;for(let o=0;o<n;o+=1)r=r<<8|t[e+o];return r>>>0},xl=(t,e,n)=>{for(let r of n)if(r.byteLength===e&&t>=r.start&&t<=r.end)return!0;return!1};import{useState as bl}from"react";var km="/api/decrypt-pdf";function Pm(t){let e=new TextDecoder("latin1"),n=Math.min(t.length,1024*1024),r=e.decode(t.subarray(0,n)),o=Math.max(0,t.length-n),i=o===0?"":e.decode(t.subarray(o));return/\/Encrypt\s+(?:\d+\s+\d+\s+R|<<)/.test(`${r}
|
|
44
|
+
${i}`)}function yl(t={}){var c;let e=(c=t.decryptUrl)!=null?c:km,[n,r]=bl(!1),[o,i]=bl(null),s=async(l,d)=>{r(!0),i(null);try{let m=new Uint8Array(await l.arrayBuffer());if(!d&&!Pm(m))return r(!1),{success:!0,pdfBytes:m,isEncrypted:!1,requiresPassword:!1};let h=new FormData;h.append("file",l),d&&h.append("password",d);let f;try{f=await fetch(e,{method:"POST",body:h})}catch{let y="This PDF is password protected. Decrypting it needs a server endpoint, which is not configured here. Set `decryptUrl` to enable encrypted PDFs.";return i(y),r(!1),{success:!1,isEncrypted:!0,requiresPassword:!0,error:y}}if(f.status===404){let y=`This PDF is password protected, but no decryption endpoint was found at "${e}". Configure \`decryptUrl\` to enable encrypted PDFs.`;return i(y),r(!1),{success:!1,isEncrypted:!0,requiresPassword:!0,error:y}}if(f.ok){let y=new Uint8Array(await f.arrayBuffer());return r(!1),{success:!0,pdfBytes:y,isEncrypted:!0,requiresPassword:!1}}f.status===401&&typeof window!="undefined"&&window.dispatchEvent(new Event("namaha:needs-auth"));let p=await f.json().catch(()=>null);if(p!=null&&p.isEncrypted&&(p!=null&&p.requiresPassword))return r(!1),{success:!1,isEncrypted:!0,requiresPassword:!0,error:p.error||"This PDF is password protected"};let w=(p==null?void 0:p.error)||"Failed to process PDF";return i(w),r(!1),{success:!1,isEncrypted:!1,requiresPassword:!1,error:w}}catch(m){let h=m instanceof Error?m.message:"Unknown error";return i(h),r(!1),{success:!1,isEncrypted:!1,requiresPassword:!1,error:h}}};return{uploadPdf:s,uploadPdfWithPasswordPrompt:async(l,d=`${l.name} is password protected. Enter the PDF password:`)=>{let m=await s(l);for(let h=0;m.requiresPassword&&h<3;h+=1){let f=window.prompt(h===0?d:`That password did not unlock ${l.name}. Try again:`);if(!f){let p="Password required to process this PDF.";return i(p),{success:!1,isEncrypted:!0,requiresPassword:!0,error:p}}m=await s(l,f)}return m},isLoading:n,error:o}}import{useEffect as Sm}from"react";var Dm=t=>{if(!t)return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||t.isContentEditable===!0};function wl({enabled:t=!0,onUndo:e,onSave:n}){Sm(()=>{if(!t)return;let r=o=>{if(!(o.ctrlKey||o.metaKey)||o.altKey)return;let i=o.key.toLowerCase();if(i==="s"){o.preventDefault(),n==null||n();return}if(i==="z"&&!o.shiftKey){if(Dm(document.activeElement))return;o.preventDefault(),e==null||e()}};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,e,n])}import{ArrowLeft as Fm,ArrowRight as Mm,Check as Fo,ChevronUp as Rm,ChevronDown as Am,Clock as Nm,Download as Em,Edit3 as Tm,Eraser as rs,Eye as Pl,FilePlus2 as Om,FileText as Mo,Highlighter as Im,Maximize2 as jm,Shapes as $m,History as Sl,Lock as Bm,MessageSquareText as Dl,MousePointer as Lm,PenTool as os,Replace as Um,RotateCw as _m,ScanText as Cl,Search as is,Image as Xm,Share2 as zm,StickyNote as Fl,Trash2 as ss,Type as Ml,Upload as as,X as gn,ZoomIn as Ym,ZoomOut as Wm}from"lucide-react";import{Fragment as tn,jsx as k,jsxs as Y}from"react/jsx-runtime";var Hm={se:"0% 0%",sw:"100% 0%",ne:"0% 100%",nw:"100% 100%",n:"50% 100%",s:"50% 0%",e:"0% 50%",w:"100% 50%"},Gm=30,xn=2,Rl=50,Km=15,Vm=2,Al=t=>{let e=new Uint8Array(t);return new Blob([e.buffer],{type:"application/pdf"})},qm=t=>{var e;try{let n=t.getContext("2d"),r=t.width,o=t.height;if(!n||r<4||o<4)return"#ffffff";let i=[[2,2],[r-3,2],[2,o-3],[r-3,o-3],[Math.floor(r/2),2],[2,Math.floor(o/2)],[r-3,Math.floor(o/2)],[Math.floor(r/2),o-3]],s=new Map;for(let[c,l]of i){let d=n.getImageData(c,l,1,1).data;if(d[3]<200)continue;let m=`${d[0]>>4}-${d[1]>>4}-${d[2]>>4}`,h=(e=s.get(m))!=null?e:{n:0,r:0,g:0,b:0};h.n++,h.r+=d[0],h.g+=d[1],h.b+=d[2],s.set(m,h)}let a=null;for(let c of s.values())(!a||c.n>a.n)&&(a=c);return a?`rgb(${Math.round(a.r/a.n)},${Math.round(a.g/a.n)},${Math.round(a.b/a.n)})`:"#ffffff"}catch{return"#ffffff"}},cs=(t,e)=>({id:crypto.randomUUID(),name:e,blob:t,type:"pdf",size:t.size,metadata:{},history:[]}),Jm=({license:t,decryptUrl:e}={})=>{var Hs,Gs;let{uploadPdf:n,isLoading:r}=yl({decryptUrl:e}),[o,i]=se(null),[s,a]=se(null),[c,l]=se([]),[d,m]=se({}),[h,f]=se(!1),[p,w]=se(!1),[y,v]=se(""),[b,C]=se("view"),[S,F]=se(""),[T,N]=se(14),[O,A]=se({r:.84,g:0,b:.19}),H=1.4,[ne,ie]=se(1),I=H*ne,ce=be(null),[le,pe]=se(0),De=be({}),[_,K]=se({}),[G,ae]=se(null),me=be(null),[Xe,Te]=se({}),[Me,lt]=se(!1),[rt,ot]=se(0),[Mt,ft]=se(!1),[bn,ye]=se(!1),[Ke,_t]=se(null),ke=be(new Set),Je=be(new Set),Qe=be({}),[Re,Rt]=se(""),[En,Xt]=se(!1),[Pr,yn]=se(!1),Ro=be(null),Sr=be(null),Dr=be(!1),ls=be(null),nn=be(null),He=be({}),ze=be({}),it=be({}),vt=be({}),Ao=be({}),rn=be(null),Cr=be(new Set),[wn,At]=se([]),[Ae,bt]=se(null),[Il,ds]=se(!1),zt=be(null),er=be(!1),[kt,vn]=se([]),No=be(null),[je,Nt]=se(null),[mt,kn]=se(null),[yt,us]=se(null),Tn=be(null),[On,hs]=se(null),tr=be(null),Et=be({}),[fs,Fr]=se(0),[jl,Mr]=se({}),[Pn,Eo]=se(null),[Rr,To]=se(null),[$l,Oo]=se(!1),[In,Ar]=se(null),nr=be(null),jn=be({}),Io=be(null),jo=be(!1),[$n,$o]=se(null),ms=be(null),[Nr,rr]=se(!1),[on,ps]=se(""),[gs,Bl]=se(""),[Er,Tr]=se(0),[st,Or]=se([]),Ir=be(null),[pt,Bn]=se([]),[et,Yt]=se([]),[Tt,Ll]=se({color:{r:1,g:.85,b:0},opacity:1,strokeWidth:2,fill:null}),Ul=u=>Ll(g=>({...g,...u})),[Sn,_l]=se("highlight"),[xs,Xl]=se("select"),[Ot,zl]=se("rect"),[or,It]=se(null),[bs,Pt]=se(null),[ys,jr]=se(!1),sn=be(null),Wt=be(null),Bo=be(!1),[ws,$r]=se(null),[Yl,Ln]=se(!1),[vs,ks]=se(null),[Ps,Br]=se(!1),Un=be(null),Lr=be(!1),Ss=be(null),[_n,Lo]=se([]),[Ds,Cs]=se(!1),Uo=()=>{var u;return{blob:(u=s!=null?s:o)!=null?u:null,annotations:pt,annots:et}},_o=(u,g,x,P,E)=>Lo(R=>{let B=[...R,{id:crypto.randomUUID(),time:new Date,action:u,icon:g,pageIndex:x,detail:P,snapshot:E}],M=B.length-Gm;return M<=0?B:B.map((L,j)=>j<M?{...L,snapshot:null}:L)}),Ht=(u,g,x,P)=>_o(u,g,x,P,Uo()),Fs=u=>{var x;if(!u.snapshot)return;let g=u.snapshot;rn.current=null,ae(null),Nt(null),kn(null),At([]),bt(null),Bn(g.annotations),Yt((x=g.annots)!=null?x:[]),It(null),Lo(P=>{let E=P.findIndex(R=>R.id===u.id);return E<0?P:P.slice(0,E)}),a(g.blob===o?null:g.blob),v("Reverted to an earlier state.")},Wl=()=>{for(let u=_n.length-1;u>=0;u--)if(_n[u].snapshot){Fs(_n[u]);return}},[Hl,Qm]=se(90),[Ms,ep]=se(0),jt=be(0);wt(()=>{Xn.getAvailableProcessors().includes("pdf-editor-core")||Xn.registerProcessor(new ao)},[]),wt(()=>{Si(t!=null?t:{})},[t]);let Rs=vl(async u=>{if(!ro())return u;try{let g=await wi(new Uint8Array(await u.arrayBuffer()));return new Blob([g],{type:"application/pdf"})}catch{return u}},[]),Ne=kl(()=>s!=null?s:o,[s,o]),Xo=(Hs=o==null?void 0:o.name)!=null?Hs:"document.pdf",zo=u=>{let g=Ao.current,x=u!=null?u:Object.keys(g).map(Number);for(let P of x){let E=g[P];E&&URL.revokeObjectURL(E),delete g[P]}},As=async(u,g)=>{var R,B;let x=g==null?void 0:g.onlyPages,P=!!x&&x.length>0,E=++jt.current;P||f(!0);try{let M=new Uint8Array(await u.arrayBuffer()),L=new Kt(M),j=L.parse(),$=Wn.getAllPages(j,{objectLoader:ee=>L.loadObject(ee)}).pages,V=$.map(ee=>{var ue;let Z=(ue=ee.mediaBox)!=null?ue:[0,0,612,792];return{pageIndex:ee.pageNum-1,pageNum:ee.pageNum,width:Math.max(1,Z[2]-Z[0]),height:Math.max(1,Z[3]-Z[1]),mediaBox:Z}});l(V);try{let ee=L.loadObject(j.rootRef),Z=new Map;for(let ge of $)Z.set(ge.pageNum-1,ge.dict);let ue=ee&&"entries"in ee?Mc(ee,Z,ge=>L.loadObject(ge)):[],xe={},Oe={};for(let ge of ue)((B=xe[R=ge.pageIndex])!=null?B:xe[R]=[]).push(ge),ge.value!==void 0&&(Oe[ge.id]=ge.value);if(Et.current=xe,nr.current){let ge=ue.find($t=>$t.name===nr.current);To(ge?ge.id:null),ge&&(jn.current[ge.id]=ge.name)}Mr(ge=>P?{...Oe,...ge}:Oe),Oo(ue.length>0),Fr(ge=>ge+1);let Ye=new Map;for(let ge of $)Ye.set(`${ge.ref.objNum}:${ge.ref.genNum}`,ge.pageNum-1);let Ie={};for(let ge of $){let $t=_i(ge.dict,Ye,Ce=>L.loadObject(Ce));$t.length&&(Ie[ge.pageNum-1]=$t)}De.current=Ie}catch{Et.current={},De.current={},Oo(!1)}if(P||(zo(),m({}),K({}),ze.current={},it.current={},vt.current={}),$.length===0){v("No pages were found in this PDF.");return}P||v($.length>xn?`Loading first ${xn} pages...`:"Rendering pages...");let D=async ee=>{var qs,Js;let Z=ee.pageNum-1,ue=(qs=ee.mediaBox)!=null?qs:[0,0,612,792],xe=Math.max(1,ue[2]-ue[0]),Oe=Math.max(1,ue[3]-ue[1]),Ye=ee.dict.entries.get("Contents"),Ie=await mi(Ye,$e=>L.loadObject($e)),ge=qt(Ie.combinedBytes),$t=ge.length;if(Ie.streamCount>1&&Ie.streamByteLengths.length>0){let $e=Ie.combinedBytes.subarray(0,Ie.streamByteLengths[0]);$t=qt($e).length}let Ce=document.createElement("canvas"),St=new kr(Ce,Math.ceil(xe),Math.ceil(Oe),H,{disableClip:!1,debug:!1});St.setFontContext(ee.resources,$e=>L.loadObject($e)),await St.renderAsync(ge),await St.renderAnnotations(ee.dict);let Xr=St.getCapturedTextRuns().filter($e=>$e.text.trim().length>0).map($e=>{let Zs=$c($e,Z,Oe,H);return Ie.streamCount>1&&$e.streamOperatorIndex>=$t?{...Zs,contentStreamIndex:1}:Zs}),Md=mo(Xr),Rd=[...St.getCapturedImages().map($e=>Ic($e,Z,Oe,H)),...St.getCapturedGraphics().map($e=>jc($e,Z,Oe,H))];if(ro()){let $e=Ce.getContext("2d");$e&&yi($e,Ce.width,Ce.height)}let Zo=await new Promise($e=>Ce.toBlob($e,"image/png"));zo([Z]);let Ks=Zo?URL.createObjectURL(Zo):Ce.toDataURL("image/png");Zo&&(Ao.current[Z]=Ks);let Ad={pageIndex:Z,pageNum:ee.pageNum,canvasDataUrl:Ks,canvasWidth:Ce.width,canvasHeight:Ce.height,mediaBox:ue,textRuns:Xr,bgCss:qm(Ce)},Qo=(Js=Qe.current[Z])!=null?Js:[],Vs=Qo.length?[...Xr,...Qo]:Xr,Nd=Qo.length?mo(Vs):Md;m($e=>({...$e,[Z]:Ad})),K($e=>({...$e,[Z]:{width:xe,height:Oe}})),ze.current={...ze.current,[Z]:Vs},it.current={...it.current,[Z]:Nd},vt.current={...vt.current,[Z]:Rd}};if(P){let ee=new Set(x);for(let ue of $)if(ee.has(ue.pageNum-1)){if(jt.current!==E)return;await D(ue)}let Z=$.filter(ue=>{let xe=ue.pageNum-1;return!ee.has(xe)&&!ze.current[xe]});for(let ue of Z){if(jt.current!==E||(await new Promise(xe=>setTimeout(xe,Rl)),jt.current!==E))return;await D(ue)}return}let z=$.slice(0,xn);for(let ee of z){if(jt.current!==E)return;await D(ee)}jt.current===E&&(f(!1),yn(!1),$.length>xn&&v(`Showing ${xn} of ${$.length} pages, loading remaining pages in background...`));let U=new Map($.slice(xn).map(ee=>[ee.pageNum-1,ee])),W=$.length>Km,J=()=>{let ee=[...U.keys()];if(W&&Cr.current.size>0){let Z,ue=1/0;for(let xe of ee)for(let Oe of Cr.current){let Ye=Math.abs(xe-Oe);Ye<=Vm&&Ye<ue&&(Z=xe,ue=Ye)}if(Z!==void 0)return Z}return Math.min(...ee)},te=0;for(;U.size>0;){if(jt.current!==E||(await new Promise(xe=>setTimeout(xe,Rl)),jt.current!==E))return;let ee=J(),Z=U.get(ee);if(U.delete(ee),!Z)continue;await D(Z),te+=1;let ue=xn+te;v(`Loaded ${ue}/${$.length} pages...`)}if(jt.current!==E)return;$.length>xn&&v(`All ${$.length} pages loaded.`)}catch(M){P||(l([]),m({}),K({}),ze.current={},it.current={},vt.current={}),v(M instanceof Error?`Engine render failed: ${M.message}`:"Engine render failed")}finally{jt.current===E&&(f(!1),yn(!1))}};wt(()=>{let u=g=>{(g.ctrlKey||g.metaKey)&&g.key==="f"&&(g.preventDefault(),rr(!0),setTimeout(()=>{var x;return(x=Ir.current)==null?void 0:x.focus()},50)),g.key==="Escape"&&rr(!1)};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[]),wt(()=>{if(!on.trim()){Or([]),Tr(0);return}let u=on.toLowerCase(),g=[];for(let x of Object.values(ze.current))for(let P of x)P.text.toLowerCase().includes(u)&&g.push(P);Or(g),Tr(0)},[on]),wt(()=>{if(!Ne){zo(),l([]),m({}),K({}),ze.current={},it.current={},vt.current={};return}let u=rn.current;rn.current=null,u?As(Ne,{onlyPages:u}):As(Ne)},[Ne]),wt(()=>{let u=Ao.current;return()=>{for(let g of Object.values(u))URL.revokeObjectURL(g)}},[]),wt(()=>{if(typeof IntersectionObserver=="undefined")return;let u=Cr.current,g=new IntersectionObserver(x=>{for(let P of x){let E=P.target.dataset.pageIndex;if(E===void 0)continue;let R=Number(E);P.isIntersecting?u.add(R):u.delete(R)}u.size&&pe(Math.min(...u))},{rootMargin:"300px"});for(let[x,P]of Object.entries(He.current))P&&(P.dataset.pageIndex=x,g.observe(P));return()=>{g.disconnect(),u.clear()}},[c]);let Gl=u=>{switch(u.type){case"insert-text":return`"${u.text}"`;case"replace-text":return`\u2192 "${u.newText}"`;case"create-form-field":return`${u.fieldType} "${u.name}"`;case"set-form-values":return u.values.map(g=>`${g.name} = "${g.value}"`).join(", ");case"delete-form-field":return`"${u.name}"`;case"rotate-page":return`${u.degrees}\xB0`;case"redact-area":return`${Math.round(u.width)}\xD7${Math.round(u.height)} area`;default:return}},at=async(u,g)=>{var P,E,R,B;if(!Ne)return;let x=Uo();w(!0),v("Applying change...");try{let M=(P=o==null?void 0:o.name)!=null?P:"document.pdf",L=cs(Ne,M),j=await Xn.runPipeline(L,{tasks:[{processorName:"pdf-editor-core",params:{operations:[u]}}]}),X=j[j.length-1];if(!(X!=null&&X.success)){v((E=X==null?void 0:X.error)!=null?E:"Operation failed");return}rn.current=u.type==="replace-text"||u.type==="insert-text"||u.type==="redact-area"||u.type==="delete-object"||u.type==="transform-object"||u.type==="insert-image"||u.type==="create-form-field"?[u.pageIndex]:u.type==="set-form-values"&&u.pageIndex!==void 0?[u.pageIndex]:null,a(X.document.blob),Nt(null),kn(null),v("Saved");let $={"replace-text":"\u270F\uFE0F","insert-text":"\u{1F4DD}","redact-area":"\u2B1B","delete-object":"\u{1F9F9}","transform-object":"\u2194\uFE0F","insert-image":"\u{1F5BC}\uFE0F","rotate-page":"\u21BB","delete-page":"\u{1F5D1}\uFE0F","create-form-field":"\u{1F532}","set-form-values":"\u270D\uFE0F","delete-form-field":"\u{1F5D1}\uFE0F","flatten-form":"\u{1F4CB}"},V={"replace-text":"Edited text","insert-text":"Added text","redact-area":"Redacted area","delete-object":"Deleted object","transform-object":"Moved object","insert-image":"Inserted image","rotate-page":"Rotated page","delete-page":"Deleted page","create-form-field":"Added form field","set-form-values":"Filled form","delete-form-field":"Deleted form field","flatten-form":"Flattened form"},D="pageIndex"in u?u.pageIndex:void 0;_o((R=V[u.type])!=null?R:u.type,(B=$[u.type])!=null?B:"\u2699\uFE0F",D,g!=null?g:Gl(u),x)}catch(M){v(M instanceof Error?M.message:"Operation failed")}finally{w(!1)}},Kl=async(u,g,x,P)=>{var R,B;if(!Ne||u.length===0)return;let E=Uo();w(!0),v("Applying change...");try{let M=(R=o==null?void 0:o.name)!=null?R:"document.pdf",L=cs(Ne,M),j=await Xn.runPipeline(L,{tasks:[{processorName:"pdf-editor-core",params:{operations:u}}]}),X=j[j.length-1];if(!(X!=null&&X.success)){v((B=X==null?void 0:X.error)!=null?B:"Operation failed");return}let $=Array.from(new Set(u.map(D=>"pageIndex"in D?D.pageIndex:-1).filter(D=>D>=0)));rn.current=$.length?$:null,a(X.document.blob),Nt(null),kn(null),v("Saved");let V=$.length?$[0]:void 0;_o(g,x,V,P,E)}catch(M){v(M instanceof Error?M.message:"Operation failed")}finally{w(!1)}},Ns=(u,g,x,P)=>{var j,X;P.stopPropagation(),P.preventDefault();let E=_[u.pageIndex],R=(j=E==null?void 0:E.width)!=null?j:612,B=(X=E==null?void 0:E.height)!=null?X:792;No.current={id:u.id,pageIndex:u.pageIndex,mode:g,handle:x,startClientX:P.clientX,startClientY:P.clientY,startRect:{x:u.x,y:u.y,width:u.width,height:u.height}};let M=$=>{var ue;let V=No.current;if(!V)return;let D=($.clientX-V.startClientX)/I,z=-($.clientY-V.startClientY)/I,U=V.startRect,W=U.x,J=U.y,te=U.width,ee=U.height;if(V.mode==="move")W=U.x+D,J=U.y+z;else{let xe=(ue=V.handle)!=null?ue:"se",Oe=U.x,Ye=U.x+U.width,Ie=U.y,ge=U.y+U.height;xe.includes("e")&&(Ye=U.x+U.width+D),xe.includes("w")&&(Oe=U.x+D),xe.includes("n")&&(ge=U.y+U.height+z),xe.includes("s")&&(Ie=U.y+z),W=Math.min(Oe,Ye),te=Math.abs(Ye-Oe),J=Math.min(Ie,ge),ee=Math.abs(ge-Ie)}let Z=4;te=Math.max(Z,te),ee=Math.max(Z,ee),W=Math.max(0,Math.min(R-te,W)),J=Math.max(0,Math.min(B-ee,J)),vn(xe=>xe.map(Oe=>Oe.id===V.id?{...Oe,x:W,y:J,width:te,height:ee}:Oe))},L=()=>{window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",L),No.current=null};window.addEventListener("mousemove",M),window.addEventListener("mouseup",L)},Vl=u=>vn(g=>g.filter(x=>x.id!==u)),ql=async()=>{if(kt.length===0)return;let u=kt.map(x=>{var X;let P=x.x,E=x.x+x.width,R=x.y,B=x.y+x.height,M=(X=ze.current[x.pageIndex])!=null?X:[],L=$=>$.pdfX<E&&$.pdfX+$.width>P&&$.pdfY<B&&$.pdfY+$.height>R,j=M.filter($=>!$.fromXObject&&L($)).flatMap($=>{var V;return(V=$.streamOperatorIndices)!=null?V:[]});return{type:"redact-area",pageIndex:x.pageIndex,x:P,y:R,width:x.width,height:x.height,color:{r:0,g:0,b:0},padding:1.5,removeOperators:j.length?{streamOperatorIndices:j}:void 0}}),g=u.length;vn([]),await Kl(u,"Redacted area","\u2B1B",`${g} area${g>1?"s":""} redacted`)},Yo=(u,g,x,P,E)=>new Promise(R=>{let B=d[u],M=_[u];if(!B||!M)return R({r:1,g:1,b:1});let L=new Image;L.onload=()=>{try{let j=document.createElement("canvas");j.width=L.width,j.height=L.height;let X=j.getContext("2d");if(!X)return R({r:1,g:1,b:1});X.drawImage(L,0,0);let $=L.width/M.width,V=L.height/M.height,D=E*.5,z=x-D,U=E+D*2,W=Math.max(0,Math.floor(g*$)),J=Math.max(0,Math.floor((M.height-z-U)*V)),te=Math.max(1,Math.min(Math.ceil(P*$),L.width-W)),ee=Math.max(1,Math.min(Math.ceil(U*V),L.height-J)),Z=X.getImageData(W,J,te,ee).data,ue=0,xe=0,Oe=0,Ye=0;for(let Ie=0;Ie<Z.length;Ie+=4)(Z[Ie]+Z[Ie+1]+Z[Ie+2])/3>160&&(ue+=Z[Ie],xe+=Z[Ie+1],Oe+=Z[Ie+2],Ye++);if(Ye===0)return R({r:1,g:1,b:1});R({r:ue/Ye/255,g:xe/Ye/255,b:Oe/Ye/255})}catch{R({r:1,g:1,b:1})}},L.onerror=()=>R({r:1,g:1,b:1}),L.src=B.canvasDataUrl}),Jl=u=>{let[g,x]=u.split(","),P=atob(x!=null?x:""),E=new Uint8Array(P.length);for(let R=0;R<P.length;R++)E[R]=P.charCodeAt(R);return{bytes:E,format:g.includes("image/png")?"png":"jpeg"}},Es=async()=>{var g,x,P,E;if(!Ne)return;let u=((g=o==null?void 0:o.name)!=null?g:"document").replace(/\.pdf$/i,"");if(et.length===0&&pt.length===0){let R=await Rs(Ne),B=URL.createObjectURL(R),M=document.createElement("a");M.href=B,M.download=`${u}-edited.pdf`,M.click(),URL.revokeObjectURL(B),Ht("Downloaded PDF","\u2B07\uFE0F");return}w(!0),v("Writing annotations\u2026");try{let R=[];for(let z of et)R.push({type:"add-annotation",annotation:z});for(let z of pt){let U=_[z.pageIndex];if(U){if(z.kind==="comment"){let W={id:z.id,pageIndex:z.pageIndex,kind:"note",rect:{x:z.x/I,y:U.height-(z.y+22)/I,width:22/I,height:22/I},text:(x=z.text)!=null?x:"",style:{color:{r:.96,g:.62,b:.04},opacity:1},createdAt:Date.now()};R.push({type:"add-annotation",annotation:W})}else if(z.kind==="sign"){let{bytes:W,format:J}=Jl(z.dataUrl);R.push({type:"insert-image",pageIndex:z.pageIndex,bytes:W,format:J,x:z.x/I,y:U.height-(z.y+z.height)/I,width:z.width/I,height:z.height/I})}}}let B=cs(Ne,(P=o==null?void 0:o.name)!=null?P:"document.pdf"),M=await Xn.runPipeline(B,{tasks:[{processorName:"pdf-editor-core",params:{operations:R}}]}),L=M[M.length-1];if(!(L!=null&&L.success)){v((E=L==null?void 0:L.error)!=null?E:"Could not write annotations.");return}let j=L.document.blob,X=R.length;a(j),Yt([]),Bn([]),It(null),rn.current=null;let $=await Rs(j),V=URL.createObjectURL($),D=document.createElement("a");D.href=V,D.download=`${u}-annotated.pdf`,D.click(),URL.revokeObjectURL(V),Ht(`Downloaded with ${X} annotation${X!==1?"s":""}`,"\u2B07\uFE0F")}catch(R){v("Download failed: "+(R instanceof Error?R.message:String(R)))}finally{w(!1),v("")}};wl({enabled:!!Ne,onUndo:Wl,onSave:()=>{p||Es()}});let Zl=async(u,g)=>{if(!Ne||b!=="add-text"&&b!=="stamp")return;let x=_[g];if(!x)return;let P=He.current[g];if(!P)return;let E=P.getBoundingClientRect(),R=ut(u.clientX,u.clientY,E,I,x.height);if(b==="add-text"){ed(g,R.x,R.y);return}let B=S.trim();if(!B){v("Type or pick a stamp first.");return}await at({type:"insert-text",pageIndex:g,text:B,x:R.x,y:R.y,size:T,color:O},`"${B}" stamp`)},Ts=(u,g,x,P,E)=>{var V;let R=Zr(u,(V=ze.current[x])!=null?V:[],P.width),B=Math.max(1,g*.1),M=Math.max(0,u.x-B),L=Math.max(0,u.y-B),j={x:M,y:L,width:Math.min(P.width,u.x+u.width+B)-M,height:Math.min(P.height,u.y+u.height+B)-L},X=Qr(j,R),$=Ge(X.x,X.y+X.height,I,P.height);return{eraseClamp:R,maskRect:{x:$.x-E.x,y:$.y-E.y,w:X.width*I,h:X.height*I}}},Os=(u,g)=>{Yo(u,g.x,g.y,g.width,Math.max(8,g.height)).then(x=>{ae(P=>P&&P.pageIndex===u&&P.pdfX===g.x&&P.pdfY===g.y?{...P,bgColor:x}:P)})},Ql=()=>{let u=Array.from(Cr.current);return u.length?Math.min(...u):0},Is=async u=>{var P;let g=d[u],x=_[u];if(!g||!x){v("Page not ready yet.");return}lt(!0),v(`Recognizing text on page ${u+1}\u2026`);try{let E=await(await fetch(g.canvasDataUrl)).blob(),R=new FormData;R.append("file",new File([E],`page-${u+1}.png`,{type:"image/png"}));let B=await fetch("/api/ocr",{method:"POST",body:R});if(!B.ok){B.status===401&&window.dispatchEvent(new Event("namaha:needs-auth"));let $=await B.json().catch(()=>({}));throw new Error($.error||`OCR failed (${B.status})`)}let{words:M}=await B.json(),L=g.canvasWidth/Math.max(1,x.width),j=Uc(M!=null?M:[],u,x.height,L);if(Je.current.add(u),j.length===0){v("No text recognized on this page."),ot($=>$+1);return}Qe.current[u]=j;let X=[...(P=ze.current[u])!=null?P:[],...j];ze.current={...ze.current,[u]:X},it.current={...it.current,[u]:mo(X)},ot($=>$+1),v(`Recognized ${j.length} line${j.length===1?"":"s"}, text is now selectable & editable.`)}catch(E){v(E instanceof Error?E.message:"OCR failed.")}finally{lt(!1)}},Wo=u=>{var x;let g=((x=u.fontName)!=null?x:"").toLowerCase();return{bold:/bold|black|heavy|semibold/.test(g),italic:/italic|oblique/.test(g),color:u.color}},Ho=()=>{G&&me.current&&me.current.commit()},js=(u,g)=>{let x=_[g];if(!x)return;Ho();let P=Ge(u.pdfX,u.pdfY+u.height,I,x.height),E={x:u.pdfX,y:u.pdfY,width:u.width,height:u.height},{eraseClamp:R,maskRect:B}=Ts(E,u.fontSize,g,x,P),M=(x.height-u.pdfBaselineY)*I;ae({pageIndex:g,value:u.text,spans:[{text:u.text,style:Wo(u)}],pdfX:u.pdfX,pdfY:u.pdfY,pdfBaselineY:u.pdfBaselineY,width:u.width,height:u.height,fontSize:u.fontSize,fontName:u.fontName,fontFamily:u.fontFamily,color:u.color,containerX:P.x,containerY:P.y,screenWidth:Math.max(60,u.width*I),screenHeight:Math.max(16,u.height*I),baselineOffsetPx:M-P.y,maxWidth:Math.max(60,x.width*I-P.x-2),eraseClamp:R,maskRect:B,streamOperatorIndices:u.streamOperatorIndices,fromXObject:u.fromXObject,originalText:u.text,ocr:u.ocr}),Os(g,E)},ed=(u,g,x)=>{let P=_[u];if(!P)return;Ho();let E=T,R=Ge(g,x+E,I,P.height);ae({pageIndex:u,value:"",spans:[],isNew:!0,pdfX:g,pdfY:x,pdfBaselineY:x,width:120,height:E,fontSize:E,color:{r:0,g:0,b:0},containerX:R.x,containerY:R.y,screenWidth:Math.max(60,120*I),screenHeight:Math.max(16,E*I),baselineOffsetPx:E*I,maxWidth:Math.max(60,P.width*I-R.x-2)})},td=(u,g)=>{var L;if(b!=="edit-text")return;let x=_[g],P=He.current[g];if(!x||!P)return;let E=P.getBoundingClientRect(),R=ut(u.clientX,u.clientY,E,I,x.height),B=(L=it.current[g])!=null?L:ze.current[g],M=Tc(R,B,6);M&&js(M,g)},$s=async u=>{var B,M,L,j;if(!on.trim())return;let g=u.text.replace(new RegExp(on.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),gs);if(g===u.text)return;let x=await Yo(u.pageIndex,u.pdfX,u.pdfY,u.width,u.height),P=Zr({x:u.pdfX,y:u.pdfY,width:u.width,height:u.height},(B=ze.current[u.pageIndex])!=null?B:[],(L=(M=_[u.pageIndex])==null?void 0:M.width)!=null?L:612);await at({type:"replace-text",pageIndex:u.pageIndex,x:u.pdfX,y:u.pdfY,width:u.width,height:u.height,baselineY:u.pdfBaselineY,newText:g,erasePadding:Math.max(1,u.fontSize*.1),eraseClamp:P,removeOperators:!u.fromXObject&&((j=u.streamOperatorIndices)!=null&&j.length)?{streamOperatorIndices:u.streamOperatorIndices}:void 0,size:u.fontSize,backgroundColor:x,font:u.fontName?{pdfName:u.fontName,sizePt:u.fontSize}:void 0,color:u.color});let E=on.toLowerCase(),R=[];for(let X of Object.values(ze.current))for(let $ of X)$.text.toLowerCase().includes(E)&&R.push($);Or(R)},nd=async()=>{let u=[...st];for(let g of u)await $s(g)},Bs=async u=>{var P,E,R,B,M,L,j;let g=(P=u.bgColor)!=null?P:await Yo(u.pageIndex,u.x,u.y,u.width,Math.max(8,u.height)),x=(M=u.eraseClamp)!=null?M:Zr({x:u.x,y:u.y,width:u.width,height:u.height},(E=ze.current[u.pageIndex])!=null?E:[],(B=(R=_[u.pageIndex])==null?void 0:R.width)!=null?B:612);await at({type:"replace-text",pageIndex:u.pageIndex,x:u.x,y:u.y,width:u.width,height:u.height,baselineY:u.baselineY,newText:u.newText,erasePadding:Math.max(1,u.fontSize*.1),eraseClamp:x,removeOperators:!u.fromXObject&&((L=u.streamOperatorIndices)!=null&&L.length)?{streamOperatorIndices:u.streamOperatorIndices}:void 0,size:u.fontSize,backgroundColor:g,font:u.fontName?{pdfName:u.fontName,sizePt:u.fontSize,color:u.color}:void 0,color:u.color,spans:(j=u.spans)!=null&&j.length?u.spans:void 0},u.detail)},rd=u=>{if(!u)return!0;let g=u.replace(/^[A-Z]{6}\+/,"").toLowerCase();return/(helvetica|arial|times|courier|symbol|zapf|calibri|cambria|verdana|georgia|tahoma|segoe|roboto|liberation|dejavu|noto|sans|serif|mono)/.test(g)},Ls=async u=>{if(u.ocr){let g=Qe.current[u.pageIndex];g&&(Qe.current[u.pageIndex]=g.filter(x=>!(Math.abs(x.pdfX-u.pdfX)<.6&&Math.abs(x.pdfY-u.pdfY)<.6)))}await Bs({pageIndex:u.pageIndex,x:u.pdfX,y:u.pdfY,baselineY:u.pdfBaselineY,width:u.width,height:u.height,newText:u.value,spans:u.spans,fontSize:u.fontSize,fontName:u.fontName,color:u.color,streamOperatorIndices:u.streamOperatorIndices,fromXObject:u.fromXObject,bgColor:u.bgColor,eraseClamp:u.eraseClamp,detail:u.originalText!==void 0&&u.originalText!==u.value?`"${u.originalText}" \u2192 "${u.value}"`:`"${u.value}"`})},od=async(u,g)=>{var X;let x=G;if(ae(null),!x)return;let P=Cn(u),E=x.isNew?{}:Wo({fontName:x.fontName,color:x.color}),R=va(P,E);if(x.isNew){if(g.trim().length===0)return;await at({type:"insert-text",pageIndex:x.pageIndex,text:g,x:x.pdfX,y:x.pdfBaselineY,size:x.fontSize,spans:R?P:void 0},`"${g}"`);return}let B=$=>Cn($).map(V=>`${V.text}\0${ln(V.style)}`).join("");if(B(P)===B((X=x.spans)!=null?X:[]))return;let M={...x,spans:R?P:void 0,value:g},L=x.fontName;if(!x.ocr&&!!L&&!rd(L)&&!ke.current.has(L)){_t(M);return}await Ls(M)},id=(u,g,x,P)=>{var B;let E=x/I,R=-P/I;Bs({pageIndex:g,x:u.pdfX+E,y:u.pdfY+R,baselineY:((B=u.pdfBaselineY)!=null?B:u.pdfY)+R,width:u.width,height:u.height,newText:u.text,fontSize:u.fontSize,fontName:u.fontName,color:u.color,streamOperatorIndices:u.streamOperatorIndices,fromXObject:u.fromXObject,detail:`moved "${u.text}"`})},sd=(u,g,x)=>{var X;let P=x.clientX,E=x.clientY,R=!u.fromXObject&&!!((X=u.streamOperatorIndices)!=null&&X.length);tr.current={pageIndex:g,run:u,dxPx:0,dyPx:0},hs({pageIndex:g,run:u,dxPx:0,dyPx:0});let B=$=>{if(!tr.current)return;let V=$.clientX-P,D=$.clientY-E;tr.current={pageIndex:g,run:u,dxPx:V,dyPx:D},Sr.current&&(Sr.current.style.transform=`translate(${V}px, ${D}px)`)},M=$=>{window.removeEventListener("mousemove",B),window.removeEventListener("mouseup",L),window.removeEventListener("keydown",j);let V=tr.current;if(tr.current=null,Sr.current=null,hs(null),Dr.current=!0,!V)return;let D=Math.abs(V.dxPx)>=3||Math.abs(V.dyPx)>=3;$&&(D?R&&id(u,g,V.dxPx,V.dyPx):js(u,g))},L=()=>M(!0),j=$=>{$.key==="Escape"&&($.stopPropagation(),M(!1))};window.addEventListener("mousemove",B),window.addEventListener("mouseup",L),window.addEventListener("keydown",j)},Ur=(u,g)=>{Mr(x=>({...x,[u.id]:g})),u.value=g,at({type:"set-form-values",pageIndex:u.pageIndex,values:[{name:u.name,fieldType:u.type,value:g}]})},ad=(u,g,x)=>{var j,X;let P={x:x.x,y:x.y,width:Math.max(12,x.width),height:Math.max(g==="checkbox"||g==="radio"?12:16,x.height)},E=`${g}_${Date.now().toString(36)}`,R=g==="dropdown"?["Option 1","Option 2"]:g==="radio"?["Choice 1","Choice 2"]:void 0,B=g==="checkbox"?"Yes":void 0,M={id:`${E}__new`,name:E,type:g,pageIndex:u,rect:P,value:g==="checkbox"?"Off":"",options:R,onState:B,fontSize:0,isNew:!0};((X=(j=Et.current)[u])!=null?X:j[u]=[]).push(M),jn.current[M.id]=E,Fr($=>$+1),Oo(!0),Go(M),Eo(null);let L=g==="radio"?(R!=null?R:[]).map(($,V)=>({x:P.x,y:P.y-V*(P.height+4),width:P.width,height:P.height})):void 0;at({type:"create-form-field",pageIndex:u,fieldType:g,name:E,rect:P,value:M.value,options:R,optionRects:L,fontSize:0})},Us=u=>{var P,E;let g=(P=jn.current[u.id])!=null?P:u.name,x=(E=Et.current[u.pageIndex])!=null?E:[];Et.current[u.pageIndex]=x.filter(R=>R.id!==u.id),delete jn.current[u.id],Go(null),Fr(R=>R+1),at({type:"delete-form-field",name:g})},cd=async()=>{await at({type:"flatten-form"}),v("Form flattened, values are now baked into the page.")},Go=u=>{var g,x;To((g=u==null?void 0:u.id)!=null?g:null),nr.current=(x=u==null?void 0:u.name)!=null?x:null},ir=kl(()=>{if(!Rr)return null;for(let u of Object.values(Et.current)){let g=u.find(x=>x.id===Rr);if(g)return g}return null},[Rr,fs]),ld=(u,g)=>{var M,L;let x=(M=Et.current[u.pageIndex])!=null?M:[],P={...u,...g,rect:{...u.rect,...(L=g.rect)!=null?L:{}}};Et.current[u.pageIndex]=x.map(j=>j.id===u.id?P:j),g.value!==void 0&&Mr(j=>{var X;return{...j,[u.id]:String((X=g.value)!=null?X:"")}}),g.name!==void 0&&(nr.current=P.name),Fr(j=>j+1),Io.current&&clearTimeout(Io.current);let E=u.id,R=P.pageIndex,B=u.name;Io.current=setTimeout(()=>{var V,D,z;let j=((V=Et.current[R])!=null?V:[]).find(U=>U.id===E);if(!j)return;let X=(D=jn.current[E])!=null?D:B,$=j.type==="radio"?((z=j.options)!=null?z:[]).map((U,W)=>({x:j.rect.x,y:j.rect.y-W*(j.rect.height+4),width:j.rect.width,height:j.rect.height})):void 0;jn.current[E]=j.name,at({type:"update-form-field",oldName:X,pageIndex:j.pageIndex,fieldType:j.type,name:j.name,rect:j.rect,value:j.value,options:j.options,optionRects:$,fontSize:j.fontSize,required:j.required,readOnly:j.readOnly,multiline:j.multiline,align:j.align,maxLength:j.maxLength,editable:j.editable})},400)},dd=.25,ud=5,Ko=u=>Math.max(dd,Math.min(ud,u)),_s=u=>ie(g=>Ko(g*u)),hd=()=>{var x;let u=ce.current,g=(x=_[le])!=null?x:_[0];!u||!g||ie(Ko((u.clientWidth-96)/(g.width*H)))},fd=()=>{var x;let u=ce.current,g=(x=_[le])!=null?x:_[0];!u||!g||ie(Ko((u.clientHeight-96)/(g.height*H)))},_r=u=>{var x;let g=Math.max(0,Math.min(c.length-1,u));(x=He.current[g])==null||x.scrollIntoView({behavior:"smooth",block:"start"})},md=(u,g)=>{if(!Pn)return;let x=He.current[u],P=_[u];if(!x||!P)return;g.preventDefault(),g.stopPropagation();let E=x.getBoundingClientRect(),R=g.clientX-E.left,B=g.clientY-E.top,M=Pn,L=X=>{let $=Math.min(R,X.clientX-E.left),V=Math.min(B,X.clientY-E.top),D=Math.abs(X.clientX-E.left-R),z=Math.abs(X.clientY-E.top-B);Ar({pageIndex:u,x:$,y:V,w:D,h:z})},j=X=>{window.removeEventListener("mousemove",L),window.removeEventListener("mouseup",j),Ar(null);let $=X.clientX-E.left,V=X.clientY-E.top,D=Math.min(R,$),z=Math.min(B,V),U=Math.max(Math.abs($-R),80),W=Math.max(Math.abs(V-B),M==="checkbox"||M==="radio"?16:22),J=D/I,te=P.height-(z+W)/I;ad(u,M,{x:J,y:te,width:U/I,height:W/I})};Ar({pageIndex:u,x:R,y:B,w:0,h:0}),window.addEventListener("mousemove",L),window.addEventListener("mouseup",j)},pd=(u,g)=>{let x=ze.current[u];if(!x)return[];let P=Math.min(g.startPdfX,g.endPdfX),E=Math.max(g.startPdfX,g.endPdfX),R=Math.min(g.startPdfY,g.endPdfY),B=Math.max(g.startPdfY,g.endPdfY);return x.filter(M=>M.pdfX<E&&M.pdfX+M.width>P&&M.pdfY<B&&M.pdfY+M.height>R)},Xs=(u,g)=>{for(let x=et.length-1;x>=0;x--){let P=et[x];if(P.pageIndex===u&&Ka(g,P))return P}return null},zs=(u,g,x,P)=>{let E=P.clientX,R=P.clientY,B=!1,M=j=>{let X=(j.clientX-E)/I,$=-(j.clientY-R)/I;(Math.abs(j.clientX-E)>2||Math.abs(j.clientY-R)>2)&&(B=!0),Yt(V=>V.map(D=>{if(D.id!==u.id)return D;if(g==="move")return Va(u,X,$);let z=ct(u),U=z.x,W=z.y,J=z.width,te=z.height;return x==="ne"?(J=z.width+X,te=z.height+$):x==="nw"?(U=z.x+X,J=z.width-X,te=z.height+$):x==="se"?(W=z.y+$,J=z.width+X,te=z.height-$):x==="sw"&&(U=z.x+X,W=z.y+$,J=z.width-X,te=z.height-$),J<5||te<5?D:qa(u,{x:U,y:W,width:J,height:te})}))},L=()=>{window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",L),B&&(Bo.current=!0,Ht(g==="move"?"Moved annotation":"Resized annotation","\u2725"))};window.addEventListener("mousemove",M),window.addEventListener("mouseup",L)},gd=(u,g,x)=>{let P=et.find(E=>E.id===u);P&&zs(P,"resize",g,x)},xd=(u,g)=>{if(u.button!==0||b==="view"||b==="form")return;if(b==="annotate"||b==="draw"){let B=_[g],M=He.current[g];if(!B||!M)return;u.preventDefault();let L=M.getBoundingClientRect(),j=ut(u.clientX,u.clientY,L,I,B.height);if(b==="annotate"){Sn==="brush"?(sn.current={pageIndex:g,pt:j},Pt({kind:"ink",pageIndex:g,points:[j]})):Sn==="highlight"&&xs==="box"?(sn.current={pageIndex:g,pt:j},Pt({kind:"box",pageIndex:g,rect:{x:j.x,y:j.y,width:0,height:0}})):(sn.current={pageIndex:g,pt:j},Pt({kind:"quads",pageIndex:g,quads:[]})),jr(!0);return}if(Ot==="polygon")return;sn.current={pageIndex:g,pt:j},Pt(Ot==="line"||Ot==="arrow"?{kind:"line",pageIndex:g,a:j,b:j,arrow:Ot==="arrow"}:{kind:"box",pageIndex:g,rect:{x:j.x,y:j.y,width:0,height:0}}),jr(!0);return}if(b==="select"){let B=_[g],M=He.current[g];if(B&&M){let L=M.getBoundingClientRect(),j=ut(u.clientX,u.clientY,L,I,B.height),X=Xs(g,j);if(X){u.preventDefault(),It(X.id),Nt(null),zs(X,"move",void 0,u);return}}if(je&&!je.fromXObject&&je.pageIndex===g){let L=_[g],j=He.current[g];if(!L||!j)return;let X=j.getBoundingClientRect(),$=ut(u.clientX,u.clientY,X,I,L.height);fo($,vt.current[g])===je&&(u.preventDefault(),Ys(je,"move",null,u))}return}if(b!=="edit-text"&&b!=="redact")return;u.preventDefault();let x=_[g],P=He.current[g];if(!x||!P)return;let E=P.getBoundingClientRect(),R=ut(u.clientX,u.clientY,E,I,x.height);er.current=!1,Dr.current=!1,zt.current={pageIndex:g,pdfX:R.x,pdfY:R.y},ds(!0),At([]),bt(null),ae(null)},bd=(u,g)=>{var B;if(b==="select"){if(Tn.current)return;let M=_[g],L=He.current[g];if(!M||!L)return;let j=L.getBoundingClientRect(),X=ut(u.clientX,u.clientY,j,I,M.height),$=fo(X,vt.current[g]);kn(V=>V===$?V:$);return}if(b==="draw"&&Ot==="polygon"&&((B=Wt.current)==null?void 0:B.pageIndex)===g){let M=_[g],L=He.current[g];if(!M||!L)return;let j=L.getBoundingClientRect(),X=ut(u.clientX,u.clientY,j,I,M.height);Pt({kind:"polygon",pageIndex:g,points:Wt.current.points,cursor:X});return}if(ys&&sn.current&&sn.current.pageIndex===g){let M=_[g],L=He.current[g];if(!M||!L)return;let j=L.getBoundingClientRect(),X=ut(u.clientX,u.clientY,j,I,M.height),$=sn.current.pt;Pt(V=>{var D,z;if(!V)return V;if(V.kind==="quads"){let U=(z=(D=it.current[g])!=null?D:ze.current[g])!=null?z:[];return{kind:"quads",pageIndex:g,quads:Dc(U,$,X).quads}}return V.kind==="box"?{kind:"box",pageIndex:g,rect:{x:Math.min($.x,X.x),y:Math.min($.y,X.y),width:Math.abs(X.x-$.x),height:Math.abs(X.y-$.y)}}:V.kind==="line"?{...V,b:X}:V.kind==="ink"?{...V,points:[...V.points,X]}:V});return}if(!Il||!zt.current||zt.current.pageIndex!==g)return;let x=_[g],P=He.current[g];if(!x||!P)return;let E=P.getBoundingClientRect(),R=ut(u.clientX,u.clientY,E,I,x.height);if(!er.current){let M=Math.abs(R.x-zt.current.pdfX)*I,L=Math.abs(R.y-zt.current.pdfY)*I;if(M<6&&L<6)return;er.current=!0,bt({pageIndex:g,startPdfX:zt.current.pdfX,startPdfY:zt.current.pdfY,endPdfX:R.x,endPdfY:R.y});return}bt({pageIndex:g,startPdfX:zt.current.pdfX,startPdfY:zt.current.pdfY,endPdfX:R.x,endPdfY:R.y})},yd=(u,g)=>{if(ys){jr(!1),sn.current=null;let P=bs;if(Pt(null),!P||P.pageIndex!==g)return;let E={color:Tt.color,opacity:Tt.opacity,strokeWidth:Tt.strokeWidth,fill:Tt.fill},R={id:crypto.randomUUID(),pageIndex:g,style:E,createdAt:Date.now()},B=(M,L,j)=>{Yt(X=>[...X,M]),Ht(L,j,g)};if(P.kind==="quads"){if(!P.quads.length)return;let M=Sn==="underline"?"underline":Sn==="strikeout"?"strikeout":"highlight",L=M==="underline"?"Underlined text":M==="strikeout"?"Struck through text":"Highlighted text";B({...R,kind:M,quads:P.quads,text:""},L,"\u{1F58A}\uFE0F")}else if(P.kind==="box"){if(P.rect.width<3||P.rect.height<3)return;if(b==="annotate"){let M=P.rect;B({...R,kind:"highlight",quads:[{x:M.x,y:M.y,width:M.width,height:M.height,baselineY:M.y+M.height*.2}],text:""},"Added highlight","\u{1F7E1}")}else{let M=[{x:P.rect.x,y:P.rect.y},{x:P.rect.x+P.rect.width,y:P.rect.y+P.rect.height}];B({...R,kind:Ot==="ellipse"?"ellipse":"rect",points:M},Ot==="ellipse"?"Added ellipse":"Added rectangle","\u25FB\uFE0F")}}else if(P.kind==="line"){if(Math.hypot(P.b.x-P.a.x,P.b.y-P.a.y)<3)return;B({...R,kind:P.arrow?"arrow":"line",points:[P.a,P.b]},P.arrow?"Added arrow":"Added line","\u2197\uFE0F")}else if(P.kind==="ink"){if(P.points.length<2)return;B({...R,kind:"ink",strokes:[P.points]},"Freehand drawing","\u270F\uFE0F")}return}if(ds(!1),!er.current){At([]),bt(null);return}if(!Ae||Ae.pageIndex!==g)return;if(b==="redact"){let P=Math.min(Ae.startPdfX,Ae.endPdfX),E=Math.max(Ae.startPdfX,Ae.endPdfX),R=Math.min(Ae.startPdfY,Ae.endPdfY),B=Math.max(Ae.startPdfY,Ae.endPdfY),M=E-P,L=B-R;if(bt(null),At([]),M<3||L<3)return;vn(j=>[...j,{id:crypto.randomUUID(),pageIndex:g,x:P,y:R,width:M,height:L}]),v("Adjust the box, then press \u201CApply redactions\u201D. Add more boxes as needed.");return}let x=pd(g,Ae);At(x),x.length>0?v(`Selected ${x.length} text run(s). Click Edit or drag to re-select.`):(v("No text selected in that area."),bt(null))},wd=(u,g)=>{var x;if(b==="draw"&&Ot==="polygon"&&((x=Wt.current)==null?void 0:x.pageIndex)===g){let P=Wt.current.points;if(Wt.current=null,Pt(null),P.length>=3){let E={color:Tt.color,opacity:Tt.opacity,strokeWidth:Tt.strokeWidth,fill:Tt.fill};Yt(R=>[...R,{id:crypto.randomUUID(),pageIndex:g,style:E,createdAt:Date.now(),kind:"polygon",points:P}]),Ht("Added polygon","\u2B21",g)}}},vd=(u,g)=>{if(jo.current){jo.current=!1;return}if(Bo.current){Bo.current=!1;return}let x=_[g],P=He.current[g];if(!x||!P)return;let E=P.getBoundingClientRect(),R=ut(u.clientX,u.clientY,E,I,x.height),B=Xs(g,R);if(B){It(B.id),Nt(null);return}It(null);let M=fo(R,vt.current[g]);Nt(M),M!=null&&M.fromXObject?v("This object is part of a reusable form and is locked in this version."):M&&v(`Selected ${M.kind==="image"?"image":"graphic"}, press Delete to remove it.`)},Vo=vl(()=>{if(!je||je.fromXObject)return;let u=je;Nt(null),kn(null),at({type:"delete-object",pageIndex:u.pageIndex,spans:[{start:u.spanStart,end:u.spanEnd}]})},[je,Ne]),kd=async u=>{try{let g=new Uint8Array(await u.arrayBuffer()),x=g[0]===137&&g[1]===80&&g[2]===78&&g[3]===71,P=g[0]===255&&g[1]===216;if(!x&&!P){v("Only PNG and JPEG images can be inserted.");return}let E=await new Promise((R,B)=>{let M=URL.createObjectURL(u),L=new window.Image;L.onload=()=>{R({w:L.naturalWidth,h:L.naturalHeight}),URL.revokeObjectURL(M)},L.onerror=()=>{B(new Error("unreadable image")),URL.revokeObjectURL(M)},L.src=M});$o({bytes:g,format:x?"png":"jpeg",naturalWidth:Math.max(1,E.w),naturalHeight:Math.max(1,E.h)}),v("Click on a page to place the image (Esc to cancel).")}catch{v("Could not read that image file.")}},Pd=(u,g)=>{let x=$n,P=_[g],E=He.current[g];if(!x||!P||!E)return;let R=E.getBoundingClientRect(),B=ut(u.clientX,u.clientY,R,I,P.height),M=P.width*.5,L=x.naturalWidth*.75,j=Math.min(M,Math.max(16,L)),X=j*(x.naturalHeight/x.naturalWidth),$=Math.max(0,Math.min(P.width-j,B.x-j/2)),V=Math.max(0,Math.min(P.height-X,B.y-X/2));$o(null),at({type:"insert-image",pageIndex:g,x:$,y:V,width:j,height:X,bytes:x.bytes,format:x.format})};wt(()=>{if(!$n)return;let u=g=>{g.key==="Escape"&&($o(null),v("Image placement cancelled."))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[$n]);let Sd=u=>{let g=u.object,x=null;if(u.mode==="move"){if(Math.abs(u.dxPx)<2&&Math.abs(u.dyPx)<2)return;let P=u.dxPx/I,E=-u.dyPx/I;x=[1,0,0,1,P,E]}else if(u.handle){let P=u.scaleX,E=u.scaleY;if(Math.abs(P-1)<.01&&Math.abs(E-1)<.01)return;let R=g.pdfX,B=g.pdfX+g.width,M=g.pdfY,L=g.pdfY+g.height,j=u.handle.includes("w")?B:R,X=u.handle.includes("n")?M:L;x=[P,0,0,E,j-P*j,X-E*X]}x&&(jo.current=!0,Nt(null),kn(null),at({type:"transform-object",pageIndex:g.pageIndex,span:{start:g.spanStart,end:g.spanEnd},matrix:x,baseCtm:g.ctm}))},Ys=(u,g,x,P)=>{let E={object:u,mode:g,handle:x,startClientX:P.clientX,startClientY:P.clientY,dxPx:0,dyPx:0,scaleX:1,scaleY:1};Tn.current=E,us(E);let R=Math.max(1,u.width*I),B=Math.max(1,u.height*I),M=$=>{var J;let V=Tn.current;if(!V)return;let D=$.clientX-V.startClientX,z=$.clientY-V.startClientY,U,W;if(V.mode==="move")U={...V,dxPx:D,dyPx:z},W=`translate(${D}px, ${z}px)`;else{let te=(J=V.handle)!=null?J:"se",ee=1,Z=1;if(te.includes("e")&&(ee=(R+D)/R),te.includes("w")&&(ee=(R-D)/R),te.includes("s")&&(Z=(B+z)/B),te.includes("n")&&(Z=(B-z)/B),V.object.kind==="image"&&te.length===2){let ue=Math.max(Math.abs(ee),Math.abs(Z));ee=ue,Z=ue}U={...V,scaleX:Math.max(.05,ee),scaleY:Math.max(.05,Z)},W=`scale(${U.scaleX}, ${U.scaleY})`}Tn.current=U,Ro.current&&(Ro.current.style.transform=W)},L=$=>{window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",j),window.removeEventListener("keydown",X);let V=Tn.current;Tn.current=null,us(null),$&&V&&Sd(V)},j=()=>L(!0),X=$=>{$.key==="Escape"&&($.stopPropagation(),L(!1))};window.addEventListener("mousemove",M),window.addEventListener("mouseup",j),window.addEventListener("keydown",X)};wt(()=>{if(!je)return;let u=g=>{let x=g.target;x&&(x.tagName==="INPUT"||x.tagName==="TEXTAREA")||(g.key==="Delete"||g.key==="Backspace"?(g.preventDefault(),Vo()):g.key==="Escape"&&Nt(null))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[je,Vo]),wt(()=>{if(!or)return;let u=g=>{let x=g.target;x&&(x.tagName==="INPUT"||x.tagName==="TEXTAREA")||(g.key==="Delete"||g.key==="Backspace"?(g.preventDefault(),Yt(P=>P.filter(E=>E.id!==or)),It(null),Ht("Deleted annotation","\u{1F5D1}\uFE0F")):g.key==="Escape"&&It(null))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[or]),wt(()=>{Nt(null),kn(null),Eo(null),To(null),nr.current=null,Ar(null),vn([]),It(null),Pt(null),jr(!1),Wt.current=null},[b]),wt(()=>{if(b!=="redact"||kt.length===0)return;let u=g=>{g.key==="Escape"&&(vn([]),v("Redaction marks cleared."))};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[b,kt.length]);let Dd=()=>{if(wn.length===0||!Ae)return;Ho();let u=[...wn].sort((W,J)=>W.pageIndex!==J.pageIndex?W.pageIndex-J.pageIndex:Math.abs(J.pdfY-W.pdfY)>10?J.pdfY-W.pdfY:W.pdfX-J.pdfX),g=u[0].pageIndex,x=_[g],P=He.current[g];if(!x||!P)return;let E=u.map(W=>W.text).join(" "),R=Math.min(...u.map(W=>W.pdfX)),B=Math.min(...u.map(W=>W.pdfY)),M=Math.max(...u.map(W=>W.pdfX+W.width)),L=Math.max(...u.map(W=>W.pdfY+W.height)),j=u.reduce((W,J)=>W+J.fontSize,0)/u.length,X=u.reduce((W,J)=>W+J.pdfBaselineY,0)/u.length,$=u.find(W=>W.fontName||W.color),V=Ge(R,B+(L-B),I,x.height),D={x:R,y:B,width:M-R,height:L-B},{eraseClamp:z,maskRect:U}=Ts(D,j,g,x,V);ae({pageIndex:g,value:E,spans:[{text:E,style:Wo({fontName:$==null?void 0:$.fontName,color:$==null?void 0:$.color})}],pdfX:R,pdfY:B,pdfBaselineY:X,width:M-R,height:L-B,fontSize:j,fontName:$==null?void 0:$.fontName,fontFamily:$==null?void 0:$.fontFamily,color:$==null?void 0:$.color,containerX:V.x,containerY:V.y,screenWidth:Math.max(150,(M-R)*I+12),screenHeight:Math.max(30,(L-B)*I+8),maxWidth:Math.max(60,x.width*I-V.x-2),eraseClamp:z,maskRect:U,streamOperatorIndices:u.every(W=>{var J;return((J=W.streamOperatorIndices)!=null?J:[]).length>0})?u.flatMap(W=>{var J;return(J=W.streamOperatorIndices)!=null?J:[]}):void 0,fromXObject:u.some(W=>W.fromXObject)}),Os(g,D),At([]),bt(null)},Cd=async()=>{if(wn.length===0||!Ae)return;let u=Ae.pageIndex;if(!_[u])return;let x=wn.filter(M=>M.pageIndex===u),P=x.length>0?Math.min(...x.map(M=>M.pdfX)):Math.min(Ae.startPdfX,Ae.endPdfX),E=x.length>0?Math.max(...x.map(M=>M.pdfX+M.width)):Math.max(Ae.startPdfX,Ae.endPdfX),R=x.length>0?Math.min(...x.map(M=>M.pdfY)):Math.min(Ae.startPdfY,Ae.endPdfY),B=x.length>0?Math.max(...x.map(M=>M.pdfY+M.height)):Math.max(Ae.startPdfY,Ae.endPdfY);At([]),bt(null),await at({type:"redact-area",pageIndex:u,x:P,y:R,width:E-P,height:B-R,color:{r:0,g:0,b:0},padding:x.length>0?Math.max(1.75,x.reduce((M,L)=>M+L.fontSize,0)/x.length*.14):1.75})},qo=()=>{var u;(u=ls.current)==null||u.click()},Ws=async()=>{if(!nn.current||!Re.trim())return;yn(!0);let u=await n(nn.current,Re);if(u.success&&u.pdfBytes){let g=Al(u.pdfBytes);rn.current=null,i(nn.current),a(g),l([]),m({}),K({}),ze.current={},it.current={},vt.current={},At([]),bt(null),ae(null),v("Rendering PDF..."),Rt(""),Xt(!1),nn.current=null}else v("Incorrect password. Please try again."),yn(!1),Xt(!0)},Fd=Ne?`${(Ne.size/1024).toFixed(1)} KB`:"No file loaded",Jo=(()=>{var u,g,x;if(!Ne||Mt)return null;for(let P of Object.keys(d)){let E=Number(P);if(Je.current.has(E))continue;let R=((u=ze.current[E])!=null?u:[]).filter(M=>!M.ocr).length,B=(x=(g=vt.current[E])==null?void 0:g.length)!=null?x:0;if(R===0&&B>0)return E}return null})();return Y("div",{className:"paper-grain flex h-full min-h-0 flex-col overflow-hidden bg-paper-editor text-ink dark:bg-[#16130f] dark:text-white",children:[Y("header",{className:"flex h-14 shrink-0 items-center gap-3.5 border-b border-ink-line bg-paper-card px-4 dark:border-white/10 dark:bg-[#1a1712]",children:[Y("div",{className:"flex items-center gap-2.5 pr-4 border-r border-ink-line dark:border-white/10",children:[k("div",{className:"flex h-7 w-7 items-center justify-center rounded-lg bg-crimson-600 shadow-[0_2px_7px_-2px_rgba(162,7,48,0.5)]",children:k(Mo,{className:"h-4 w-4 text-white"})}),Y("span",{className:"font-display text-[18px] font-semibold tracking-[-0.01em] text-ink dark:text-white",children:["Namaha",k("span",{className:"text-crimson-600",children:"PDF"})]})]}),k("div",{className:"flex min-w-0 items-center gap-2",children:Ne?Y(tn,{children:[k("span",{className:"truncate text-[13.5px] font-semibold text-ink dark:text-zinc-200",children:Xo}),k("span",{className:"shrink-0 rounded bg-surface-container-high px-1.5 py-0.5 text-[10px] font-semibold text-ink-soft dark:bg-zinc-800 dark:text-zinc-400",children:Fd}),p&&k("span",{className:"shrink-0 text-xs text-crimson-600 animate-pulse",children:"saving\u2026"}),!p&&y&&Y("span",{className:"shrink-0 inline-flex items-center gap-1 text-xs text-emerald-700 dark:text-green-400",children:[k(Fo,{className:"h-3 w-3"}),y]})]}):k("span",{className:"text-sm text-ink-muted",children:"No document open"})}),k("div",{className:"flex-1"}),Y("div",{title:"Private. Stays on your device.",className:"hidden items-center rounded-full border border-emerald-200 bg-emerald-50 p-1.5 lg:flex dark:border-emerald-900/40 dark:bg-emerald-950/30",children:[k(Bm,{className:"h-3.5 w-3.5 text-emerald-700 dark:text-emerald-400"}),k("span",{className:"sr-only",children:"Private. Stays on your device."})]}),Y("div",{className:"flex items-center gap-1.5",children:[Ne&&k("button",{type:"button",title:"Activity log",onClick:()=>Cs(u=>!u),className:`flex h-8 w-8 items-center justify-center rounded-lg transition-colors ${Ds?"bg-crimson-100 text-crimson-600":"text-ink-soft hover:bg-paper hover:text-ink dark:text-zinc-400 dark:hover:bg-zinc-800"}`,children:k(Sl,{className:"h-4 w-4"})}),Ne&&k("button",{type:"button",title:"Recognize text (OCR), for scanned/outlined pages",disabled:Me,onClick:()=>{Is(Ql())},className:"flex h-8 w-8 items-center justify-center rounded-lg text-ink-soft transition-colors hover:bg-paper hover:text-ink disabled:opacity-50 dark:text-zinc-400 dark:hover:bg-zinc-800",children:k(Cl,{className:`h-4 w-4 ${Me?"animate-pulse":""}`})}),Y("button",{type:"button",onClick:qo,className:"flex h-8 items-center gap-1.5 rounded-lg border border-ink-line-strong bg-paper-raised px-3 text-xs font-semibold text-ink-soft transition-colors hover:bg-paper dark:border-white/10 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700",children:[k(as,{className:"h-3.5 w-3.5"}),"Open"]}),Y("button",{type:"button",className:"flex h-8 items-center gap-1.5 rounded-lg border border-ink-line-strong bg-paper-raised px-3 text-xs font-semibold text-ink-soft transition-colors hover:bg-paper dark:border-white/10 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700",children:[k(zm,{className:"h-3.5 w-3.5"}),"Share"]}),Y("button",{type:"button",onClick:Ne?()=>{Es()}:qo,disabled:p,className:"flex h-8 items-center gap-1.5 rounded-lg bg-crimson-600 px-4 text-xs font-bold text-white shadow-crimson transition-all hover:bg-crimson-700 active:scale-95 disabled:cursor-not-allowed disabled:opacity-60",children:[k(Em,{className:"h-3.5 w-3.5"}),Ne?et.length+pt.length>0?`Download (${et.length+pt.length} annot.)`:"Download":"Open PDF"]})]})]}),Jo!==null&&Y("div",{className:"flex items-center gap-3 border-b border-amber-200 bg-amber-50 px-4 py-2 text-xs text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300",children:[k(Cl,{className:"h-4 w-4 shrink-0"}),Y("span",{className:"flex-1",children:["Page ",Jo+1," looks scanned or has outlined text. Recognize it to make the text selectable and editable."]}),k("button",{type:"button",disabled:Me,onClick:()=>{Is(Jo)},className:"rounded-md bg-amber-600 px-2.5 py-1 font-semibold text-white transition hover:brightness-110 disabled:opacity-60",children:Me?"Recognizing\u2026":"Recognize text"}),k("button",{type:"button",onClick:()=>ft(!0),className:"rounded p-1 hover:bg-amber-100 dark:hover:bg-amber-900/40",title:"Dismiss",children:k(gn,{className:"h-3.5 w-3.5"})})]}),Ne&&!bn&&Y("div",{className:"flex items-center gap-3 border-b border-blue-200 bg-blue-50 px-4 py-2 text-xs text-blue-800 dark:border-blue-900/50 dark:bg-blue-950/30 dark:text-blue-300",children:[k("span",{className:"flex-1",children:"Heads-up: if some text looks overlapped or crowded here, it's only a preview/display quirk in the editor, you can still select and edit it normally, and your downloaded PDF will look correct."}),k("button",{type:"button",onClick:()=>ye(!0),className:"rounded p-1 hover:bg-blue-100 dark:hover:bg-blue-900/40",title:"Dismiss",children:k(gn,{className:"h-3.5 w-3.5"})})]}),Ke&&k("div",{className:"fixed inset-0 z-[120] flex items-center justify-center bg-black/50 p-4",onClick:()=>_t(null),children:Y("div",{className:"w-full max-w-sm rounded-2xl border border-zinc-200 bg-white p-6 shadow-2xl dark:border-white/10 dark:bg-zinc-900",onClick:u=>u.stopPropagation(),children:[k("h2",{className:"text-lg font-bold text-zinc-900 dark:text-white",children:"Switch font for this edit?"}),Y("p",{className:"mt-2 text-sm text-zinc-600 dark:text-zinc-400",children:["This text uses a custom font",Ke.fontName?Y(tn,{children:[" (",k("span",{className:"font-medium",children:Ke.fontName.replace(/^[A-Z]{6}\+/,"")}),")"]}):null," ","that can't be edited reliably, keeping it can render your edit as garbled characters (\u25A1 / \uFFFD). Save your change using the closest matching standard font instead?"]}),Y("div",{className:"mt-5 flex gap-2",children:[k("button",{type:"button",onClick:()=>{let u=Ke;u.fontName&&ke.current.add(u.fontName),_t(null),Ls(u)},className:"flex-1 rounded-full bg-primary px-4 py-2.5 text-sm font-semibold text-white transition hover:brightness-110",children:"Save with closest font"}),k("button",{type:"button",onClick:()=>_t(null),className:"rounded-full border border-zinc-300 px-4 py-2.5 text-sm font-medium text-zinc-600 transition hover:bg-black/[0.04] dark:border-white/15 dark:text-zinc-300 dark:hover:bg-white/[0.06]",children:"Cancel"})]})]})}),!Ne&&k("div",{className:"flex flex-1 items-center justify-center p-8",children:Y("div",{className:"w-full max-w-xl text-center",children:[k("h1",{className:"mb-2 font-display text-[34px] font-medium tracking-[-0.02em] text-ink dark:text-white",children:"Open a document to begin"}),k("p",{className:"mb-7 text-[15px] leading-relaxed text-ink-soft dark:text-zinc-400",children:"Everything happens on your device, your file is never uploaded."}),Y("button",{type:"button",onClick:qo,className:"group flex w-full flex-col items-center gap-4 rounded-2xl border-2 border-dashed border-ink-line-strong bg-paper-raised p-11 text-center shadow-paper-lg transition-all hover:border-crimson-400 hover:bg-crimson-50/40 dark:border-white/10 dark:bg-zinc-900 dark:hover:border-crimson-500",children:[Y("div",{className:"relative flex h-[76px] w-[76px] items-center justify-center",style:{animation:"floaty 4s ease-in-out infinite"},children:[k("div",{className:"absolute inset-0 -rotate-[7deg] rounded-xl bg-gradient-to-br from-crimson-200 to-crimson-400 shadow-[0_8px_18px_-6px_rgba(162,7,48,0.4)]"}),k("div",{className:"absolute inset-0 flex items-center justify-center rounded-xl border border-[#E7DECB] bg-paper-raised text-crimson-600",children:k(Om,{className:"h-8 w-8"})})]}),Y("div",{children:[k("p",{className:"font-display text-[21px] font-semibold text-ink dark:text-white",children:"Drag & drop your PDF here"}),k("p",{className:"mt-1 text-sm text-ink-muted",children:"or click to browse"})]}),Y("span",{className:"flex items-center gap-2 rounded-xl bg-crimson-600 px-6 py-3 text-sm font-bold text-white shadow-crimson transition-all group-hover:bg-crimson-700",children:[k(as,{className:"h-4 w-4"}),"Choose a file"]}),k("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-x-5 gap-y-2 text-xs text-ink-muted",children:["Up to 2 GB","Never uploaded","Works offline"].map(u=>Y("span",{className:"inline-flex items-center gap-1.5",children:[k(Fo,{className:"h-3 w-3 text-emerald-700"}),u]},u))})]})]})}),Y("div",{className:"sr-only",children:[k("input",{ref:ls,type:"file",accept:"application/pdf",onChange:async u=>{var P,E;let g=(E=(P=u.target.files)==null?void 0:P[0])!=null?E:null;if(!g)return;nn.current=g,yn(!0),Xt(!1),Rt(""),v("Rendering PDF...");let x=await n(g);if(x.success&&x.pdfBytes){let R=Al(x.pdfBytes);rn.current=null,i(g),a(R),l([]),m({}),K({}),ze.current={},it.current={},vt.current={},At([]),bt(null),ae(null),v("Rendering PDF...")}else x.requiresPassword?(Xt(!0),yn(!1),v("")):(v(x.error||"Failed to load PDF"),yn(!1),Xt(!1),nn.current=null)},className:"p-2 border rounded"}),Ne&&Y("p",{className:"text-sm",style:{color:"var(--footer-muted)"},children:["Current file: ",Xo," \xB7 ",(Ne.size/1024).toFixed(1)," KB"]})]}),Ne&&Y("div",{className:"flex flex-1 flex-col overflow-hidden",children:[Y("div",{className:"flex shrink-0 items-center gap-3 border-b border-ink-line bg-paper-card px-4 py-1.5 text-xs dark:border-white/10 dark:bg-[#1a1712]",children:[k(Mo,{className:"h-3.5 w-3.5 shrink-0 text-ink-muted"}),k("span",{className:"truncate font-medium text-ink-soft dark:text-zinc-300",children:Xo}),Y("span",{className:"shrink-0 rounded bg-surface-container-high px-1.5 py-0.5 font-semibold text-ink-soft dark:bg-zinc-800 dark:text-zinc-400",children:[c.length," ",c.length===1?"page":"pages"]}),h&&k("span",{className:"shrink-0 animate-pulse text-crimson-600",children:"Rendering\u2026"}),k("div",{className:"flex-1"}),k("span",{className:"shrink-0 font-semibold capitalize text-ink-muted dark:text-zinc-400",children:b.replace(/-/g," ")})]}),Nr&&Y("div",{className:"flex shrink-0 flex-wrap items-center gap-2 border-b border-amber-400/20 bg-amber-50/80 px-4 py-2 dark:bg-amber-950/30",children:[k(is,{className:"h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),k("input",{ref:Ir,type:"text",placeholder:"Find\u2026",value:on,onChange:u=>ps(u.target.value),className:"h-7 w-40 rounded-md border border-amber-200 bg-paper-raised px-2 text-xs text-ink outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400/30 dark:border-white/10 dark:bg-zinc-900 dark:text-white"}),k("input",{type:"text",placeholder:"Replace with\u2026",value:gs,onChange:u=>Bl(u.target.value),className:"h-7 w-40 rounded-md border border-amber-200 bg-paper-raised px-2 text-xs text-ink outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400/30 dark:border-white/10 dark:bg-zinc-900 dark:text-white"}),st.length>0&&Y(tn,{children:[Y("span",{className:"text-xs font-semibold text-amber-700 dark:text-amber-400",children:[Er+1," / ",st.length]}),k("button",{type:"button",onClick:()=>Tr(u=>(u-1+st.length)%st.length),className:"flex h-6 w-6 items-center justify-center rounded hover:bg-amber-200/60 dark:hover:bg-amber-900/40",title:"Previous",children:k(Fm,{className:"h-3.5 w-3.5 text-amber-700 dark:text-amber-400"})}),k("button",{type:"button",onClick:()=>Tr(u=>(u+1)%st.length),className:"flex h-6 w-6 items-center justify-center rounded hover:bg-amber-200/60 dark:hover:bg-amber-900/40",title:"Next",children:k(Mm,{className:"h-3.5 w-3.5 text-amber-700 dark:text-amber-400"})})]}),on&&st.length===0&&k("span",{className:"text-xs text-zinc-400",children:"No matches"}),Y("div",{className:"flex gap-1",children:[Y("button",{type:"button",onClick:()=>{st[Er]&&$s(st[Er])},disabled:st.length===0,className:"flex h-7 items-center gap-1 rounded-md bg-amber-500 px-2.5 text-xs font-semibold text-white transition-colors hover:bg-amber-400 disabled:opacity-40",children:[k(Um,{className:"h-3 w-3"}),"Replace"]}),Y("button",{type:"button",onClick:()=>{nd()},disabled:st.length===0,className:"flex h-7 items-center gap-1 rounded-md border border-amber-300 bg-white px-2.5 text-xs font-semibold text-amber-700 transition-colors hover:bg-amber-50 disabled:opacity-40 dark:border-amber-700 dark:bg-zinc-900 dark:text-amber-400",children:["All (",st.length,")"]})]}),k("button",{type:"button",onClick:()=>{rr(!1),ps(""),Or([])},className:"ml-auto flex h-6 w-6 items-center justify-center rounded hover:bg-amber-200/60 dark:hover:bg-amber-900/40",children:k(gn,{className:"h-3.5 w-3.5 text-amber-700 dark:text-amber-400"})})]}),b==="sign"&&Ps&&Y("div",{className:"flex items-center gap-2 border-b border-amber-500/30 bg-amber-500/10 px-4 py-2 text-xs text-amber-600 dark:text-amber-300",children:[k(os,{className:"h-3.5 w-3.5"}),k("span",{className:"font-semibold",children:"Click anywhere on the page to place your signature"}),k("button",{type:"button",onClick:()=>Br(!1),className:"ml-auto text-amber-500 hover:text-amber-400",children:k(gn,{className:"h-3.5 w-3.5"})})]}),(b==="stamp"||b==="add-text")&&Y("div",{className:"flex flex-wrap items-center gap-2 border-b border-ink-line bg-paper-card px-4 py-2 text-xs text-ink-soft",children:[b==="stamp"?k(Dl,{className:"h-3.5 w-3.5 text-primary"}):k(Ml,{className:"h-3.5 w-3.5 text-primary"}),b==="stamp"&&Y(tn,{children:[k("span",{className:"font-semibold text-ink-muted",children:"Presets:"}),["APPROVED","CONFIDENTIAL","DRAFT","REVIEWED"].map(u=>k("button",{type:"button",onClick:()=>F(u),className:`rounded px-2 py-0.5 text-[10px] font-bold tracking-wide transition-colors ${S===u?"bg-primary text-white":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:u},u)),k("span",{className:"mx-1 h-4 w-px bg-ink-line"})]}),b==="stamp"&&k("input",{type:"text",value:S,onChange:u=>F(u.target.value),placeholder:"Custom stamp text\u2026",className:"h-7 w-44 rounded border border-ink-line bg-paper-raised px-2 text-xs text-ink placeholder:text-ink-muted focus:border-crimson-600 focus:outline-none"}),k("span",{className:"font-semibold text-ink-muted",children:b==="add-text"?"Default size:":"Size:"}),[10,14,18,24,36].map(u=>k("button",{type:"button",onClick:()=>N(u),className:`rounded px-1.5 py-0.5 text-xs font-bold ${T===u?"bg-primary text-white":"text-ink-muted hover:text-ink"}`,children:u},u)),b==="stamp"&&Y(tn,{children:[k("span",{className:"font-semibold text-ink-muted",children:"Color:"}),[{hex:"#D6002F",rgb:{r:.84,g:0,b:.19}},{hex:"#1A1A2E",rgb:{r:.1,g:.1,b:.18}},{hex:"#1D4ED8",rgb:{r:.11,g:.31,b:.85}},{hex:"#047857",rgb:{r:.02,g:.47,b:.34}}].map(({hex:u,rgb:g})=>k("button",{type:"button",title:u,onClick:()=>A(g),style:{background:u,width:18,height:18,borderRadius:4,border:O.r===g.r&&O.b===g.b?"2px solid white":"1px solid rgba(255,255,255,0.2)"}},u))]}),k("span",{className:"ml-1 font-semibold text-primary",children:b==="add-text"?"Click the page to add a text box, then type & format":"Click the page to place"})]}),b==="view"&&Y("div",{className:"flex flex-wrap items-center gap-2 border-b border-ink-line bg-paper-card px-4 py-1.5 text-xs text-ink-soft dark:border-white/10 dark:bg-[#1a1712]",children:[k(Pl,{className:"h-3.5 w-3.5 text-crimson-600"}),k("button",{type:"button",onClick:()=>_s(1/1.2),title:"Zoom out",className:"flex h-7 w-7 items-center justify-center rounded hover:bg-paper dark:hover:bg-zinc-800",children:k(Wm,{className:"h-3.5 w-3.5"})}),Y("span",{className:"w-12 text-center font-semibold text-ink-muted",children:[Math.round(ne*100),"%"]}),k("button",{type:"button",onClick:()=>_s(1.2),title:"Zoom in",className:"flex h-7 w-7 items-center justify-center rounded hover:bg-paper dark:hover:bg-zinc-800",children:k(Ym,{className:"h-3.5 w-3.5"})}),Y("button",{type:"button",onClick:hd,title:"Fit width",className:"flex h-7 items-center gap-1 rounded px-2 font-semibold hover:bg-paper dark:hover:bg-zinc-800",children:[k(jm,{className:"h-3.5 w-3.5"})," Width"]}),k("button",{type:"button",onClick:fd,title:"Fit page",className:"flex h-7 items-center rounded px-2 font-semibold hover:bg-paper dark:hover:bg-zinc-800",children:"Page"}),k("span",{className:"mx-1 h-4 w-px bg-ink-line dark:bg-white/10"}),k("button",{type:"button",onClick:()=>_r(le-1),disabled:le<=0,title:"Previous page",className:"flex h-7 w-7 items-center justify-center rounded hover:bg-paper disabled:opacity-30 dark:hover:bg-zinc-800",children:k(Rm,{className:"h-3.5 w-3.5"})}),k("input",{type:"number",min:1,max:c.length,value:le+1,onChange:u=>_r((Number(u.target.value)||1)-1),className:"h-7 w-12 rounded border border-ink-line bg-paper-raised px-1.5 text-center text-xs text-ink outline-none focus:border-crimson-600 dark:border-white/10 dark:bg-zinc-900 dark:text-white"}),Y("span",{className:"text-ink-muted",children:["/ ",c.length]}),k("button",{type:"button",onClick:()=>_r(le+1),disabled:le>=c.length-1,title:"Next page",className:"flex h-7 w-7 items-center justify-center rounded hover:bg-paper disabled:opacity-30 dark:hover:bg-zinc-800",children:k(Am,{className:"h-3.5 w-3.5"})}),Y("div",{className:"ml-auto flex items-center gap-2",children:[Y("button",{type:"button",onClick:()=>{rr(u=>!u),setTimeout(()=>{var u;return(u=Ir.current)==null?void 0:u.focus()},50)},className:`flex h-7 items-center gap-1 rounded px-2 font-semibold transition-colors ${Nr?"bg-amber-500 text-white":"hover:bg-paper dark:hover:bg-zinc-800"}`,children:[k(is,{className:"h-3.5 w-3.5"})," Find"]}),k("span",{className:"text-ink-muted",children:"Drag to select \xB7 Ctrl+C to copy"})]})]}),b==="redact"&&Y("div",{className:"flex flex-wrap items-center gap-2 border-b border-ink-line bg-paper-card px-4 py-2 text-xs text-ink-soft",children:[k(rs,{className:"h-3.5 w-3.5 text-primary"}),k("span",{className:"font-semibold text-ink-muted",children:"Redact:"}),k("span",{children:"Drag over text to mark it. Resize the green boxes, then apply, text is deleted and a black box is drawn."}),Y("div",{className:"ml-auto flex items-center gap-3",children:[k("span",{className:"text-ink-muted",children:kt.length?`${kt.length} mark${kt.length>1?"s":""}`:"No marks yet"}),k("button",{type:"button",onClick:()=>vn([]),disabled:kt.length===0||p,className:"rounded bg-paper px-2.5 py-1 font-semibold text-ink-soft hover:bg-ink-line disabled:opacity-40",children:"Clear marks"}),Y("button",{type:"button",onClick:()=>{ql()},disabled:kt.length===0||p,title:"Permanently delete the marked text and draw black boxes",className:"flex items-center gap-1 rounded bg-red-600 px-2.5 py-1 font-semibold text-white hover:bg-red-700 disabled:opacity-40",children:[k(rs,{className:"h-3 w-3"})," Apply redactions"]})]})]}),Y("div",{className:"relative flex flex-1 overflow-hidden",children:[Y("aside",{className:"z-30 flex w-[72px] shrink-0 flex-col items-center gap-0.5 self-stretch overflow-y-auto overflow-x-hidden border-r border-ink-line bg-paper-card px-1.5 py-3 [scrollbar-width:thin] [&>*]:shrink-0 dark:border-white/10 dark:bg-[#1a1712]",children:[k("div",{className:"mb-2 flex h-8 w-8 items-center justify-center rounded-lg bg-crimson-100",children:k(Mo,{className:"h-4 w-4 text-crimson-600"})}),k("div",{className:"mb-1 h-px w-10 bg-ink-line"}),Y("button",{type:"button",title:"Find & Replace (Ctrl+F)",onClick:()=>{rr(u=>!u),setTimeout(()=>{var u;return(u=Ir.current)==null?void 0:u.focus()},50)},className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${Nr?"bg-amber-500 text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[k(is,{className:"h-4 w-4"}),k("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:"Find"})]}),k("div",{className:"my-1 h-px w-10 bg-ink-line"}),[{t:"view",icon:k(Pl,{className:"h-4 w-4"}),label:"View",hint:"Read, select text, zoom, navigate & follow links"},{t:"select",icon:k(Lm,{className:"h-4 w-4"}),label:"Select",hint:"Select, move, resize or delete images and graphics"},{t:"edit-text",icon:k(Tm,{className:"h-4 w-4"}),label:"Edit",hint:"Edit text"},{t:"add-text",icon:k(Ml,{className:"h-4 w-4"}),label:"Add Text",hint:"Add new text"}].map(({t:u,icon:g,label:x,hint:P})=>Y("button",{type:"button",title:P!=null?P:x,onClick:()=>C(u),className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${b===u?"bg-primary text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[g,k("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:x})]},u)),k("div",{className:"my-1.5 h-px w-10 bg-ink-line"}),k("span",{className:"mb-0.5 text-[7px] font-bold uppercase tracking-widest text-ink-muted",children:"Annotate"}),[{t:"annotate",icon:k(Im,{className:"h-4 w-4"}),label:"Annotate"},{t:"draw",icon:k($m,{className:"h-4 w-4"}),label:"Draw"},{t:"comment",icon:k(Fl,{className:"h-4 w-4"}),label:"Comment"}].map(({t:u,icon:g,label:x})=>Y("button",{type:"button",title:x,onClick:()=>C(u),className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${b===u?"bg-primary text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[g,k("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:x})]},u)),k("div",{className:"my-1.5 h-px w-10 bg-ink-line"}),k("span",{className:"mb-0.5 text-[7px] font-bold uppercase tracking-widest text-ink-muted",children:"Edit"}),[{t:"sign",icon:k(os,{className:"h-4 w-4"}),label:"Sign"},{t:"redact",icon:k(rs,{className:"h-4 w-4"}),label:"Redact"},{t:"stamp",icon:k(Dl,{className:"h-4 w-4"}),label:"Stamp"},{t:"form",icon:k(Mo,{className:"h-4 w-4"}),label:"Forms"}].map(({t:u,icon:g,label:x})=>Y("button",{type:"button",title:x,onClick:()=>C(u),className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${b===u?"bg-primary text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"}`,children:[g,k("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:x})]},u)),Y("button",{type:"button",title:"Insert image (PNG/JPEG)",onClick:()=>{var u;return(u=ms.current)==null?void 0:u.click()},disabled:p,className:`flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-center transition-all ${$n?"bg-primary text-white shadow-md":"text-ink-soft hover:bg-paper hover:text-ink"} disabled:opacity-30`,children:[k(Xm,{className:"h-4 w-4"}),k("span",{className:"mt-1 text-[8px] font-semibold leading-tight",children:"Image"})]}),k("input",{ref:ms,type:"file",accept:"image/png,image/jpeg",className:"hidden",onChange:u=>{var x;let g=(x=u.target.files)==null?void 0:x[0];u.target.value="",g&&kd(g)}}),k("div",{className:"flex-1"}),k("div",{className:"mt-1 h-px w-10 bg-ink-line"}),Y("button",{type:"button",title:"Rotate page",onClick:()=>at({type:"rotate-page",pageIndex:Ms,degrees:Hl}),disabled:p,className:"flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-ink-muted transition-all hover:bg-paper hover:text-ink disabled:opacity-30",children:[k(_m,{className:"h-4 w-4"}),k("span",{className:"mt-1 text-[8px] font-semibold",children:"Rotate"})]}),Y("button",{type:"button",title:"Delete page",onClick:()=>at({type:"delete-page",pageIndex:Ms}),disabled:p,className:"flex w-full flex-col items-center justify-center rounded-lg py-2.5 text-red-500/70 transition-all hover:bg-red-50 hover:text-red-600 disabled:opacity-30",children:[k(ss,{className:"h-4 w-4"}),k("span",{className:"mt-1 text-[8px] font-semibold",children:"Delete"})]}),et.length+pt.length>0&&Y("div",{className:"mt-2 w-full rounded-lg bg-primary/20 py-1 text-center text-[8px] font-bold text-primary",children:[et.length+pt.length," annot."]})]}),Y("main",{ref:ce,className:"flex-1 overflow-auto p-6 md:p-12",style:{backgroundImage:"radial-gradient(#d8cdb8 1px, transparent 1px)",backgroundSize:"20px 20px"},children:[h&&k("div",{className:"mx-auto mb-6 max-w-4xl rounded-xl border border-outline-variant/40 bg-surface-container-lowest p-4 text-sm text-on-secondary-container shadow-sm",children:"Rendering with Avni engine..."}),!h&&c.length===0&&k("div",{className:"mx-auto max-w-4xl rounded-xl border border-outline-variant/40 bg-surface-container-lowest p-4 text-sm text-on-secondary-container shadow-sm",children:"No engine-rendered pages available."}),c.map(u=>{var B,M,L,j,X,$,V;let g=d[u.pageIndex],x=u.pageIndex,P=!!g,E=`${Math.ceil(u.width*I)}px`,R=`${Math.ceil(u.height*I)}px`;return Y("div",{className:"relative mx-auto mb-10 overflow-hidden rounded-[3px] shadow-[0_12px_40px_-10px_rgba(33,29,23,0.28)]",ref:D=>{He.current[x]=D},style:{width:E,minHeight:R,background:(B=g==null?void 0:g.bgCss)!=null?B:"#ffffff",cursor:$n?"crosshair":b==="form"?Pn?"crosshair":"default":["add-text","annotate","stamp","draw","comment","sign"].includes(b)?"crosshair":b==="select"?mt&&mt.pageIndex===x?mt.fromXObject?"not-allowed":"pointer":"default":"text",userSelect:b==="view"?"text":"none"},onMouseDown:D=>xd(D,x),onMouseMove:D=>bd(D,x),onMouseUp:D=>yd(D,x),onDoubleClick:D=>wd(D,x),onClick:D=>{var z;if($n){Pd(D,x);return}if(b!=="view"){if(b==="select"){vd(D,x);return}if(b==="comment"){let U=He.current[x];if(!U)return;let W=U.getBoundingClientRect(),J={id:crypto.randomUUID(),kind:"comment",pageIndex:x,x:D.clientX-W.left,y:D.clientY-W.top,text:"",color:"#F59E0B"};Ht("Added comment","\u{1F4AC}",x),Bn(te=>[...te,J]),$r(J.id);return}if(b==="sign"){if(vs&&Ps){let U=He.current[x];if(!U)return;let W=U.getBoundingClientRect();Ht("Placed signature","\u2712\uFE0F",x),Bn(J=>[...J,{id:crypto.randomUUID(),kind:"sign",pageIndex:x,x:D.clientX-W.left-100,y:D.clientY-W.top-40,width:200,height:80,dataUrl:vs}]),Br(!1)}else Ln(!0);return}if(b==="draw"&&Ot==="polygon"){let U=_[x],W=He.current[x];if(!U||!W)return;let J=W.getBoundingClientRect(),te=ut(D.clientX,D.clientY,J,I,U.height),Z=[...((z=Wt.current)==null?void 0:z.pageIndex)===x?Wt.current.points:[],te];Wt.current={pageIndex:x,points:Z},Pt({kind:"polygon",pageIndex:x,points:Z,cursor:te});return}if(b==="add-text"||b==="stamp"){Zl(D,x);return}if(Dr.current){Dr.current=!1;return}!er.current&&wn.length===0&&td(D,x)}},children:[P?k("img",{src:g.canvasDataUrl,alt:`Engine rendered page ${g.pageNum}`,draggable:!1,decoding:"async",style:{display:"block",width:E,height:R,background:(M=g.bgCss)!=null?M:"#fff"}}):k("div",{className:"flex h-full w-full items-center justify-center",style:{minHeight:R,background:"linear-gradient(90deg, rgba(127,127,127,0.08) 25%, rgba(127,127,127,0.16) 37%, rgba(127,127,127,0.08) 63%)",backgroundSize:"400% 100%",animation:"avni-skeleton 1.4s ease-in-out infinite"},children:Y("div",{className:"rounded-full bg-white px-3 py-1 text-xs font-medium text-on-secondary-container shadow-sm",children:["Loading page ",u.pageNum,"..."]})}),_[x]&&k(Li,{pageIndex:x,pageHeight:_[x].height,scale:I,annots:et,live:bs,liveStyle:Tt,selectedId:or,interactive:b==="select",liveMarkupKind:Sn==="underline"?"underline":Sn==="strikeout"?"strikeout":"highlight",onBeginResize:gd}),Y("svg",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"visible",zIndex:10,pointerEvents:"none"},xmlns:"http://www.w3.org/2000/svg",children:[pt.filter(D=>D.pageIndex===x&&D.kind==="sign").map(D=>k("image",{href:D.dataUrl,x:D.x,y:D.y,width:D.width,height:D.height},D.id)),pt.filter(D=>D.pageIndex===x&&D.kind==="comment").map(D=>Y("g",{style:{pointerEvents:"auto",cursor:"pointer"},onClick:z=>{z.stopPropagation(),$r(ws===D.id?null:D.id)},children:[k("rect",{x:D.x,y:D.y,width:22,height:22,rx:4,fill:D.color}),k("text",{x:D.x+11,y:D.y+15,textAnchor:"middle",fontSize:13,fill:"white",style:{fontFamily:"sans-serif",userSelect:"none"},children:"\u270E"})]},D.id))]}),pt.filter(D=>D.pageIndex===x&&D.kind==="comment"&&D.id===ws).map(D=>k("div",{style:{position:"absolute",left:D.x+26,top:D.y,zIndex:60,minWidth:220},onClick:z=>z.stopPropagation(),children:Y("div",{className:"rounded-xl bg-white shadow-xl ring-1 ring-black/10 overflow-hidden",children:[Y("div",{className:"flex items-center gap-2 bg-amber-400 px-3 py-2",children:[k(Fl,{className:"h-3.5 w-3.5 text-white"}),k("span",{className:"text-xs font-bold text-white",children:"Comment"}),k("div",{className:"flex-1"}),k("button",{className:"text-white/70 hover:text-white",onClick:()=>{Bn(z=>z.filter(U=>U.id!==D.id)),$r(null)},children:k(gn,{className:"h-3.5 w-3.5"})})]}),k("textarea",{className:"block w-full resize-none px-3 py-2 text-xs text-on-surface outline-none",rows:3,placeholder:"Add a comment...",defaultValue:D.text,autoFocus:!0,onBlur:z=>Bn(U=>U.map(W=>W.id===D.id?{...W,text:z.target.value}:W))}),k("div",{className:"flex justify-end gap-1 border-t border-outline-variant/20 px-3 py-1.5",children:Y("button",{className:"rounded-lg px-3 py-1 text-xs font-bold text-primary hover:bg-primary/10",onClick:()=>$r(null),children:[k(Fo,{className:"mr-1 inline h-3 w-3"}),"Done"]})})]})},D.id)),b==="select"&&_[x]&&(()=>{var ee;let D=et.find(Z=>Z.id===or&&Z.pageIndex===x);if(!D)return null;let z=ct(D),U=Ge(z.x,z.y+z.height,I,_[x].height),W=D.kind==="highlight"||D.kind==="underline"||D.kind==="strikeout"||D.kind==="squiggly",J=D.kind==="rect"||D.kind==="ellipse"||D.kind==="polygon",te=Z=>Yt(ue=>ue.map(xe=>xe.id===D.id?{...xe,style:{...xe.style,...Z}}:xe));return k("div",{style:{position:"absolute",left:Math.max(0,U.x),top:Math.max(0,U.y-12),zIndex:60,width:230},onMouseDown:Z=>Z.stopPropagation(),onClick:Z=>Z.stopPropagation(),children:Y("div",{className:"flex flex-col gap-3 rounded-xl bg-white p-3 shadow-xl ring-1 ring-black/10 dark:bg-zinc-800 dark:ring-white/10",children:[k(Bt,{label:W?"Color":"Stroke",color:D.style.color,onColor:Z=>te({color:Z}),opacity:D.style.opacity,onOpacity:Z=>te({opacity:Z})}),J&&k(Bt,{label:"Fill",color:(ee=D.style.fill)!=null?ee:{r:1,g:1,b:1},onColor:Z=>te({fill:Z}),allowNone:!0,isNone:!D.style.fill,onNone:()=>te({fill:null})}),Y("button",{type:"button",onClick:()=>{Yt(Z=>Z.filter(ue=>ue.id!==D.id)),It(null),Ht("Deleted annotation","\u{1F5D1}\uFE0F")},className:"flex items-center justify-center gap-1.5 rounded-lg border border-red-200 px-3 py-1.5 text-xs font-semibold text-red-500 transition-colors hover:bg-red-50 dark:border-red-500/30 dark:hover:bg-red-500/10",children:[k(ss,{className:"h-3.5 w-3.5"})," Delete"]})]})})})(),b==="select"&&P?Y("div",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:6},children:[mt&&!yt&&mt.pageIndex===x&&mt!==je?(()=>{var z;let D=Ge(mt.pdfX,mt.pdfY+mt.height,I,((z=_[x])==null?void 0:z.height)||792);return k("div",{style:{position:"absolute",left:`${D.x}px`,top:`${D.y}px`,width:`${mt.width*I}px`,height:`${mt.height*I}px`,border:"1.5px dashed rgba(59, 130, 246, 0.8)",borderRadius:"2px",background:"rgba(59, 130, 246, 0.05)",cursor:mt.fromXObject?"not-allowed":"move"},children:!mt.fromXObject&&k("span",{className:"pointer-events-none absolute left-0 -top-6 whitespace-nowrap rounded bg-blue-600/90 px-2 py-0.5 text-[10px] font-medium text-white shadow",children:"\u270B Drag to move \xB7 handles to resize"})})})():null,je&&!yt&&je.pageIndex===x?(()=>{var W;let D=Ge(je.pdfX,je.pdfY+je.height,I,((W=_[x])==null?void 0:W.height)||792),z=je.width*I,U=je.height*I;return Y("div",{style:{position:"absolute",left:`${D.x}px`,top:`${D.y}px`,width:`${z}px`,height:`${U}px`,border:je.fromXObject?"2px solid rgba(156, 163, 175, 0.9)":"2px solid rgba(59, 130, 246, 0.9)",borderRadius:"2px",background:"rgba(59, 130, 246, 0.06)",pointerEvents:"none"},children:[k("div",{style:{position:"absolute",top:"-30px",right:0,display:"flex",gap:"4px",pointerEvents:"auto"},children:je.fromXObject?k("span",{className:"rounded bg-gray-700 px-2 py-1 text-[10px] font-medium text-white shadow",title:"This object lives inside a reusable form XObject and cannot be edited in this version.",children:"\u{1F512} Locked (inside form)"}):Y(tn,{children:[k("span",{className:"rounded bg-blue-600/90 px-2 py-1 text-[10px] font-medium text-white shadow",children:"\u270B Drag to move \xB7 handles to resize"}),Y("button",{className:"flex items-center gap-1 rounded bg-red-600 px-2 py-1 text-[11px] font-medium text-white shadow hover:bg-red-700",onClick:J=>{J.stopPropagation(),Vo()},children:[k(ss,{className:"h-3 w-3"})," Delete"]})]})}),je.fromXObject?null:["nw","n","ne","e","se","s","sw","w"].filter(J=>je.kind==="image"||J.length===2).map(J=>{let te={position:"absolute",width:"9px",height:"9px",background:"#fff",border:"1.5px solid rgba(59, 130, 246, 0.95)",borderRadius:"2px",pointerEvents:"auto",cursor:`${J}-resize`};return J.includes("n")?te.top="-5px":J.includes("s")?te.bottom="-5px":te.top="calc(50% - 5px)",J.includes("w")?te.left="-5px":J.includes("e")?te.right="-5px":te.left="calc(50% - 5px)",k("div",{style:te,onMouseDown:ee=>{ee.stopPropagation(),ee.preventDefault(),Ys(je,"resize",J,ee)}},J)})]})})():null,yt&&yt.object.pageIndex===x&&g?(()=>{var J,te,ee;let D=yt.object,z=Ge(D.pdfX,D.pdfY+D.height,I,((J=_[x])==null?void 0:J.height)||792),U=D.width*I,W=D.height*I;return Y(tn,{children:[k("div",{style:{position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:`${U}px`,height:`${W}px`,background:(te=g.bgCss)!=null?te:"#fff"}}),k("div",{ref:Z=>{Ro.current=Z},style:{position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:`${U}px`,height:`${W}px`,backgroundImage:`url(${g.canvasDataUrl})`,backgroundPosition:`-${z.x}px -${z.y}px`,backgroundSize:`${g.canvasWidth}px ${g.canvasHeight}px`,transform:yt.mode==="move"?`translate(${yt.dxPx}px, ${yt.dyPx}px)`:`scale(${yt.scaleX}, ${yt.scaleY})`,transformOrigin:yt.mode==="resize"?Hm[(ee=yt.handle)!=null?ee:"se"]:void 0,willChange:"transform",outline:"2px solid rgba(59, 130, 246, 0.9)",boxShadow:"0 8px 24px rgba(0,0,0,0.25)",opacity:.95}})]})})():null]}):null,b==="edit-text"&&P&&((L=it.current[x])!=null&&L.length)?k("div",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:5},children:it.current[x].map((D,z)=>{var ee,Z;let U=Ge(D.pdfX,D.pdfY+D.height,I,((ee=_[x])==null?void 0:ee.height)||792),W=!D.fromXObject&&!!((Z=D.streamOperatorIndices)!=null&&Z.length),J=(On==null?void 0:On.run)===D&&On.pageIndex===x,te=J?`translate(${On.dxPx}px, ${On.dyPx}px)`:void 0;return k("div",{ref:J?ue=>{Sr.current=ue}:void 0,title:W?"Click to edit \xB7 drag to move":"Click to edit",onMouseDown:ue=>{ue.button===0&&(ue.stopPropagation(),ue.preventDefault(),sd(D,x,ue))},style:{position:"absolute",left:`${U.x}px`,top:`${U.y}px`,width:`${D.width*I}px`,height:`${D.height*I}px`,cursor:W?"move":"text",pointerEvents:"auto",border:"1px solid rgba(16, 185, 129, 0.5)",borderBottom:"2px solid rgba(16, 185, 129, 0.7)",borderRadius:"1px",background:J?"rgba(16, 185, 129, 0.18)":"rgba(16, 185, 129, 0.04)",transform:te,transition:J?"none":"background 0.12s",willChange:J?"transform":void 0,zIndex:J?20:void 0},onMouseEnter:ue=>{J||(ue.currentTarget.style.background="rgba(16, 185, 129, 0.12)")},onMouseLeave:ue=>{J||(ue.currentTarget.style.background="rgba(16, 185, 129, 0.04)")}},z)})}):null,(b==="form"||b==="view")&&P?(()=>{var z;let D=b==="form";return Y("div",{"data-fv":fs,style:{position:"absolute",inset:0,zIndex:6,pointerEvents:"none"},children:[D&&Pn&&k("div",{style:{position:"absolute",inset:0,cursor:"crosshair",pointerEvents:"auto"},onMouseDown:U=>md(x,U)}),D&&In&&In.pageIndex===x&&k("div",{style:{position:"absolute",left:`${In.x}px`,top:`${In.y}px`,width:`${In.w}px`,height:`${In.h}px`,border:"2px dashed rgba(99,102,241,0.9)",background:"rgba(99,102,241,0.12)",pointerEvents:"none"}}),((z=Et.current[x])!=null?z:[]).map(U=>{var Oe,Ye,Ie,ge,$t;let W=Ge(U.rect.x,U.rect.y+U.rect.height,I,((Oe=_[x])==null?void 0:Oe.height)||792),J=U.rect.width*I,te=U.rect.height*I,ee=Rr===U.id,Z=(Ie=(Ye=jl[U.id])!=null?Ye:U.value)!=null?Ie:"",ue={position:"absolute",left:`${W.x}px`,top:`${W.y}px`,width:`${J}px`,height:`${te}px`,outline:D?ee?"2px solid rgba(99,102,241,0.95)":"1px solid rgba(99,102,241,0.55)":"1px solid rgba(99,102,241,0.35)",background:"rgba(99,102,241,0.06)",borderRadius:"2px",pointerEvents:D&&Pn?"none":"auto",boxSizing:"border-box"},xe=()=>{D&&Go(U)};return Y(Cm.Fragment,{children:[U.type==="text"||U.type==="signature"?k("input",{type:"text",value:Z,readOnly:U.readOnly||U.type==="signature",placeholder:U.type==="signature"?"Signature":"",onFocus:xe,onChange:Ce=>Mr(St=>({...St,[U.id]:Ce.target.value})),onBlur:Ce=>Ur(U,Ce.target.value),style:{...ue,padding:"0 4px",fontSize:`${Math.min(te*.7,14)}px`,color:"#111",fontStyle:U.type==="signature"?"italic":"normal"}}):U.type==="checkbox"?k("input",{type:"checkbox",checked:Z===U.onState||Z==="Yes"||Z==="On"||Z==="true",onFocus:xe,onChange:Ce=>{var St;return Ur(U,Ce.target.checked?(St=U.onState)!=null?St:"Yes":"Off")},style:{...ue,padding:0,accentColor:"#6366f1"}}):U.type==="dropdown"?Y("select",{value:Z,onFocus:xe,onChange:Ce=>Ur(U,Ce.target.value),style:{...ue,padding:"0 4px",fontSize:`${Math.min(te*.7,14)}px`,color:"#111"},children:[k("option",{value:""}),((ge=U.options)!=null?ge:[]).map(Ce=>k("option",{value:Ce,children:Ce},Ce))]}):U.type==="radio"?k("div",{style:{...ue,display:"flex",flexDirection:"column",justifyContent:"space-around",padding:"2px 4px",fontSize:"11px",color:"#111"},onClick:xe,children:(($t=U.options)!=null?$t:[]).map(Ce=>Y("label",{style:{display:"flex",alignItems:"center",gap:4},children:[k("input",{type:"radio",name:`${U.id}`,checked:Z===Ce,onChange:()=>Ur(U,Ce),style:{accentColor:"#6366f1"}}),Ce]},Ce))}):null,D&&ee&&!Pn&&k("button",{type:"button",title:"Delete field",onClick:()=>Us(U),style:{position:"absolute",left:`${W.x+J-8}px`,top:`${W.y-10}px`,zIndex:7,pointerEvents:"auto"},className:"flex h-5 w-5 items-center justify-center rounded-full bg-red-600 text-white shadow hover:bg-red-700",children:k(gn,{className:"h-3 w-3"})})]},U.id)})]})})():null,b==="view"&&P&&Math.abs(x-le)<=2&&((j=it.current[x])!=null&&j.length)?k(Xi,{runs:it.current[x],scale:I,pageHeight:((X=_[x])==null?void 0:X.height)||792}):null,b==="view"&&P&&(($=De.current[x])!=null&&$.length)?k("div",{style:{position:"absolute",inset:0,zIndex:7,pointerEvents:"none"},children:De.current[x].map((D,z)=>{var J,te;let U=Ge(D.rect.x,D.rect.y+D.rect.height,I,((J=_[x])==null?void 0:J.height)||792),W={position:"absolute",left:`${U.x}px`,top:`${U.y}px`,width:`${D.rect.width*I}px`,height:`${D.rect.height*I}px`,cursor:"pointer",pointerEvents:"auto",borderRadius:"2px"};return D.uri?k("a",{href:D.uri,target:"_blank",rel:"noopener noreferrer",title:D.uri,style:W},z):k("div",{title:`Go to page ${((te=D.destPageIndex)!=null?te:0)+1}`,style:W,onClick:()=>{var ee;return _r((ee=D.destPageIndex)!=null?ee:0)}},z)})}):null,Nr&&st.filter(D=>D.pageIndex===x).length>0&&k("div",{style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:8},children:st.filter(D=>D.pageIndex===x).map((D,z)=>{var J;let U=Ge(D.pdfX,D.pdfY+D.height,I,((J=_[x])==null?void 0:J.height)||792),W=st.indexOf(D)===Er;return k("div",{style:{position:"absolute",left:`${U.x}px`,top:`${U.y}px`,width:`${D.width*I}px`,height:`${D.height*I}px`,background:W?"rgba(245, 158, 11, 0.45)":"rgba(245, 158, 11, 0.2)",outline:W?"2px solid rgba(245, 158, 11, 0.8)":"none",borderRadius:"1px"}},z)})}),b==="redact"&&kt.some(D=>D.pageIndex===x)&&k("div",{style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:11},children:kt.filter(D=>D.pageIndex===x).map(D=>{var J;let z=Ge(D.x,D.y+D.height,I,((J=_[x])==null?void 0:J.height)||792),U=D.width*I,W=D.height*I;return Y("div",{style:{position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:`${U}px`,height:`${W}px`,border:"2px solid rgba(22, 163, 74, 0.95)",background:"rgba(22, 163, 74, 0.18)",borderRadius:"2px",pointerEvents:"auto",cursor:"move"},title:"Drag to move \xB7 handles to resize \xB7 \xD7 to remove",onMouseDown:te=>Ns(D,"move",null,te),children:[k("button",{onMouseDown:te=>te.stopPropagation(),onClick:te=>{te.stopPropagation(),Vl(D.id)},title:"Remove this mark",style:{position:"absolute",top:"-10px",right:"-10px",width:"20px",height:"20px",borderRadius:"9999px",background:"#dc2626",color:"#fff",fontSize:"12px",lineHeight:"18px",textAlign:"center",border:"1.5px solid #fff",boxShadow:"0 1px 4px rgba(0,0,0,0.3)",cursor:"pointer"},children:"\xD7"}),["nw","n","ne","e","se","s","sw","w"].map(te=>{let ee={position:"absolute",width:"9px",height:"9px",background:"#fff",border:"1.5px solid rgba(22, 163, 74, 0.95)",borderRadius:"2px",cursor:`${te}-resize`};return te.includes("n")?ee.top="-5px":te.includes("s")?ee.bottom="-5px":ee.top="calc(50% - 5px)",te.includes("w")?ee.left="-5px":te.includes("e")?ee.right="-5px":ee.left="calc(50% - 5px)",k("div",{style:ee,onMouseDown:Z=>Ns(D,"resize",te,Z)},te)})]},D.id)})}),Ae&&Ae.pageIndex===x&&k("div",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:10},children:wn.map((D,z)=>{var W;let U=Ge(D.pdfX,D.pdfY+D.height,I,((W=_[x])==null?void 0:W.height)||792);return k("div",{style:{position:"absolute",left:`${U.x}px`,top:`${U.y}px`,width:`${D.width*I}px`,height:`${D.height*I}px`,background:"rgba(186, 0, 48, 0.12)",border:"2px solid rgba(186, 0, 48, 0.55)",borderRadius:"2px"}},z)})}),wn.length>0&&(Ae==null?void 0:Ae.pageIndex)===x&&Y("div",{className:"absolute right-3 top-3 z-[100] flex items-center gap-1 rounded-full bg-inverse-surface px-2 py-1 text-inverse-on-surface shadow-2xl",children:[k("button",{onClick:()=>Dd(),disabled:b==="redact",className:"rounded-full px-3 py-1 text-[10px] font-bold transition-colors hover:text-primary disabled:opacity-40",children:"Edit"}),k("span",{className:"h-3 w-px bg-inverse-on-surface/20"}),k("button",{onClick:()=>Cd(),className:"rounded-full px-3 py-1 text-[10px] font-bold transition-colors hover:text-error",children:"Delete"}),k("span",{className:"h-3 w-px bg-inverse-on-surface/20"}),k("button",{onClick:()=>{At([]),bt(null)},className:"rounded-full px-3 py-1 text-[10px] font-bold opacity-70 transition-opacity hover:opacity-100",children:"Clear"})]}),(G==null?void 0:G.pageIndex)===x&&k(pc,{ref:me,containerX:G.containerX,containerY:G.containerY,screenWidth:G.screenWidth,screenHeight:G.screenHeight,scale:I,fontSizePt:G.fontSize,fontFamily:G.fontFamily,baselineOffsetPx:G.baselineOffsetPx,maxWidth:G.maxWidth,initialSpans:(V=G.spans)!=null?V:[],baseColor:G.color,maskRect:G.maskRect,bgColor:G.bgColor,ocr:G.ocr,onCommit:(D,z)=>{od(D,z)},onCancel:()=>ae(null),onActiveStyleChange:Te},`rt-${x}-${Math.round(G.pdfX)}-${Math.round(G.pdfY)}-${G.isNew?"n":"e"}`)]},u.pageNum)})]}),k(Bi,{tool:b,textActive:!!G,textStyle:Xe,fallbackSizePt:(Gs=G==null?void 0:G.fontSize)!=null?Gs:T,fontName:G==null?void 0:G.fontName,onToggle:u=>{var g;return(g=me.current)==null?void 0:g.toggle(u)},onSize:u=>{var g;return(g=me.current)==null?void 0:g.setSize(u)},onColor:u=>{var g;return(g=me.current)==null?void 0:g.setColor(u)},annotSubtool:Sn,setAnnotSubtool:_l,highlightMode:xs,setHighlightMode:Xl,drawShape:Ot,setDrawShape:zl,annotStyle:Tt,setAnnotStyle:Ul,annotationCount:et.length,onClearAnnotations:()=>{Yt([]),It(null)},addFieldType:Pn,setAddFieldType:Eo,hasFormFields:$l,selectedField:ir,onUpdateField:u=>{ir&&ld(ir,u)},onDeleteField:()=>{ir&&Us(ir)},onFlattenForm:()=>{cd()}}),Ds&&Y("aside",{className:"flex w-72 shrink-0 flex-col border-l border-ink-line bg-paper-card dark:border-white/10 dark:bg-[#1a1712]",children:[Y("div",{className:"flex items-center gap-2 border-b border-ink-line px-4 py-3 dark:border-white/10",children:[k(Sl,{className:"h-4 w-4 text-crimson-600"}),k("span",{className:"font-display text-sm font-bold text-ink dark:text-white",children:"Activity"}),k("div",{className:"flex-1"}),k("button",{type:"button",onClick:()=>Cs(!1),className:"rounded-lg p-1 text-ink-muted hover:bg-paper hover:text-ink dark:hover:bg-zinc-800",children:k(gn,{className:"h-3.5 w-3.5"})})]}),k("div",{className:"flex-1 overflow-y-auto",children:_n.length===0?Y("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[k(Nm,{className:"h-8 w-8 text-ink-muted dark:text-zinc-600"}),k("p",{className:"text-xs text-ink-muted dark:text-zinc-500",children:"No activity yet"})]}):k("ul",{className:"divide-y divide-ink-line/60 dark:divide-white/5",children:[..._n].reverse().map(u=>Y("li",{className:"group flex items-start gap-3 px-4 py-3",children:[k("span",{className:"mt-0.5 text-base leading-none",children:u.icon}),Y("div",{className:"min-w-0 flex-1",children:[k("p",{className:"truncate text-xs font-medium text-ink dark:text-zinc-200",children:u.action}),u.detail&&k("p",{className:"mt-0.5 truncate text-[11px] text-ink-soft dark:text-zinc-400",title:u.detail,children:u.detail}),Y("p",{className:"mt-0.5 text-[10px] text-ink-muted dark:text-zinc-500",children:[u.time.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),u.pageIndex!==void 0&&` \xB7 p.${u.pageIndex+1}`]})]}),u.snapshot?k("button",{type:"button",onClick:()=>Fs(u),disabled:p,title:"Undo this action and everything after it",className:"mt-0.5 shrink-0 rounded-md border border-ink-line-strong px-2 py-1 text-[10px] font-semibold text-ink-soft opacity-0 transition-opacity hover:border-crimson-300 hover:text-crimson-600 group-hover:opacity-100 disabled:opacity-30 dark:border-white/10 dark:text-zinc-400",children:"Undo to here"}):k("span",{className:"mt-0.5 shrink-0 text-[9px] text-ink-muted dark:text-zinc-600",title:"Too old to undo",children:"-"})]},u.id))})}),_n.length>0&&k("div",{className:"border-t border-ink-line px-4 py-2 dark:border-white/10",children:k("button",{type:"button",onClick:()=>Lo([]),className:"text-[11px] text-ink-muted hover:text-crimson-600 dark:text-zinc-500",children:"Clear history"})})]})]}),Y("div",{className:"flex h-6 shrink-0 items-center gap-3 border-t border-ink-line bg-paper-card px-4 text-[11px] text-ink-muted dark:border-white/10 dark:bg-[#1a1712] dark:text-zinc-500",children:[Y("span",{children:[c.length," ",c.length===1?"page":"pages"]}),k("span",{className:"opacity-40",children:"\xB7"}),k("span",{className:"capitalize",children:b.replace(/-/g," ")}),et.length+pt.length>0&&Y(tn,{children:[k("span",{className:"opacity-40",children:"\xB7"}),Y("span",{className:"text-primary",children:[et.length+pt.length," annotation",et.length+pt.length!==1?"s":""]})]}),p&&Y(tn,{children:[k("span",{className:"opacity-40",children:"\xB7"}),k("span",{className:"animate-pulse text-primary",children:"Saving\u2026"})]})]})]}),Pr&&k("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:Y("div",{className:"flex flex-col items-center gap-4",children:[Y("div",{className:"relative h-16 w-16",children:[k("div",{className:"absolute inset-0 rounded-full border-4 border-white/20"}),k("div",{className:"absolute inset-0 animate-spin rounded-full border-4 border-transparent border-t-primary border-r-primary"})]}),Y("div",{className:"text-center",children:[k("p",{className:"font-semibold text-white",children:"Rendering PDF..."}),k("p",{className:"text-sm text-white/70",children:"Please wait while we process your document"})]})]})}),En&&nn.current&&k("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",children:Y("div",{className:"rounded-2xl bg-surface dark:bg-zinc-900 p-8 shadow-2xl max-w-md w-full mx-4",children:[k("h2",{className:"text-xl font-bold text-on-surface dark:text-white mb-2",children:"Password Protected PDF"}),k("p",{className:"text-on-surface-variant dark:text-zinc-400 mb-6",children:"This PDF requires a password to unlock. Please enter it below."}),y&&y.includes("Incorrect")&&k("div",{className:"mb-4 rounded-lg bg-red-50 dark:bg-red-950/20 p-3 border border-red-200 dark:border-red-800",children:k("p",{className:"text-sm text-red-700 dark:text-red-400",children:y})}),k("input",{type:"password",value:Re,onChange:u=>Rt(u.target.value),onKeyDown:u=>{u.key==="Enter"&&Re.trim()&&Ws()},className:"w-full rounded-xl border border-outline-variant/40 dark:border-white/10 bg-surface-container-lowest dark:bg-zinc-950 px-4 py-3 text-sm text-on-surface dark:text-zinc-100 outline-none focus:border-primary focus:ring-1 focus:ring-primary/50 mb-6",placeholder:"Enter password",autoFocus:!0}),Y("div",{className:"flex gap-3",children:[k("button",{type:"button",onClick:()=>{Rt(""),Xt(!1),nn.current=null,v("")},className:"flex-1 rounded-full border border-outline-variant/40 dark:border-white/10 px-4 py-3 text-sm font-semibold text-on-surface dark:text-white hover:bg-surface-container-highest dark:hover:bg-zinc-800 transition-colors",children:"Cancel"}),k("button",{type:"button",onClick:Ws,disabled:!Re.trim(),className:"flex-1 rounded-full bg-primary px-4 py-3 text-sm font-semibold text-white disabled:opacity-60 disabled:cursor-not-allowed hover:bg-primary/90 transition-colors",children:"Unlock"})]})]})}),Yl&&k("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:()=>Ln(!1),children:Y("div",{className:"w-[480px] max-w-[95vw] rounded-2xl bg-paper-raised shadow-2xl dark:bg-zinc-900",onClick:u=>u.stopPropagation(),children:[Y("div",{className:"flex items-center gap-3 border-b border-ink-line px-6 py-4 dark:border-white/10",children:[k(os,{className:"h-5 w-5 text-primary"}),k("h2",{className:"font-headline text-lg font-bold text-on-surface dark:text-white",children:"Add Signature"}),k("div",{className:"flex-1"}),k("button",{type:"button",onClick:()=>Ln(!1),className:"rounded-full p-1 text-on-surface-variant hover:bg-surface-container-high dark:text-zinc-400 dark:hover:bg-zinc-800",children:k(gn,{className:"h-4 w-4"})})]}),Y("div",{className:"px-6 py-4",children:[Y("div",{className:"mb-3 flex items-center justify-between",children:[k("p",{className:"text-sm text-on-secondary-container dark:text-zinc-400",children:"Draw your signature below:"}),Y("button",{type:"button",onClick:()=>{var u;return(u=Ss.current)==null?void 0:u.click()},className:"inline-flex items-center gap-1.5 rounded-lg border border-outline-variant/40 px-3 py-1.5 text-xs font-semibold text-on-secondary-container hover:bg-surface-container-high dark:border-white/10 dark:text-zinc-300 dark:hover:bg-zinc-800",children:[k(as,{className:"h-3.5 w-3.5"})," Upload image"]}),k("input",{ref:Ss,type:"file",accept:"image/png,image/jpeg",className:"hidden",onChange:u=>{var P;let g=(P=u.target.files)==null?void 0:P[0];if(u.target.value="",!g)return;let x=new FileReader;x.onload=()=>{typeof x.result=="string"&&(ks(x.result),Ln(!1),Br(!0))},x.readAsDataURL(g)}})]}),k("canvas",{ref:Un,width:420,height:150,className:"w-full rounded-lg border-2 border-dashed border-outline-variant/60 bg-white dark:border-white/10 dark:bg-zinc-800",style:{cursor:"crosshair",touchAction:"none"},onMouseDown:u=>{let g=u.currentTarget.getBoundingClientRect(),x=u.currentTarget.getContext("2d");x&&(x.beginPath(),x.moveTo((u.clientX-g.left)*(u.currentTarget.width/g.width),(u.clientY-g.top)*(u.currentTarget.height/g.height)),x.strokeStyle="#1a1a2e",x.lineWidth=2.5,x.lineCap="round",x.lineJoin="round",Lr.current=!0)},onMouseMove:u=>{if(!Lr.current)return;let g=u.currentTarget.getBoundingClientRect(),x=u.currentTarget.getContext("2d");x&&(x.lineTo((u.clientX-g.left)*(u.currentTarget.width/g.width),(u.clientY-g.top)*(u.currentTarget.height/g.height)),x.stroke())},onMouseUp:()=>{Lr.current=!1},onMouseLeave:()=>{Lr.current=!1}}),k("p",{className:"mt-2 text-xs text-on-secondary-container/60 dark:text-zinc-500",children:"After applying, click on the page to place it"})]}),Y("div",{className:"flex items-center gap-3 border-t border-ink-line px-6 py-4 dark:border-white/10",children:[k("button",{type:"button",onClick:()=>{var g;let u=(g=Un.current)==null?void 0:g.getContext("2d");u&&Un.current&&u.clearRect(0,0,Un.current.width,Un.current.height)},className:"rounded-xl border border-outline-variant/40 px-4 py-2 text-sm font-semibold text-on-secondary-container hover:bg-surface-container-high dark:border-white/10 dark:text-zinc-400 dark:hover:bg-zinc-800",children:"Clear"}),k("div",{className:"flex-1"}),k("button",{type:"button",onClick:()=>Ln(!1),className:"rounded-xl border border-outline-variant/40 px-4 py-2 text-sm font-semibold text-on-secondary-container hover:bg-surface-container-high dark:border-white/10 dark:text-zinc-400",children:"Cancel"}),Y("button",{type:"button",onClick:()=>{let u=Un.current;u&&(ks(u.toDataURL("image/png")),Ln(!1),Br(!0))},className:"inline-flex items-center gap-2 rounded-xl bg-primary px-5 py-2 text-sm font-bold text-on-primary hover:brightness-110",children:[k(Fo,{className:"h-4 w-4"}),"Apply Signature"]})]})]})})]})},Nl=Jm;import{jsx as El}from"react/jsx-runtime";function Ol({licenseKey:t,activationUrl:e,decryptUrl:n,className:r,style:o}){let i=Tl.useMemo(()=>({licenseKey:t,activationUrl:e}),[t,e]);return El("div",{className:r?`namahapdf-root ${r}`:"namahapdf-root",style:o,children:El(Nl,{license:i,decryptUrl:n})})}var Zm=Ol;export{Ol as NamahaEditor,Si as configureLicense,Zm as default,Ru as getLicenseState,Ya as isFeatureEnabled,Au as onLicenseChange,ro as shouldWatermark};
|